diff --git a/lib/data/csv_export.dart b/lib/data/csv_export.dart index e061cafe6..f62981815 100644 --- a/lib/data/csv_export.dart +++ b/lib/data/csv_export.dart @@ -283,6 +283,42 @@ const kCsvExportSets = [ ORDER BY d.date ASC ''', ), + CsvExportSet( + name: 'bp_research', + title: 'BP research captures (EXPERIMENTAL)', + // Cuff readings plus their band window. Absent stats stay empty. + columns: [ + 'measured_at_ms', + 'device', + 'posture', + 'conditions', + 'systolic_mmhg', + 'diastolic_mmhg', + 'captured_at_ms', + 'window_start_ms', + 'window_end_ms', + 'onehz_rows', + 'rr_beats', + 'hr_mean', + 'rr_ms_mean', + 'rr_ms_min', + 'rr_ms_max', + 'rmssd_ms', + 'meta_json', + ], + sql: ''' + SELECT r.measured_at_ms, COALESCE(r.device, '') AS device, + COALESCE(r.posture, '') AS posture, + COALESCE(r.conditions, '') AS conditions, + r.systolic_mmhg, r.diastolic_mmhg, r.captured_at_ms, + w.window_start_ms, w.window_end_ms, w.onehz_rows, w.rr_beats, + w.hr_mean, w.rr_ms_mean, w.rr_ms_min, w.rr_ms_max, w.rmssd_ms, + COALESCE(w.meta_json, '') AS meta_json + FROM bp_research_reference r + LEFT JOIN bp_research_window w ON w.reference_id = r.id + ORDER BY r.measured_at_ms ASC + ''', + ), ]; /// What CSV deliberately does NOT carry, and why. Shown to the user on the diff --git a/lib/data/db.dart b/lib/data/db.dart index f4ee1ecfe..edd3cf081 100644 --- a/lib/data/db.dart +++ b/lib/data/db.dart @@ -33,6 +33,7 @@ import '../import/import_container.dart'; import 'coverage_resolver.dart' show CoverageInterval; import 'day_label.dart'; import 'journal_fields.dart'; +import '../health/bp_research_capture.dart'; import 'live_coverage_policy.dart'; import 'med_store.dart'; import 'models.dart'; @@ -166,6 +167,8 @@ class LocalDb { /// flash as we ACK, so in practice this is the only copy of those days too. static const _salvageTables = [ // Hand-entered. The only copy that exists anywhere. + 'bp_research_reference', + 'bp_research_window', 'journal', 'journal_metric', 'journal_field_def', @@ -349,7 +352,7 @@ class LocalDb { /// pass it: sqflite throws `ArgumentError('onCreate must be null if no /// version is specified')` BEFORE opening anything when `onCreate` is given /// without `version` (sqflite_common database_mixin.dart). - static const int schemaVersion = 54; + static const int schemaVersion = 55; /// SQLite caps host parameters per statement (`SQLITE_MAX_VARIABLE_NUMBER` — /// only 999 on the builds shipped with older Android/iOS). Any `IN (?, ?, …)` @@ -461,6 +464,7 @@ class LocalDb { await _createNotifFired(db); await _createNotifSlots(db); await _createAlarmSchedule(db); + await _createBpResearch(db); await _ensureCoachViews(db); }, onUpgrade: (db, oldV, newV) async { @@ -1073,6 +1077,11 @@ class LocalDb { // next free rung rather than collide with any of them. await _createEcgTables(db); } + if (oldV < 55) { + // BP research capture tables. Create-only, nothing derived reads + // them, so no kAlgoVersion bump. + await _createBpResearch(db); + } }, onOpen: (db) async { await _repairOpenSchema(db); @@ -1163,6 +1172,7 @@ class LocalDb { 'INTEGER NOT NULL DEFAULT 0', ); await _createEcgTables(db); + await _createBpResearch(db); // Views LAST — they depend on metric_series / day_result / baselines / sessions // / notifications all existing. DROP+CREATE so a shape change takes effect. await _ensureCoachViews(db); @@ -1582,6 +1592,203 @@ class LocalDb { ); } + + /// BP research capture store (dev mode only). Read only by the dev screen + /// and the CSV export; bp_research_isolation_test.dart keeps it that way. + /// Foreign keys are off in this database, so the window's cascade is inert + /// and every delete takes the window row explicitly. + static Future _createBpResearch(Database db) async { + await db.execute(''' + CREATE TABLE IF NOT EXISTS bp_research_reference ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + measured_at_ms INTEGER NOT NULL, + device TEXT, + posture TEXT, + conditions TEXT, + systolic_mmhg REAL NOT NULL, + diastolic_mmhg REAL NOT NULL, + captured_at_ms INTEGER NOT NULL, + UNIQUE (measured_at_ms, device) + ) + '''); + await db.execute(''' + CREATE TABLE IF NOT EXISTS bp_research_window ( + reference_id INTEGER NOT NULL PRIMARY KEY + REFERENCES bp_research_reference(id) ON DELETE CASCADE, + window_start_ms INTEGER NOT NULL, + window_end_ms INTEGER NOT NULL, + onehz_rows INTEGER, + rr_beats INTEGER, + hr_mean REAL, + rr_ms_mean REAL, + rr_ms_min REAL, + rr_ms_max REAL, + rmssd_ms REAL, + meta_json TEXT + ) + '''); + await db.execute( + 'CREATE INDEX IF NOT EXISTS idx_bp_research_reference_at ' + 'ON bp_research_reference(measured_at_ms)', + ); + } + + /// Insert one cuff reading plus its window, replacing any capture with the + /// same `(measured_at_ms, device)`. + static Future putBpResearchCapture(BpResearchCapture c) async { + final db = await instance; + await db.transaction((txn) async { + // device is stored as '' rather than NULL so the UNIQUE key holds. + await txn.rawDelete( + 'DELETE FROM bp_research_window WHERE reference_id IN ' + '(SELECT id FROM bp_research_reference ' + 'WHERE measured_at_ms = ? AND device = ?)', + [c.measuredAtMs, c.device ?? ''], + ); + await txn.rawDelete( + 'DELETE FROM bp_research_reference ' + 'WHERE measured_at_ms = ? AND device = ?', + [c.measuredAtMs, c.device ?? ''], + ); + final id = await txn.rawInsert( + 'INSERT INTO bp_research_reference ' + '(measured_at_ms, device, posture, conditions, systolic_mmhg, ' + 'diastolic_mmhg, captured_at_ms) VALUES (?, ?, ?, ?, ?, ?, ?)', + [ + c.measuredAtMs, + c.device ?? '', + c.posture, + c.conditions, + c.systolicMmHg, + c.diastolicMmHg, + c.capturedAtMs, + ], + ); + // No band data = no window row. + final w = c.window; + if (w == null) return; + await txn.rawInsert( + 'INSERT OR REPLACE INTO bp_research_window ' + '(reference_id, window_start_ms, window_end_ms, onehz_rows, ' + 'rr_beats, hr_mean, rr_ms_mean, rr_ms_min, rr_ms_max, rmssd_ms, ' + 'meta_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', + [ + id, + w.windowStartMs, + w.windowEndMs, + w.onehzRows, + w.rrBeats, + w.hrMean, + w.rrMsMean, + w.rrMsMin, + w.rrMsMax, + w.rmssdMs, + w.metaJson, + ], + ); + }); + } + + /// All captures, newest first, for the dev screen and the CSV export. + static Future>> bpResearchCaptures() async { + final db = await instance; + return db.rawQuery(''' + SELECT r.id, r.measured_at_ms, r.device, r.posture, r.conditions, + r.systolic_mmhg, r.diastolic_mmhg, r.captured_at_ms, + w.window_start_ms, w.window_end_ms, w.onehz_rows, w.rr_beats, + w.hr_mean, w.rr_ms_mean, w.rr_ms_min, w.rr_ms_max, w.rmssd_ms, + w.meta_json + FROM bp_research_reference r + LEFT JOIN bp_research_window w ON w.reference_id = r.id + ORDER BY r.measured_at_ms DESC + '''); + } + + /// Beats of one record share rr_ts_ms; beat_index orders them. Ranged on + /// ts_ms (= rr_ts_ms for every row) so the read rides the + /// (device_id, ts_ms, beat_index) PK. rr_ts_ms has no index, so ranging on + /// it scanned and sorted the whole store once per pending capture. + @visibleForTesting + static const bpResearchRrWindowSql = 'SELECT rr_ts_ms, rr_ms FROM decoded_rr ' + 'WHERE device_id = ? AND ts_ms >= ? AND ts_ms <= ? ' + 'ORDER BY ts_ms ASC, beat_index ASC'; + + /// Fill the window of every capture that has none yet, once the primary + /// band's synced 1 Hz data reaches the window end. At capture time the + /// window is still in the future and the band hasn't offloaded it, so it + /// can only be read later. Returns that data edge in epoch ms (null when + /// nothing is decoded): a windowless capture before it is still pending, + /// one at or after it had no band data. + static Future fillBpResearchWindows() async { + final db = await instance; + final edgeSec = Sqflite.firstIntValue(await db.rawQuery( + 'SELECT MAX(rec_ts) FROM decoded_onehz WHERE device_id = ?', + [kPrimaryDeviceId], + )); + if (edgeSec == null) return null; + final edgeMs = edgeSec * 1000; + final pending = await db.rawQuery( + 'SELECT r.id, r.measured_at_ms FROM bp_research_reference r ' + 'LEFT JOIN bp_research_window w ON w.reference_id = r.id ' + 'WHERE w.reference_id IS NULL AND r.measured_at_ms <= ?', + [edgeMs - kBpResearchWindowPostMs], + ); + for (final r in pending) { + final at = r['measured_at_ms'] as int; + final start = at - kBpResearchWindowPreMs; + final end = at + kBpResearchWindowPostMs; + final w = researchWindowFrom( + measuredAtMs: at, + onehzRows: await db.rawQuery( + 'SELECT rec_ts, hr FROM decoded_onehz ' + 'WHERE device_id = ? AND rec_ts >= ? AND rec_ts <= ? ' + 'ORDER BY rec_ts ASC', + [kPrimaryDeviceId, start ~/ 1000, end ~/ 1000], + ), + rrRows: await db.rawQuery( + bpResearchRrWindowSql, + [kPrimaryDeviceId, start, end], + ), + ); + if (w == null) continue; + await db.insert( + 'bp_research_window', + { + 'reference_id': r['id'], + 'window_start_ms': w.windowStartMs, + 'window_end_ms': w.windowEndMs, + 'onehz_rows': w.onehzRows, + 'rr_beats': w.rrBeats, + 'hr_mean': w.hrMean, + 'rr_ms_mean': w.rrMsMean, + 'rr_ms_min': w.rrMsMin, + 'rr_ms_max': w.rrMsMax, + 'rmssd_ms': w.rmssdMs, + 'meta_json': w.metaJson, + }, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + return edgeMs; + } + + /// Delete one capture and its window. + static Future deleteBpResearchCapture(int id) async { + final db = await instance; + await db.transaction((txn) async { + await txn.delete( + 'bp_research_window', + where: 'reference_id = ?', + whereArgs: [id], + ); + await txn.delete( + 'bp_research_reference', + where: 'id = ?', + whereArgs: [id], + ); + }); + } + /// Atomically claim [key] for a one-time OS notification fire. /// /// Returns true iff THIS caller won the claim (the row did not exist and we @@ -8590,6 +8797,8 @@ class LocalDb { // banked. They were also simply MISSING here until now — nutrition, // medication, strength sets, symptoms and routes did not survive a // backup/restore round trip at all, the same omission `wipeAll` documents. + 'bp_research_reference', + 'bp_research_window', 'journal', 'journal_metric', 'journal_field_def', @@ -8746,6 +8955,85 @@ class LocalDb { if (e.isNoSuchTableError()) continue; rethrow; } + // BP research captures merge on (measured_at_ms, device), never by + // source id, and keep the destination id so a local window stays + // attached. Both tables go in one transaction on the reference pass. + if (t == 'bp_research_window') continue; + if (t == 'bp_research_reference') { + try { + final refs = + await src.rawQuery('SELECT * FROM bp_research_reference'); + var wins = const >[]; + try { + wins = await src.rawQuery('SELECT * FROM bp_research_window'); + } on DatabaseException catch (e) { + // A missing or unreadable window table only costs the + // windows; the hand-entered references still come across. + if (!e.isNoSuchTableError() && !tolerant) rethrow; + } + final winBySrcId = { + for (final w in wins) + if (w['reference_id'] is num) + (w['reference_id'] as num).toInt(): w, + }; + final winCols = await destCols('bp_research_window'); + var winCount = 0; + await db.transaction((txn) async { + for (final r in refs) { + final device = (r['device'] as String?) ?? ''; + final values = [ + r['posture'], + r['conditions'], + r['systolic_mmhg'], + r['diastolic_mmhg'], + r['captured_at_ms'], + ]; + final existing = await txn.rawQuery( + 'SELECT id FROM bp_research_reference ' + 'WHERE measured_at_ms = ? AND device = ?', + [r['measured_at_ms'], device], + ); + final int destId; + if (existing.isNotEmpty) { + destId = (existing.first['id'] as num).toInt(); + await txn.rawUpdate( + 'UPDATE bp_research_reference SET posture = ?, ' + 'conditions = ?, systolic_mmhg = ?, diastolic_mmhg = ?, ' + 'captured_at_ms = ? WHERE id = ?', + [...values, destId], + ); + } else { + destId = await txn.rawInsert( + 'INSERT INTO bp_research_reference ' + '(posture, conditions, systolic_mmhg, diastolic_mmhg, ' + 'captured_at_ms, measured_at_ms, device) ' + 'VALUES (?, ?, ?, ?, ?, ?, ?)', + [...values, r['measured_at_ms'], device], + ); + } + final srcId = r['id']; + final w = srcId is num ? winBySrcId[srcId.toInt()] : null; + if (w == null) continue; + await txn.insert( + 'bp_research_window', + { + for (final e in w.entries) + if (winCols.contains(e.key)) e.key: e.value, + 'reference_id': destId, + }, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + winCount++; + } + }); + counts[t] = refs.length; + counts['bp_research_window'] = winCount; + } catch (_) { + if (!tolerant) rethrow; + counts[t] = 0; + } + continue; + } if (t == 'day_result') importedDays = {}; if (firstPage.isEmpty) { counts[t] = 0; @@ -10883,6 +11171,12 @@ class LocalDb { /// TIME (epoch seconds) is strictly before [cutoffSec]. static Future pruneDecodedBeforeRecTs(int cutoffSec) async { final db = await instance; + // A pending BP research window can only be read from the decoded rows this + // is about to delete, so fill it first. Best effort: a dev-only capture + // must not stall retention. + try { + await fillBpResearchWindows(); + } catch (_) {} // `deleted` used to just stay 0 forever - none of the txn.delete() calls' // return values (rows actually deleted) were ever added to it, so the // caller's `if (deleted > 0) log(...)` never fired even on a real prune. diff --git a/lib/health/bp_research_capture.dart b/lib/health/bp_research_capture.dart new file mode 100644 index 000000000..424a0dd3a --- /dev/null +++ b/lib/health/bp_research_capture.dart @@ -0,0 +1,151 @@ +// BP research capture (developer mode only): a cuff reading the user typed in, +// paired with the band's decoded data from the minutes around it, for +// analysis outside the app via the CSV export. Nothing derived reads these +// tables (bp_research_isolation_test.dart). No band data = NULL window. + +import 'dart:math' as math; + +/// Window half-widths around the cuff instant. +const int kBpResearchWindowPreMs = 2 * 60 * 1000; +const int kBpResearchWindowPostMs = 2 * 60 * 1000; + +/// The band window around one reference instant. A stat that can't be +/// computed (no valid HR, no beats) is null, not zero. +class BpResearchWindow { + const BpResearchWindow({ + required this.windowStartMs, + required this.windowEndMs, + this.onehzRows, + this.rrBeats, + this.hrMean, + this.rrMsMean, + this.rrMsMin, + this.rrMsMax, + this.rmssdMs, + this.metaJson, + }); + + final int windowStartMs; + final int windowEndMs; + final int? onehzRows; + final int? rrBeats; + final double? hrMean; + final double? rrMsMean; + final double? rrMsMin; + final double? rrMsMax; + final double? rmssdMs; + + /// Optional provenance JSON, stored verbatim. + final String? metaJson; +} + +/// One cuff reference reading plus its window, ready to store. +class BpResearchCapture { + const BpResearchCapture({ + required this.measuredAtMs, + required this.systolicMmHg, + required this.diastolicMmHg, + required this.capturedAtMs, + required this.device, + this.posture, + this.conditions, + this.window, + }); + + final int measuredAtMs; + final double systolicMmHg; + final double diastolicMmHg; + final int capturedAtMs; + + /// The cuff's own name ('OMRON', 'Withings BPM', …). NULL when the user + /// typed a bare pair of numbers with no device named. + final String? device; + final String? posture; + final String? conditions; + + /// Null when the band had nothing decoded in the window. + final BpResearchWindow? window; +} + +/// Same bounds as `health_measurement_import.dart`. Out-of-range input is +/// rejected, never clamped. +const (double, double) kResearchSystolicBounds = (50, 300); +const (double, double) kResearchDiastolicBounds = (20, 200); + +/// Window stats around [measuredAtMs] from `decoded_onehz` / `decoded_rr` +/// rows (rr rows ordered by `rr_ts_ms, beat_index`). Null when neither table +/// has a row in the window. +BpResearchWindow? researchWindowFrom({ + required int measuredAtMs, + required List> onehzRows, + required List> rrRows, + int? preMs, + int? postMs, + String? deviceId, + String? metaJson, +}) { + final pre = preMs ?? kBpResearchWindowPreMs; + final post = postMs ?? kBpResearchWindowPostMs; + final start = measuredAtMs - pre; + final end = measuredAtMs + post; + + // decoded_onehz.rec_ts is epoch SECONDS; rr is rr_ts_ms (epoch ms). + final onehz = onehzRows + .where((r) { + final ts = r['rec_ts']; + return ts is int && ts * 1000 >= start && ts * 1000 <= end; + }) + .toList(growable: false); + final rr = rrRows + .where((r) { + final ts = r['rr_ts_ms']; + return ts is int && ts >= start && ts <= end; + }) + .toList(growable: false); + + if (onehz.isEmpty && rr.isEmpty) return null; + + // hr 0 / null is "no reading", not a heart rate. + final hrs = onehz + .map((r) => r['hr']) + .whereType() + .where((h) => h > 0) + .toList(growable: false); + final hrMean = hrs.isEmpty + ? null + : hrs.reduce((a, b) => a + b) / hrs.length; + + final rrs = rr + .map((r) => r['rr_ms']) + .whereType() + .map((v) => v.toDouble()) + .toList(growable: false); + double? rrMean, rrMin, rrMax, rmssd; + if (rrs.isNotEmpty) { + rrMean = rrs.reduce((a, b) => a + b) / rrs.length; + rrMin = rrs.reduce((a, b) => a < b ? a : b); + rrMax = rrs.reduce((a, b) => a > b ? a : b); + // Raw RMSSD over successive beats, no ectopic or gap rejection. + if (rrs.length >= 2) { + var sumSq = 0.0; + for (var i = 1; i < rrs.length; i++) { + final d = rrs[i] - rrs[i - 1]; + sumSq += d * d; + } + rmssd = math.sqrt(sumSq / (rrs.length - 1)); + } + } + + return BpResearchWindow( + windowStartMs: start, + windowEndMs: end, + onehzRows: onehz.isEmpty ? null : onehz.length, + rrBeats: rr.isEmpty ? null : rr.length, + hrMean: hrMean, + rrMsMean: rrMean, + rrMsMin: rrMin, + rrMsMax: rrMax, + rmssdMs: rmssd, + metaJson: metaJson, + ); +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index ae97e419e..6086fb69b 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -12441,5 +12441,122 @@ "type": "int" } } + }, + "settingsBpResearchRowTitle": "BP research capture", + "@settingsBpResearchRowTitle": { + "description": "Developer settings row title for the experimental blood-pressure research capture screen" + }, + "settingsBpResearchRowSub": "Experimental. Pair cuff readings with band data for analysis outside the app", + "@settingsBpResearchRowSub": { + "description": "Developer settings row subtitle for the BP research capture screen" + }, + "bpResearchTitle": "BP research capture", + "@bpResearchTitle": { + "description": "Title of the experimental BP research capture screen" + }, + "bpResearchIntro": "Experimental. Take a cuff reading, type it in and press capture. Band data from 2 minutes either side is added once the band has synced it.", + "@bpResearchIntro": { + "description": "Intro text of the BP research capture screen" + }, + "bpResearchSystolic": "Systolic (mmHg)", + "@bpResearchSystolic": { + "description": "Text field label for the systolic reference value" + }, + "bpResearchDiastolic": "Diastolic (mmHg)", + "@bpResearchDiastolic": { + "description": "Text field label for the diastolic reference value" + }, + "bpResearchDevice": "Cuff device (optional)", + "@bpResearchDevice": { + "description": "Text field label for the cuff device name" + }, + "bpResearchPosture": "Posture (optional)", + "@bpResearchPosture": { + "description": "Text field label for the posture during the reading" + }, + "bpResearchConditions": "Conditions (optional)", + "@bpResearchConditions": { + "description": "Text field label for measurement conditions" + }, + "bpResearchCapture": "Capture now", + "@bpResearchCapture": { + "description": "Button label to store one capture" + }, + "bpResearchHistory": "Captures", + "@bpResearchHistory": { + "description": "Section header for the stored capture list" + }, + "bpResearchBadValue": "That pair is outside the supported range (systolic 50–300, diastolic 20–200 mmHg, diastolic below systolic). It was not saved.", + "@bpResearchBadValue": { + "description": "Snackbar text for an out-of-bounds reference pair, which is rejected, never clamped" + }, + "bpResearchExportHint": "Included in Your data › Export as spreadsheets. Backups and an opt-in health share include them too.", + "@bpResearchExportHint": { + "description": "Hint under the capture list explaining the CSV export path" + }, + "bpResearchWindowPending": "Waiting for the band to sync", + "@bpResearchWindowPending": { + "description": "Capture list subtitle while the band data around the reading has not synced yet" + }, + "bpResearchWindowEmpty": "No band data in the window", + "@bpResearchWindowEmpty": { + "description": "Capture list subtitle when the band recorded nothing around the reading" + }, + "bpResearchRefreshFailed": "Saved, but the list failed to refresh. ({error})", + "@bpResearchRefreshFailed": { + "description": "Snackbar when the capture was stored but the list reload threw", + "placeholders": { + "error": { + "type": "String" + } + } + }, + "bpResearchLoadFailed": "The capture list failed to update. ({error})", + "@bpResearchLoadFailed": { + "description": "Snackbar when reloading the capture list (on open or after a delete) threw", + "placeholders": { + "error": { + "type": "String" + } + } + }, + "bpResearchCaptureFailed": "Capture failed, nothing was saved. ({error})", + "@bpResearchCaptureFailed": { + "description": "Snackbar when storing the capture threw", + "placeholders": { + "error": { + "type": "String" + } + } + }, + "bpResearchWindowHr": "HR {bpm} bpm", + "@bpResearchWindowHr": { + "description": "Capture list subtitle part: mean heart rate in the window", + "placeholders": { + "bpm": { + "type": "String" + } + } + }, + "bpResearchWindowRmssd": "RMSSD {ms} ms", + "@bpResearchWindowRmssd": { + "description": "Capture list subtitle part: RMSSD in the window", + "placeholders": { + "ms": { + "type": "String" + } + } + }, + "bpResearchWindowCounts": "{rows} 1 Hz rows, {beats} beats", + "@bpResearchWindowCounts": { + "description": "Capture list subtitle part: how much band data the window holds", + "placeholders": { + "rows": { + "type": "String" + }, + "beats": { + "type": "String" + } + } } } diff --git a/lib/ui2/profile/bp_research.dart b/lib/ui2/profile/bp_research.dart new file mode 100644 index 000000000..8e3799d7c --- /dev/null +++ b/lib/ui2/profile/bp_research.dart @@ -0,0 +1,256 @@ +// BP research capture (developer mode only): type in a cuff reading, and +// the band's synced data from 2 minutes either side is stored next to it. + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; + +import '../../data/db.dart'; +import '../../health/bp_research_capture.dart'; +import '../../l10n/app_localizations.dart'; +import '../ui2.dart'; +import 'devices.dart' show formatDayTime; + +class BpResearchScreen extends StatefulWidget { + const BpResearchScreen({super.key}); + + @override + State createState() => _BpResearchScreenState(); +} + +class _BpResearchScreenState extends State { + final _sys = TextEditingController(); + final _dia = TextEditingController(); + final _device = TextEditingController(); + final _posture = TextEditingController(); + final _conditions = TextEditingController(); + List> _rows = const []; + int? _edgeMs; + bool _busy = false; + + @override + void initState() { + super.initState(); + _reload(); + } + + @override + void dispose() { + _sys.dispose(); + _dia.dispose(); + _device.dispose(); + _posture.dispose(); + _conditions.dispose(); + super.dispose(); + } + + Future _refresh() async { + final edge = await LocalDb.fillBpResearchWindows(); + final rows = await LocalDb.bpResearchCaptures(); + if (mounted) { + setState(() { + _rows = rows; + _edgeMs = edge; + }); + } + } + + /// Runs [before] (if any) then [_refresh]; a throw becomes a snackbar + /// instead of an unhandled async error. + Future _reload([Future Function()? before]) async { + try { + await before?.call(); + await _refresh(); + } catch (e) { + if (!mounted) return; + final l = AppLocalizations.of(context); + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(l?.bpResearchLoadFailed('$e') ?? + 'The capture list failed to update. ($e)'), + )); + } + } + + Future _capture() async { + if (_busy) return; + final sys = double.tryParse(_sys.text); + final dia = double.tryParse(_dia.text); + final l = AppLocalizations.of(context); + if (sys == null || + dia == null || + sys < kResearchSystolicBounds.$1 || + sys > kResearchSystolicBounds.$2 || + dia < kResearchDiastolicBounds.$1 || + dia > kResearchDiastolicBounds.$2 || + dia >= sys) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(l?.bpResearchBadValue ?? + 'That pair is outside the supported range (systolic 50–300, ' + 'diastolic 20–200 mmHg, diastolic below systolic). It was not ' + 'saved.'), + )); + } + return; + } + setState(() => _busy = true); + var stored = false; + try { + final now = DateTime.now().millisecondsSinceEpoch; + // The window is filled in by _refresh once the band has synced it. + await LocalDb.putBpResearchCapture(BpResearchCapture( + measuredAtMs: now, + systolicMmHg: sys, + diastolicMmHg: dia, + capturedAtMs: now, + device: _device.text.trim().isEmpty ? null : _device.text.trim(), + posture: _posture.text.trim().isEmpty ? null : _posture.text.trim(), + conditions: + _conditions.text.trim().isEmpty ? null : _conditions.text.trim(), + )); + stored = true; + _sys.clear(); + _dia.clear(); + await _refresh(); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(stored + ? (l?.bpResearchRefreshFailed('$e') ?? + 'Saved, but the list failed to refresh. ($e)') + : (l?.bpResearchCaptureFailed('$e') ?? + 'Capture failed, nothing was saved. ($e)')), + )); + } + } finally { + if (mounted) setState(() => _busy = false); + } + } + + @override + Widget build(BuildContext c) { + final l = AppLocalizations.of(c); + final p = P.of(c); + return Scaffold( + appBar: AppBar( + title: Text(l?.bpResearchTitle ?? 'BP research capture'), + ), + body: ListView( + padding: const EdgeInsets.all(S.x4), + children: [ + Text( + l?.bpResearchIntro ?? + 'Experimental. Take a cuff reading, type it in and press ' + 'capture. Band data from 2 minutes either side is added once ' + 'the band has synced it.', + style: F.cap.copyWith(color: p.ink2, height: 1.5), + ), + const SizedBox(height: S.x4), + TextField( + controller: _sys, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))], + decoration: InputDecoration( + labelText: l?.bpResearchSystolic ?? 'Systolic (mmHg)', + ), + ), + const SizedBox(height: S.x2), + TextField( + controller: _dia, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))], + decoration: InputDecoration( + labelText: l?.bpResearchDiastolic ?? 'Diastolic (mmHg)', + ), + ), + const SizedBox(height: S.x2), + TextField( + controller: _device, + decoration: InputDecoration( + labelText: l?.bpResearchDevice ?? 'Cuff device (optional)', + ), + ), + const SizedBox(height: S.x2), + TextField( + controller: _posture, + decoration: InputDecoration( + labelText: l?.bpResearchPosture ?? 'Posture (optional)', + ), + ), + const SizedBox(height: S.x2), + TextField( + controller: _conditions, + decoration: InputDecoration( + labelText: l?.bpResearchConditions ?? 'Conditions (optional)', + ), + ), + const SizedBox(height: S.x4), + FilledButton.icon( + onPressed: _busy ? null : _capture, + icon: const Icon(LucideIcons.plus), + label: Text(l?.bpResearchCapture ?? 'Capture now'), + ), + const SizedBox(height: S.x6), + if (_rows.isNotEmpty) ...[ + Text(l?.bpResearchHistory ?? 'Captures', + style: F.head), + const SizedBox(height: S.x2), + for (final r in _rows) + ListTile( + dense: true, + title: Text( + '${(r['systolic_mmhg'] as num).round()}/' + '${(r['diastolic_mmhg'] as num).round()} mmHg · ' + '${formatDayTime(DateTime.fromMillisecondsSinceEpoch( + r['measured_at_ms'] as int), l)}', + ), + subtitle: Text(_windowSummary(r, l)), + trailing: IconButton( + icon: const Icon(LucideIcons.trash2, size: 18), + onPressed: () async { + await _reload(() => + LocalDb.deleteBpResearchCapture(r['id'] as int)); + }, + ), + ), + const SizedBox(height: S.x4), + Text( + l?.bpResearchExportHint ?? + 'Included in Your data › Export as spreadsheets. Backups ' + 'and an opt-in health share include them too.', + style: F.cap.copyWith(color: p.ink2, height: 1.5), + ), + ], + ], + ), + ); + } + + String _windowSummary(Map r, AppLocalizations? l) { + final onehz = r['onehz_rows']; + final beats = r['rr_beats']; + final hr = r['hr_mean']; + final rmssd = r['rmssd_ms']; + + if (onehz == null && beats == null) { + final edge = _edgeMs; + final end = (r['measured_at_ms'] as int) + kBpResearchWindowPostMs; + return edge == null || end > edge + ? (l?.bpResearchWindowPending ?? 'Waiting for the band to sync') + : (l?.bpResearchWindowEmpty ?? 'No band data in the window'); + } + final parts = []; + if (hr is num) { + final v = hr.toStringAsFixed(0); + parts.add(l?.bpResearchWindowHr(v) ?? 'HR $v bpm'); + } + if (rmssd is num) { + final v = rmssd.toStringAsFixed(0); + parts.add(l?.bpResearchWindowRmssd(v) ?? 'RMSSD $v ms'); + } + final rows = '${onehz ?? 0}', n = '${beats ?? 0}'; + parts.add( + l?.bpResearchWindowCounts(rows, n) ?? '$rows 1 Hz rows, $n beats'); + return parts.join(' · '); + } +} diff --git a/lib/ui2/profile/settings.dart b/lib/ui2/profile/settings.dart index 2d24b6d13..091bdfc5a 100644 --- a/lib/ui2/profile/settings.dart +++ b/lib/ui2/profile/settings.dart @@ -36,6 +36,7 @@ import '../../theme/theme_controller.dart'; import '../ui2.dart'; import 'alarm.dart'; import 'band_notifications.dart'; +import 'bp_research.dart'; import 'data.dart'; import 'gallery.dart'; import 'gestures.dart'; @@ -793,6 +794,12 @@ class MoreSettingsView extends StatelessWidget { 'Every component, at any text scale, in either ' 'theme', onTap: onGallery), + SetRow(LucideIcons.heartPulse, C.purple, + l?.settingsBpResearchRowTitle ?? 'BP research capture', + sub: l?.settingsBpResearchRowSub ?? + 'Experimental. Pair cuff readings with band data ' + 'for analysis outside the app', + onTap: () => goto(c, const BpResearchScreen())), SetRow(LucideIcons.code, C.n500, l?.settingsDeveloperModeRowTitle ?? 'Developer mode', value: on, chevron: false, onTap: onToggleDev), diff --git a/test/bp_research_capture_test.dart b/test/bp_research_capture_test.dart new file mode 100644 index 000000000..0d0e10d20 --- /dev/null +++ b/test/bp_research_capture_test.dart @@ -0,0 +1,77 @@ +// Unit tests for the pure window computation behind the BP research capture. +// +// The rules under test are the ones the storage and UI lean on: +// · a window with no band data is NULL, not zeroes; +// · a stat the window cannot honestly compute (no valid HR, too few +// beats for RMSSD) is absent, never zero; +// · rows outside the window are ignored, whatever their table's epoch +// base is (decoded_onehz.rec_ts is SECONDS, decoded_rr.rr_ts_ms is ms). + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/health/bp_research_capture.dart'; + +void main() { + const at = 1700000000000; // ms + + test('no band data in the window yields a NULL window, not zeroes', () { + final w = researchWindowFrom( + measuredAtMs: at, + onehzRows: const [], + rrRows: const [], + ); + expect(w, isNull); + }); + + test('rows outside the ±2 min window are ignored (seconds vs ms bases)', () { + final w = researchWindowFrom( + measuredAtMs: at, + onehzRows: [ + // rec_ts is epoch SECONDS. Inside the window (at/1000 ± 120). + {'rec_ts': at ~/ 1000, 'hr': 60}, + // 10 minutes before: outside, must not land in any stat. + {'rec_ts': at ~/ 1000 - 600, 'hr': 180}, + ], + rrRows: [ + // rr_ts_ms is epoch MS. Inside. + {'rr_ts_ms': at, 'rr_ms': 1000}, + ], + ); + expect(w, isNotNull); + expect(w!.onehzRows, 1); + expect(w.hrMean, 60.0); + expect(w.rrBeats, 1); + expect(w.rmssdMs, isNull); // one beat forms no successive difference + }); + + test('invalid HR rows do not drag the mean toward zero', () { + final w = researchWindowFrom( + measuredAtMs: at, + onehzRows: [ + {'rec_ts': at ~/ 1000, 'hr': 0}, + {'rec_ts': at ~/ 1000 - 1, 'hr': 58}, + {'rec_ts': at ~/ 1000 - 2, 'hr': 62}, + ], + rrRows: const [], + ); + expect(w!.onehzRows, 3); + expect(w.hrMean, 60.0); // 0 excluded as invalid, not averaged in + }); + + test('RMSSD over successive differences, min/max preserved', () { + final w = researchWindowFrom( + measuredAtMs: at, + onehzRows: const [], + rrRows: [ + {'rr_ts_ms': at - 3000, 'rr_ms': 1000}, + {'rr_ts_ms': at - 2000, 'rr_ms': 1100}, + {'rr_ts_ms': at - 1000, 'rr_ms': 900}, + ], + ); + expect(w!.rrBeats, 3); + expect(w.rrMsMin, 900.0); + expect(w.rrMsMax, 1100.0); + // diffs: +100, -200 → sqrt((100² + 200²)/2) = sqrt(25000) = 158.11… + expect(w.rmssdMs!, closeTo(158.11, 0.01)); + expect(w.hrMean, isNull); // no 1 Hz rows: absent, not zero + }); +} diff --git a/test/bp_research_db_test.dart b/test/bp_research_db_test.dart new file mode 100644 index 000000000..e57b5641c --- /dev/null +++ b/test/bp_research_db_test.dart @@ -0,0 +1,425 @@ +// The BP research store guarantees the review fixes made explicit: +// · a retake with NO device text replaces the reference instead of +// duplicating it (NULL never equals NULL in a UNIQUE constraint, so +// the store normalizes to '' — the rows must stay one, not two); +// · deleting a capture removes its window row in the same transaction +// (no PRAGMA foreign_keys here, so the ON DELETE CASCADE is inert); +// · a retake that now finds band data replaces the old window instead +// of orphaning it under the replaced reference's old id. +// Runs the REAL LocalDb over sqflite_common_ffi. +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/data/db.dart'; +import 'package:openstrap_edge/health/bp_research_capture.dart'; +import 'package:path/path.dart' as p; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +const _at = 1700000000000; // ms + +BpResearchCapture _capture( + int measuredAtMs, { + String? device, + BpResearchWindow? window, +}) => + BpResearchCapture( + measuredAtMs: measuredAtMs, + device: device, + posture: 'sitting', + conditions: 'rest', + systolicMmHg: 120, + diastolicMmHg: 80, + capturedAtMs: measuredAtMs, + window: window, + ); + +const _win = BpResearchWindow( + windowStartMs: _at - 120000, + windowEndMs: _at + 120000, + onehzRows: 240, + rrBeats: 200, + hrMean: 62.5, + rrMsMean: 960, + rrMsMin: 800, + rrMsMax: 1100, + rmssdMs: 42, + metaJson: null, +); + +void main() { + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + LocalDb.dbName = 'bp_research_db_test.db'; + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + }); + + tearDownAll(() async { + final db = await LocalDb.instance; + await db.close(); + }); + + test('a retake with no device replaces the reference, not duplicates it', + () async { + await LocalDb.putBpResearchCapture(_capture(_at)); + await LocalDb.putBpResearchCapture(_capture(_at, window: _win)); + final rows = await LocalDb.bpResearchCaptures(); + expect(rows, hasLength(1)); + expect(rows.first['device'], ''); + expect(rows.first['hr_mean'], 62.5); + }); + + test('a named device stays distinct from the no-device row', () async { + await LocalDb.putBpResearchCapture(_capture(_at, device: 'omron')); + final rows = await LocalDb.bpResearchCaptures(); + expect(rows, hasLength(2)); // the '' row from the previous test + omron + expect(rows.where((r) => r['device'] == 'omron'), hasLength(1)); + }); + + test('delete removes the window row too (the SQL cascade is inert)', + () async { + final db = await LocalDb.instance; + final before = + await db.rawQuery('SELECT COUNT(*) c FROM bp_research_window'); + expect(before.first['c'], greaterThan(0)); + final refs = await db + .rawQuery('SELECT id FROM bp_research_reference WHERE device = ?', + ['omron']); + await LocalDb.deleteBpResearchCapture(refs.first['id'] as int); + final orphaned = await db.rawQuery( + 'SELECT COUNT(*) c FROM bp_research_window ' + 'WHERE reference_id NOT IN (SELECT id FROM bp_research_reference)', + ); + expect(orphaned.first['c'], 0); + }); + + test('a retake that now finds band data replaces the absent window', + () async { + final later = _at + 60000; + await LocalDb.putBpResearchCapture(_capture(later)); + await LocalDb.putBpResearchCapture(_capture(later, window: _win)); + final db = await LocalDb.instance; + final windows = await db.rawQuery( + 'SELECT COUNT(*) c FROM bp_research_window ' + 'WHERE reference_id IN ' + '(SELECT id FROM bp_research_reference WHERE measured_at_ms = ?)', + [later]); + expect(windows.first['c'], 1); + final orphaned = await db.rawQuery( + 'SELECT COUNT(*) c FROM bp_research_window ' + 'WHERE reference_id NOT IN (SELECT id FROM bp_research_reference)', + ); + expect(orphaned.first['c'], 0); + }); + + test('the research tables ride the backup restore and salvage lists', + () async { + expect(LocalDb.restoreTablesForTest, contains('bp_research_reference')); + expect(LocalDb.restoreTablesForTest, contains('bp_research_window')); + expect(LocalDb.salvageTablesForTest, contains('bp_research_reference')); + expect(LocalDb.salvageTablesForTest, contains('bp_research_window')); + // Parent before child, in both lists. + int posOf(List l, String t) => l.indexOf(t); + expect( + posOf(LocalDb.restoreTablesForTest, 'bp_research_reference'), + lessThan(posOf(LocalDb.restoreTablesForTest, 'bp_research_window')), + ); + expect( + posOf(LocalDb.salvageTablesForTest, 'bp_research_reference'), + lessThan(posOf(LocalDb.salvageTablesForTest, 'bp_research_window')), + ); + }); + + // A foreign export's AUTOINCREMENT ids are meaningless on this install: + // its id=1 must never REPLACE an unrelated local capture that happens to + // hold id=1. The merge keys references on (measured_at_ms, device) and + // remaps each window onto the DESTINATION reference id. + test('restore merges captures by natural key, never by source id', + () async { + // Start from a clean store: earlier tests in this file leave rows + // behind, and this one asserts exact row sets. + final db0 = await LocalDb.instance; + await db0.delete('bp_research_window'); + await db0.delete('bp_research_reference'); + // Local state: one capture (id=1 by AUTOINCREMENT) plus its window. + await LocalDb.putBpResearchCapture(_capture(_at, device: 'local')); + // A foreign export whose DIFFERENT capture also carries id=1. + final srcPath = + p.join(await databaseFactory.getDatabasesPath(), 'bp_foreign.db'); + await databaseFactory.deleteDatabase(srcPath); + final src = await databaseFactory.openDatabase(srcPath); + await src.execute( + 'CREATE TABLE bp_research_reference (' + 'id INTEGER PRIMARY KEY AUTOINCREMENT, ' + 'measured_at_ms INTEGER NOT NULL, ' + 'device TEXT, posture TEXT, conditions TEXT, ' + 'systolic_mmhg REAL NOT NULL, diastolic_mmhg REAL NOT NULL, ' + 'captured_at_ms INTEGER NOT NULL, ' + 'UNIQUE (measured_at_ms, device))'); + await src.execute( + 'CREATE TABLE bp_research_window (' + 'reference_id INTEGER NOT NULL PRIMARY KEY, ' + 'window_start_ms INTEGER NOT NULL, window_end_ms INTEGER NOT NULL, ' + 'onehz_rows INTEGER, rr_beats INTEGER, hr_mean REAL, rr_ms_mean REAL, ' + 'rr_ms_min REAL, rr_ms_max REAL, rmssd_ms REAL, meta_json TEXT)'); + await src.insert('bp_research_reference', { + 'id': 1, // deliberately collides with the local capture's id + 'measured_at_ms': _at + 60000, + 'device': 'local', + 'posture': 'sitting', + 'conditions': 'rest', + 'systolic_mmhg': 130, + 'diastolic_mmhg': 85, + 'captured_at_ms': _at + 60000, + }); + await src.insert('bp_research_window', { + 'reference_id': 1, + 'window_start_ms': _at + 60000 - 120000, + 'window_end_ms': _at + 60000 + 120000, + 'onehz_rows': 240, + 'rr_beats': 200, + 'hr_mean': 71.0, + }); + await src.close(); + + final counts = await LocalDb.importFromDbFile(srcPath); + expect(counts['bp_research_reference'], 1); + expect(counts['bp_research_window'], 1); + + final db = await LocalDb.instance; + // Both captures survive: the foreign id=1 did not eat the local one. + final refs = await db.rawQuery( + 'SELECT measured_at_ms, systolic_mmhg FROM bp_research_reference ' + 'ORDER BY measured_at_ms'); + expect(refs, hasLength(2)); + expect(refs[0]['measured_at_ms'], _at); + expect(refs[0]['systolic_mmhg'], 120.0); + expect(refs[1]['measured_at_ms'], _at + 60000); + expect(refs[1]['systolic_mmhg'], 130.0); + // The imported window rides the imported reference's DESTINATION id, + // and no window is orphaned. + final orphaned = await db.rawQuery( + 'SELECT COUNT(*) c FROM bp_research_window ' + 'WHERE reference_id NOT IN (SELECT id FROM bp_research_reference)', + ); + expect(orphaned.first['c'], 0); + final importedWin = await db.rawQuery( + 'SELECT hr_mean FROM bp_research_window w ' + 'JOIN bp_research_reference r ON r.id = w.reference_id ' + 'WHERE r.measured_at_ms = ?', [_at + 60000]); + expect(importedWin.first['hr_mean'], 71.0); + await databaseFactory.deleteDatabase(srcPath); + }); + + test('a colliding restore keeps the destination id and its window', + () async { + final db0 = await LocalDb.instance; + await db0.delete('bp_research_window'); + await db0.delete('bp_research_reference'); + // Local capture WITH a window. + await LocalDb.putBpResearchCapture( + _capture(_at, device: 'local', window: _win)); + final localId = (await db0.rawQuery( + 'SELECT id FROM bp_research_reference')).first['id'] as int; + + // A foreign export of the SAME instant (same natural key) with no + // window row: the capture's fields update, the window survives. + final srcPath = + p.join(await databaseFactory.getDatabasesPath(), 'bp_foreign3.db'); + await databaseFactory.deleteDatabase(srcPath); + final src = await databaseFactory.openDatabase(srcPath); + await src.execute( + 'CREATE TABLE bp_research_reference (' + 'id INTEGER PRIMARY KEY AUTOINCREMENT, ' + 'measured_at_ms INTEGER NOT NULL, ' + 'device TEXT, posture TEXT, conditions TEXT, ' + 'systolic_mmhg REAL NOT NULL, diastolic_mmhg REAL NOT NULL, ' + 'captured_at_ms INTEGER NOT NULL, ' + 'UNIQUE (measured_at_ms, device))'); + await src.insert('bp_research_reference', { + 'id': 7, + 'measured_at_ms': _at, + 'device': 'local', + 'posture': 'standing', + 'conditions': 'after exercise', + 'systolic_mmhg': 140, + 'diastolic_mmhg': 90, + 'captured_at_ms': _at + 1000, + }); + await src.close(); + + await LocalDb.importFromDbFile(srcPath); + + final db = await LocalDb.instance; + final refs = await db.rawQuery( + 'SELECT id, posture, systolic_mmhg FROM bp_research_reference'); + expect(refs, hasLength(1)); + // The destination id is KEPT, so the window stays attached. + expect(refs.first['id'], localId); + expect(refs.first['posture'], 'standing'); + expect(refs.first['systolic_mmhg'], 140.0); + final orphaned = await db.rawQuery( + 'SELECT COUNT(*) c FROM bp_research_window ' + 'WHERE reference_id NOT IN (SELECT id FROM bp_research_reference)', + ); + expect(orphaned.first['c'], 0); + final win = await db.rawQuery( + 'SELECT hr_mean FROM bp_research_window WHERE reference_id = ?', + [localId]); + expect(win.first['hr_mean'], 62.5); + await databaseFactory.deleteDatabase(srcPath); + }); + + test('a re-import of the same export converges (idempotent merge)', + () async { + final db0 = await LocalDb.instance; + await db0.delete('bp_research_window'); + await db0.delete('bp_research_reference'); + final srcPath = + p.join(await databaseFactory.getDatabasesPath(), 'bp_foreign2.db'); + await databaseFactory.deleteDatabase(srcPath); + final src = await databaseFactory.openDatabase(srcPath); + await src.execute( + 'CREATE TABLE bp_research_reference (' + 'id INTEGER PRIMARY KEY AUTOINCREMENT, ' + 'measured_at_ms INTEGER NOT NULL, ' + 'device TEXT, posture TEXT, conditions TEXT, ' + 'systolic_mmhg REAL NOT NULL, diastolic_mmhg REAL NOT NULL, ' + 'captured_at_ms INTEGER NOT NULL, ' + 'UNIQUE (measured_at_ms, device))'); + await src.insert('bp_research_reference', { + 'id': 1, + 'measured_at_ms': _at + 120000, + 'device': '', + 'systolic_mmhg': 118, + 'diastolic_mmhg': 76, + 'captured_at_ms': _at + 120000, + }); + await src.close(); + + await LocalDb.importFromDbFile(srcPath); + await LocalDb.importFromDbFile(srcPath); + final db = await LocalDb.instance; + final n = (await db.rawQuery( + 'SELECT COUNT(*) c FROM bp_research_reference ' + 'WHERE measured_at_ms = ?', [_at + 120000])).first['c']; + expect(n, 1); + await databaseFactory.deleteDatabase(srcPath); + }); + + test('the window is filled once the band has synced past its end', + () async { + final at = _at + 10 * 86400000; + final sec = at ~/ 1000; + final db = await LocalDb.instance; + Future onehz(int t, int hr) => db.insert('decoded_onehz', { + 'device_id': LocalDb.kPrimaryDeviceId, + 'ts_ms': t * 1000, + 'rec_ts': t, + 'counter': t, + 'hr': hr, + }); + Future beat(int t, int i, int rr) => db.insert('decoded_rr', { + 'device_id': LocalDb.kPrimaryDeviceId, + 'ts_ms': t * 1000, + 'rec_ts': t, + 'beat_index': i, + 'rr_ts_ms': t * 1000, + 'rr_ms': rr, + }); + // Beats of one record share rr_ts_ms; insert out of beat order. + await beat(sec, 1, 1000); + await beat(sec, 0, 800); + await beat(sec + 1, 0, 1100); + await onehz(sec, 60); + await onehz(sec + 1, 0); + await LocalDb.putBpResearchCapture(_capture(at)); + + Future> row() async => (await LocalDb + .bpResearchCaptures()) + .firstWhere((r) => r['measured_at_ms'] == at); + + // Synced data stops short of the window end: still pending. + final edge = await LocalDb.fillBpResearchWindows(); + expect(edge, (sec + 1) * 1000); + expect((await row())['onehz_rows'], isNull); + + await onehz(sec + 121, 61); + await LocalDb.fillBpResearchWindows(); + final r = await row(); + expect(r['onehz_rows'], 2); + expect(r['rr_beats'], 3); + expect(r['hr_mean'], 60); + // 800, 1000, 1100 in beat order. + expect(r['rmssd_ms'] as double, closeTo(158.11, 0.01)); + }); + + test('the prune fills a pending window before deleting its rows', + () async { + final at = _at + 20 * 86400000; + final sec = at ~/ 1000; + final db = await LocalDb.instance; + for (final t in [sec, sec + 121]) { + await db.insert('decoded_onehz', { + 'device_id': LocalDb.kPrimaryDeviceId, + 'ts_ms': t * 1000, + 'rec_ts': t, + 'counter': t, + 'hr': 70, + }); + } + await LocalDb.putBpResearchCapture(_capture(at)); + // Nobody opened the dev screen; retention moves past the window. + await LocalDb.pruneDecodedBeforeRecTs(sec + 120); + final r = (await LocalDb.bpResearchCaptures()) + .firstWhere((r) => r['measured_at_ms'] == at); + expect(r['onehz_rows'], 1); + expect(r['hr_mean'], 70); + }); + + test('the window RR read seeks the store instead of scanning it', + () async { + // A capture with no band data stays pending and is re-read on every + // prune, so this read must not walk and sort the whole decoded_rr. + final db = await LocalDb.instance; + final plan = (await db.rawQuery( + 'EXPLAIN QUERY PLAN ${LocalDb.bpResearchRrWindowSql}', + [LocalDb.kPrimaryDeviceId, 1, 9], + )).map((r) => r['detail'].toString()).join(' | '); + expect(plan.toUpperCase(), contains('TS_MS'), reason: plan); + expect(plan.toUpperCase(), isNot(contains('USE TEMP B-TREE')), + reason: plan); + }); + + test('a salvage with an unreadable window table keeps the references', + () async { + const name = 'bp_research_salvage_test.db'; + final path = p.join(await databaseFactory.getDatabasesPath(), name); + await LocalDb.close(); + await databaseFactory.deleteDatabase(path); + LocalDb.dbName = name; + await LocalDb.putBpResearchCapture(_capture(_at, device: 'salvage')); + await LocalDb.close(); + // Brick the ladder (see startup_and_rebuild_recovery_test.dart) and make + // every read of the window table fail with something other than + // "no such table". + final raw = await databaseFactory.openDatabase(path); + await raw.execute('CREATE TABLE _raw_old (hex TEXT)'); + await raw.execute('DROP TABLE bp_research_window'); + await raw.execute('CREATE VIEW bp_research_window AS ' + 'SELECT abs(-9223372036854775807 - 1) AS reference_id'); + await raw.execute('PRAGMA user_version = 2'); + await raw.close(); + LocalDb.lastRebuild = null; + + final db = await LocalDb.instance; + expect(LocalDb.lastRebuild, isNotNull); + final refs = await db.query('bp_research_reference'); + expect(refs, hasLength(1)); + expect(refs.first['device'], 'salvage'); + expect(LocalDb.lastRebuild!.salvaged['bp_research_reference'], 1); + final q = File(LocalDb.lastRebuild!.quarantinePath); + if (q.existsSync()) q.deleteSync(); + }); +} diff --git a/test/bp_research_isolation_test.dart b/test/bp_research_isolation_test.dart new file mode 100644 index 000000000..113bc2618 --- /dev/null +++ b/test/bp_research_isolation_test.dart @@ -0,0 +1,42 @@ +// Nothing outside the allow-list may name the BP research tables or their +// helpers, so a cuff reading can never become an input to derived output. + +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +const _allowed = { + 'lib/data/db.dart', + 'lib/data/csv_export.dart', + 'lib/health/bp_research_capture.dart', + 'lib/ui2/profile/bp_research.dart', +}; + +void main() { + test('no file outside the allow-list names a BP research table', () { + final offenders = []; + final lib = Directory('lib'); + for (final f in lib.listSync(recursive: true).whereType()) { + if (!f.path.endsWith('.dart')) continue; + final rel = p.normalize(f.path); + final s = f.readAsStringSync(); + final hit = s.contains('bp_research_reference') || + s.contains('bp_research_window') || + s.contains('bpResearchCaptures') || + s.contains('putBpResearchCapture') || + s.contains('deleteBpResearchCapture') || + s.contains('fillBpResearchWindows'); + if (hit && !_allowed.contains(rel)) offenders.add(rel); + } + expect(offenders, isEmpty, + reason: 'files naming the BP research store must be on the allow-list ' + 'in test/bp_research_isolation_test.dart'); + }); + + test('the allow-list files themselves all exist', () { + for (final rel in _allowed) { + expect(File(rel).existsSync(), isTrue, reason: '$rel has vanished'); + } + }); +} diff --git a/test/ui2_tokens_test.dart b/test/ui2_tokens_test.dart index 05a6a0a55..51ec408cd 100644 --- a/test/ui2_tokens_test.dart +++ b/test/ui2_tokens_test.dart @@ -275,6 +275,8 @@ const _notComponents = { // 120 s network call and the keychain. `CoachFigure` — the part a gallery can // actually hold — IS in it. 'CoachScreen', 'CoachSetup', 'AiBriefingScreen', + // Dev-only Scaffold route over its own research tables. + 'BpResearchScreen', // The two day-scoped Scaffold routes: each resolves a day, then reads the // bundle plus three or four stores to fill it. Their BODIES are what a // gallery can hold and both are in it as cases — `timeline_day`,