From 667d0767f4fe9135765b3d3bf60f6d9991d85a07 Mon Sep 17 00:00:00 2001 From: magnetarQ <340235260+magnetarQ@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:38:48 +0300 Subject: [PATCH 1/2] noop import: skip dates already held before reading them, and say so Re-importing a NOOP backup the app already has read and grouped every row of every day, then kept every day (isMeasuredDay) and reported "nothing in it this app could use". On a 67-day, 7M-row backup that was minutes of work on a phone for no result. Days that failed or timed out to derive were only logged and read the same way. - The .noopbak reader finds the source dates with indexed seeks and skips a date the device already holds, unless the next date needs it as its previous evening or it carries step-counter rows. The engine's commit-time guard is unchanged. - deriveImportedDays reports kept and failed days; NoopImportResult carries keptDates and failedDates. - The import report counts kept dates as "already measured here and left alone" and names failed days. --- lib/compute/derivation_engine.dart | 7 + lib/import/noop_backup_import.dart | 194 +++++++++---- lib/import/noop_import.dart | 14 +- lib/import/noop_ingest.dart | 24 +- lib/ui2/onboarding/welcome.dart | 13 + .../noop_import_duplicate_preflight_test.dart | 266 ++++++++++++++++++ test/noop_ingest_plausibility_test.dart | 2 + test/noop_reimport_report_test.dart | 70 +++++ test/noop_step_coverage_reset_test.dart | 5 +- 9 files changed, 540 insertions(+), 55 deletions(-) create mode 100644 test/noop_import_duplicate_preflight_test.dart create mode 100644 test/noop_reimport_report_test.dart diff --git a/lib/compute/derivation_engine.dart b/lib/compute/derivation_engine.dart index f73d6696e4..f7cef6dc04 100644 --- a/lib/compute/derivation_engine.dart +++ b/lib/compute/derivation_engine.dart @@ -6905,6 +6905,11 @@ class DerivationEngine { Profile profile, Set dates, { void Function(String day)? onDayDone, + // Why a date did NOT derive. The count alone made "already held", + // "failed" and "no data" indistinguishable to the import screen, which then + // told a user re-importing their own backup it had nothing usable in it. + void Function(String day)? onDayKept, + void Function(String day, Object error)? onDayFailed, int? resetGeneration, }) async { if (sub.isEmpty || dates.isEmpty) return 0; @@ -6948,6 +6953,7 @@ class DerivationEngine { if (LocalDb.isMeasuredDayRow(existing) && !importReachesFurther(existing, dataNowSec)) { _log('import day ${day.date} kept (already measured on this device)'); + onDayKept?.call(day.date); continue; } try { @@ -6958,6 +6964,7 @@ class DerivationEngine { onDayDone?.call(day.date); } catch (e) { _log('import day ${day.date} FAILED/skipped: $e'); + onDayFailed?.call(day.date, e); } } return done; diff --git a/lib/import/noop_backup_import.dart b/lib/import/noop_backup_import.dart index c377d62171..11cab89183 100644 --- a/lib/import/noop_backup_import.dart +++ b/lib/import/noop_backup_import.dart @@ -42,6 +42,8 @@ import 'package:sqflite/sqflite.dart'; import '../compute/derivation_engine.dart'; import '../compute/profile.dart'; +import '../compute/substrate.dart' show localDateLabel; +import '../data/db.dart'; import 'import_container.dart'; import 'noop_import.dart'; import 'noop_ingest.dart'; @@ -80,6 +82,11 @@ const Map> _kTableCols = { }; class NoopBackupImporter { + /// Read every date, as before the held-date preflight existed — so a test can + /// show a preflight import derives exactly what a full read does. + @visibleForTesting + static bool debugSkipHeldDatePreflight = false; + /// Import an already-extracted `noop-backup.sqlite` at [path]. /// /// Opened READ-ONLY — a backup is the user's only copy of their history and @@ -307,6 +314,13 @@ class NoopBackupImporter { final ingest = NoopIngest(profile, engine, onProgress: onProgress); + // Dates this device already holds, decided BEFORE any sample is read. The + // engine would keep them anyway (its commit-time guard below stays), but + // only after this walk had read and grouped every row of every day: a + // re-import of a backup the app already has spent minutes reading + // millions of rows to derive nothing. + final skip = await _heldDatesToSkip(src, readable, ids, minTs); + // Walk LOCAL days. Built through the DateTime(y, m, d + 1) constructor // rather than `add(Duration(days: 1))` so a DST boundary lands on real local // midnight instead of 23:00 or 01:00. @@ -315,52 +329,57 @@ class NoopBackupImporter { final next = DateTime(dayStart.year, dayStart.month, dayStart.day + 1); final from = dayStart.millisecondsSinceEpoch ~/ 1000; final to = next.millisecondsSinceEpoch ~/ 1000; - - // [NoopIngest] re-sorts by timestamp but keeps rows that share a second in - // arrival order, so beats within a second must come in detection order - // (the `ts, rowid` order above). The DAYS must also arrive in ascending - // order, since the high-water date is what closes out and derives the - // previous one. - await _read(src, tables, columns, ordered, ids, corrupt, - 'hrSample', from, to, (r) async { - final ts = _int(r['ts']), v = _int(r['bpm']); - if (ts == null || v == null) return; - if (await ingest.offer(ts)) ingest.hr(ts, v); - }); - await _read(src, tables, columns, ordered, ids, corrupt, - 'rrInterval', from, to, (r) async { - final ts = _int(r['ts']), v = _num(r['rrMs']); - if (ts == null || v == null) return; - if (await ingest.offer(ts)) ingest.rr(ts, v); - }); - await _read(src, tables, columns, ordered, ids, corrupt, - 'gravitySample', from, to, (r) async { - final ts = _int(r['ts']); - if (ts == null) return; - if (await ingest.offer(ts)) { - ingest.gravity(ts, _num(r['x']), _num(r['y']), _num(r['z'])); - } - }); - await _read(src, tables, columns, ordered, ids, corrupt, - 'skinTempSample', from, to, (r) async { - final ts = _int(r['ts']); - if (ts == null) return; - if (await ingest.offer(ts)) ingest.skinTemp(ts, _int(r['raw'])); - }); - await _read(src, tables, columns, ordered, ids, corrupt, - 'spo2Sample', from, to, (r) async { - final ts = _int(r['ts']); - if (ts == null) return; - if (await ingest.offer(ts)) { - ingest.spo2(ts, _int(r['red']), _int(r['ir'])); - } - }); - await _read(src, tables, columns, ordered, ids, corrupt, - 'stepSample', from, to, (r) async { - final ts = _int(r['ts']), v = _int(r['counter']); - if (ts == null || v == null) return; - if (await ingest.offer(ts)) ingest.stepCounter(ts, v); - }); + final label = localDateLabel(from); + final skipDay = skip.contains(label); + if (skipDay) ingest.markKept(label); + + if (!skipDay) { + // [NoopIngest] re-sorts by timestamp but keeps rows that share a second in + // arrival order, so beats within a second must come in detection order + // (the `ts, rowid` order above). The DAYS must also arrive in ascending + // order, since the high-water date is what closes out and derives the + // previous one. + await _read(src, tables, columns, ordered, ids, corrupt, + 'hrSample', from, to, (r) async { + final ts = _int(r['ts']), v = _int(r['bpm']); + if (ts == null || v == null) return; + if (await ingest.offer(ts)) ingest.hr(ts, v); + }); + await _read(src, tables, columns, ordered, ids, corrupt, + 'rrInterval', from, to, (r) async { + final ts = _int(r['ts']), v = _num(r['rrMs']); + if (ts == null || v == null) return; + if (await ingest.offer(ts)) ingest.rr(ts, v); + }); + await _read(src, tables, columns, ordered, ids, corrupt, + 'gravitySample', from, to, (r) async { + final ts = _int(r['ts']); + if (ts == null) return; + if (await ingest.offer(ts)) { + ingest.gravity(ts, _num(r['x']), _num(r['y']), _num(r['z'])); + } + }); + await _read(src, tables, columns, ordered, ids, corrupt, + 'skinTempSample', from, to, (r) async { + final ts = _int(r['ts']); + if (ts == null) return; + if (await ingest.offer(ts)) ingest.skinTemp(ts, _int(r['raw'])); + }); + await _read(src, tables, columns, ordered, ids, corrupt, + 'spo2Sample', from, to, (r) async { + final ts = _int(r['ts']); + if (ts == null) return; + if (await ingest.offer(ts)) { + ingest.spo2(ts, _int(r['red']), _int(r['ir'])); + } + }); + await _read(src, tables, columns, ordered, ids, corrupt, + 'stepSample', from, to, (r) async { + final ts = _int(r['ts']), v = _int(r['counter']); + if (ts == null || v == null) return; + if (await ingest.offer(ts)) ingest.stepCounter(ts, v); + }); + } // Jump straight to the next local day holding a sample, so a gap between // export spans (or one stray early row) is not walked an empty day at a @@ -396,7 +415,7 @@ class NoopBackupImporter { dayStart = after; } - if (ingest.rows == 0) { + if (ingest.rows == 0 && ingest.keptDates.isEmpty) { // Every channel we read came back corrupt (see [_isCorruptPageError]) — // this is not "the backup is empty", it is "SQLite itself cannot read // the file", and the two must never share a message. @@ -409,7 +428,86 @@ class NoopBackupImporter { } await ingest.finish(); return NoopImportResult(ingest.days, ingest.rows, ingest.lateRows, - ingest.steps, ingest.strandedDates, corrupt); + ingest.steps, ingest.strandedDates, corrupt, + Set.unmodifiable(ingest.keptDates), Map.unmodifiable(ingest.failedDates)); + } + + /// Local dates whose samples need not be read: the device already holds the + /// date ([LocalDb.isMeasuredDay], the same test the engine applies when it + /// commits), AND the next date holding samples does not need it as context. + /// + /// The context rule is why this cannot simply stop after a run of + /// duplicates: a new night whose sleep began the previous evening derives + /// from the previous date's samples too, so a held date directly before a + /// new one is still read (the engine then keeps it). A held date carrying + /// step-counter rows is also read, so step banking is exactly as before. + /// + /// Empty — read everything, as before — when the dates cannot be found + /// cheaply: a table without a usable deviceId would make every probe below a + /// whole-table scan, and a torn page is left for [_read] to report. + static Future> _heldDatesToSkip( + Database src, + Set readable, + Map> ids, + int minTs, + ) async { + if (debugSkipHeldDatePreflight) return {}; + if (readable.isEmpty || !readable.every(ids.containsKey)) return {}; + final dates = []; + final hasSteps = {}; + try { + var cursor = _localMidnight(minTs).millisecondsSinceEpoch ~/ 1000; + while (true) { + num? lo; + for (final t in readable) { + for (final d in ids[t]!) { + final r = await src.rawQuery( + 'SELECT ts FROM $t WHERE deviceId = ? AND ts >= ? ' + 'AND ts <= ? ORDER BY ts LIMIT 1', + // Same upper bound as the read walk: a microsecond-scaled + // row would otherwise reach DateTime and throw. + [d, cursor, noopMaxPlausibleTs()]); + final a = r.isEmpty ? null : _raw(r.first['ts']); + if (a != null && (lo == null || a < lo)) lo = a; + } + } + if (lo == null) break; + final day = _localMidnight(lo.floor()); + final next = DateTime(day.year, day.month, day.day + 1); + final from = day.millisecondsSinceEpoch ~/ 1000; + final to = next.millisecondsSinceEpoch ~/ 1000; + final label = localDateLabel(from); + dates.add(label); + if (readable.contains('stepSample')) { + final dev = ids['stepSample']!; + final r = await src.rawQuery( + 'SELECT 1 FROM stepSample WHERE ${_idIn(dev)} ' + 'AND ts >= ? AND ts < ? LIMIT 1', + [...dev, from, to]); + if (r.isNotEmpty) hasSteps.add(label); + } + cursor = to; + } + } catch (e) { + if (!_isCorruptPageError(e)) rethrow; + return {}; + } + + final held = { + for (final d in dates) + if (await LocalDb.isMeasuredDay(d)) d, + }; + final skip = {}; + for (var i = 0; i < dates.length; i++) { + final d = dates[i]; + if (!held.contains(d) || hasSteps.contains(d)) continue; + final after = i + 1 < dates.length ? dates[i + 1] : null; + final neededAsContext = after != null && + !held.contains(after) && + NoopIngest.isDayAfter(d, after); + if (!neededAsContext) skip.add(d); + } + return skip; } /// Page one table's rows for the half-open window [from, to) into [onRow]. diff --git a/lib/import/noop_import.dart b/lib/import/noop_import.dart index c4e0567bb7..be9f9945c0 100644 --- a/lib/import/noop_import.dart +++ b/lib/import/noop_import.dart @@ -83,11 +83,20 @@ class NoopImportResult { /// imported; only the empty set here means the backup read cleanly. final Set corruptTables; + /// Dates this device already held. Their existing results were kept, not + /// replaced; a re-import of a backup the app already has is all kept dates. + final Set keptDates; + + /// Dates whose derivation failed, with the first error for each. + final Map failedDates; + NoopImportResult(this.days, this.rows, [this.lateRows = 0, this.steps = 0, this.strandedDates = const {}, - this.corruptTables = const {}]); + this.corruptTables = const {}, + this.keptDates = const {}, + this.failedDates = const {}]); } class NoopImporter { @@ -265,7 +274,8 @@ class NoopImporter { await ingest.finish(); return NoopImportResult(ingest.days, ingest.rows, ingest.lateRows, - ingest.steps, ingest.strandedDates); + ingest.steps, ingest.strandedDates, const {}, + Set.unmodifiable(ingest.keptDates), Map.unmodifiable(ingest.failedDates)); } /// Documented default column order (used only if the export omits its header). diff --git a/lib/import/noop_ingest.dart b/lib/import/noop_ingest.dart index 93fc42c72e..c1f6ce7345 100644 --- a/lib/import/noop_ingest.dart +++ b/lib/import/noop_ingest.dart @@ -112,6 +112,22 @@ class NoopIngest { int days = 0; int steps = 0; + /// Dates this device already held, so the import kept its own result rather + /// than replace it: either found by the source before reading ([markKept]) + /// or by the engine's commit-time guard. + final Set keptDates = {}; + + /// Dates whose derivation threw, with the first error each — reported rather + /// than folded into "nothing usable". + final Map failedDates = {}; + + /// Record [date] as already held without reading it. Only for a source that + /// knows the date's samples are not needed, as context or otherwise. + void markKept(String date) => keptDates.add(date); + + void _kept(String day) => keptDates.add(day); + void _failed(String day, Object e) => failedDates.putIfAbsent(day, () => '$e'); + /// Samples whose local date had ALREADY been derived and pruned by the time /// they arrived (a genuinely out-of-order source). They cannot be folded back /// in, so they are counted rather than silently dropped. @@ -152,7 +168,7 @@ class NoopIngest { // a time under a 400-iteration guard: past ~400 days it never reaches // the target date, `deriveImportedDays` returns 0, and the day is // silently missing from an import that reported success. - if (!_isDayAfter(prev, date)) { + if (!isDayAfter(prev, date)) { _secs.clear(); _rrTs.clear(); _rrMs.clear(); @@ -235,7 +251,7 @@ class NoopIngest { if (st != null) steps += await flushStepCoverage(st, last, resetGeneration: _resetGen); final sub = _buildSubstrate(_secs, _rrTs, _rrMs); days += await _engine.deriveImportedDays(sub, _profile, {last}, - resetGeneration: _resetGen); + onDayKept: _kept, onDayFailed: _failed, resetGeneration: _resetGen); onProgress?.call(days); } // A date that carried ONLY a step counter still banks its real count — @@ -260,7 +276,7 @@ class NoopIngest { // midnight its context. final sub = _buildSubstrate(_secs, _rrTs, _rrMs); days += await _engine.deriveImportedDays(sub, _profile, {date}, - resetGeneration: _resetGen); + onDayKept: _kept, onDayFailed: _failed, resetGeneration: _resetGen); onProgress?.call(days); // Keep [date]'s samples as the prior evening for the NEXT date; drop older. _secs.removeWhere((ts, _) => localDateLabel(ts) != date); @@ -279,7 +295,7 @@ class NoopIngest { /// True when [next] is the calendar day immediately after [prev]. Built /// through DateTime so a month, year or DST boundary is handled by the /// calendar rather than by string arithmetic. - static bool _isDayAfter(String prev, String next) { + static bool isDayAfter(String prev, String next) { final p = DateTime.tryParse(prev), n = DateTime.tryParse(next); if (p == null || n == null) return false; final after = DateTime(p.year, p.month, p.day + 1); diff --git a/lib/ui2/onboarding/welcome.dart b/lib/ui2/onboarding/welcome.dart index 243d5c8713..7d676091fd 100644 --- a/lib/ui2/onboarding/welcome.dart +++ b/lib/ui2/onboarding/welcome.dart @@ -517,6 +517,19 @@ Future runImport( late += r.lateRows; stranded += r.strandedDates.length; corruptTables.addAll(r.corruptTables); + // A NOOP day is derived by this app's own engine, so a re-import of a + // backup already imported keeps every date. That used to reach the + // report as 0 days and read "nothing in it this app could use"; it is + // the same "already measured here and left alone" the vendor path says. + skipped += r.keptDates.length; + // A day whose derivation threw (or timed out) was only logged, so a + // backup whose every day failed also read as "nothing usable". + if (r.failedDates.isNotEmpty) { + final first = (r.failedDates.keys.toList()..sort()).first; + final n = r.failedDates.length; + fileErrors.add('${nameOf(p)}: $n day${n == 1 ? '' : 's'} could not ' + 'be calculated (first: $first, ${r.failedDates[first]})'); + } } } } diff --git a/test/noop_import_duplicate_preflight_test.dart b/test/noop_import_duplicate_preflight_test.dart new file mode 100644 index 0000000000..8a59b89261 --- /dev/null +++ b/test/noop_import_duplicate_preflight_test.dart @@ -0,0 +1,266 @@ +// Re-importing a NOOP backup whose dates the app already holds. +// +// A NOOP import derives each day with this app's own engine, so the result is +// stored as measured data and a second import of the same backup keeps every +// day (`isMeasuredDay`). It used to find that out only AFTER reading and +// grouping every row of every day — minutes of work on a phone for a large +// backup — and then report "nothing in it this app could use", because the +// result carried only the count of days derived. +// +// What these pin: +// * dates the app already holds are not read at all, unless the next date +// needs them as its previous evening (a sleep that began before midnight); +// * the result says which dates were kept and which failed, so the screen can +// say "already imported" instead of "nothing usable"; +// * a new day after a run of duplicates derives exactly as it would in a +// full import. + +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'package:openstrap_edge/compute/derivation_engine.dart'; +import 'package:openstrap_edge/compute/profile.dart'; +import 'package:openstrap_edge/compute/substrate.dart' show Substrate; +import 'package:openstrap_edge/data/db.dart'; +import 'package:openstrap_edge/import/noop_backup_import.dart'; +import 'package:openstrap_edge/import/noop_import.dart'; + +/// Local wall-clock time as epoch seconds, so the fixtures land on the same +/// local dates whatever zone the suite runs in. +int _local(int y, int m, int d, [int h = 0, int min = 0]) => + DateTime(y, m, d, h, min).millisecondsSinceEpoch ~/ 1000; + +String _date(int y, int m, int d) => + '$y-${m.toString().padLeft(2, '0')}-${d.toString().padLeft(2, '0')}'; + +/// A NOOP-schema database holding 1 Hz [segments] of (start, seconds). No step +/// counter unless [steps]: a date with step rows is always read, by design. +Future _writeNoopDb( + Directory dir, + String name, + List<(int, int)> segments, { + bool steps = false, +}) async { + final path = p.join(dir.path, name); + if (File(path).existsSync()) File(path).deleteSync(); + final db = await databaseFactory.openDatabase(path); + await db.execute('CREATE TABLE hrSample (deviceId TEXT NOT NULL, ' + 'ts INTEGER NOT NULL, bpm INTEGER NOT NULL, PRIMARY KEY (deviceId, ts))'); + await db.execute('CREATE TABLE rrInterval (deviceId TEXT NOT NULL, ' + 'ts INTEGER NOT NULL, rrMs INTEGER NOT NULL, ' + 'PRIMARY KEY (deviceId, ts, rrMs))'); + await db.execute('CREATE TABLE gravitySample (deviceId TEXT NOT NULL, ' + 'ts INTEGER NOT NULL, x DOUBLE NOT NULL, y DOUBLE NOT NULL, ' + 'z DOUBLE NOT NULL, PRIMARY KEY (deviceId, ts))'); + await db.execute('CREATE TABLE skinTempSample (deviceId TEXT NOT NULL, ' + 'ts INTEGER NOT NULL, raw INTEGER NOT NULL, PRIMARY KEY (deviceId, ts))'); + await db.execute('CREATE TABLE stepSample (deviceId TEXT NOT NULL, ' + 'ts INTEGER NOT NULL, counter INTEGER NOT NULL, ' + 'PRIMARY KEY (deviceId, ts))'); + final batch = db.batch(); + var counter = 1000; + for (final (t0, secs) in segments) { + for (var i = 0; i < secs; i++) { + final ts = t0 + i; + batch.insert('hrSample', + {'deviceId': 'my-whoop', 'ts': ts, 'bpm': 52 + (i % 7)}); + batch.insert('gravitySample', + {'deviceId': 'my-whoop', 'ts': ts, 'x': 0.1, 'y': 0.2, 'z': 0.97}); + batch.insert('skinTempSample', + {'deviceId': 'my-whoop', 'ts': ts, 'raw': 3240}); + if (i.isEven) { + batch.insert('rrInterval', + {'deviceId': 'my-whoop', 'ts': ts, 'rrMs': 1100 + i % 40}); + } + if (steps) { + batch.insert('stepSample', + {'deviceId': 'my-whoop', 'ts': ts, 'counter': counter++}); + } + } + } + await batch.commit(noResult: true); + await db.close(); + return path; +} + +/// Rows the importer offers per second of fixture: hr + gravity + skin temp, +/// and one beat every other second. +int _rowsFor(int secs) => secs * 3 + (secs + 1) ~/ 2; + +/// A day this device already holds — the same shape as a band-derived row. +Future _seedMeasured(String day) => LocalDb.putDayResult( + dayId: day, + algoVersion: kAlgoVersion, + payloadJson: jsonEncode({'date': day, 'source': 'onehz', 'real': true}), + windowJson: '{}', + rhr: 50.0, + series: {'rhr': 50.0}, + ); + +Future?> _servedDay(String day) async { + final db = await LocalDb.instance; + final rows = await db.query('day_result', + where: 'day_id = ?', whereArgs: [day], orderBy: 'algo_version DESC'); + return rows.isEmpty ? null : rows.first; +} + +/// An engine whose every import day fails, to check the failure is reported. +class _FailingEngine extends DerivationEngine { + @override + Future deriveImportedDays( + Substrate sub, + Profile profile, + Set dates, { + void Function(String day)? onDayDone, + void Function(String day)? onDayKept, + void Function(String day, Object error)? onDayFailed, + int? resetGeneration, + }) async { + for (final d in dates) { + onDayFailed?.call(d, StateError('derive exploded')); + } + return 0; + } + + @override + Future finalizeImport(Profile profile) async {} +} + +void main() { + late Directory tmp; + var dbSeq = 0; + + /// A fresh, empty app database for each test. + Future freshAppDb() async { + await LocalDb.close(); + LocalDb.dbName = 'openstrap_noop_preflight_${dbSeq++}.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + } + + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + tmp = await Directory.systemTemp.createTemp('noop_preflight'); + }); + + setUp(freshAppDb); + + tearDownAll(() async { + await LocalDb.close(); + final dir = await databaseFactory.getDatabasesPath(); + for (var i = 0; i < dbSeq; i++) { + await databaseFactory + .deleteDatabase(p.join(dir, 'openstrap_noop_preflight_$i.db')); + } + if (tmp.existsSync()) tmp.deleteSync(recursive: true); + }); + + test('a backup the app already holds is not read, and says so', () async { + final days = [for (var d = 10; d <= 14; d++) (2026, 8, d)]; + final path = await _writeNoopDb(tmp, 'dup.sqlite', [ + for (final (y, m, d) in days) (_local(y, m, d, 12), 600), + ]); + for (final (y, m, d) in days) { + await _seedMeasured(_date(y, m, d)); + } + + final res = await NoopImporter.importFile( + path, const Profile(), DerivationEngine()); + + expect(res.days, 0); + expect(res.rows, 0, + reason: 'every date is already held, so no sample needs reading'); + expect(res.keptDates, {for (final (y, m, d) in days) _date(y, m, d)}); + expect(res.failedDates, isEmpty); + for (final (y, m, d) in days) { + final row = await _servedDay(_date(y, m, d)); + expect(jsonDecode(row!['payload_json'] as String)['real'], true, + reason: 'a kept day is never replaced'); + } + }, timeout: const Timeout(Duration(minutes: 5))); + + test('a new night after a run of duplicates derives exactly as in a full ' + 'import, with its previous evening', () async { + // Five held days at noon, then the evening of the fifth running across + // midnight into a NEW sixth day. + final segments = [ + for (var d = 10; d <= 14; d++) (_local(2026, 8, d, 12), 600), + (_local(2026, 8, 14, 21), 3 * 3600), // 21:00 to midnight + (_local(2026, 8, 15, 0), 6 * 3600 + 1800), // midnight to 06:30 + ]; + final path = await _writeNoopDb(tmp, 'mixed.sqlite', segments); + final newDay = _date(2026, 8, 15); + + Future holdFiveDays() async { + for (var d = 10; d <= 14; d++) { + await _seedMeasured(_date(2026, 8, d)); + } + } + + // Reference: the same app state, every date read (no preflight). + await holdFiveDays(); + NoopBackupImporter.debugSkipHeldDatePreflight = true; + final NoopImportResult full; + try { + full = await NoopImporter.importFile( + path, const Profile(), DerivationEngine()); + } finally { + NoopBackupImporter.debugSkipHeldDatePreflight = false; + } + expect(full.days, 1); + expect(full.rows, greaterThan(_rowsFor(3 * 3600 + 6 * 3600 + 1800 + 600)), + reason: 'the reference read the held days too'); + final reference = await _servedDay(newDay); + expect(reference, isNotNull); + + // With the preflight. + await freshAppDb(); + await holdFiveDays(); + final res = await NoopImporter.importFile( + path, const Profile(), DerivationEngine()); + + expect(res.days, 1); + expect(res.keptDates, {for (var d = 10; d <= 14; d++) _date(2026, 8, d)}); + // Only the 14th (the new night's previous evening) and the 15th are read. + expect(res.rows, _rowsFor(600) + _rowsFor(3 * 3600) + _rowsFor(6 * 3600 + 1800)); + + final got = await _servedDay(newDay); + expect(got, isNotNull); + expect(got!['payload_json'], reference!['payload_json'], + reason: 'skipping held days must not change what a new day derives'); + final held = await _servedDay(_date(2026, 8, 14)); + expect(jsonDecode(held!['payload_json'] as String)['real'], true); + }, timeout: const Timeout(Duration(minutes: 10))); + + test('a held date with step-counter rows is still read', () async { + final path = await _writeNoopDb( + tmp, 'steps.sqlite', [(_local(2026, 8, 20, 12), 600)], + steps: true); + await _seedMeasured(_date(2026, 8, 20)); + + final res = await NoopImporter.importFile( + path, const Profile(), DerivationEngine()); + + expect(res.rows, greaterThan(0), + reason: 'step banking is unchanged: the date is read'); + expect(res.steps, 599); + expect(res.keptDates, {_date(2026, 8, 20)}); + }, timeout: const Timeout(Duration(minutes: 5))); + + test('a day that fails to derive is reported as failed, not as nothing', + () async { + final path = await _writeNoopDb( + tmp, 'fail.sqlite', [(_local(2026, 8, 25, 12), 600)]); + + final res = + await NoopImporter.importFile(path, const Profile(), _FailingEngine()); + + expect(res.days, 0); + expect(res.failedDates.keys, [_date(2026, 8, 25)]); + expect(res.failedDates.values.single, contains('derive exploded')); + }, timeout: const Timeout(Duration(minutes: 5))); +} diff --git a/test/noop_ingest_plausibility_test.dart b/test/noop_ingest_plausibility_test.dart index 00644f32e1..c5769e60fc 100644 --- a/test/noop_ingest_plausibility_test.dart +++ b/test/noop_ingest_plausibility_test.dart @@ -17,6 +17,8 @@ class _CapturingEngine extends DerivationEngine { Profile profile, Set dates, { void Function(String day)? onDayDone, + void Function(String day)? onDayKept, + void Function(String day, Object error)? onDayFailed, int? resetGeneration, }) async { subs.add(sub); diff --git a/test/noop_reimport_report_test.dart b/test/noop_reimport_report_test.dart new file mode 100644 index 0000000000..e74d53d2ea --- /dev/null +++ b/test/noop_reimport_report_test.dart @@ -0,0 +1,70 @@ +// The import report for a NOOP backup whose dates the app already holds, or +// whose days failed to derive. Both used to land on "Nothing was imported — +// the file was read but there was nothing in it this app could use", because +// the only thing that reached the report was the count of days derived. + +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/import/noop_import.dart'; +import 'package:openstrap_edge/state/app_state.dart'; +import 'package:openstrap_edge/ui2/onboarding/welcome.dart'; + +class _Spy extends AppState { + _Spy(this.result) : super.forTesting(); + final NoopImportResult result; + + @override + Future importNoopCsv(String path, + {void Function(int days)? onProgress}) async { + lastNoopImport = result; + return result.days; + } +} + +const _noopCsv = 'unix_s,iso_utc,stream,hr_bpm,rr_ms,grav_x,grav_y,grav_z\n' + '1754000000,2026-08-01T00:00:00Z,hr,61,,,,\n'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory tmp; + late String file; + setUp(() async { + tmp = await Directory.systemTemp.createTemp('noop_reimport_report_'); + file = (File('${tmp.path}/backup.csv') + ..writeAsBytesSync(utf8.encode(_noopCsv))) + .path; + }); + tearDown(() async { + if (tmp.existsSync()) await tmp.delete(recursive: true); + }); + + test('a backup the app already holds reports its kept days, not nothing', + () async { + final kept = {for (var d = 1; d <= 67; d++) 'day-$d'}; + final out = await runImport( + _Spy(NoopImportResult(0, 0, 0, 0, const {}, const {}, kept)), [file]); + + expect(out.skippedDays, 67); + expect(out.nothingLanded, isFalse, + reason: '"already here" is an answer, not "nothing usable"'); + expect(out.readError, isNull); + }); + + test('days that failed to derive are named, not folded into nothing', + () async { + final out = await runImport( + _Spy(NoopImportResult(1, 10, 0, 0, const {}, const {}, const {}, { + '2026-08-25': 'TimeoutException: day-bundle timed out after 0:01:30', + '2026-08-26': 'StateError: boom', + })), + [file]); + + expect(out.days, 1); + expect(out.readError, contains('2 days could not be calculated')); + expect(out.readError, contains('2026-08-25')); + expect(out.readError, contains('timed out')); + }); +} diff --git a/test/noop_step_coverage_reset_test.dart b/test/noop_step_coverage_reset_test.dart index 37829c1a03..4c5ef1ba3c 100644 --- a/test/noop_step_coverage_reset_test.dart +++ b/test/noop_step_coverage_reset_test.dart @@ -16,7 +16,10 @@ import 'support/app_state_derive_harness.dart'; class _Engine extends DerivationEngine { @override Future deriveImportedDays(Substrate sub, Profile profile, Set dates, - {void Function(String day)? onDayDone, int? resetGeneration}) async => 0; + {void Function(String day)? onDayDone, + void Function(String day)? onDayKept, + void Function(String day, Object error)? onDayFailed, + int? resetGeneration}) async => 0; @override Future finalizeImport(Profile profile) async {} } From 8525638c5eb7192b500f467215395bfdbdf0b685 Mon Sep 17 00:00:00 2001 From: magnetarQ <340235260+magnetarQ@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:27:17 +0300 Subject: [PATCH 2/2] noop import: read a held import snapshot when the backup reaches past its edge --- lib/import/noop_backup_import.dart | 53 +++++++++++++++++-- .../noop_import_duplicate_preflight_test.dart | 41 ++++++++++++++ 2 files changed, 90 insertions(+), 4 deletions(-) diff --git a/lib/import/noop_backup_import.dart b/lib/import/noop_backup_import.dart index 11cab89183..96e0a2a0bb 100644 --- a/lib/import/noop_backup_import.dart +++ b/lib/import/noop_backup_import.dart @@ -44,6 +44,7 @@ import '../compute/derivation_engine.dart'; import '../compute/profile.dart'; import '../compute/substrate.dart' show localDateLabel; import '../data/db.dart'; +import '../data/series_codec.dart'; import 'import_container.dart'; import 'noop_import.dart'; import 'noop_ingest.dart'; @@ -445,6 +446,31 @@ class NoopBackupImporter { /// Empty — read everything, as before — when the dates cannot be found /// cheaply: a table without a usable deviceId would make every probe below a /// whole-table scan, and a torn page is left for [_read] to report. + /// Whether any readable table has a row of these devices in [from, to). + /// A torn page reads as "yes", so the date is read rather than skipped. + static Future _hasRowsIn( + Database src, + Set readable, + Map> ids, + int from, + int to, + ) async { + for (final t in readable) { + final dev = ids[t]!; + try { + final r = await src.rawQuery( + 'SELECT 1 FROM $t WHERE ${_idIn(dev)} AND ts >= ? AND ts < ? ' + 'LIMIT 1', + [...dev, from, to]); + if (r.isNotEmpty) return true; + } catch (e) { + if (!_isCorruptPageError(e)) rethrow; + return true; + } + } + return false; + } + static Future> _heldDatesToSkip( Database src, Set readable, @@ -455,6 +481,8 @@ class NoopBackupImporter { if (readable.isEmpty || !readable.every(ids.containsKey)) return {}; final dates = []; final hasSteps = {}; + // Each date's [from, to) local-day bounds, for the snapshot check below. + final bounds = {}; try { var cursor = _localMidnight(minTs).millisecondsSinceEpoch ~/ 1000; while (true) { @@ -478,6 +506,7 @@ class NoopBackupImporter { final to = next.millisecondsSinceEpoch ~/ 1000; final label = localDateLabel(from); dates.add(label); + bounds[label] = (from, to); if (readable.contains('stepSample')) { final dev = ids['stepSample']!; final r = await src.rawQuery( @@ -493,10 +522,26 @@ class NoopBackupImporter { return {}; } - final held = { - for (final d in dates) - if (await LocalDb.isMeasuredDay(d)) d, - }; + final held = {}; + for (final d in dates) { + final row = await LocalDb.dayResult(d); + if (!LocalDb.isMeasuredDayRow(row)) continue; + // An earlier import's snapshot is replaced when this import reaches past + // the edge it was derived against (DerivationEngine.importReachesFurther): + // a backup exported mid-night left the rest of that night out. That edge + // is the snapshot day's last sample, so the date is only held when this + // backup has nothing later on it. Unknown edge: read it, as before. + final p = SeriesCodec.decodePayloadJson(row!['payload_json']); + if (p != null && p['import_snapshot'] == true) { + final edge = (p['data_edge_sec'] as num?)?.toInt(); + final (_, to) = bounds[d]!; + if (edge == null || + await _hasRowsIn(src, readable, ids, edge + 1, to)) { + continue; + } + } + held.add(d); + } final skip = {}; for (var i = 0; i < dates.length; i++) { final d = dates[i]; diff --git a/test/noop_import_duplicate_preflight_test.dart b/test/noop_import_duplicate_preflight_test.dart index 8a59b89261..fb2e2d6e16 100644 --- a/test/noop_import_duplicate_preflight_test.dart +++ b/test/noop_import_duplicate_preflight_test.dart @@ -251,6 +251,47 @@ void main() { expect(res.keptDates, {_date(2026, 8, 20)}); }, timeout: const Timeout(Duration(minutes: 5))); + test('a longer backup still finishes a day an earlier import cut short', + () async { + // Backup A was exported in the middle of the night: the 22nd ends at + // 03:00, so its import snapshot is derived from those hours only. Backup B + // is a later export of the same night that runs on to 08:00. + final pathA = await _writeNoopDb( + tmp, 'cut.sqlite', [(_local(2026, 8, 22, 0), 3 * 3600)]); + final pathB = await _writeNoopDb( + tmp, 'longer.sqlite', [(_local(2026, 8, 22, 0), 8 * 3600)]); + final day = _date(2026, 8, 22); + + // Reference: import A, then B with every date read (no preflight). + await NoopImporter.importFile(pathA, const Profile(), DerivationEngine()); + final cut = await _servedDay(day); + expect(jsonDecode(cut!['payload_json'] as String)['import_snapshot'], true); + NoopBackupImporter.debugSkipHeldDatePreflight = true; + try { + await NoopImporter.importFile(pathB, const Profile(), DerivationEngine()); + } finally { + NoopBackupImporter.debugSkipHeldDatePreflight = false; + } + final reference = await _servedDay(day); + expect(reference!['payload_json'], isNot(cut['payload_json']), + reason: 'a full read extends the morning-only snapshot'); + + // With the preflight: B must still be read for that day and extend it. + await freshAppDb(); + await NoopImporter.importFile(pathA, const Profile(), DerivationEngine()); + final res = await NoopImporter.importFile( + pathB, const Profile(), DerivationEngine()); + expect(res.days, 1); + expect(res.keptDates, isEmpty); + expect((await _servedDay(day))!['payload_json'], reference['payload_json']); + + // The same longer backup again reaches no further: not read, kept. + final again = await NoopImporter.importFile( + pathB, const Profile(), DerivationEngine()); + expect(again.rows, 0); + expect(again.keptDates, {day}); + }, timeout: const Timeout(Duration(minutes: 10))); + test('a day that fails to derive is reported as failed, not as nothing', () async { final path = await _writeNoopDb(