From dadd659a94402b6da785e909f07d23719f0a7f40 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:20:00 -0400 Subject: [PATCH] fix(#850): live adverts feed discovery only, not the contact list A long-lived session drifted hundreds of contacts above radio truth (#838): the client promoted every overheard advert into the persisted contact list using only the radio's auto-add type policy, applying neither the radio's hop limit nor its capacity, and ignoring its eviction/full pushes. The firmware fires NEW_ADVERT (0x8A) and the raw RX firehose (0x88) even for adverts it rejects, so those became phantom contacts the next manual sync had to prune. Option A, sync is truth: the persisted contact list is populated only by the contact sync stream. Both live-advert paths now feed discovery only; a new advert whose type the radio would auto-add nudges a debounced incremental reconcile so a contact the radio actually stored still surfaces without a manual sync, while one it rejected simply never returns in the stream. The existing-contact path/GPS refresh and the reconnect full-sync prune are unchanged. The reconcile debounce (and the sibling channels-changed debounce) is cancelled on both disconnect paths so a timer scheduled against one radio can't fire against the next (pre-PR Gemini review finding). Epic #842. Build #850. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 88 ++++++--- .../connector/advert_discovery_only_test.dart | 185 ++++++++++++++++++ 2 files changed, 250 insertions(+), 23 deletions(-) create mode 100644 test/connector/advert_discovery_only_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index e4bb3896..44e95b3e 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -549,6 +549,7 @@ class MeshCoreConnector extends ChangeNotifier { bool _channelSyncInFlight = false; Timer? _channelSyncTimeout; Timer? _channelsChangedDebounce; + Timer? _advertReconcileDebounce; int _channelSyncRetries = 0; int _nextChannelIndexToRequest = 0; int _totalChannelsToRequest = 0; @@ -3505,6 +3506,10 @@ class MeshCoreConnector extends ChangeNotifier { _offbandCaps2 = null; _femLnaEnabled = null; _blockListRetryTimer?.cancel(); + // Per-connection debounce timers must die with the connection so a timer + // scheduled against this radio can't fire against the next one (#838 review). + _advertReconcileDebounce?.cancel(); + _channelsChangedDebounce?.cancel(); _blockDumpInFlight = false; _blockKeysTouchedDuringDump.clear(); _firmwareVersion = null; @@ -4012,6 +4017,31 @@ class MeshCoreConnector extends ChangeNotifier { await getContacts(since: _latestContactLastmod(), preserveExisting: true); } + /// True when the connected radio's own auto-add policy covers this contact + /// type, i.e. the radio would have stored a new advert of this type (subject + /// to its hop/capacity limits, which only the radio enforces). Mirrors the + /// radio's type policy so a reconcile is nudged only when the radio might + /// actually hold something new. (#838) + bool _isAutoAddEligible(int type) => + (_autoAddUsers && type == advTypeChat) || + (_autoAddRepeaters && type == advTypeRepeater) || + (_autoAddRoomServers && type == advTypeRoom) || + (_autoAddSensors && type == advTypeSensor); + + /// Coalesce a burst of new adverts into a single incremental contact sync so + /// a node the radio actually added surfaces without a manual sync, while a + /// node it rejected simply never comes back in the stream. (#838) + static const Duration _advertReconcileWindow = Duration(milliseconds: 800); + + void _scheduleContactReconcile() { + if (!isConnected || _isLoadingContacts) return; + _advertReconcileDebounce?.cancel(); + _advertReconcileDebounce = Timer(_advertReconcileWindow, () { + if (!isConnected || _isLoadingContacts) return; + unawaited(refreshContactsSinceLastmod()); + }); + } + /// The latest short full sync, kept until dismissed or a complete sync. ContactSyncShortfall? get contactSyncShortfall => _contactSyncShortfall; @@ -7441,25 +7471,30 @@ class MeshCoreConnector extends ChangeNotifier { 'After merge: pathOverride=${_contacts[existingIndex].pathOverride}, devicePath=${_pathDiag(_contacts[existingIndex].path, _contacts[existingIndex].pathLength, _contacts[existingIndex].pathHashWidth)}', tag: 'Connector', ); + } else if (isContact) { + // The contact sync stream is radio truth; it is the only thing that + // populates the persisted list. + _contacts.add(contact); + appLogger.info( + 'Added new contact ${contact.name}: pathLen=${_pathDiag(contact.path, contact.pathLength, contact.pathHashWidth)}', + tag: 'Connector', + ); } else { - if ((_autoAddUsers && contact.type == advTypeChat) || - (_autoAddRepeaters && contact.type == advTypeRepeater) || - (_autoAddRoomServers && contact.type == advTypeRoom) || - (_autoAddSensors && contact.type == advTypeSensor) || - isContact) { - _contacts.add(contact); - appLogger.info( - 'Added new contact ${contact.name}: pathLen=${_pathDiag(contact.path, contact.pathLength, contact.pathHashWidth)}', - tag: 'Connector', - ); - } else { - appLogger.info( - "Discovered contact ${contact.name} (type ${contact.typeLabelRaw}) not added due to auto-add settings", - tag: 'Connector', - ); - notifyListeners(); - return; - } + // #838: a live advert (NEW_ADVERT push) is NOT proof the radio stored + // the node. The firmware fires it even for adverts it rejects (beyond + // the auto-add hop limit, or when the contact table is full), and the + // client applies neither limit, so promoting them here drifted a + // long-lived session hundreds of contacts above radio truth. Keep it in + // discovery (added above) and, when the radio's own policy would have + // added it, nudge a reconcile so a genuinely-new contact still surfaces + // without a manual sync. + appLogger.info( + "Discovered contact ${contact.name} (type ${contact.typeLabelRaw}) left in discovery; not a synced contact", + tag: 'Connector', + ); + if (_isAutoAddEligible(contact.type)) _scheduleContactReconcile(); + notifyListeners(); + return; } _knownContactKeys.add(contact.publicKeyHex); _loadMessagesForContact(contact.publicKeyHex); @@ -9450,6 +9485,10 @@ class MeshCoreConnector extends ChangeNotifier { _notifySubscription = null; _connectionSubscription?.cancel(); _connectionSubscription = null; + // Per-connection debounce timers must not survive the drop and fire against + // the next radio (#838 review). + _advertReconcileDebounce?.cancel(); + _channelsChangedDebounce?.cancel(); _device = null; _rxCharacteristic = null; @@ -9610,6 +9649,7 @@ class MeshCoreConnector extends ChangeNotifier { _gpsLocationPollTimer?.cancel(); _radioStatsPollTimer?.cancel(); _channelsChangedDebounce?.cancel(); + _advertReconcileDebounce?.cancel(); _contactRequestWatchdog?.cancel(); _pendingKeyCheck?.timer?.cancel(); _recoverySettleTimer?.cancel(); @@ -9856,17 +9896,19 @@ class MeshCoreConnector extends ChangeNotifier { longitude: longitude, lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000), ); - if ((_autoAddUsers && type == advTypeChat) || - (_autoAddRepeaters && type == advTypeRepeater) || - (_autoAddRoomServers && type == advTypeRoom) || - (_autoAddSensors && type == advTypeSensor)) { - _handleContactAdvert(newContact); + // #838: a raw overheard advert is not proof the radio stored the node, so + // it never joins the persisted contact list (that is what drifted a long + // session above radio truth). It feeds discovery, and when the radio's own + // auto-add policy would have added it, a reconcile pulls the radio's real + // entry in. The persisted list stays a mirror of the contact sync. + if (_isAutoAddEligible(type)) { _handleDiscovery( newContact, rawPacket, noNotify: true, addActive: true, ); + _scheduleContactReconcile(); } else { _handleDiscovery(newContact, rawPacket); } diff --git a/test/connector/advert_discovery_only_test.dart b/test/connector/advert_discovery_only_test.dart new file mode 100644 index 00000000..d1843dda --- /dev/null +++ b/test/connector/advert_discovery_only_test.dart @@ -0,0 +1,185 @@ +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.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'; + +// #838 Option A (sync is truth): a live advert the client overhears must NOT be +// promoted into the persisted contact list (that is what drifted a long session +// above radio truth). It feeds discovery only, and nudges a reconcile so a +// contact the radio actually added still surfaces. Only the sync stream, which +// is radio truth, populates the contact list. +Uint8List _u32(int v) => + Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little); + +/// A contact-stream / NEW_ADVERT frame in the respCodeContact layout. +Uint8List _contactFrame( + int keyByte, + String name, { + int code = respCodeContact, +}) { + final b = BytesBuilder() + ..addByte(code) + ..add(List.filled(32, keyByte)) + ..addByte(advTypeChat) + ..addByte(0) // flags + ..addByte(0xFF) // flood path + ..add(List.filled(64, 0)) + ..add(Uint8List(32)..setRange(0, name.length, name.codeUnits)) + ..add(_u32(1790000000)) + ..add(_u32(0)) + ..add(_u32(0)) + ..add(_u32(1790000000)); + return b.toBytes(); +} + +/// A raw over-the-air advert wrapped in PUSH_CODE_LOG_RX_DATA (0x88), the +/// firehose the radio sends for everything it hears. routeType 0x01 keeps it +/// off the flood/direct transport-byte path. +Uint8List _rxAdvertFrame(int keyByte, String name) { + final header = (payloadTypeADVERT << 2) | 0x01; + final payload = BytesBuilder() + ..add(List.filled(32, keyByte)) + ..add(_u32(1790000000)) // timestamp + ..add(List.filled(64, 0)) // signature + ..addByte(advTypeChat | 0x80) // type + hasName + ..add(name.codeUnits) + ..addByte(0); // C-string terminator + return (BytesBuilder() + ..addByte(pushCodeLogRxData) + ..addByte(0) // snr + ..addByte(0) // rssi + ..addByte(header) + ..addByte(0) // pathLenRaw -> no path + ..add(payload.toBytes())) + .toBytes(); +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + connector = MeshCoreConnector(); + connector.contactsForTest.clear(); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.setConnectedForTest(); + // The radio's auto-add policy says chat nodes are eligible; pre-fix this is + // exactly what made the client promote every overheard chat advert. + connector.handleFrameForTest( + Uint8List.fromList([respCodeAutoAddConfig, autoAddChatFlag]), + ); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Set contactNames() => + connector.contactsForTest.map((c) => c.name).toSet(); + Set discoveredNames() => + connector.discoveredContactsForTest.map((c) => c.name).toSet(); + int getContactsRequests() => + sent.where((f) => f.isNotEmpty && f[0] == cmdGetContacts).length; + + test( + 'a NEW_ADVERT push for an unknown node stays out of the contact list', + () async { + connector.handleFrameForTest( + _contactFrame(0x44, 'Delta', code: pushCodeNewAdvert), + ); + await Future.delayed(Duration.zero); + + expect( + contactNames(), + isNot(contains('Delta')), + reason: 'a live advert must not be promoted to a persisted contact', + ); + expect( + discoveredNames(), + contains('Delta'), + reason: 'it belongs in discovery instead', + ); + }, + ); + + test( + 'a raw over-the-air advert (0x88) stays out of the contact list', + () async { + connector.handleFrameForTest(_rxAdvertFrame(0x55, 'Echo')); + await Future.delayed(Duration.zero); + + expect(contactNames(), isNot(contains('Echo'))); + expect(discoveredNames(), contains('Echo')); + }, + ); + + test( + 'an unknown auto-add-eligible advert nudges a contact reconcile', + () async { + final before = getContactsRequests(); + connector.handleFrameForTest( + _contactFrame(0x66, 'Foxtrot', code: pushCodeNewAdvert), + ); + // The reconcile is debounced; give it room to fire. + await Future.delayed(const Duration(milliseconds: 1200)); + + expect( + getContactsRequests(), + greaterThan(before), + reason: 'a new advert should pull the radio truth, not add locally', + ); + }, + ); + + test( + 'the contact sync stream still populates the list (sync is truth)', + () async { + await connector.getContacts(); + connector.handleFrameForTest( + Uint8List.fromList([respCodeContactsStart, ..._u32(1)]), + ); + connector.handleFrameForTest(_contactFrame(0x77, 'Golf')); + connector.handleFrameForTest( + Uint8List.fromList([respCodeEndOfContacts, ..._u32(0)]), + ); + await Future.delayed(Duration.zero); + + expect(contactNames(), contains('Golf')); + }, + ); + + test('a NEW_ADVERT for an EXISTING contact still refreshes it', () async { + await connector.getContacts(); + connector.handleFrameForTest( + Uint8List.fromList([respCodeContactsStart, ..._u32(1)]), + ); + connector.handleFrameForTest(_contactFrame(0x88, 'Hotel')); + connector.handleFrameForTest( + Uint8List.fromList([respCodeEndOfContacts, ..._u32(0)]), + ); + await Future.delayed(Duration.zero); + expect(contactNames(), contains('Hotel')); + + // A later advert for the same node must keep it (it is radio truth). + connector.handleFrameForTest( + _contactFrame(0x88, 'Hotel', code: pushCodeNewAdvert), + ); + await Future.delayed(Duration.zero); + expect(contactNames(), contains('Hotel')); + }); +}