task(#937): B2+B3 path history and delivery observations per radio

Both scoped by the device-key prefix, and the legacy untagged data deleted
per the owner's decision 1 rather than orphaned.

**#854 path history: per radio AND out of SharedPreferences.** Two changes in
one migration, because doing them separately means two migrations over the
same data. The key was prefix + contact, so a route measured by a 1 W
handheld was applied to a repeater and the reverse. It now lives in drift as
prefix + device key + contact.

The move out of prefs is not gold-plating: that one store held 2,092 keys and
86% of a 4.28 MB file, and every prefs write on Windows re-encodes the whole
file (#923). This resolves #924 and makes every unrelated settings write
cheaper in proportion.

**#856 delivery observations: per radio, staying in prefs.** A repeater's
45-second deliveries were training the ACK-timeout model a 1 W handheld then
used. One small key, 3,091 bytes and 14 entries on the owner's install, so
unlike path history there is no cost argument for moving it and a move would
be churn.

**The legacy purge is chunked, and that is measured rather than guessed.**
Each prefs `remove` re-encodes and rewrites the whole file, so I measured the
real sequence against the owner's live prefs before designing it: 2,092 keys,
12.7 s of total work, mean 6.1 ms, but 32 ms for the first removal and under
1 ms by the last, because the file collapses from 4.28 MB to 45 KB as it
goes. I had assumed ~57 s and was wrong; it is tractable.

One unbroken pass would still block for 12.7 s, well past the 5 s watchdog,
which is the exact failure #917 just fixed. So it yields every 20 removals.
It runs after the startup loads so it never delays first paint, and it is
idempotent: no writes once there is nothing left, so running it on every
connect is safe.

Legacy and new cannot be confused, which is what makes the purge safe: the
new scheme writes to drift and the legacy keys are in prefs, so no length or
shape heuristic is needed to tell them apart. That is decision 2 making
decision 1 unambiguous.

**Wiring:** StorageService is shared with PathHistoryService and
TimeoutPredictionService, so the connector cannot own it like the other
per-radio stores. It is injected from main() and fed the device key on
SELF_INFO alongside them. Unset, both surfaces load nothing and never write,
so a read before the handshake cannot serve another radio's data (#754
precedent).

**Tests: Epic A's bleed tests inverted, 11 of them.** Every expectation that
demanded the bleed now demands isolation, and the before/after is the git
history of one file. Plus the purges: prefix-only, idempotent, and the
scoped data surviving the purge of the unscoped.

**Not done, and flagged rather than dropped:** the plan's B2 also said "bound
what persists to what PathHistoryService actually caches". That bound existed
to stop the prefs file growing. In drift a write costs one row and growth
costs nothing per write, so the bound would now delete regenerable route
history for no benefit. Skipping it is a judgement, not an oversight, and it
is called out here and in the PR.

The inventory's known-holes set is empty for the first time: {854, 855, 856}
at Epic B's start, then {854, 856} after B1, now none. An Epic A sanity
assertion that holes must exist failed on that and was corrected, because the
invariant that matters is conditional: if a hole is declared it must name an
issue, and empty satisfies it.

Citadel: meshcore-open-0z3, meshcore-open-z8t
Refs #937, #854, #856, #924, #853

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
feat/938-blocked-per-radio
diffwireauto 1 month ago committed by Benjamin Wiechel
parent a7882b62e0
commit a475cc21b4

@ -29,6 +29,7 @@ import '../helpers/cayenne_lpp.dart';
import '../helpers/path_helper.dart';
import '../services/app_debug_log_service.dart';
import '../services/ble_debug_log_service.dart';
import '../services/storage_service.dart';
import '../services/linux_ble_error_classifier.dart';
import '../services/linux_ble_pairing_service_stub.dart'
if (dart.library.io) '../services/linux_ble_pairing_service.dart';
@ -577,6 +578,15 @@ class MeshCoreConnector extends ChangeNotifier {
final ContactDiscoveryStore _discoveryContactStore = ContactDiscoveryStore();
final ChannelStore _channelStore = ChannelStore();
final UnreadStore _unreadStore = UnreadStore();
/// Injected from `main()`, because `StorageService` is shared with
/// `PathHistoryService` and `TimeoutPredictionService` and so cannot be
/// owned here like the stores above.
///
/// Needed since #854 and #856: path history and delivery observations are
/// per-radio now, so this service needs the device key on connect like
/// every other per-radio store.
StorageService? storageService;
List<Channel> _cachedChannels = [];
final Map<int, bool> _channelCyr2LatEnabled = {};
final Map<int, String?> _channelCyr2LatProfileId = {};
@ -6800,6 +6810,11 @@ class MeshCoreConnector extends ChangeNotifier {
// they don't bleed across radios on one host (#754). The startup load that
// follows clears and reloads the in-memory list from this radio's key.
_discoveryContactStore.setPublicKeyHex = selfPublicKeyHex;
// Path history and delivery observations, same reasoning (#854, #856): a
// route or an ACK timing is what THIS radio measured. Unset, both load
// nothing and never write, so a read before this point cannot serve
// another radio's data.
storageService?.setPublicKeyHex = selfPublicKeyHex;
// Now that we have self info, we can load all the persisted data for this
// node. Each step is timed: this sequence has stalled the UI isolate for
@ -6833,6 +6848,24 @@ class MeshCoreConnector extends ChangeNotifier {
await step('channelMessages', () => loadAllChannelMessages());
await step('unreadState', loadUnreadState);
await step('discoveredContacts', _loadDiscoveredContactCache);
// One-time cleanup of the pre-#854/#856 untagged keys, after the loads so
// it never delays first paint. Both are no-ops once done, so this is safe
// to run on every connect, and both chunk or are small enough not to
// block: the path-history purge measured 12.7 s of total work on the
// owner's 2,092 keys and yields every 20 removals (plan decision 1).
await step('purgeLegacyStorage', () async {
final removed = await storageService?.purgeLegacyPathHistory() ?? 0;
final hadObs =
await storageService?.purgeLegacyDeliveryObservations() ?? false;
if (removed > 0 || hadObs) {
appLogger.info(
'Legacy storage purge: $removed path-history keys, '
'${hadObs ? "the" : "no"} global observation list (#854, #856)',
tag: 'Storage',
);
}
});
}
/// Extract the additive `offband_caps` byte from a device-info reply.

@ -85,6 +85,12 @@ void main() async {
// Initialize services
final storage = StorageService();
final connector = MeshCoreConnector();
// StorageService is shared with PathHistoryService and
// TimeoutPredictionService, so the connector cannot own it the way it owns
// the other per-radio stores. It still needs the device key on connect,
// because path history and delivery observations are per-radio now
// (#854, #856).
connector.storageService = storage;
final pathHistoryService = PathHistoryService(storage);
final meshTopologyService = MeshTopologyService();
final retryService = MessageRetryService();

@ -1,7 +1,9 @@
import 'dart:convert';
import '../models/delivery_observation.dart';
import '../models/path_history.dart';
import '../storage/drift/blob_store.dart';
import '../storage/prefs_manager.dart';
import '../utils/app_logger.dart';
class StorageService {
static const String _pathHistoryPrefix = 'path_history_';
@ -42,47 +44,127 @@ class StorageService {
await prefs.setString(_repeaterAutoClockSyncAfterLoginKey, jsonStr);
}
/// First 10 hex of the connected radio's public key, like every per-radio
/// store. Set on connect.
///
/// Path history is what THIS radio learned about reaching a contact. Keyed
/// by contact alone (the pre-#854 scheme) a route measured by a 1 W handheld
/// was applied to a repeater, and the reverse.
String publicKeyHex = '';
set setPublicKeyHex(String value) =>
publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
String _pathKey(String contactPubKeyHex) =>
'$_pathHistoryPrefix$publicKeyHex$contactPubKeyHex';
/// Per-radio, and in drift rather than SharedPreferences (#854, #924).
///
/// Two changes in one migration, because doing them separately would mean
/// two migrations over the same data. Prefs is a settings store: on Windows
/// every write re-encodes and rewrites the whole file, and this one store
/// held 2,092 keys and 86% of a 4.28 MB file, which made every unrelated
/// settings write cost ~32 ms (#923).
///
/// With no radio key set this loads nothing and never writes, so it cannot
/// read or clobber anything. That is the #754 precedent.
Future<void> savePathHistory(
String contactPubKeyHex,
ContactPathHistory history,
) async {
final prefs = PrefsManager.instance;
final key = '$_pathHistoryPrefix$contactPubKeyHex';
final jsonStr = jsonEncode(history.toJson());
await prefs.setString(key, jsonStr);
if (publicKeyHex.isEmpty) return;
await BlobStore.instance.write(
_pathKey(contactPubKeyHex),
jsonEncode(history.toJson()),
);
}
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async {
final prefs = PrefsManager.instance;
final key = '$_pathHistoryPrefix$contactPubKeyHex';
final jsonStr = prefs.getString(key);
if (jsonStr == null) return null;
if (publicKeyHex.isEmpty) return null;
final jsonStr = await BlobStore.instance.read(_pathKey(contactPubKeyHex));
if (jsonStr == null || jsonStr.isEmpty) return null;
try {
final json = jsonDecode(jsonStr) as Map<String, dynamic>;
return ContactPathHistory.fromJson(contactPubKeyHex, json);
} catch (e) {
appLogger.error(
'Failed to decode path history for $contactPubKeyHex: $e',
tag: 'Storage',
);
return null;
}
}
Future<void> clearPathHistory(String contactPubKeyHex) async {
final prefs = PrefsManager.instance;
final key = '$_pathHistoryPrefix$contactPubKeyHex';
await prefs.remove(key);
if (publicKeyHex.isEmpty) return;
await BlobStore.instance.delete(_pathKey(contactPubKeyHex));
}
/// Clears this radio's path history only. Another radio's routes are not
/// touched, which they were before #854 because the key had no radio in it.
Future<void> clearAllPathHistories() async {
if (publicKeyHex.isEmpty) return;
final mine = '$_pathHistoryPrefix$publicKeyHex';
for (final key in await BlobStore.instance.keysWithPrefix(mine)) {
await BlobStore.instance.delete(key);
}
}
/// Removes the pre-#854 untagged `path_history_<contact>` keys from
/// SharedPreferences, a chunk at a time, yielding between chunks.
///
/// These cannot be migrated: the key records which CONTACT a route reaches
/// and never which radio measured it, so attributing them to a radio would
/// be a guess. The owner's decision (plan §9, decision 1) is to delete them
/// rather than orphan them, because routes relearn in normal use and here
/// the orphaned data is itself the performance problem.
///
/// Chunked because each `remove` re-encodes and rewrites the whole prefs
/// file. Measured against the owner's real file: 2,092 keys, **12.7 s of
/// total work**, mean 6.1 ms, but 32 ms for the first removal and under
/// 1 ms by the last, because the file collapses from 4.28 MB to 45 KB as it
/// goes. One unbroken pass would block for 12.7 s, well past the 5 s
/// watchdog, which is the very failure #917 just fixed. [chunkSize] keeps
/// any single block near 20 removals' worth and the yield lets the UI
/// breathe between them.
///
/// Returns how many keys it removed. Safe to call repeatedly: when there is
/// nothing left it does no writes at all.
Future<int> purgeLegacyPathHistory({int chunkSize = 20}) async {
final prefs = PrefsManager.instance;
final keys = prefs.getKeys();
final pathHistoryKeys = keys.where(
(key) => key.startsWith(_pathHistoryPrefix),
// A legacy key is one in PREFS. The new scheme writes to drift, so the
// two backends cannot be confused and no length or shape heuristic is
// needed to tell them apart.
final legacy = prefs
.getKeys()
.where((k) => k.startsWith(_pathHistoryPrefix))
.toList();
if (legacy.isEmpty) return 0;
appLogger.info(
'Purging ${legacy.length} pre-#854 untagged path_history keys from '
'prefs, $chunkSize at a time. These record which contact a route '
'reaches and never which radio measured it, so they cannot be '
'attributed; routes relearn in normal use (#854, plan decision 1).',
tag: 'Storage',
);
for (final key in pathHistoryKeys) {
await prefs.remove(key);
var removed = 0;
for (var i = 0; i < legacy.length; i++) {
await prefs.remove(legacy[i]);
removed++;
if ((i + 1) % chunkSize == 0) {
// Let the UI isolate run. Without this the whole purge is one block.
await Future<void>.delayed(Duration.zero);
}
}
appLogger.info(
'Purged $removed legacy path_history keys. Every remaining prefs write '
'is now cheaper in proportion (#923).',
tag: 'Storage',
);
return removed;
}
/// Save a repeater password by public key hex
@ -133,17 +215,32 @@ class StorageService {
await prefs.remove(_repeaterPasswordsKey);
}
String get _observationsKey => '$_deliveryObservationsKey$publicKeyHex';
/// Per-radio (#856).
///
/// These feed the ACK-timeout prediction model. On one global key, a
/// repeater's 45-second deliveries trained the model a 1 W handheld then
/// used, and the reverse. Silent accuracy loss rather than a visible
/// failure, which is why nobody reported it.
///
/// Stays in SharedPreferences, unlike path history: this is one small key
/// (3,091 bytes and 14 entries on the owner's install), not 2,092 keys and
/// 86% of the file, so there is no cost argument for moving it and a move
/// would be churn.
Future<void> saveDeliveryObservations(
List<DeliveryObservation> observations,
) async {
if (publicKeyHex.isEmpty) return;
final prefs = PrefsManager.instance;
final jsonStr = jsonEncode(observations.map((o) => o.toJson()).toList());
await prefs.setString(_deliveryObservationsKey, jsonStr);
await prefs.setString(_observationsKey, jsonStr);
}
Future<List<DeliveryObservation>> loadDeliveryObservations() async {
if (publicKeyHex.isEmpty) return [];
final prefs = PrefsManager.instance;
final jsonStr = prefs.getString(_deliveryObservationsKey);
final jsonStr = prefs.getString(_observationsKey);
if (jsonStr == null) return [];
@ -153,12 +250,37 @@ class StorageService {
.map((e) => DeliveryObservation.fromJson(e as Map<String, dynamic>))
.toList();
} catch (e) {
appLogger.error(
'Failed to decode delivery observations: $e',
tag: 'Storage',
);
return [];
}
}
Future<void> clearDeliveryObservations() async {
if (publicKeyHex.isEmpty) return;
await PrefsManager.instance.remove(_observationsKey);
}
/// Removes the pre-#856 untagged global observation list.
///
/// One key, so no chunking is needed. Deleted rather than attributed to a
/// radio (plan §9, decision 1): it is a mixture of every radio's RF timing,
/// and mixed data is worse than no data for the model, which retrains from
/// live sends within normal use.
///
/// Returns true if there was one to remove.
Future<bool> purgeLegacyDeliveryObservations() async {
final prefs = PrefsManager.instance;
if (!prefs.containsKey(_deliveryObservationsKey)) return false;
await prefs.remove(_deliveryObservationsKey);
appLogger.info(
'Purged the pre-#856 global delivery-observation list. It mixed every '
'radio\'s RF timing, so it is deleted rather than attributed; the '
'model retrains per radio from live sends (#856).',
tag: 'Storage',
);
return true;
}
}

@ -171,23 +171,25 @@ const List<StorageSurface> storageSurfaces = [
// ---------------------------------------------------------------------------
StorageSurface(
'path_history_',
verdict: ScopingVerdict.knownHole,
issue: 854,
verdict: ScopingVerdict.perRadio,
reason:
'keyed by contact public key only, with no radio in the key, so a '
'learned mesh route bleeds between any two radios that share a '
'contact. Also unbounded at 2,041 keys and 86% of the prefs file '
'(#924), while PathHistoryService caches only 50',
'prefix + device key + contact key, in DRIFT, since #854 and #924. '
'Was keyed by contact alone in prefs, so a route measured by a 1 W '
'handheld was applied to a repeater. The move out of prefs went with '
'the scoping because that one store held 2,092 keys and 86% of a '
'4.28 MB file, and every prefs write re-encodes the whole file '
'(#923). Unset key loads nothing and never writes',
owner: 'lib/services/storage_service.dart',
),
StorageSurface(
'delivery_observations',
verdict: ScopingVerdict.knownHole,
issue: 856,
verdict: ScopingVerdict.perRadio,
reason:
'one global list feeding the ACK-timeout ML model, so one radio\'s '
'RF timing trains another radio\'s predictions. Silent accuracy loss, '
'which is why it was never reported',
'prefix + device key since #856. Was one global list, so a '
'repeater\'s 45-second deliveries trained the ACK-timeout model a '
'1 W handheld then used. Stays in prefs unlike path history: one '
'small key, 3,091 bytes and 14 entries on the owner\'s install, so '
'there is no cost argument for moving it',
owner: 'lib/services/storage_service.dart',
),
// `pending_messages` (#855) was listed here and is GONE, not reclassified.

@ -1,31 +1,37 @@
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/delivery_observation.dart';
import 'package:meshcore_open/models/path_history.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/services/timeout_prediction_service.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// #936 A2: the two remaining bleeds, reproduced against the real store.
/// #937 B2 and B3: the two bleeds, now isolated.
///
/// **These assert the BUG on purpose.** They are characterization tests: they
/// pin exactly what bleeds today so Epic B (#937) has something concrete to
/// invert, and so the bleed cannot be quietly half-fixed. Each one names the
/// issue it characterizes and says what Epic B replaces it with.
/// These were written in Epic A (#936) asserting the BUG, so Epic B had
/// something concrete to invert rather than a prose description. This is that
/// inversion: every expectation that previously demanded the bleed now demands
/// isolation, and the before/after is in the git history of this one file.
///
/// Why characterization rather than genuinely-failing tests, which is what the
/// plan's A2 asked for: a red test cannot merge, and Epic A's PR has to land
/// before Epic B starts. These demonstrate the bleed just as concretely and go
/// red the moment it stops, which is the property that matters.
///
/// They use the REAL `StorageService` against real prefs, not the
/// `FakeStorageService` the existing path-history tests use, because the defect
/// is in the KEY rather than in the service logic. A fake would hide it.
/// Still against the REAL `StorageService` rather than a fake, because the
/// defect was in the key and a fake would have hidden it.
void main() {
late OffbandDatabase db;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
});
tearDown(() async {
await db.close();
BlobStore.clearTestOverride();
});
PathRecord record(int hops, int ms) => PathRecord(
@ -38,79 +44,114 @@ void main() {
failureCount: 0,
);
group('#854 path history bleeds between radios', () {
test('BUG: the stored key carries no radio, only the contact '
'(Epic B scopes it)', () async {
final storage = StorageService();
await storage.savePathHistory(
'cafebabe',
ContactPathHistory(
contactPubKeyHex: 'cafebabe',
recentPaths: [record(2, 500)],
),
StorageService radio(String key) =>
StorageService()..setPublicKeyHex = key * 20;
ContactPathHistory history(String contact, int hops, int ms) =>
ContactPathHistory(
contactPubKeyHex: contact,
recentPaths: [record(hops, ms)],
);
final keys = PrefsManager.instance
.getKeys()
.where((k) => k.contains('path_history_'))
.toList();
group('#854 path history is per radio', () {
test('the key carries the radio, not just the contact', () async {
await radio('a').savePathHistory('cafebabe', history('cafebabe', 2, 500));
final keys = await BlobStore.instance.keysWithPrefix('path_history_');
expect(keys.length, 1, reason: 'one contact, one key');
expect(keys.length, 1);
expect(
keys.single,
contains('path_history_cafebabe'),
'path_history_aaaaaaaaaacafebabe',
reason:
'the key is prefix + contact. There is no radio in it, '
'which IS the bug: any radio that shares this contact reads '
'and overwrites the same route',
'prefix + radio + contact. Before #854 this was '
'path_history_cafebabe, with no radio in it',
);
});
test('BUG: a route learned under radio A is served to radio B '
'(Epic B isolates them)', () async {
// Nothing here distinguishes the radios, because the store offers no
// way to: `savePathHistory` takes a contact and nothing else. That is
// the defect, demonstrated rather than described. Two StorageService
// instances standing in for two connected radios share one row.
final radioA = StorageService();
final radioB = StorageService();
await radioA.savePathHistory(
'cafebabe',
ContactPathHistory(
contactPubKeyHex: 'cafebabe',
recentPaths: [record(7, 9000)],
),
test('a route learned by radio A is NOT served to radio B', () async {
await radio(
'a',
).savePathHistory('cafebabe', history('cafebabe', 7, 9000));
final seenByB = await radio('b').loadPathHistory('cafebabe');
expect(
seenByB,
isNull,
reason:
'the 7-hop route radio A measured must not reach radio B. '
'This asserted hopCount == 7 before Epic B',
);
});
final seenByB = await radioB.loadPathHistory('cafebabe');
test('each radio keeps its own route to the same contact', () async {
await radio('a').savePathHistory('cafebabe', history('cafebabe', 2, 400));
await radio(
'b',
).savePathHistory('cafebabe', history('cafebabe', 7, 9000));
expect(
seenByB?.recentPaths.single.hopCount,
(await radio(
'a',
).loadPathHistory('cafebabe'))!.recentPaths.single.hopCount,
2,
);
expect(
(await radio(
'b',
).loadPathHistory('cafebabe'))!.recentPaths.single.hopCount,
7,
);
});
test('an unset radio key loads nothing and writes nothing', () async {
final unset = StorageService();
await unset.savePathHistory('cafebabe', history('cafebabe', 2, 400));
expect(await unset.loadPathHistory('cafebabe'), isNull);
expect(
await BlobStore.instance.keysWithPrefix('path_history_'),
isEmpty,
reason:
'radio B sees a 7-hop route it never learned. A route '
'measured by a 1 W handheld is applied to a repeater. After '
'Epic B this must be null for radio B',
'the #754 precedent: with no radio connected it must not '
'write an unscoped key that a later radio could pick up',
);
});
test('clearing one radio does not touch another', () async {
await radio('a').savePathHistory('cafebabe', history('cafebabe', 2, 400));
await radio(
'b',
).savePathHistory('cafebabe', history('cafebabe', 7, 9000));
await radio('a').clearAllPathHistories();
expect(await radio('a').loadPathHistory('cafebabe'), isNull);
expect(
await radio('b').loadPathHistory('cafebabe'),
isNotNull,
reason:
'clearAllPathHistories was global before #854 and would have '
'taken radio B\'s routes with it',
);
});
});
group('#856 delivery observations bleed between radios', () {
test('BUG: observations live under one global key '
'(Epic B scopes it)', () async {
final storage = StorageService();
await storage.saveDeliveryObservations([
DeliveryObservation(
contactKey: 'cafebabe',
pathLength: 3,
messageBytes: 100,
secondsSinceLastRx: 10,
isFlood: false,
deliveryMs: 2500,
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000),
),
]);
group('#856 delivery observations are per radio', () {
DeliveryObservation obs(int ms, int hops) => DeliveryObservation(
contactKey: 'cafebabe',
pathLength: hops,
messageBytes: 100,
secondsSinceLastRx: 10,
isFlood: false,
deliveryMs: ms,
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000),
);
test('the key carries the radio', () async {
await radio('a').saveDeliveryObservations([obs(2500, 3)]);
final keys = PrefsManager.instance
.getKeys()
@ -119,50 +160,139 @@ void main() {
expect(keys.length, 1);
expect(
keys.single.endsWith('delivery_observations'),
keys.single.endsWith('delivery_observations${'a' * 10}'),
isTrue,
reason:
'no radio component. Every radio trains on, and pollutes, '
'the same ACK-timeout model',
reason: 'before #856 this was the bare key, shared by every radio',
);
});
test('BUG: one radio\'s RF timing reaches another radio\'s model '
'(Epic B isolates them)', () async {
// A slow, many-hop repeater observation, then a fresh service standing
// in for a different radio. It inherits the other radio's timing.
await StorageService().saveDeliveryObservations([
DeliveryObservation(
contactKey: 'cafebabe',
pathLength: 7,
messageBytes: 100,
secondsSinceLastRx: 10,
isFlood: false,
deliveryMs: 45000,
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000),
),
]);
final otherRadio = TimeoutPredictionService(StorageService());
await otherRadio.initialize();
test(
'one radio\'s RF timing does NOT reach another radio\'s model',
() async {
// A repeater's slow 45-second delivery.
await radio('a').saveDeliveryObservations([obs(45000, 7)]);
final otherRadio = TimeoutPredictionService(radio('b'));
await otherRadio.initialize();
expect(
otherRadio.observationCount,
0,
reason:
'radio B has sent nothing, so it must start with no training '
'data. This asserted 1 before Epic B',
);
},
);
test('each radio trains on its own observations', () async {
await radio('a').saveDeliveryObservations([obs(45000, 7)]);
await radio('b').saveDeliveryObservations([obs(800, 1), obs(900, 1)]);
final a = TimeoutPredictionService(radio('a'));
final b = TimeoutPredictionService(radio('b'));
await a.initialize();
await b.initialize();
expect(a.observationCount, 1);
expect(b.observationCount, 2);
});
});
group('legacy purges (plan decision 1: delete, do not orphan)', () {
test(
'untagged path-history keys are removed, scoped ones are not',
() async {
// Pre-#854 keys live in PREFS; the new scheme writes to drift, so the
// two cannot be confused and no shape heuristic is needed.
SharedPreferences.setMockInitialValues({
'flutter.path_history_aaaa': '{}',
'flutter.path_history_bbbb': '{}',
'flutter.unrelated_setting': 'keep me',
});
PrefsManager.reset();
await PrefsManager.initialize();
final storage = radio('a');
await storage.savePathHistory('cafebabe', history('cafebabe', 2, 400));
final removed = await storage.purgeLegacyPathHistory(chunkSize: 1);
expect(removed, 2);
expect(
PrefsManager.instance.getKeys().where(
(k) => k.contains('path_history_'),
),
isEmpty,
);
expect(
PrefsManager.instance.getString('unrelated_setting'),
'keep me',
reason: 'the purge must touch only its own prefix',
);
expect(
await storage.loadPathHistory('cafebabe'),
isNotNull,
reason: 'the drift-side scoped history survives the prefs purge',
);
},
);
test('purging twice is a no-op, not an error', () async {
SharedPreferences.setMockInitialValues({
'flutter.path_history_aaaa': '{}',
});
PrefsManager.reset();
await PrefsManager.initialize();
final storage = radio('a');
expect(await storage.purgeLegacyPathHistory(), 1);
expect(
otherRadio.observationCount,
1,
await storage.purgeLegacyPathHistory(),
0,
reason:
'this radio has sent nothing, yet it starts with another '
'radio\'s 45-second observation in its training data. After '
'Epic B this must be 0',
'it runs on every connect, so it has to be idempotent and '
'do no writes when there is nothing left',
);
});
});
// #855's round-trip test was here and is gone with the API it pinned (B1).
// Its job was to prove the thing being deleted actually worked, so the
// deletion was provably removal of dead code and not of a live feature. It
// served that purpose and then became a test of nothing.
//
// What still guards the deletion: the inventory's "declared but vanished
// from source" check, which fails if `pending_messages` ever returns
// undeclared.
test(
'the global observation list is removed, the scoped one is not',
() async {
SharedPreferences.setMockInitialValues({
'flutter.delivery_observations': '[]',
});
PrefsManager.reset();
await PrefsManager.initialize();
final storage = radio('a');
await storage.saveDeliveryObservations([
DeliveryObservation(
contactKey: 'cafebabe',
pathLength: 1,
messageBytes: 10,
secondsSinceLastRx: 1,
isFlood: false,
deliveryMs: 100,
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000),
),
]);
expect(await storage.purgeLegacyDeliveryObservations(), isTrue);
expect(
PrefsManager.instance.containsKey('delivery_observations'),
isFalse,
);
expect(
(await storage.loadDeliveryObservations()).length,
1,
reason: 'this radio\'s own observations are not collateral',
);
expect(
await storage.purgeLegacyDeliveryObservations(),
isFalse,
reason: 'idempotent',
);
},
);
});
}

@ -46,7 +46,11 @@ void main() {
final holes = storageSurfaces.where(
(s) => s.verdict == ScopingVerdict.knownHole,
);
expect(holes, isNotEmpty, reason: 'sanity: the holes are the point');
// No `isNotEmpty` sanity check any more. Epic A had one, reasoning that
// "the holes are the point", and Epic B closing the last hole made it
// fail. The invariant that actually matters is conditional: IF a hole
// is declared, it must name an issue. An empty set satisfies that and
// is the desired end state.
for (final s in holes) {
expect(
s.issue,
@ -67,19 +71,27 @@ void main() {
);
});
test('the known holes are exactly the ones Epic B has left to fix', () {
// Pins the set. A NEW hole cannot hide among the known ones, and a hole
// Epic B has fixed cannot be left mislabelled here.
test('no known holes remain', () {
// This expectation shrank as Epic B landed: {854, 855, 856} at the
// start, then {854, 856} once B1 deleted the dead pending_messages
// surface, now empty. #855 was deleted, #854 and #856 are scoped per
// radio.
//
// #855 is absent on purpose: Epic B DELETED that surface rather than
// scoping it, so there is no hole left to track. This expectation
// shrinks as B1, B2 and B3 land, and reaching an empty set is what
// closing Epic B looks like.
// Empty is the state Epic B exists to reach, and the assertion stays so
// a future hole cannot be added quietly: adding one makes this fail
// until somebody deliberately changes the expectation.
final holes = {
for (final s in storageSurfaces)
if (s.verdict == ScopingVerdict.knownHole) s.issue!,
if (s.verdict == ScopingVerdict.knownHole) s.issue,
};
expect(holes, {854, 856});
expect(
holes,
isEmpty,
reason:
'every surface is now perRadio or globalOnPurpose with a '
'reason. A new hole here needs a deliberate decision, not a '
'silent label',
);
});
});

Loading…
Cancel
Save

Powered by TurnKey Linux.