diff --git a/lib/compute/derivation_engine.dart b/lib/compute/derivation_engine.dart index 8133baa6c..65584a4cb 100644 --- a/lib/compute/derivation_engine.dart +++ b/lib/compute/derivation_engine.dart @@ -32,6 +32,7 @@ import 'dart:math' as math; import 'quiet_level_seed.dart' show seedQuietHrrHistoryOnce; import 'strain_backfill.dart' show backfillStrainScale; +import 'stress_backfill.dart' show backfillStressScale; import 'readiness_calibration_backfill.dart' show backfillReadinessCalibration, seedRecentReadinessZ; @@ -1893,7 +1894,14 @@ import 'vendor_sleep.dart'; // no window does, instead of the longest of the search window's sessions. // HrvFreqStream v2, CardioRowCache v3 and policy-bound PRSA states require cold // rebuilds of old checkpoints, isolated by this algorithm version. -const int kAlgoVersion = 124; +// 124 → 125 (edge-side recalibration, no sibling repin): stress score. The +// Baevsky SI -> 0-100 map floored at SI 20, clamping every genuinely low night +// (SI < 50 is Baevsky's own "low" band) to a flat 0 and losing all variation +// for high-HRV sleepers (#631). `kStressScoreFloorSi` is now 5. +// stress_backfill.dart rescales stored history in place from each day's own +// `stress.si` so the trend has no step at the bump. User-visible: every stress score moves +// up once (e.g. SI 160 reads ~72, was ~61); nights that read 0 now read low. +const int kAlgoVersion = 125; /// The sibling SHAs this version was derived against, asserted against /// pubspec.yaml in test/db_serve_version_and_reads_test.dart. /// @@ -4205,6 +4213,26 @@ class DerivationEngine { } catch (e) { _log('[derive] strain rescale failed (kept old values): $e'); } + // Same one-shot shape as the strain rescale and for the same reason: + // low nights older than `rawRetentionDays` keep a floor-20 score that a + // version bump alone cannot reach. Pure function of each day's stored + // `stress.si`, so it needs no baseline (#631). + _diag['stage'] = 'stress_rescale'; + var stressRescaled = false; + try { + final rescaled = await backfillStressScale(); + if (rescaled.didWork) { + stressRescaled = true; + _log('[derive] stress rescale: ${rescaled.bundleDays} row(s), ' + '${rescaled.seriesDays} trend point(s) rescaled in place, ' + '${rescaled.skipped} skipped (no stored index or imported)'); + } + } catch (e) { + // Each day commits on its own, so days before the failure stay + // rescaled; the marker is not written, so the next pass resumes. + stressRescaled = true; + _log('[derive] stress rescale stopped, will retry next pass: $e'); + } // ONE-SHOT, after the sweep for the same reason as the strain rescale: // the rest of the readiness_z history, then a re-score of every day // below v112 that has no raw substrate left (substrate days were just @@ -4236,10 +4264,10 @@ class DerivationEngine { } catch (e) { _log('[derive] readiness calibration failed (will retry): $e'); } - // The strain rescale rewrote stored days after the rollup of this pass - // was built from the old values. When the calibration above did not + // The strain or stress rescale rewrote stored days after the rollup of + // this pass was built from the old values. When the calibration above did not // rebuild it (no work, or it failed), rebuild it here. - if (strainRescaled && !crossDayRebuilt) { + if ((strainRescaled || stressRescaled) && !crossDayRebuilt) { try { await _refreshBaselines(); await _runCrossDay(profile); @@ -8610,7 +8638,8 @@ class DerivationEngine { String name, int nowOffsetMin, int janOffsetMin, int julOffsetMin) => '$name|$nowOffsetMin|$janOffsetMin|$julOffsetMin'; - /// Whether the stored cross-day ROLLUP was built in another zone. The + /// Whether the stored cross-day ROLLUP was built in another zone or by + /// another algorithm version. The /// rollup, not its inputs: [_refreshBaselines] re-stamps the inputs before /// the rollup is written, so a rollup that then timed out would read as /// current on the inputs' stamp and never be retried. @@ -8619,7 +8648,12 @@ class DerivationEngine { if (raw is! String || raw.isEmpty) return false; try { final decoded = jsonDecode(raw); - return decoded is Map && decoded['zone'] != crossDayZoneStamp(); + // A rollup from another algorithm version is rejected by its readers + // (`getInsights`), so it is as stale as one from another zone: rebuild it + // from stored days even when nothing else in the pass has work. + return decoded is Map && + (decoded['zone'] != crossDayZoneStamp() || + (decoded['algo_version'] as num?)?.toInt() != kAlgoVersion); } catch (_) { return false; } diff --git a/lib/compute/onehz_pipeline.dart b/lib/compute/onehz_pipeline.dart index 71d8545b7..312008ffa 100644 --- a/lib/compute/onehz_pipeline.dart +++ b/lib/compute/onehz_pipeline.dart @@ -1672,11 +1672,7 @@ Map _deriveDayBundle(Map inputJson, // stress screen reads this {score, si, lf_hf, rmssd, level} block directly. final si = stress.present ? stress.value!.si : null; final lfhf = hrvF.present ? hrvF.value!.lfhf : null; - double? stressScore; - if (si != null && si > 0) { - final lo = math.log(20), hi = math.log(600); - stressScore = (100 * (math.log(si) - lo) / (hi - lo)).clamp(0.0, 100.0); - } + final stressScore = stressScoreFromSi(si); final stressBlock = { 'value': stressScore == null ? '—' : _round(stressScore, 1), 'score': stressScore == null ? null : _round(stressScore, 1), @@ -2371,6 +2367,27 @@ double? _stddev(List xs) { return math.sqrt(s / (xs.length - 1)); } +/// Baevsky Stress Index → a 0-100 resting-tension score, log-mapped over the +/// plausible resting SI range [kStressScoreFloorSi, kStressScoreCeilingSi]. +/// Null when there is no usable index (never 0 for absence — 0 is a real score +/// at the floor). +/// +/// CALIBRATION: the floor was 20, which clamped every genuinely low-tension +/// night (Baevsky's own "low" band is SI < 50) to a flat 0 and lost all +/// information for high-HRV sleepers (#631). A lower floor restores variation +/// at the bottom. Moving it shifts every user's number, so it is changed +/// deliberately, with a kAlgoVersion bump and a one-shot rescale of stored +/// history (stress_backfill.dart). ONE source for the mapping: the live derive +/// above and that rescale both call this. +const double kStressScoreFloorSi = 5; +const double kStressScoreCeilingSi = 600; + +double? stressScoreFromSi(double? si) { + if (si == null || !si.isFinite || si <= 0) return null; + final lo = math.log(kStressScoreFloorSi), hi = math.log(kStressScoreCeilingSi); + return (100 * (math.log(si) - lo) / (hi - lo)).clamp(0.0, 100.0); +} + double _round(double v, int dp) { final p = math.pow(10, dp); return (v * p).round() / p; diff --git a/lib/compute/stress_backfill.dart b/lib/compute/stress_backfill.dart new file mode 100644 index 000000000..b7b58f09a --- /dev/null +++ b/lib/compute/stress_backfill.dart @@ -0,0 +1,182 @@ +// ONE-SHOT BACKFILL — stored stress scores onto the recalibrated floor (#631). +// +// The Baevsky SI → 0-100 map used to floor at SI 20, so every genuinely low +// night (Baevsky's own "low" band is SI < 50) read as a flat 0 and high-HRV +// sleepers saw 0 every single night. The floor is now `kStressScoreFloorSi`. +// Every day derived before that change carries a score on the old scale, so the +// stress trend and the day-detail screen would show a step at the release date +// rather than a real change. +// +// WHY NOT JUST RE-DERIVE: raw 1 Hz substrate is pruned `rawRetentionDays` behind +// the data edge, so a kAlgoVersion bump alone can only fix the last few days. +// +// It does not need raw. The new score is a PURE function of the Baevsky index, +// and each stored day_result already carries its own `stress.si`. +// +// IN PLACE, NOT A NEW VERSION ROW. The rescale rewrites only the stress score +// (`stress.score`/`value`, `scalars.stress`, the `stress` trend point) of the +// rows that exist, at the version they already have. It does not stamp a day +// current, so: +// * a day that still has raw is still re-derived by the version gate (no +// guess at where the raw window ends is needed); +// * the strain and readiness one-shots, which key on the row's version, +// still see every day they are owed; +// * provenance (device family, coverage, method stamps, naps) is untouched. +// The rewrite is idempotent (score = f(stored si)), so a row a fresh derive +// already wrote is a no-op. +// +// ONE source for the mapping: `stressScoreFromSi`, the same function the live +// derive calls. + +import 'dart:convert'; + +import '../data/db.dart'; +import '../data/series_codec.dart'; +import 'onehz_pipeline.dart' show stressScoreFromSi; + +/// `compute_freshness` key marking the rescale as applied. Bumped with the algo +/// version so a later recalibration is a new one-shot rather than a no-op. +const String kStressRescaleKey = 'stress_rescale_v125'; + +class StressBackfillResult { + /// Days whose `metric_series` stress score was rewritten (trend / v_daily). + final int seriesDays; + + /// `day_result` rows whose stress score was rewritten in place. + final int bundleDays; + + /// Rows left exactly as they were: no usable index, imported, or unreadable. + final int skipped; + + const StressBackfillResult({ + required this.seriesDays, + required this.bundleDays, + required this.skipped, + }); + + bool get didWork => seriesDays > 0 || bundleDays > 0; +} + +/// Rescale every stored stress score in place. A one-shot once it has walked a +/// non-empty store; an empty store is not marked, so rows a restore merges in +/// later are still rescaled. Set [force] to re-run. +Future backfillStressScale({bool force = false}) async { + const none = StressBackfillResult(seriesDays: 0, bundleDays: 0, skipped: 0); + if (!force && await LocalDb.computeFreshness(kStressRescaleKey) != null) { + return none; + } + + final db = await LocalDb.instance; + final days = [ + for (final r in await db.rawQuery( + 'SELECT DISTINCT day_id FROM day_result WHERE day_id IS NOT NULL ' + 'ORDER BY day_id')) + r['day_id'] as String, + ]; + if (days.isEmpty) return none; + + var seriesDays = 0; + var bundleDays = 0; + var skipped = 0; + + for (final day in days) { + // One transaction per day: the rows are read and rewritten together, so a + // derive in another isolate cannot land between the read and the write + // and be overwritten by an older payload. + await db.transaction((txn) async { + final rows = await txn.query('day_result', + columns: ['algo_version', 'payload_json', 'partial'], + where: 'day_id = ?', + whereArgs: [day], + orderBy: 'algo_version DESC'); + // The build that last wrote this day's series, when stamped. + final stamp = ((await txn.query('metric_series_version', + columns: ['algo_version'], + where: 'date = ?', + whereArgs: [day])) + .firstOrNull?['algo_version'] as num?) + ?.toInt(); + double? seriesScore; + var seriesPicked = false; + for (final row in rows) { + final payload = _decode(row['payload_json']); + final blk = payload?['stress']; + final si = blk is Map ? _finite(blk['si']) : null; + final next = stressScoreFromSi(si); + // The trend point comes ONLY from the row that wrote it: the stamped + // writer, else the newest complete row (a partial row never writes the + // series). If that row has no usable score the trend stays as it is. + if (!seriesPicked && + (row['partial'] as num?)?.toInt() != 1 && + (stamp == null || (row['algo_version'] as num?)?.toInt() == stamp)) { + seriesPicked = true; + if (payload?['imported'] != true) seriesScore = next; + } + // No usable index, or another source's day: a rescaled day must not + // become 0 (a score, not an absence), and an imported score is not + // ours to re-price. + if (payload == null || next == null || payload['imported'] == true) { + skipped++; + continue; + } + final rounded = _round1(next); + final scalars = payload['scalars']; + if ((blk as Map)['score'] == rounded && + blk['value'] == rounded && + (scalars is! Map || scalars['stress'] == next)) { + continue; // already on the new scale + } + // `value`/`score` are the rounded headline the screens read; the + // derive also writes the unrounded score into `scalars`. + blk['score'] = rounded; + blk['value'] = rounded; + if (scalars is Map) scalars['stress'] = next; + await txn.update( + 'day_result', + {'payload_json': SeriesCodec.encodePayloadJson(jsonEncode(payload))}, + where: 'day_id = ? AND algo_version = ?', + whereArgs: [day, row['algo_version']], + ); + bundleDays++; + } + if (seriesScore == null) return; + // UPDATE only: never create a trend point the derive did not write, and + // leave a day whose series another source produced alone. + final n = await txn.rawUpdate( + "UPDATE metric_series SET value = ? WHERE date = ? AND key = 'stress' " + 'AND (value IS NULL OR value <> ?) AND NOT EXISTS (SELECT 1 FROM ' + 'metric_series_version v WHERE v.date = ? AND v.source IS NOT NULL ' + "AND v.source <> 'band')", + [seriesScore, day, seriesScore, day], + ); + if (n > 0) seriesDays++; + }); + } + + await LocalDb.putComputeFreshness( + kStressRescaleKey, jsonEncode({'done': true})); + return StressBackfillResult( + seriesDays: seriesDays, + bundleDays: bundleDays, + skipped: skipped, + ); +} + +/// A finite number, or null — a wrong-typed index is skipped, not thrown on. +double? _finite(Object? v) { + if (v is! num) return null; + final d = v.toDouble(); + return d.isFinite ? d : null; +} + +double _round1(double v) => (v * 10).round() / 10; + +Map? _decode(Object? json) { + if (json is! String) return null; + try { + final v = jsonDecode(json); + return v is Map ? v.cast() : null; + } catch (_) { + return null; + } +} diff --git a/test/crossday_as_of_zone_test.dart b/test/crossday_as_of_zone_test.dart index bc8ae34fe..94134576a 100644 --- a/test/crossday_as_of_zone_test.dart +++ b/test/crossday_as_of_zone_test.dart @@ -44,6 +44,36 @@ Future _putInput(String zone) async { ); } +Future _seedRestoredDays() async { + for (var i = 0; i < 5; i++) { + final day = '2026-09-0${i + 2}'; + final onset = + DateTime.utc(2026, 9, i + 1, 22).millisecondsSinceEpoch ~/ 1000; + await LocalDb.putDayResult( + dayId: day, + algoVersion: kAlgoVersion, + finalized: true, + rhr: 52, + readiness: 70, + windowJson: '{}', + payloadJson: jsonEncode({ + 'scalars': {'rhr': 52, 'readiness': 70, 'efficiency': 95}, + 'sleep': { + 'window': { + 'value': { + 'onset_ms': onset * 1000, + 'offset_ms': (onset + 8 * 3600) * 1000, + }, + }, + 'accounting': { + 'value': {'tst_sec': 27000}, + }, + }, + }), + ); + } +} + void main() { setUpAll(() async { sqfliteFfiInit(); @@ -82,33 +112,7 @@ void main() { test('a restored backup with no band data rebuilds an old-zone rollup', () async { // Stored days, no decoded rows, and a rollup from before a flight. - for (var i = 0; i < 5; i++) { - final day = '2026-09-0${i + 2}'; - final onset = - DateTime.utc(2026, 9, i + 1, 22).millisecondsSinceEpoch ~/ 1000; - await LocalDb.putDayResult( - dayId: day, - algoVersion: kAlgoVersion, - finalized: true, - rhr: 52, - readiness: 70, - windowJson: '{}', - payloadJson: jsonEncode({ - 'scalars': {'rhr': 52, 'readiness': 70, 'efficiency': 95}, - 'sleep': { - 'window': { - 'value': { - 'onset_ms': onset * 1000, - 'offset_ms': (onset + 8 * 3600) * 1000, - }, - }, - 'accounting': { - 'value': {'tst_sec': 27000}, - }, - }, - }), - ); - } + await _seedRestoredDays(); await LocalDb.putBaseline( 'crossday', jsonEncode({ @@ -131,6 +135,31 @@ void main() { expect(rollup['zone'], DerivationEngine.crossDayZoneStamp()); }); + test('a restored backup with no band data rebuilds an old-version rollup', + () async { + // Same zone, but written by the previous algorithm version, which the + // insights reader rejects. + await _seedRestoredDays(); + await LocalDb.putBaseline( + 'crossday', + jsonEncode({ + 'algo_version': kAlgoVersion - 1, + 'zone': DerivationEngine.crossDayZoneStamp(), + 'recent': const [], + }), + ); + await _putInput(DerivationEngine.crossDayZoneStamp()); + await DerivationEngine().run(const Profile( + ageYears: 35, + sex: 'm', + weightKg: 75, + heightCm: 178, + )); + final rollup = jsonDecode( + (await LocalDb.baseline('crossday'))!['payload_json'] as String) as Map; + expect(rollup['algo_version'], kAlgoVersion); + }); + test('a stored rollup from another zone is not served as current', () async { await _putInput('Elsewhere|-420'); diff --git a/test/ed2b_algo_version_114_test.dart b/test/ed2b_algo_version_114_test.dart index b3de3bd82..93dc86202 100644 --- a/test/ed2b_algo_version_114_test.dart +++ b/test/ed2b_algo_version_114_test.dart @@ -6,7 +6,7 @@ import 'package:openstrap_edge/compute/derivation_engine.dart'; void main() { // WHY: finalized days need a new version when the analytics pin changes outputs. test('ED-2b adoption and workout rest repin name their output changes', () { - expect(kAlgoVersion, 124); + expect(kAlgoVersion, 125); expect(kAnalyticsPin, 'a438df40b38a4586a52a68ab7e1c100fca111ccd'); final src = File('lib/compute/derivation_engine.dart').readAsStringSync(); final at = src.indexOf('// 121 → 122'); @@ -25,11 +25,19 @@ void main() { 'duration-cap', 'saved-session overlap']) { expect(repinEntry, contains(change)); } - final mainRepin = src.substring(src.indexOf('// 123 → 124')); + final mainRepin = src.substring( + src.indexOf('// 123 → 124'), src.indexOf('// 124 → 125')); for (final change in ['a438df4', '#102-#110', '#110', 'regressing clocks', '5%', 'Cosinor', 'SDNN', 'uncertainty', 'HrvFreqStream v2', 'CardioRowCache v3', 'PRSA']) { expect(mainRepin, contains(change)); } + // A bump must name its output change: v125 is the stress recalibration. + final stressEntry = src.substring( + src.indexOf('// 124 → 125'), src.indexOf('const int kAlgoVersion')); + for (final change in ['#631', 'stress', 'kStressScoreFloorSi', + 'stress_backfill']) { + expect(stressEntry, contains(change)); + } }); } diff --git a/test/stress_rescale_backfill_test.dart b/test/stress_rescale_backfill_test.dart new file mode 100644 index 000000000..d922bee16 --- /dev/null +++ b/test/stress_rescale_backfill_test.dart @@ -0,0 +1,186 @@ +// One-shot backfill of stored stress scores onto the recalibrated floor (#631). +// +// Raw 1 Hz substrate is pruned `rawRetentionDays` behind the data edge, so the +// stress history CANNOT be re-derived from raw and a kAlgoVersion bump alone +// leaves old low nights flat at 0. It does not need raw: the score is a pure +// function of the stored Baevsky index, which every day_result already carries, +// so the rescale reads `stress.si` and re-maps it with `stressScoreFromSi`, +// in place, at the version each row already has. + +import 'dart:convert'; + +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/onehz_pipeline.dart' + show stressScoreFromSi; +import 'package:openstrap_edge/compute/stress_backfill.dart'; +import 'package:openstrap_edge/data/db.dart'; + +/// Seed a derived day the way the engine would have on the OLD (floor-20) scale. +Future seedStressDay( + String day, { + required Object? si, + required double? score, + bool partial = false, + bool imported = false, + int algoVersion = 120, +}) async { + await LocalDb.putDayResult( + dayId: day, + algoVersion: algoVersion, + payloadJson: jsonEncode({ + 'date': day, + 'imported': ?(imported ? true : null), + 'scalars': {'rhr': 55, 'stress': ?score}, + 'stress': {'value': score, 'score': score, 'si': si, 'level': 'low'}, + }), + windowJson: '{}', + finalized: true, + partial: partial, + series: {'stress': ?score}, + ); +} + +Future seriesValue(String day) async { + for (final r in await LocalDb.metricSeries('stress')) { + if (r['date'] == day) return (r['value'] as num?)?.toDouble(); + } + return null; +} + +Future> stored(String day, int version) async { + final db = await LocalDb.instance; + final row = (await db.query('day_result', + where: 'day_id = ? AND algo_version = ?', whereArgs: [day, version])) + .single; + final payload = jsonDecode(row['payload_json'] as String) as Map; + return { + 'score': (payload['stress'] as Map)['score'], + 'value': (payload['stress'] as Map)['value'], + 'scalar': (payload['scalars'] as Map)['stress'], + }; +} + +void main() { + setUpAll(() { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + LocalDb.dbName = 'openstrap_stress_backfill_test.db'; + }); + + // Every test starts from an empty database, so none depends on another's + // writes or on run order. + setUp(() async { + await LocalDb.close(); + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + }); + + tearDownAll(() async { + await LocalDb.close(); + final dir = await databaseFactory.getDatabasesPath(); + await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); + }); + + final raw = stressScoreFromSi(12)!; + final rounded = ((raw * 10).round()) / 10; + + test('a flat-0 low night is rescaled in place from its own index', () async { + // SI 12 was exactly 0 under the floor of 20. + await seedStressDay('2026-05-01', si: 12, score: 0); + + final result = await backfillStressScale(); + expect(result.bundleDays, 1); + expect(result.seriesDays, 1); + + expect(rounded, greaterThan(0)); // the whole point of #631 + // Same row, same version: the derive gate, the strain and readiness + // one-shots and the day's provenance all see what they saw before. + final s = await stored('2026-05-01', 120); + expect(s['score'], rounded); + expect(s['value'], rounded); + expect(s['scalar'], closeTo(raw, 1e-9)); // unrounded, as the derive writes + expect(await seriesValue('2026-05-01'), closeTo(raw, 1e-9)); + }); + + test('a missing or wrong-typed index is skipped, never zeroed or thrown on', + () async { + await seedStressDay('2026-05-01', si: null, score: 40); + await seedStressDay('2026-05-02', si: '12', score: 41); + await seedStressDay('2026-05-03', si: 12, score: 0); + + final result = await backfillStressScale(); + + expect(result.skipped, 2); + for (final (day, v) in [('2026-05-01', 40.0), ('2026-05-02', 41.0)]) { + final s = await stored(day, 120); + expect(s['score'], v); + expect(s['scalar'], v); + expect(await seriesValue(day), v); + } + // A bad row does not stop the walk. + expect(await seriesValue('2026-05-03'), closeTo(raw, 1e-9)); + }); + + test('a partial newest row: the trend point follows the complete row', + () async { + await seedStressDay('2026-05-01', si: 12, score: 0); // wrote the series + await seedStressDay('2026-05-01', + si: 300, score: 73, partial: true, algoVersion: 121); + + await backfillStressScale(); + + expect(await seriesValue('2026-05-01'), closeTo(raw, 1e-9)); + expect((await stored('2026-05-01', 121))['score'], + ((stressScoreFromSi(300)! * 10).round()) / 10); + }); + + test('the trend follows only its writer row, never an older one', () async { + await seedStressDay('2026-05-01', si: 12, score: 0); + // Newest complete row has no usable index: the trend stays as it wrote it. + await seedStressDay('2026-05-01', si: null, score: 40, algoVersion: 121); + + await backfillStressScale(); + + expect(await seriesValue('2026-05-01'), 40); + // The older bundle is still rescaled on its own. + expect((await stored('2026-05-01', 120))['score'], rounded); + }); + + test('a stamped series writer wins over a newer complete row', () async { + await seedStressDay('2026-05-01', si: 300, score: 73, algoVersion: 121); + // A rolled-back build rewrote the series (and its stamp) at v120. + await seedStressDay('2026-05-01', si: 12, score: 0); + + await backfillStressScale(); + + expect(await seriesValue('2026-05-01'), closeTo(raw, 1e-9)); + }); + + test('an imported day keeps its score', () async { + await seedStressDay('2026-05-01', si: 12, score: 0, imported: true); + + final result = await backfillStressScale(); + + expect(result.didWork, isFalse); + expect((await stored('2026-05-01', 120))['score'], 0); + expect(await seriesValue('2026-05-01'), 0); + }); + + test('an empty store is not marked done', () async { + expect((await backfillStressScale()).didWork, isFalse); + expect(await LocalDb.computeFreshness(kStressRescaleKey), isNull); + }); + + test('it is a one-shot: a second pass rewrites nothing', () async { + await seedStressDay('2026-05-01', si: 12, score: 0); + + expect((await backfillStressScale()).didWork, isTrue); + expect(await LocalDb.computeFreshness(kStressRescaleKey), isNotNull); + expect((await backfillStressScale()).didWork, isFalse); + // Forced, an already-rescaled store is a no-op. + expect((await backfillStressScale(force: true)).didWork, isFalse); + }); +} diff --git a/test/stress_score_floor_test.dart b/test/stress_score_floor_test.dart new file mode 100644 index 000000000..c4ff48d21 --- /dev/null +++ b/test/stress_score_floor_test.dart @@ -0,0 +1,47 @@ +// #631: the Baevsky SI → 0-100 stress score clamped every genuinely low night +// to a flat 0, because the scale floor sat at SI 20 while Baevsky's own "low" +// band is SI < 50. High-HRV sleepers (nightly SI ~10-14) saw 0 on every night, +// which reads as "no data" rather than "low". The floor is now 5, so the low +// end varies again. This pins the mapping, which the live derive and the +// one-shot history rescale both call. +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/compute/onehz_pipeline.dart' + show stressScoreFromSi, kStressScoreFloorSi, kStressScoreCeilingSi; + +void main() { + group('stressScoreFromSi', () { + test('no usable index is absence, never 0', () { + expect(stressScoreFromSi(null), isNull); + expect(stressScoreFromSi(0), isNull); + expect(stressScoreFromSi(-1), isNull); + expect(stressScoreFromSi(double.nan), isNull); + expect(stressScoreFromSi(double.infinity), isNull); + }); + + test('the floor is 0 and the ceiling is 100', () { + expect(stressScoreFromSi(kStressScoreFloorSi), 0.0); + expect(stressScoreFromSi(kStressScoreCeilingSi), 100.0); + expect(stressScoreFromSi(kStressScoreCeilingSi * 2), 100.0); // clamped + expect(stressScoreFromSi(kStressScoreFloorSi / 2), 0.0); // clamped + }); + + test('genuinely low nights no longer flatten to 0 (the #631 symptom)', () { + // Under the old floor of 20 every one of these was exactly 0. + for (final si in const [10.0, 12.0, 14.0, 18.0]) { + expect(stressScoreFromSi(si), greaterThan(0.0), + reason: 'SI $si used to clamp to 0'); + } + expect(stressScoreFromSi(10), closeTo(14.5, 0.6)); + expect(stressScoreFromSi(20), closeTo(29.0, 0.6)); + }); + + test('monotonic in the index', () { + double last = -1; + for (final si in const [5.0, 10.0, 20.0, 50.0, 150.0, 600.0]) { + final s = stressScoreFromSi(si)!; + expect(s, greaterThanOrEqualTo(last)); + last = s; + } + }); + }); +}