Repository navigation
noop import: skip dates already held before reading them, and say so #1026
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6905,6 +6905,11 @@ class DerivationEngine { | |
| Profile profile, | ||
| Set<String> 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, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Report second-half timeouts through the new outcome path. If the second half times out, The import report therefore counts this date as calculated and shows no failure warning. Propagate an outcome that distinguishes a completed day, a kept day, and a partial failure. Keep the persisted headline result when reporting the partial failure.
|
||
| 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; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -42,6 +42,9 @@ 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 '../data/series_codec.dart'; | ||
| import 'import_container.dart'; | ||
| import 'noop_import.dart'; | ||
| import 'noop_ingest.dart'; | ||
|
|
@@ -80,6 +83,11 @@ const Map<String, List<String>> _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 +315,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 +330,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 +416,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 +429,130 @@ 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. | ||
| /// 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<bool> _hasRowsIn( | ||
| Database src, | ||
| Set<String> readable, | ||
| Map<String, List<Object>> 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<Set<String>> _heldDatesToSkip( | ||
| Database src, | ||
| Set<String> readable, | ||
| Map<String, List<Object>> ids, | ||
| int minTs, | ||
| ) async { | ||
| if (debugSkipHeldDatePreflight) return {}; | ||
| if (readable.isEmpty || !readable.every(ids.containsKey)) return {}; | ||
| final dates = <String>[]; | ||
| final hasSteps = <String>{}; | ||
| // Each date's [from, to) local-day bounds, for the snapshot check below. | ||
| final bounds = <String, (int, int)>{}; | ||
| 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', | ||
|
Comment on lines
+491
to
+494
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Duplicate imports take excessive time When a backup has many device IDs and dates, or a readable source table lacks an index supporting the device-and-timestamp query, Replace the repeated per-device, per-date probes with a batched lookup that avoids repeated table scans. Prompt for AI agentsIn `lib/import/noop_backup_import.dart` at lines 463-466:
**Duplicate imports take excessive time**
When a backup has many device IDs and dates, or a readable source table lacks an index supporting the device-and-timestamp query, `_heldDatesToSkip` issues sequential probes for each device ID, table, and date; without a supporting index, each ordered probe scans the table, delaying the import before its normal walk can proceed.
Replace the repeated per-device, per-date probes with a batched lookup that avoids repeated table scans. |
||
| // 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); | ||
| bounds[label] = (from, to); | ||
| 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 = <String>{}; | ||
| 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 = <String>{}; | ||
| 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]. | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Medium · Existing overrides stop compiling
When a consumer subclasses
DerivationEngineand overridesderiveImportedDaysusing the former signature, a downstream subclass overridingderiveImportedDayswith the previous named-parameter list no longer accepts every call allowed by the base method, so Dart rejects the override and the consumer fails to compile.Avoid changing the overridable method’s signature, or provide a compatibility design that lets existing overrides remain valid.
Prompt for AI agents