Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,12 @@ a hotspot.
whole-row REPLACE let a same-second temperature sample null the HR. A write that
replaces a second must replace that `(device_id, ts_ms)`'s `decoded_rr`
beats in the same batch, never another device's (`_queueRrBeats` via
`_queueDecodedOneHz`, and `_queueNeutralOneHz`). Known gap: the restore
`_queueDecodedOneHz`, and `_queueNeutralOneHz`). One narrow exception: a
record (WHOOP 4 or gen5) whose beats all have a `beat_ts_ms` replaces only the
beats at those times (and any untimed beat of the second), because two records
can share a Unix second and the neighbour's beats are not its to delete. A
re-decode of the same record that drops a beat leaves that beat in place. The
`decoded_onehz` row is still one per second, newest wins. Known gap: the restore
merge in `_mergeFromDbFile` only clears beats for seconds the import
carries beats for. Every path that deletes 1 Hz rows (the prune,
`deleteDays`) must delete their beats with them.
Expand Down
116 changes: 98 additions & 18 deletions lib/data/db.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7962,8 +7962,10 @@ class LocalDb {
}


/// Replaces this second's RR beats. Returns the ops queued.
/// Writes one record's RR beats. Returns the ops queued.
///
/// With a beat time for every beat the record's beats are merged into the
/// second by `beat_ts_ms` (see below); otherwise the second is replaced.
/// Clear the second before reinserting so a SHRINKING beat count can't strand
/// stale high-index beats. The child's key extends the parent's `(device_id,
/// ts_ms)`, so this single DELETE of the writing device's second replaces the
Expand All @@ -7977,7 +7979,64 @@ class LocalDb {
String? deviceFamily,
String deviceId = kPrimaryDeviceId,
bool preDeviceKey = false,
// Queue nothing unless the beats can be merged by time: for a caller that
// must not replace a second it did not write.
bool mergeOnly = false,
}) {
final beatTs = beatTimesMs(recTs, decoded.tsSubsec, decoded.rrIntervalsMs);
// MERGE BY BEAT TIME, when every beat of this record has one. A WHOOP 4
// record comes every 0.9614 s, so about one in 26 shares its Unix second
// with a neighbour, and the neighbour's beats are not this record's to
// delete. Each beat replaces only the row at its own `beat_ts_ms` (so a
// re-offload of the same record is idempotent and keeps its slot) or, if
// new, takes the next free `beat_index` of the second. The indices stay
// dense, which the restore merge relies on (it clears the tail past the
// backup's highest index). A record re-offloaded after its neighbour is
// unaffected: it keeps its slot, so read order is insertion order, and the
// beat axis already holds backward placements.
// Rows with no beat time (written before the column existed) cannot be
// told apart from this record's beats, so they are replaced with it.
final merge = !preDeviceKey &&
decoded.tsSubsec != null &&
!beatTs.contains(null);
if (!merge && mergeOnly) return 0;
if (merge) {
batch.rawDelete(
'DELETE FROM decoded_rr WHERE device_id = ? AND ts_ms = ? '
'AND beat_ts_ms IS NULL',
[deviceId, recTs * 1000],
);
var ops = 1;
for (var i = 0; i < decoded.rrIntervalsMs.length; i++) {
final rr = decoded.rrIntervalsMs[i];
if (rr <= 0) continue;
batch.rawInsert(
'INSERT OR REPLACE INTO decoded_rr (device_id, ts_ms, rec_ts, '
'beat_index, rr_ts_ms, rr_ms, beat_ts_ms, device_family) '
'VALUES (?, ?, ?, COALESCE('
'(SELECT beat_index FROM decoded_rr '
'WHERE device_id = ? AND ts_ms = ? AND beat_ts_ms = ?), '
'(SELECT COALESCE(MAX(beat_index) + 1, 0) '
'FROM decoded_rr WHERE device_id = ? AND ts_ms = ?)), ?, ?, ?, ?)',
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
[
deviceId,
recTs * 1000,
recTs,
deviceId,
recTs * 1000,
beatTs[i],
deviceId,
recTs * 1000,
recTs * 1000,
rr,
beatTs[i],
deviceFamily,
],
);
ops++;
}
return ops;
}
// SCOPED TO THE WRITING DEVICE (v47). Unscoped, this cleared every device's
// beats for the second — so a second band writing one row deleted the
// first band's R-R for that second, permanently (no raw copy is kept to
Expand All @@ -7991,7 +8050,6 @@ class LocalDb {
[deviceId, recTs * 1000],
);
}
final beatTs = beatTimesMs(recTs, decoded.tsSubsec, decoded.rrIntervalsMs);
var ops = 1;
for (var i = 0; i < decoded.rrIntervalsMs.length; i++) {
final rr = decoded.rrIntervalsMs[i];
Expand Down Expand Up @@ -9345,7 +9403,7 @@ class LocalDb {
// DIFFERENT devices sharing a second (or a byte-identical frame, the
// exact case the v51 rekey exists to preserve) must not collapse into
// one another.
final byDeviceRecTs = <(String, int), (RawRecord, Sample)>{};
final byDeviceRecTs = <(String, int), List<(RawRecord, Sample)>>{};
for (final r in rows) {
final deviceId =
preArchiveDeviceKey ? kPrimaryDeviceId : r['device_id'] as String;
Expand All @@ -9366,7 +9424,15 @@ class LocalDb {
// is the decoded timestamp — and a record with no plausible time has
// nowhere to land in a table keyed by one.
if (recTs <= 0) continue;
byDeviceRecTs[(deviceId, recTs)] = (raw, s);
(byDeviceRecTs[(deviceId, recTs)] ??= []).add((raw, s));
}
// Oldest record first inside a second, so the newest is the one whose
// 1 Hz row stays and every record's beats are merged in.
for (final l in byDeviceRecTs.values) {
l.sort((a, b) {
final c = (a.$2.tsSubsec ?? 0).compareTo(b.$2.tsSubsec ?? 0);
return c != 0 ? c : a.$1.counter.compareTo(b.$1.counter);
});
}
if (byDeviceRecTs.isEmpty) {
if (budget != null && clock.elapsed > budget) {
Expand Down Expand Up @@ -9435,22 +9501,36 @@ class LocalDb {
final batch = ex.batch();
var queued = 0;
for (final e in byDeviceRecTs.entries) {
if (taken.contains(e.key)) continue;
final t = e.key.$2;
if (excluded.any((w) => t >= w.$1 && t < w.$2)) continue;
final (raw, sample) = e.value;
// `sample` is handed back as `preferred` so the hex is decoded once,
// not twice; `_queueDecodedOneHz` returns it straight back out.
// `deviceFamily` is deliberately omitted — see the doc comment.
if (_queueDecodedOneHz(
batch,
raw,
sample,
deviceId: e.key.$1,
preDeviceKey: preDeviceKey,
) >
0) {
queued++;
for (final (raw, sample) in e.value) {
if (taken.contains(e.key)) {
// The second already has its 1 Hz row, which a replay never
// evicts. A record that sits beside it keeps its own beats
// though: they are merged by beat time, so this adds nothing
// the second does not already hold and drops nothing it does.
if (!preDeviceKey &&
sample.rrIntervalsMs.isNotEmpty &&
_queueRrBeats(batch, t, sample,
deviceId: e.key.$1, mergeOnly: true) >
1) {
queued++;
}
continue;
}
// `sample` is handed back as `preferred` so the hex is decoded
// once, not twice; `_queueDecodedOneHz` returns it straight back
// out. `deviceFamily` is deliberately omitted, see the doc comment.
if (_queueDecodedOneHz(
batch,
raw,
sample,
deviceId: e.key.$1,
preDeviceKey: preDeviceKey,
) >
0) {
queued++;
}
}
}
if (queued > 0) await batch.commit(noResult: true);
Expand Down
186 changes: 186 additions & 0 deletions test/decoded_rr_same_second_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
// Two WHOOP 4 v24 records can share one Unix second (they are 0.9614 s apart).
// decoded_onehz keeps one row per second (newest wins), but the R-R beats of
// both records are kept: merged by beat time, so a re-offload is idempotent.
//
// The pair: counters 32324863 / 32324864, second 1775395280, sub-seconds 816
// and 32320; the first carries R-R 569 and 903 ms, the second none.

import 'dart:typed_data';

import 'package:flutter_test/flutter_test.dart';
import 'package:openstrap_protocol/openstrap_protocol.dart' as proto;
import 'package:path/path.dart' as p;
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:openstrap_edge/data/db.dart';
import 'package:openstrap_edge/data/models.dart';

const _base =
'2f1805f13ced01c261d2698848805454016202d802f5010000000000609f0fff80de233d'
'3dda19be5c87a9be7b14803f0020dc463dda19be5c87a9be7b14803f16028402bc028602'
'5e01000b010c020c0000000000370001510c000000000000';
const _ts = 1775395280;

String _frame(int counter, int subsec, List<int> rr) {
final b = Uint8List.fromList(proto.hexToBytes(_base));
final v = b.buffer.asByteData();
v.setUint32(3, counter, Endian.little);
v.setUint32(7, _ts, Endian.little);
v.setUint16(11, subsec, Endian.little);
b[18] = rr.length;
for (var i = 0; i < rr.length; i++) {
v.setInt16(19 + 2 * i, rr[i], Endian.little);
}
return b.map((x) => x.toRadixString(16).padLeft(2, '0')).join();
}

final _first = _frame(32324863, 816, [569, 903]);
final _second = _frame(32324864, 32320, []);
final _third = _frame(32324865, 20000, [800]);

RawRecord _raw(int counter, String hex) => RawRecord(
counter: counter,
packetType: 0x2F,
hex: hex,
capturedAt: _ts * 1000,
recTs: _ts,
);

Future<List<Map<String, Object?>>> _beats() async => (await LocalDb.instance)
.rawQuery('SELECT rr_ms, beat_ts_ms FROM decoded_rr WHERE rec_ts = ? '
'ORDER BY beat_ts_ms', [_ts]);

Future<void> _reset() async {
final db = await LocalDb.instance;
await db.delete('decoded_rr');
await db.delete('decoded_onehz');
await db.delete(LocalDb.rawArchiveTable);
}

void main() {
setUpAll(() async {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
LocalDb.dbName = 'openstrap_decoded_rr_same_second_test.db';
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));
});

setUp(_reset);

void expectTwoBeats(List<Map<String, Object?>> rows) {
expect([for (final r in rows) r['rr_ms']], [569, 903]);
expect(rows[0]['beat_ts_ms'], lessThan(rows[1]['beat_ts_ms'] as int));
}

Future<List<Object?>> indices() async => [
for (final r in await (await LocalDb.instance).rawQuery(
'SELECT beat_index FROM decoded_rr WHERE rec_ts = ? '
'ORDER BY beat_index', [_ts]))
r['beat_index'],
];

for (final (name, order) in const [
('in order', [0, 1]),
('reversed', [1, 0]),
]) {
test('live ingest $name, then again: exactly two beats, one row', () async {
final recs = [(32324863, _first), (32324864, _second)];
for (var pass = 0; pass < 2; pass++) {
for (final i in order) {
await LocalDb.insertRecord(_raw(recs[i].$1, recs[i].$2), null);
}
expectTwoBeats(await _beats());
final db = await LocalDb.instance;
expect(
(await db.rawQuery('SELECT COUNT(*) AS n FROM decoded_onehz '
'WHERE rec_ts = ?', [_ts])).single['n'],
1,
reason: 'one 1 Hz row per second');
}
});
}

test('A, C, A again leaves dense beat indices (the restore merge needs them)',
() async {
for (final (c, h) in [
(32324863, _first),
(32324865, _third),
(32324863, _first),
]) {
await LocalDb.insertRecord(_raw(c, h), null);
}
expect((await _beats()).length, 3);
expect(await indices(), [0, 1, 2]);
});

test('a batch ingest of the pair keeps both records beats', () async {
await LocalDb.insertRecordsBatch(
[_raw(32324863, _first), _raw(32324864, _second)],
[null, null],
);
expectTwoBeats(await _beats());
});

test('a record with no sub-second still replaces its second', () async {
final db = await LocalDb.instance;
await db.insert('decoded_rr', {
'device_id': LocalDb.kPrimaryDeviceId,
'ts_ms': _ts * 1000,
'rec_ts': _ts,
'beat_index': 0,
'rr_ts_ms': _ts * 1000,
'rr_ms': 700,
});
// A pre-existing row with no beat time is replaced by the record's beats.
await LocalDb.insertRecord(_raw(32324863, _first), null);
expectTwoBeats(await _beats());
});

test('archive replay of the pair ends with two beats, and twice is the same',
() async {
final db = await LocalDb.instance;
for (final (c, h) in [(32324863, _first), (32324864, _second)]) {
await LocalDb.archiveRawRecord(ArchiveRecord(
counter: c,
hex: h,
packetType: 0x2F,
capturedAt: _ts * 1000,
reason: 'undecodable_rec_v24',
));
}
await LocalDb.redriveArchivedRecords(db);
expectTwoBeats(await _beats());
await LocalDb.redriveArchivedRecords(db);
expectTwoBeats(await _beats());
expect(
(await db.rawQuery('SELECT COUNT(*) AS n FROM decoded_onehz '
'WHERE rec_ts = ?', [_ts])).single['n'],
1);
});

test('archive replay adds a neighbour beats to a second already decoded',
() async {
final db = await LocalDb.instance;
// The second was decoded live (record two, no beats), the first record
// only sits in the archive.
await LocalDb.insertRecord(_raw(32324864, _second), null);
expect(await _beats(), isEmpty);
await LocalDb.archiveRawRecord(ArchiveRecord(
counter: 32324863,
hex: _first,
packetType: 0x2F,
capturedAt: _ts * 1000,
reason: 'undecodable_rec_v24',
));
await LocalDb.redriveArchivedRecords(db);
expectTwoBeats(await _beats());
await LocalDb.redriveArchivedRecords(db);
expectTwoBeats(await _beats());
});
}
Loading