fix(#671): never let a short contact sync overwrite saved contacts

A full contact sync cleared the app's list, then saved whatever the
radio streamed as the whole list. The owner's RAK declared 350 contacts
and streamed 106; the app kept the 106 and silently lost the rest,
favorites included (#660).

A full sync now leaves the local list in place and records which
contacts the radio delivered. Only a complete sync (received equals the
declared total) drops the contacts the radio no longer holds. A short
or undeclared sync merges what arrived, removes nothing, logs an error,
and retries once per connection. If the retry is short too, the
connector exposes a pending decision (keep local, default, or use the
radio's list) for the UI in #674.

Removes the now-dead _preserveContactsOnRefresh flag. Adds test-only
seams to feed frames and capture sent frames. Tests cover complete,
short, undeclared, retry bound, both decisions, mid-sync adverts and
incremental sync; with the old clear reinstated, 5 of them fail.

Epic #668.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/753/head
Strycher 2 months ago committed by Benjamin Wiechel
parent 2c7e21e484
commit c314663623

@ -241,6 +241,20 @@ class MeshCoreRadioStateSnapshot {
});
}
/// A full contact sync that delivered fewer contacts than the radio declared.
/// [declared] is null when the radio sent no total (older firmware).
class ContactSyncShortfall {
final int? declared;
final int received;
final int keptLocally;
const ContactSyncShortfall({
required this.declared,
required this.received,
required this.keptLocally,
});
}
class MeshCoreConnector extends ChangeNotifier {
// Message windowing to limit memory usage
static const int _messageWindowSize = 200;
@ -399,7 +413,6 @@ class MeshCoreConnector extends ChangeNotifier {
bool _pendingInitialQueuedMessageSync = false;
bool _bleInitialSyncStarted = false;
bool _webInitialHandshakeRequestSent = false;
bool _preserveContactsOnRefresh = false;
int _autoAddMaxHops = 0;
int _manualAddContactsRaw = 0;
bool _autoAddUsers = false;
@ -421,6 +434,16 @@ class MeshCoreConnector extends ChangeNotifier {
int? _contactSyncTotal;
int _contactSyncReceived = 0;
bool _contactSyncUsesSinceFilter = false;
// A full sync never clears the local list. It records which contacts the
// radio delivered, and only a complete sync (received == declared) may drop
// the ones it did not. A short sync once replaced the owner's 350 saved
// contacts with the 106 the radio sent (#660, #668).
bool _contactSyncIsFull = false;
int? _contactSyncDeclaredTotal;
final Set<String> _contactSyncDeliveredKeys = {};
bool _contactSyncRetryUsed = false;
bool _contactSyncDecisionPending = false;
ContactSyncShortfall? _contactSyncShortfall;
bool _isSyncingQueuedMessages = false;
bool _deferQueuedContactMessagesUntilContacts = false;
bool _isProcessingDeferredQueuedContactMessages = false;
@ -3075,6 +3098,13 @@ class MeshCoreConnector extends ChangeNotifier {
@visibleForTesting
void handleFrameForTest(List<int> frame) => _handleFrameInner(frame);
/// When set, [sendFrame] hands frames here instead of a transport.
@visibleForTesting
void Function(Uint8List data)? sendFrameOverrideForTest;
@visibleForTesting
void setConnectedForTest() => _state = MeshCoreConnectionState.connected;
@visibleForTesting
Map<int, List<ChannelMessage>> get channelMessagesForTest => _channelMessages;
@ -3097,6 +3127,11 @@ class MeshCoreConnector extends ChangeNotifier {
_contactSyncTotal = null;
_contactSyncReceived = 0;
_contactSyncUsesSinceFilter = false;
_contactSyncIsFull = false;
_contactSyncDeclaredTotal = null;
_contactSyncDeliveredKeys.clear();
_contactSyncRetryUsed = false;
_contactSyncDecisionPending = false;
_isLoadingContacts = false;
_hasLoadedContacts = false;
_isLoadingChannels = false;
@ -3312,6 +3347,11 @@ class MeshCoreConnector extends ChangeNotifier {
if (!isConnected) {
throw Exception("Not connected to a MeshCore device");
}
final override = sendFrameOverrideForTest;
if (override != null) {
override(data);
return;
}
_bleDebugLogService?.logFrame(data, outgoing: true);
if (_activeTransport == MeshCoreTransportType.usb) {
@ -3654,13 +3694,12 @@ class MeshCoreConnector extends ChangeNotifier {
if (!isConnected) return;
_isLoadingContacts = true;
_preserveContactsOnRefresh = preserveExisting;
_contactSyncTotal = null;
_contactSyncReceived = 0;
_contactSyncUsesSinceFilter = since != null;
_beginContactSync(full: since == null);
if (!preserveExisting) {
_hasLoadedContacts = false;
_contacts.clear();
}
notifyListeners();
@ -3675,6 +3714,120 @@ class MeshCoreConnector extends ChangeNotifier {
await getContacts(since: _latestContactLastmod(), preserveExisting: true);
}
/// The latest short full sync, kept until dismissed or a complete sync.
ContactSyncShortfall? get contactSyncShortfall => _contactSyncShortfall;
/// True after the automatic retry was also short: the owner chooses between
/// keeping the local list and accepting the radio's.
bool get contactSyncDecisionPending => _contactSyncDecisionPending;
/// Contacts the app holds that the last full sync did not deliver, i.e. what
/// "use the radio's list" would remove.
int get contactSyncUndeliveredCount => _contacts
.where((c) => !_contactSyncDeliveredKeys.contains(c.publicKeyHex))
.length;
/// A full sync is complete only when the radio declared a total and at
/// least that many contacts arrived. No declared total (older firmware) is
/// unverifiable, so it is never treated as complete.
@visibleForTesting
static bool isContactSyncComplete({
required int? declared,
required int received,
}) => declared != null && received >= declared;
void _beginContactSync({required bool full}) {
_contactSyncIsFull = full;
_contactSyncDeclaredTotal = null;
_contactSyncDeliveredKeys.clear();
if (full) _contactSyncDecisionPending = false;
}
void _finishFullContactSync() {
final declared = _contactSyncDeclaredTotal;
final received = _contactSyncReceived;
if (isContactSyncComplete(declared: declared, received: received)) {
final before = _contacts.length;
_contacts.removeWhere(
(c) => !_contactSyncDeliveredKeys.contains(c.publicKeyHex),
);
final removed = before - _contacts.length;
if (removed > 0) {
_appDebugLogService?.info(
'Contact sync complete ($received of $declared): removed $removed '
'contact(s) the radio no longer holds',
tag: 'ContactSync',
);
}
_contactSyncShortfall = null;
_contactSyncDecisionPending = false;
return;
}
final kept = contactSyncUndeliveredCount;
_contactSyncShortfall = ContactSyncShortfall(
declared: declared,
received: received,
keptLocally: kept,
);
final message =
'Contact sync incomplete: radio declared ${declared ?? 'no total'}, '
'sent $received. Kept $kept saved contact(s) it did not send; '
'nothing removed.';
debugPrint(message);
_appDebugLogService?.error(message, tag: 'ContactSync');
if (!_contactSyncRetryUsed) {
_contactSyncRetryUsed = true;
_appDebugLogService?.warn(
'Retrying the contact sync once',
tag: 'ContactSync',
);
unawaited(
getContacts().catchError((Object e) {
_appDebugLogService?.error(
'Contact sync retry failed to send: $e',
tag: 'ContactSync',
);
}),
);
} else {
_contactSyncDecisionPending = true;
}
}
/// The owner chose to keep the local list after a short sync.
void resolveContactSyncKeepLocal() {
_contactSyncDecisionPending = false;
_appDebugLogService?.info(
'Owner kept the local contact list after a short sync',
tag: 'ContactSync',
);
notifyListeners();
}
/// The owner chose the radio's list after a short sync: drop what it did not
/// deliver.
Future<void> resolveContactSyncUseRadio() async {
final removed = contactSyncUndeliveredCount;
_contacts.removeWhere(
(c) => !_contactSyncDeliveredKeys.contains(c.publicKeyHex),
);
_contactSyncDecisionPending = false;
_contactSyncShortfall = null;
_appDebugLogService?.warn(
'Owner accepted the radio\'s contact list: removed $removed contact(s)',
tag: 'ContactSync',
);
notifyListeners();
await _persistContacts();
}
void dismissContactSyncShortfall() {
_contactSyncShortfall = null;
notifyListeners();
}
Future<void> getContactByKey(Uint8List pubKey) async {
if (!isConnected) return;
await sendFrame(buildGetContactByKeyFrame(pubKey));
@ -5525,17 +5678,17 @@ class MeshCoreConnector extends ChangeNotifier {
break;
case respCodeContactsStart:
debugPrint('Got CONTACTS_START');
if (!_preserveContactsOnRefresh) {
_contacts.clear();
}
_isLoadingContacts = true;
_contactSyncReceived = 0;
_contactSyncDeliveredKeys.clear();
_contactSyncDeclaredTotal = null;
// Firmware v3+ includes total contacts after CONTACTS_START.
// Incremental sync reports total contacts, not filtered result count.
if (frame.length >= 5 && !_contactSyncUsesSinceFilter) {
final reader = BufferReader(frame);
reader.skipBytes(1);
_contactSyncTotal = reader.readUInt32LE();
_contactSyncDeclaredTotal = _contactSyncTotal;
} else if (!_contactSyncUsesSinceFilter) {
// Older firmwares may omit the count; use the nRF node capacity as
// a conservative progress fallback instead of hiding the progress.
@ -5559,10 +5712,12 @@ class MeshCoreConnector extends ChangeNotifier {
break;
case respCodeEndOfContacts:
debugPrint('Got END_OF_CONTACTS');
final wasFullSync = _contactSyncIsFull && _isLoadingContacts;
_isLoadingContacts = false;
_hasLoadedContacts = true;
_preserveContactsOnRefresh = false;
_contactSyncUsesSinceFilter = false;
_contactSyncIsFull = false;
if (wasFullSync) _finishFullContactSync();
unawaited(updateKnownDiscovered());
notifyListeners();
unawaited(_persistContacts());
@ -5746,8 +5901,6 @@ class MeshCoreConnector extends ChangeNotifier {
if (contact != null) {
_pathHistoryService!.handlePathUpdated(contact);
// Refresh just this specific contact instead of all contacts.
// This avoids race conditions with _preserveContactsOnRefresh flag
// that can occur when using refreshContactsSinceLastmod().
getContactByKey(pubKey);
}
}
@ -6325,6 +6478,12 @@ class MeshCoreConnector extends ChangeNotifier {
if (isContact && _isLoadingContacts) {
_contactSyncReceived++;
}
// Adverts heard mid-sync count as delivered too: the radio holds them,
// so a complete sync must not drop them just because they arrived as a
// push rather than in the contact stream.
if (_isLoadingContacts) {
_contactSyncDeliveredKeys.add(contactTmp.publicKeyHex);
}
if (listEquals(contactTmp.publicKey, _selfPublicKey)) {
appLogger.info(
'Ignoring contact with self public key: ${contactTmp.name}',

@ -0,0 +1,233 @@
import 'dart:convert';
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/models/contact.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';
/// #660 / #668: a radio declared 350 contacts, streamed 106, and the app
/// replaced the owner's saved list with the 106. A full sync must never drop a
/// contact unless the radio proved it sent everything.
Uint8List _contactFrame(
int keyByte,
String name, {
int code = respCodeContact,
}) {
final b = BytesBuilder()
..addByte(code)
..add(List<int>.filled(32, keyByte))
..addByte(advTypeChat)
..addByte(0) // flags
..addByte(0xFF) // flood path
..add(List<int>.filled(64, 0))
..add(Uint8List(32)..setRange(0, name.length, utf8.encode(name)))
..add(_u32(1790000000)) // last advert
..add(_u32(0)) // lat
..add(_u32(0)) // lon
..add(_u32(1790000000)); // lastmod
return b.toBytes();
}
Uint8List _u32(int v) =>
Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little);
Uint8List _start(int declared) =>
Uint8List.fromList([respCodeContactsStart, ..._u32(declared)]);
Uint8List get _end => Uint8List.fromList([respCodeEndOfContacts, ..._u32(0)]);
Contact _saved(int keyByte, String name) => Contact(
publicKey: Uint8List.fromList(List<int>.filled(32, keyByte)),
name: name,
type: advTypeChat,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime.utc(2026, 7, 1),
);
void main() {
late OffbandDatabase db;
late MeshCoreConnector connector;
late List<Uint8List> 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();
});
tearDown(() async {
BlobStore.clearTestOverride();
await db.close();
});
Set<String> names() => connector.contactsForTest.map((c) => c.name).toSet();
int contactRequests() =>
sent.where((f) => f.isNotEmpty && f[0] == cmdGetContacts).length;
/// Seeds saved contacts A, B, C; the radio then streams [streamed] under a
/// declared total of [declared].
Future<void> fullSync({
required int declared,
required List<Uint8List> streamed,
}) async {
await connector.getContacts();
connector.handleFrameForTest(_start(declared));
for (final f in streamed) {
connector.handleFrameForTest(f);
}
connector.handleFrameForTest(_end);
await Future<void>.delayed(Duration.zero);
}
void seedSaved() {
connector.contactsForTest
..add(_saved(0x11, 'Alpha'))
..add(_saved(0x22, 'Bravo'))
..add(_saved(0x33, 'Charlie'));
}
test('completeness needs a declared total and at least that many', () {
expect(
MeshCoreConnector.isContactSyncComplete(declared: 3, received: 3),
isTrue,
);
expect(
MeshCoreConnector.isContactSyncComplete(declared: 350, received: 106),
isFalse,
);
expect(
MeshCoreConnector.isContactSyncComplete(declared: null, received: 50),
isFalse,
);
});
test('starting a full sync does not clear the saved list', () async {
seedSaved();
await connector.getContacts();
connector.handleFrameForTest(_start(3));
expect(names(), {'Alpha', 'Bravo', 'Charlie'});
});
test('a complete sync replaces the list, removals included', () async {
seedSaved();
await fullSync(
declared: 2,
streamed: [_contactFrame(0x11, 'Alpha'), _contactFrame(0x44, 'Delta')],
);
expect(names(), {'Alpha', 'Delta'});
expect(connector.contactSyncShortfall, isNull);
expect(contactRequests(), 1, reason: 'no retry after a complete sync');
});
test('a short sync removes nothing, merges, reports, and retries', () async {
seedSaved();
await fullSync(
declared: 350,
streamed: [_contactFrame(0x11, 'Alpha'), _contactFrame(0x44, 'Delta')],
);
expect(names(), {'Alpha', 'Bravo', 'Charlie', 'Delta'});
final shortfall = connector.contactSyncShortfall!;
expect(shortfall.declared, 350);
expect(shortfall.received, 2);
expect(shortfall.keptLocally, 2);
expect(connector.contactSyncDecisionPending, isFalse);
expect(contactRequests(), 2, reason: 'one automatic retry');
});
test('no declared total is never treated as complete', () async {
seedSaved();
await connector.getContacts();
connector.handleFrameForTest(Uint8List.fromList([respCodeContactsStart]));
connector.handleFrameForTest(_contactFrame(0x11, 'Alpha'));
connector.handleFrameForTest(_end);
await Future<void>.delayed(Duration.zero);
expect(names(), {'Alpha', 'Bravo', 'Charlie'});
expect(connector.contactSyncShortfall!.declared, isNull);
});
group('after the retry is also short', () {
Future<void> twoShortSyncs() async {
seedSaved();
final streamed = [_contactFrame(0x11, 'Alpha')];
await fullSync(declared: 350, streamed: streamed);
// The retry was sent by the first END; the radio answers it short too.
connector.handleFrameForTest(_start(350));
connector.handleFrameForTest(streamed.first);
connector.handleFrameForTest(_end);
await Future<void>.delayed(Duration.zero);
}
test('the owner decision is raised and nothing is removed', () async {
await twoShortSyncs();
expect(connector.contactSyncDecisionPending, isTrue);
expect(connector.contactSyncUndeliveredCount, 2);
expect(names(), {'Alpha', 'Bravo', 'Charlie'});
expect(contactRequests(), 2, reason: 'retry is bounded to one');
});
test('keep my contacts leaves the list as is', () async {
await twoShortSyncs();
connector.resolveContactSyncKeepLocal();
expect(connector.contactSyncDecisionPending, isFalse);
expect(names(), {'Alpha', 'Bravo', 'Charlie'});
});
test('use the radio list drops what it did not send', () async {
await twoShortSyncs();
await connector.resolveContactSyncUseRadio();
expect(connector.contactSyncDecisionPending, isFalse);
expect(connector.contactSyncShortfall, isNull);
expect(names(), {'Alpha'});
});
});
test('an advert heard mid-sync survives a complete sync', () async {
seedSaved();
await connector.getContacts();
connector.handleFrameForTest(_start(1));
connector.handleFrameForTest(_contactFrame(0x11, 'Alpha'));
connector.contactsForTest.add(_saved(0x55, 'Echo'));
connector.handleFrameForTest(
_contactFrame(0x55, 'Echo', code: pushCodeNewAdvert),
);
connector.handleFrameForTest(_end);
await Future<void>.delayed(Duration.zero);
expect(names(), {'Alpha', 'Echo'});
});
test('an incremental sync never removes anything', () async {
seedSaved();
await connector.getContacts(since: 1, preserveExisting: true);
connector.handleFrameForTest(_start(350));
connector.handleFrameForTest(_contactFrame(0x11, 'Alpha'));
connector.handleFrameForTest(_end);
await Future<void>.delayed(Duration.zero);
expect(names(), {'Alpha', 'Bravo', 'Charlie'});
expect(connector.contactSyncShortfall, isNull);
expect(contactRequests(), 1);
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.