From bf936068b732fdc22130b12a28100e3494d9728b Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:30:42 -0400 Subject: [PATCH] feat(#966): a durable audit of what the sweep deleted The owner asked whether the delete and compact are logged or silent. Checked rather than assumed, and the answer was bad on two counts: - A delete logged only a COUNT. "Cleared 40" names nothing, so there was no record of WHICH keys were reclaimed. Refusals were already logged properly, with the key and up to three missing records; deletions were not. - All of it goes through appLogger, which is gated on appDebugLogEnabled. That is off by default and off on his install, so on a normal install an irreversible delete left no trail at all. Both fixed. The summary now names the cleared and kept keys, and the sweep also writes a durable entry into the database itself, under __msgrows_reclaim_audit: timestamp, the cleared keys in full, the refused keys, and the byte counts either side. In the database because that survives restarts and the logging toggle, and can be read back without the app running, which is also how it gets verified on hardware. Key lists are stored in full. Truncating them would recreate the "Cleared 40" problem the entry exists to solve. Capped at the last 5 sweeps instead, which is generous given a key is cleared once and then has no blob to consider again, so this is close to a once-per-install operation. A failure to write the audit is logged and tolerated rather than failing the sweep: the deletes already happened and were each verified, so losing the record is worse than nothing but far better than reporting a correct sweep as broken. An unreadable audit likewise starts a fresh list and is logged, never silently replaced. scoping_inventory gained the key, globalOnPurpose: one sweep spans every radio and the entries name store keys that already carry the radio. Six tests: a sweep records which keys it deleted; the entry survives a fresh store object over the same database, so it is really on disk; refusals are recorded too; a sweep that did nothing writes no entry; the cap drops the oldest and keeps the newest; and an unreadable audit does not stop a sweep. Lands on Epic B's branch rather than Epic A's, where the sweep lives, to avoid restacking B over a changed A for a change that reaches dev through both either way. Origin is #965's engine. Full suite 1,489 pass, 1 skipped. analyze clean, format clean. Task: meshcore-open-gan Agent Mail: TealGlen Co-Authored-By: Claude Opus 5 --- lib/services/stale_history_sweep.dart | 24 ++++++- lib/storage/drift/blob_store.dart | 64 ++++++++++++++++++ lib/storage/scoping_inventory.dart | 11 +++ test/storage/stale_history_sweep_test.dart | 79 ++++++++++++++++++++++ 4 files changed, 177 insertions(+), 1 deletion(-) diff --git a/lib/services/stale_history_sweep.dart b/lib/services/stale_history_sweep.dart index 2b42e21d..09a9aea0 100644 --- a/lib/services/stale_history_sweep.dart +++ b/lib/services/stale_history_sweep.dart @@ -186,12 +186,34 @@ class StaleHistorySweep { } if (cleared.isNotEmpty || refused.isNotEmpty) { + // Names the keys, not just a count. "Cleared 40" is not an audit trail + // for a delete that cannot be undone. appLogger.info( 'Stale history sweep: cleared ${cleared.length}, kept ' '${refused.length} that could not be verified, ' - '${bytesBefore - bytesAfter} bytes returned.', + '${bytesBefore - bytesAfter} bytes returned.\n' + 'cleared: ${cleared.join(', ')}' + '${refused.isEmpty ? '' : '\nkept: ${refused.join(', ')}'}', tag: 'Storage', ); + + // And durably, because the log above is gated on the app-debug-logging + // setting, which is off by default. Without this an irreversible delete + // would leave no trail at all on a normal install. + try { + await _blobs.appendReclaimAudit( + at: at, + cleared: cleared, + refused: refused, + bytesBefore: bytesBefore, + bytesAfter: bytesAfter, + ); + } catch (e) { + appLogger.warn( + 'Could not write the reclaim audit entry: $e', + tag: 'Storage', + ); + } } return StaleHistoryOutcome( diff --git a/lib/storage/drift/blob_store.dart b/lib/storage/drift/blob_store.dart index 9d891e78..851dc462 100644 --- a/lib/storage/drift/blob_store.dart +++ b/lib/storage/drift/blob_store.dart @@ -480,6 +480,70 @@ class BlobStore { }); } + /// A durable record of what each reclaim sweep deleted (#962). + /// + /// Why this exists rather than relying on the log: `appLogger` is gated on + /// the app-debug-logging setting, which is **off by default**, so the only + /// trail of an irreversible delete would not exist on a normal install. And + /// the log previously recorded a count, never which keys went. "Cleared 40" + /// is not an audit trail. + /// + /// Written into the database itself, so it survives restarts and the logging + /// toggle, and can be read back without the app running. + static const String reclaimAuditKey = '__msgrows_reclaim_audit'; + + /// How many sweeps the audit keeps. A key is cleared once and then has no + /// blob to consider again, so this operation is close to once per install + /// and a handful of entries is a generous history rather than a stingy one. + static const int reclaimAuditEntries = 5; + + /// Appends one sweep's outcome to the audit, oldest entries dropped. + /// + /// The key lists are stored in full: naming what was deleted is the entire + /// point, and truncating them would recreate the "Cleared 40" problem. + Future appendReclaimAudit({ + required DateTime at, + required List cleared, + required List refused, + required int bytesBefore, + required int bytesAfter, + }) async { + await synchronized(reclaimAuditKey, () async { + final entries = await reclaimAudit(); + entries.add({ + 'at': at.toIso8601String(), + 'cleared': cleared, + 'refused': refused, + 'bytesBefore': bytesBefore, + 'bytesAfter': bytesAfter, + }); + while (entries.length > reclaimAuditEntries) { + entries.removeAt(0); + } + await write(reclaimAuditKey, jsonEncode(entries)); + }); + } + + /// The reclaim audit, oldest first. Empty when nothing has ever been swept. + Future>> reclaimAudit() async { + final raw = await read(reclaimAuditKey); + if (raw == null || raw.isEmpty) return >[]; + try { + return (jsonDecode(raw) as List) + .cast>() + .toList(); + } catch (e) { + // An unreadable audit must not stop a sweep, and must not be silently + // replaced either: it is logged and the next append starts a fresh list. + appLogger.error( + 'Could not decode the reclaim audit; the next sweep starts a new ' + 'one: $e', + tag: 'Storage', + ); + return >[]; + } + } + /// When [storeKey] migrated to rows, or null if it has not or is unstamped. Future messageRowsMigratedAt(String storeKey) async { final ms = (await _loadMigratedAt())[storeKey]; diff --git a/lib/storage/scoping_inventory.dart b/lib/storage/scoping_inventory.dart index 39c47d80..e0627a74 100644 --- a/lib/storage/scoping_inventory.dart +++ b/lib/storage/scoping_inventory.dart @@ -294,6 +294,17 @@ const List storageSurfaces = [ 'it into a map would put a migration on the hottest storage path', owner: 'lib/storage/drift/blob_store.dart', ), + StorageSurface( + '__msgrows_reclaim_audit', + verdict: ScopingVerdict.globalOnPurpose, + reason: + 'a durable record of what each stale-blob sweep deleted (#962). Global ' + 'because one sweep spans every radio and the entries name store keys, ' + 'which already carry the radio. It exists because the app log is gated ' + 'on a setting that is off by default, so an irreversible delete would ' + 'otherwise leave no trail at all; capped at the last few sweeps', + owner: 'lib/storage/drift/blob_store.dart', + ), ]; /// Constants that match the key shape but are not persistence keys. diff --git a/test/storage/stale_history_sweep_test.dart b/test/storage/stale_history_sweep_test.dart index 977620c1..366e84c7 100644 --- a/test/storage/stale_history_sweep_test.dart +++ b/test/storage/stale_history_sweep_test.dart @@ -369,6 +369,85 @@ void main() { }); }); + group('the audit trail', () { + test('a sweep records WHICH keys it deleted, durably', () async { + // The app log is gated on a setting that is off by default, so without + // this an irreversible delete leaves no trail on a normal install. And + // a count is not an audit trail. + await migratedDaysAgo(key, 31); + + final outcome = await StaleHistorySweep(blobs).run(); + expect(outcome.cleared, [key]); + + final audit = await blobs.reclaimAudit(); + expect(audit, hasLength(1)); + expect(audit.single['cleared'], [key]); + expect(audit.single['refused'], isEmpty); + expect(audit.single['bytesBefore'], outcome.bytesBefore); + expect(audit.single['bytesAfter'], outcome.bytesAfter); + expect(audit.single['at'], isA()); + }); + + test('it survives a fresh store object, so it is really on disk', () async { + await migratedDaysAgo(key, 31); + await StaleHistorySweep(blobs).run(); + + // A new BlobStore over the same database is what a restart looks like + // to storage. The audit has to come back. + final reopened = BlobStore(db); + expect((await reopened.reclaimAudit()).single['cleared'], [key]); + }); + + test('refusals are recorded too, not only deletions', () async { + await migratedDaysAgo(key, 31); + await blobs.deleteMessageRow( + key, + (await blobs.messageMergeKeys(key)).first, + ); + + await StaleHistorySweep(blobs).run(); + + final audit = await blobs.reclaimAudit(); + expect(audit.single['cleared'], isEmpty); + expect(audit.single['refused'], [key]); + }); + + test('a sweep that did nothing writes no entry', () async { + await migratedDaysAgo(key, 1); // inside the window + await StaleHistorySweep(blobs).run(); + expect(await blobs.reclaimAudit(), isEmpty); + }); + + test('it is capped, so it cannot grow without bound', () async { + for (var i = 0; i < BlobStore.reclaimAuditEntries + 3; i++) { + final k = 'channel_messages_aaaaaaaaaapsk_run$i'; + await migratedDaysAgo(k, 31, messages: 2); + await StaleHistorySweep(blobs).run(); + } + + final audit = await blobs.reclaimAudit(); + expect(audit, hasLength(BlobStore.reclaimAuditEntries)); + // Oldest dropped, newest kept. + expect( + audit.last['cleared'], + contains( + 'channel_messages_aaaaaaaaaapsk_run' + '${BlobStore.reclaimAuditEntries + 2}', + ), + ); + }); + + test('an unreadable audit does not stop a sweep', () async { + await blobs.write(BlobStore.reclaimAuditKey, 'not json'); + await migratedDaysAgo(key, 31); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.cleared, [key], reason: 'the sweep still has to work'); + expect((await blobs.reclaimAudit()).single['cleared'], [key]); + }); + }); + group('what the manual action relies on (#966)', () { test('olderThan zero makes a key migrated seconds ago eligible', () async { // The button passes Duration.zero, which is the whole point of it: no