Merge remote-tracking branch 'origin/feat/1063-message-state-hardening' into feat/1068-radio-channel-notify
# Conflicts: # lib/connector/meshcore_connector.dartpull/1102/head
commit
21fa162d4a
@ -0,0 +1,45 @@
|
||||
# Feature #1061 channel slot resync truth: OUTCOMES
|
||||
|
||||
Status: BUILT and machine-verified; PRs opened on the owner's word (decision below), validation moves to live testing after merge. Branch stack: `feat/1062-channel-sync-truth` (Epic A) ← `feat/1063-message-state-hardening` (Epics B + C), rebased onto dev `180c01e6`.
|
||||
|
||||
## What was built
|
||||
| Epic | Commit | Content |
|
||||
|---|---|---|
|
||||
| A #1062 | `da08b7eb` | fail-closed atomic sync (no backfill, unconfirmed slots tracked + bannered with Retry, cache kept on holes), ingress barrier (messages held unbounded, raw sniffs bounded 64, flush post-sync), per-slot PSK identity diff (UI notice + warn log), unread preserved only on same PSK, fail-closed `_findChannelByIndex`, notification suppression for unconfirmed slots, self-retry on failed live sync |
|
||||
| B #1063 | `b658fe14` | in-memory conversation dropped + reloaded under the new PSK on slot identity change; setChannel reassignment clear narrowed to legacy slot keys (PSK history survives re-add; deleteChannel keeps the full clear); write-side index fallback escalated to an error naming the orphaning consequence; stale #193-era comments corrected, setChannel/resolver interplay documented |
|
||||
| C #1064 | `2a9d1e16` | the three integration scenarios below, the notify-decision test probe, store wiring test hook, and one fix the tests exposed (next section) |
|
||||
|
||||
## Gap found by the integration tests (fixed in `2a9d1e16`)
|
||||
Epic A's flush documented that a held frame for a still-unconfirmed slot re-holds, but the handler only gated on the list-level barrier: after a PARTIAL sync completed, a held message for an unconfirmed slot would have filed by raw index against an unknown identity and persisted under the legacy index key. `_handleIncomingChannelMessage` now re-holds such frames until a sync confirms the slot. This is the "prove the check can fail" discipline paying for itself; the flaky-sync scenario below fails without the fix.
|
||||
|
||||
## Gemini adversarial gate (gemini-2.5-pro, 2026-11-03, at the pre-push stack head)
|
||||
Four findings, all addressed before push:
|
||||
1. **HIGH, unbounded held frames:** cap deliberately NOT added (held frames are popped messages; dropping one is guaranteed loss; growth is traffic-bounded at <=172 bytes/frame and drains on the next confirming sync). Verifying it exposed a sharper defect the review did not name: held frames survived a radio SWITCH and would have flushed into the other radio's conversations. Fixed: held message frames are keyed per radio and flush only when their own radio completes a sync.
|
||||
2. **MEDIUM, identity-change reload race:** confirmed for in-memory state only (saves merge by identity, #343). Fixed: `_loadChannelMessages` merges messages that arrived during the disk read instead of clobbering.
|
||||
3. **MEDIUM, outgoing send on an unconfirmed slot orphans the persisted copy:** confirmed. Fixed: `sendChannelMessage` refuses the write (fail closed, logged) and the chat screen shows a persistent error at every send path. New English UI string, untranslated.json regenerated.
|
||||
4. **Test gaps:** three integration tests added (race, refused send, cross-radio hold); with the three guards behaviorally disabled, exactly those three fail (+3 -3).
|
||||
|
||||
## Evidence
|
||||
Machine verification, all on the stacked branch:
|
||||
- `flutter analyze` clean on every touched file.
|
||||
- Unit tests: 7 sync-truth tests (`test/connector/channel_sync_truth_test.dart`), 5 store identity tests (`test/storage/channel_message_store_identity_test.dart`).
|
||||
- Integration tests (`test/connector/channel_slot_resync_integration_test.dart`):
|
||||
1. **#1060 bug validation (wipe + re-import, all three slots shuffled):** post-sync list matches the device exactly; all three identity changes surfaced; the old private conversation does not stay behind under #wardriving; a #test message files under #test and is notify-evaluated against #test's PSK (mode `all`); a #wardriving message is evaluated against #wardriving's PSK and its OFF mode rides along to the new slot. The reported symptoms (muted channel notifying, #test rendering in the private channel) cannot reproduce.
|
||||
2. **Manual device-side reorder:** a message persisted under Alpha's PSK follows Alpha to its new slot after the re-sync; nothing renders under Beta.
|
||||
3. **Flaky sync mid-reconnect:** a message for a never-confirmed slot is held, not filed by raw index, and no notify decision is made for it; after a confirming re-sync it files once, against the right PSK and mode.
|
||||
- **Negative evidence:** with Epic B's drop/reload and the slot-level re-hold reverted in the working tree, all three scenarios fail (`+0 -3`) on exactly the guarded assertions; restored, all pass. The checks can fail.
|
||||
- Full suite at Epic B: 1791 passed / 1 skipped, exit 0. Full suite at Epic C: 1794 passed / 1 skipped, exit 0. Full suite at the pushed head (post-rebase, post-review fixes): 1807 passed / 1 skipped, exit 0.
|
||||
|
||||
## Decisions logged
|
||||
- Epic B re-scope approved by the owner 2026-11-03 ("Agree, proceed"); storage was already PSK-keyed since #194, so no migration was needed.
|
||||
- Already-miskeyed rows from the #1060 window stay as-is: not mechanically separable, and the owner's standing history-loss bar is deliberately low. Say the word and a per-radio clear can be added instead.
|
||||
- setChannel reassignment now PRESERVES the outgoing occupant's PSK-keyed history (only legacy slot keys are purged). Re-adding a channel later restores its messages; this strengthens #194's intent and the diff is one call site, flagged for owner review on the Epic B PR.
|
||||
- Owner, 2026-11-03 in chat: "I don't have a way to reproduce right now. Push/pr if the work is done, we will validate in live testing." The pre-PR hardware gate is waived for this feature; validation moves to live testing. Merges still require the explicit per-PR grant.
|
||||
|
||||
## Open until the owner closes them
|
||||
- Live-testing validation after merge (the #1060 recovery sequence: wipe, re-import, reconnect, one sync). The owner cannot reproduce on demand right now, so this is observational.
|
||||
- The user-reported problem the owner logged this feature against: its one-liner / issue number is still pending and will be linked under #1063/#1064 when provided.
|
||||
- Merges of the stacked PRs (A into dev, then B+C) on the owner's explicit grant.
|
||||
- #1060 closes only after the owner confirms the fix in live use.
|
||||
|
||||
Agent: TurquoiseBridge (session 82d77b2f)
|
||||
@ -0,0 +1,39 @@
|
||||
# Feature PLAN: channel slot resync truth (#1060 class)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Feature** | [#1061](https://github.com/OffbandMesh/meshcore-client/issues/1061) · Citadel `meshcore-open-rwr` |
|
||||
| **Fixes** | [#1060](https://github.com/OffbandMesh/meshcore-client/issues/1060) (P0): wipe + config re-import shuffled channel slots; notifications fired for a muted channel and messages rendered inside the wrong conversation |
|
||||
| **Owner** | @Strycher |
|
||||
| **Approved** | 2026-11-02 in chat: "Agree with all 4, don't hold on 4, do it now." Epic B re-scope approved 2026-11-03: "Agree, proceed." |
|
||||
|
||||
## At a glance
|
||||
- **What:** make the device's channel list the only truth the client ever acts on, and make every piece of per-slot client state follow the channel's PSK identity instead of its reusable slot index.
|
||||
- **Why:** #1060. The radio is authoritative for slot assignments; after a wipe + re-import the same channels can sit in different slots, and any client state keyed by slot silently attaches to the wrong channel.
|
||||
- **Done when:** the integration scenarios pass (positive and negative), the #1060 reporter's sequence cannot recur, and the owner approves the OUTCOMES.
|
||||
|
||||
## 1. Diagnosis (#1060, verified in code)
|
||||
Three routes let a stale slot map poison live behavior:
|
||||
1. **Backfill:** the channel sync restored unanswered slots from `_previousChannelsCache`, so a shuffled device list came back part-fresh, part-stale.
|
||||
2. **Index filing:** raw-RX and message ingress filed by slot index through the stale list.
|
||||
3. **Poisoned resolver:** notify modes and persisted history are PSK-keyed (#839, #194), but both resolve PSKs through `_findChannelByIndex` - which consulted the stale list, so correct identity keying was fed wrong identities.
|
||||
|
||||
## 2. The four approved parts → Epics
|
||||
| Part | Epic | Scope |
|
||||
|---|---|---|
|
||||
| 1. Fail-closed, atomic channel sync | A [#1062](https://github.com/OffbandMesh/meshcore-client/issues/1062) | never backfill an unanswered slot; unconfirmed slots tracked + surfaced (banner w/ Retry); cache not overwritten on holes; self-retry on a failed live sync |
|
||||
| 2. Ingress barrier | A #1062 | no live channel frame files until THIS connection confirms the list; pull-based message frames held unbounded (the radio already popped them), raw sniffs bounded at 64; held frames flush post-sync |
|
||||
| 3. Per-slot identity diff | A #1062 | PSK diff per slot against the last truth; identity changes surfaced in UI + log; unread preserved only on same PSK; unconfirmed slots fail closed in `_findChannelByIndex` and suppress notifications |
|
||||
| 4. Identity-keyed message state | B [#1063](https://github.com/OffbandMesh/meshcore-client/issues/1063) | RE-SCOPED (see below) |
|
||||
| Validation | C [#1064](https://github.com/OffbandMesh/meshcore-client/issues/1064) | end-to-end scenarios, the #1060 bug-validation test, this folder's OUTCOMES.md |
|
||||
|
||||
## 3. Epic B re-scope (approved 2026-11-03)
|
||||
Part 4 was planned as "re-key channel_message_store by PSK with migration" from a stale #193-era comment. The store has been PSK-keyed since #194; the incident's cross-wiring came from the poisoned resolver (route 3), which Epic A fixes. Epic B therefore shrank to:
|
||||
1. drop a slot's in-memory `_channelMessages` entry on identity change and reload it under the new identity's PSK;
|
||||
2. harden the store's slot-index write fallback (error log naming the orphaning consequence);
|
||||
3. narrow setChannel's reassignment clear to the LEGACY slot keys only, so the outgoing occupant's PSK-keyed history survives and returns if the channel is re-added;
|
||||
4. correct the stale #193-era comments and document the setChannel/resolver interplay.
|
||||
|
||||
Already-miskeyed rows from the #1060 window stay as-is (not mechanically separable; owner's standing low history-loss bar).
|
||||
|
||||
Agent: TurquoiseBridge (session 82d77b2f)
|
||||
@ -0,0 +1,415 @@
|
||||
// #1064 (Epic C of #1061): end-to-end slot-shuffle scenarios across Epic A
|
||||
// (#1062, fail-closed sync + ingress barrier) and Epic B (#1063, per-slot
|
||||
// state never crosses identities). The first test is the #1060 bug-validation
|
||||
// scenario: a wipe + config re-import rearranged the device's channel slots,
|
||||
// #wardriving notified with its mode off, and #test messages rendered inside
|
||||
// the private channel.
|
||||
|
||||
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/app_settings.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/services/app_settings_service.dart';
|
||||
import 'package:meshcore_open/services/message_retry_service.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/storage_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';
|
||||
|
||||
Uint8List _channelInfoFrame({
|
||||
required int index,
|
||||
required String name,
|
||||
required int pskSeed,
|
||||
}) {
|
||||
final frame = Uint8List(50);
|
||||
frame[0] = respCodeChannelInfo;
|
||||
frame[1] = index;
|
||||
final nameBytes = name.codeUnits;
|
||||
for (var i = 0; i < nameBytes.length && i < 31; i++) {
|
||||
frame[2 + i] = nameBytes[i];
|
||||
}
|
||||
for (var i = 0; i < 16; i++) {
|
||||
frame[34 + i] = (pskSeed + i) & 0xFF;
|
||||
}
|
||||
return frame;
|
||||
}
|
||||
|
||||
Uint8List _v3ChannelMsgFrame({required int channelIdx, String text = 'A: hi'}) {
|
||||
return Uint8List.fromList([
|
||||
respCodeChannelMsgRecvV3,
|
||||
0, 0, 0,
|
||||
channelIdx,
|
||||
1, // path_len: 1 hop, width 1
|
||||
txtTypePlain,
|
||||
0x40, 0xE2, 0x01, 0x00,
|
||||
...text.codeUnits,
|
||||
]);
|
||||
}
|
||||
|
||||
Channel _channel(int index, String name, int pskSeed) {
|
||||
final psk = Uint8List.fromList(
|
||||
List<int>.generate(16, (i) => (pskSeed + i) & 0xFF),
|
||||
);
|
||||
return Channel(index: index, name: name, psk: psk);
|
||||
}
|
||||
|
||||
typedef _NotifyDecision = ({
|
||||
int channelIndex,
|
||||
String channelName,
|
||||
String? pskHex,
|
||||
ChannelNotifyMode? mode,
|
||||
});
|
||||
|
||||
Future<void> _settle([int turns = 25]) async {
|
||||
for (var i = 0; i < turns; i++) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late OffbandDatabase db;
|
||||
late AppSettingsService settings;
|
||||
late MeshCoreConnector c;
|
||||
late List<_NotifyDecision> notifyDecisions;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
db = OffbandDatabase(NativeDatabase.memory());
|
||||
BlobStore.overrideForTest(BlobStore(db));
|
||||
|
||||
settings = AppSettingsService();
|
||||
await settings.loadSettings();
|
||||
|
||||
c = MeshCoreConnector();
|
||||
c.initialize(
|
||||
retryService: MessageRetryService(),
|
||||
pathHistoryService: PathHistoryService(StorageService()),
|
||||
appSettingsService: settings,
|
||||
);
|
||||
c.sendFrameOverrideForTest = (_) {};
|
||||
c.setConnectedForTest();
|
||||
c.setSelfPublicKeyForTest(
|
||||
Uint8List.fromList(List<int>.generate(32, (i) => i)),
|
||||
);
|
||||
c.wireMessageStoreForTest();
|
||||
|
||||
notifyDecisions = [];
|
||||
c.channelNotifyProbeForTest = (index, name, pskHex, mode) {
|
||||
notifyDecisions.add((
|
||||
channelIndex: index,
|
||||
channelName: name,
|
||||
pskHex: pskHex,
|
||||
mode: mode,
|
||||
));
|
||||
};
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
BlobStore.clearTestOverride();
|
||||
await db.close();
|
||||
});
|
||||
|
||||
Future<void> syncWith(List<Channel> deviceArrangement, {int? max}) async {
|
||||
await c.getChannels(
|
||||
force: true,
|
||||
maxChannels: max ?? deviceArrangement.length,
|
||||
);
|
||||
for (final ch in deviceArrangement) {
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: ch.index, name: ch.name, pskSeed: ch.psk[0]),
|
||||
);
|
||||
await _settle(2);
|
||||
}
|
||||
await _settle();
|
||||
}
|
||||
|
||||
test('#1060 bug validation: wipe + re-import with shuffled slots', () async {
|
||||
// Before the wipe this radio had: slot0 #wardriving (notify OFF),
|
||||
// slot1 #test, slot2 the private channel (an old conversation on screen).
|
||||
final wardriving = _channel(0, 'wardriving', 40);
|
||||
final testCh = _channel(1, 'test', 50);
|
||||
final private = _channel(2, 'Private', 60);
|
||||
c.seedCachedChannelsForTest([wardriving, testCh, private]);
|
||||
await settings.setChannelNotifyMode(
|
||||
devicePrefix: c.selfPublicKeyHex,
|
||||
pskHex: wardriving.pskHex,
|
||||
channelName: wardriving.name,
|
||||
mode: ChannelNotifyMode.off,
|
||||
);
|
||||
c.channelMessagesForTest[2] = [
|
||||
ChannelMessage(
|
||||
senderName: 'friend',
|
||||
text: 'old private talk',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000),
|
||||
isOutgoing: false,
|
||||
channelIndex: 2,
|
||||
messageId: 'old-private',
|
||||
),
|
||||
];
|
||||
|
||||
// The re-imported config put the same channels in DIFFERENT slots.
|
||||
await syncWith([
|
||||
_channel(0, 'test', 50),
|
||||
_channel(1, 'Private', 60),
|
||||
_channel(2, 'wardriving', 40),
|
||||
]);
|
||||
|
||||
// The list matches the device, and every slot's change was surfaced.
|
||||
expect(c.channels.map((ch) => ch.name), ['test', 'Private', 'wardriving']);
|
||||
expect(c.slotIdentityChanges, hasLength(3));
|
||||
expect(c.unconfirmedChannelSlots, isEmpty);
|
||||
|
||||
// The old private conversation did not stay behind in slot 2, which
|
||||
// #wardriving now occupies.
|
||||
expect(c.channelMessagesForTest[2] ?? const <ChannelMessage>[], isEmpty);
|
||||
|
||||
// A #test message files under #test's slot and is evaluated against
|
||||
// #test's PSK (default mode), not against whatever used to live there.
|
||||
c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 0, text: 'B: to test'));
|
||||
await _settle();
|
||||
expect(c.channelMessagesForTest[0]!.single.text, 'to test');
|
||||
expect(
|
||||
c.channelMessagesForTest[1] ?? const <ChannelMessage>[],
|
||||
isEmpty,
|
||||
reason: '#test traffic must not render inside the private channel',
|
||||
);
|
||||
final testDecision = notifyDecisions.single;
|
||||
expect(testDecision.channelName, 'test');
|
||||
expect(testDecision.pskHex, testCh.pskHex);
|
||||
expect(testDecision.mode, ChannelNotifyMode.all);
|
||||
|
||||
// A #wardriving message follows #wardriving's OFF mode to its NEW slot:
|
||||
// the #1060 complaint was notifications firing with the mode off.
|
||||
notifyDecisions.clear();
|
||||
c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 2, text: 'B: war'));
|
||||
await _settle();
|
||||
expect(c.channelMessagesForTest[2]!.single.text, 'war');
|
||||
final warDecision = notifyDecisions.single;
|
||||
expect(warDecision.pskHex, wardriving.pskHex);
|
||||
expect(
|
||||
warDecision.mode,
|
||||
ChannelNotifyMode.off,
|
||||
reason: 'the OFF mode belongs to the PSK and must ride along to slot 2',
|
||||
);
|
||||
});
|
||||
|
||||
test('manual reorder on the device: history follows the channel, '
|
||||
'not the slot', () async {
|
||||
// First sync: Alpha in slot 0, Beta in slot 1. A message lands in Alpha
|
||||
// and is persisted under Alpha's PSK identity.
|
||||
await syncWith([_channel(0, 'Alpha', 10), _channel(1, 'Beta', 30)]);
|
||||
c.handleFrameForTest(
|
||||
_v3ChannelMsgFrame(channelIdx: 0, text: 'A: hello alpha'),
|
||||
);
|
||||
await _settle();
|
||||
expect(c.channelMessagesForTest[0]!.single.text, 'hello alpha');
|
||||
// Let the unawaited persistence land before the reorder.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
|
||||
// The operator swaps the slots on the device; the client re-syncs.
|
||||
await syncWith([_channel(0, 'Beta', 30), _channel(1, 'Alpha', 10)]);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
await _settle();
|
||||
|
||||
expect(c.channels.map((ch) => ch.name), ['Beta', 'Alpha']);
|
||||
expect(
|
||||
c.channelMessagesForTest[0] ?? const <ChannelMessage>[],
|
||||
isEmpty,
|
||||
reason: "Alpha's conversation must not render under Beta",
|
||||
);
|
||||
expect(
|
||||
(c.channelMessagesForTest[1] ?? const <ChannelMessage>[]).map(
|
||||
(m) => m.text,
|
||||
),
|
||||
['hello alpha'],
|
||||
reason: "Alpha's PSK-keyed history reloads at its new slot",
|
||||
);
|
||||
});
|
||||
|
||||
test('flaky sync mid-reconnect: held traffic files only after a '
|
||||
'confirming sync, against the right PSK', () async {
|
||||
final alpha = _channel(0, 'Alpha', 10);
|
||||
final beta = _channel(1, 'Beta', 30);
|
||||
c.seedCachedChannelsForTest([alpha, beta]);
|
||||
await settings.setChannelNotifyMode(
|
||||
devicePrefix: c.selfPublicKeyHex,
|
||||
pskHex: beta.pskHex,
|
||||
channelName: beta.name,
|
||||
mode: ChannelNotifyMode.off,
|
||||
);
|
||||
|
||||
// The sync answers slot 0, a message for slot 1 arrives mid-sync, and
|
||||
// slot 1 never answers.
|
||||
await c.getChannels(maxChannels: 2);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'Alpha', pskSeed: 10),
|
||||
);
|
||||
await _settle(2);
|
||||
c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 1, text: 'B: held'));
|
||||
for (var i = 0; i <= 3; i++) {
|
||||
c.handleChannelSyncTimeoutForTest(1);
|
||||
await _settle(2);
|
||||
}
|
||||
await _settle();
|
||||
|
||||
expect(c.unconfirmedChannelSlots, {1});
|
||||
expect(
|
||||
c.channelMessagesForTest[1],
|
||||
isNull,
|
||||
reason: 'a message for an unconfirmed slot must not file by raw index',
|
||||
);
|
||||
expect(
|
||||
notifyDecisions.where((d) => d.channelIndex == 1 && d.mode != null),
|
||||
isEmpty,
|
||||
reason: 'no notify decision can be made for an unconfirmed slot',
|
||||
);
|
||||
|
||||
// The reconnect-style retry confirms both slots; the held message now
|
||||
// files, and Beta's OFF mode is evaluated against Beta's own PSK.
|
||||
notifyDecisions.clear();
|
||||
await syncWith([alpha, beta]);
|
||||
|
||||
expect(c.unconfirmedChannelSlots, isEmpty);
|
||||
expect(c.channels.map((ch) => ch.name), ['Alpha', 'Beta']);
|
||||
expect(c.channelMessagesForTest[1]!.single.text, 'held');
|
||||
final decision = notifyDecisions.single;
|
||||
expect(decision.channelIndex, 1);
|
||||
expect(decision.pskHex, beta.pskHex);
|
||||
expect(decision.mode, ChannelNotifyMode.off);
|
||||
});
|
||||
|
||||
test(
|
||||
'identity-change reload does not hide a message flushed meanwhile',
|
||||
() async {
|
||||
// Beta builds history at slot 1, then moves to slot 0. A live message for
|
||||
// slot 0 arrives MID-resync (held), so the flush files it while the
|
||||
// identity-change reload is still reading the store. Both must be visible
|
||||
// afterwards: the reload merges, it does not clobber (#1063 review).
|
||||
await syncWith([_channel(0, 'Alpha', 10), _channel(1, 'Beta', 30)]);
|
||||
c.handleFrameForTest(
|
||||
_v3ChannelMsgFrame(channelIdx: 1, text: 'B: beta history'),
|
||||
);
|
||||
await _settle();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
|
||||
await c.getChannels(force: true, maxChannels: 2);
|
||||
// Mid-resync: the barrier is closed, so this is held, and the flush will
|
||||
// file it in the same turn that starts the slot-0 reload.
|
||||
c.handleFrameForTest(
|
||||
_v3ChannelMsgFrame(channelIdx: 0, text: 'B: live during sync'),
|
||||
);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'Beta', pskSeed: 30),
|
||||
);
|
||||
await _settle(2);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 1, name: 'Alpha', pskSeed: 10),
|
||||
);
|
||||
await _settle();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
await _settle();
|
||||
|
||||
final slot0Texts =
|
||||
(c.channelMessagesForTest[0] ?? const <ChannelMessage>[])
|
||||
.map((m) => m.text)
|
||||
.toSet();
|
||||
expect(
|
||||
slot0Texts,
|
||||
containsAll(<String>{'beta history', 'live during sync'}),
|
||||
reason:
|
||||
'the reload must merge with what the flush just filed, '
|
||||
'not clobber it',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'outgoing send to an unconfirmed slot is refused, not orphaned',
|
||||
() async {
|
||||
final alpha = _channel(0, 'Alpha', 10);
|
||||
final beta = _channel(1, 'Beta', 30);
|
||||
c.seedCachedChannelsForTest([alpha, beta]);
|
||||
|
||||
// Slot 0 confirms, slot 1 never does.
|
||||
await c.getChannels(maxChannels: 2);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'Alpha', pskSeed: 10),
|
||||
);
|
||||
await _settle(2);
|
||||
for (var i = 0; i <= 3; i++) {
|
||||
c.handleChannelSyncTimeoutForTest(1);
|
||||
await _settle(2);
|
||||
}
|
||||
await _settle();
|
||||
expect(c.unconfirmedChannelSlots, {1});
|
||||
expect(c.canSendOnChannel(0), isTrue);
|
||||
expect(c.canSendOnChannel(1), isFalse);
|
||||
|
||||
final sentFrames = <Uint8List>[];
|
||||
c.sendFrameOverrideForTest = sentFrames.add;
|
||||
await c.sendChannelMessage(beta, 'must not be written');
|
||||
await _settle();
|
||||
|
||||
expect(sentFrames, isEmpty, reason: 'nothing may go to the radio');
|
||||
expect(
|
||||
c.channelMessagesForTest[1] ?? const <ChannelMessage>[],
|
||||
isEmpty,
|
||||
reason:
|
||||
'the refused message must not be filed (a persisted copy would '
|
||||
'fall back to the legacy slot-index key and be orphaned)',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'held frames never cross radios; they flush when their radio returns',
|
||||
() async {
|
||||
// Radio X delivers a message before its list is confirmed; the frame is
|
||||
// held. The user then connects radio Y: Y's sync must NOT flush X's frame
|
||||
// into Y's conversations. When X reconnects and syncs, the frame files.
|
||||
final radioX = Uint8List.fromList(List<int>.generate(32, (i) => i));
|
||||
final radioY = Uint8List.fromList(List<int>.generate(32, (i) => 99 + i));
|
||||
|
||||
c.handleFrameForTest(
|
||||
_v3ChannelMsgFrame(channelIdx: 0, text: 'A: from X'),
|
||||
);
|
||||
await _settle();
|
||||
|
||||
// Switch to radio Y and complete its sync.
|
||||
c.resetConnectionHandshakeStateForTest();
|
||||
c.setConnectedForTest();
|
||||
c.setSelfPublicKeyForTest(radioY);
|
||||
c.wireMessageStoreForTest();
|
||||
await syncWith([_channel(0, 'Gamma', 70)]);
|
||||
expect(
|
||||
c.channelMessagesForTest[0] ?? const <ChannelMessage>[],
|
||||
isEmpty,
|
||||
reason: "radio X's held frame must not file into radio Y's channel",
|
||||
);
|
||||
|
||||
// Back to radio X: its held frame now files against its own list.
|
||||
c.resetConnectionHandshakeStateForTest();
|
||||
c.setConnectedForTest();
|
||||
c.setSelfPublicKeyForTest(radioX);
|
||||
c.wireMessageStoreForTest();
|
||||
await syncWith([_channel(0, 'Alpha', 10)]);
|
||||
expect(
|
||||
(c.channelMessagesForTest[0] ?? const <ChannelMessage>[]).map(
|
||||
(m) => m.text,
|
||||
),
|
||||
['from X'],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,264 @@
|
||||
// #1062 (Epic A of #1061, fixing #1060): the channel sync is fail-closed and
|
||||
// atomic, live filing waits behind an ingress barrier, and per-slot state
|
||||
// never follows a slot across an identity change.
|
||||
//
|
||||
// The #1060 field case: a wipe + config re-import rearranged the device's
|
||||
// channel slots; the old sync backfilled unanswered slots from the previous
|
||||
// list, so notifications fired for the wrong channel and messages rendered
|
||||
// inside the wrong conversation.
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
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/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Uint8List _channelInfoFrame({
|
||||
required int index,
|
||||
required String name,
|
||||
required int pskSeed,
|
||||
}) {
|
||||
final frame = Uint8List(50);
|
||||
frame[0] = respCodeChannelInfo;
|
||||
frame[1] = index;
|
||||
final nameBytes = name.codeUnits;
|
||||
for (var i = 0; i < nameBytes.length && i < 31; i++) {
|
||||
frame[2 + i] = nameBytes[i];
|
||||
}
|
||||
for (var i = 0; i < 16; i++) {
|
||||
frame[34 + i] = (pskSeed + i) & 0xFF;
|
||||
}
|
||||
return frame;
|
||||
}
|
||||
|
||||
Uint8List _v3ChannelMsgFrame({required int channelIdx, String text = 'A: hi'}) {
|
||||
return Uint8List.fromList([
|
||||
respCodeChannelMsgRecvV3,
|
||||
0, 0, 0,
|
||||
channelIdx,
|
||||
1, // path_len: 1 hop, width 1
|
||||
txtTypePlain,
|
||||
0x40, 0xE2, 0x01, 0x00,
|
||||
...text.codeUnits,
|
||||
]);
|
||||
}
|
||||
|
||||
Channel _channel(int index, String name, int pskSeed) {
|
||||
final psk = Uint8List.fromList(
|
||||
List<int>.generate(16, (i) => (pskSeed + i) & 0xFF),
|
||||
);
|
||||
return Channel(index: index, name: name, psk: psk);
|
||||
}
|
||||
|
||||
MeshCoreConnector _connector() {
|
||||
final c = MeshCoreConnector();
|
||||
c.sendFrameOverrideForTest = (_) {};
|
||||
c.setConnectedForTest();
|
||||
c.setSelfPublicKeyForTest(
|
||||
Uint8List.fromList(List<int>.generate(32, (i) => i)),
|
||||
);
|
||||
return c;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
test(
|
||||
'an unanswered slot stays UNKNOWN, never backfilled from cache (#1060)',
|
||||
() async {
|
||||
final c = _connector();
|
||||
c.seedCachedChannelsForTest([_channel(1, 'StaleOccupant', 70)]);
|
||||
|
||||
await c.getChannels(maxChannels: 2);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'Fresh0', pskSeed: 10),
|
||||
);
|
||||
// Slot 1 never answers: exhaust the retries.
|
||||
for (var i = 0; i <= 3; i++) {
|
||||
c.handleChannelSyncTimeoutForTest(1);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
|
||||
expect(c.unconfirmedChannelSlots, {1});
|
||||
expect(c.channels.map((ch) => ch.name), ['Fresh0']);
|
||||
expect(
|
||||
c.channels.any((ch) => ch.name == 'StaleOccupant'),
|
||||
isFalse,
|
||||
reason: 'the stale cache occupant must not be restored into the slot',
|
||||
);
|
||||
expect(
|
||||
c.findChannelByIndexForTest(1),
|
||||
isNull,
|
||||
reason: 'lookups for an unconfirmed slot fail closed',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'messages arriving mid-sync are held, then filed after the sync',
|
||||
() async {
|
||||
final c = _connector();
|
||||
|
||||
await c.getChannels(maxChannels: 2);
|
||||
// Barrier is up: a pushed message must not file yet.
|
||||
c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 0));
|
||||
expect(c.channelMessagesForTest[0], isNull);
|
||||
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'Alpha', pskSeed: 10),
|
||||
);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 1, name: 'Beta', pskSeed: 30),
|
||||
);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(c.unconfirmedChannelSlots, isEmpty);
|
||||
expect(
|
||||
c.channelMessagesForTest[0],
|
||||
isNotNull,
|
||||
reason: 'the held frame files once the list is confirmed',
|
||||
);
|
||||
expect(c.channelMessagesForTest[0]!.single.text, 'hi');
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'unread count does not follow a slot across an identity change',
|
||||
() async {
|
||||
final c = _connector();
|
||||
final stale = _channel(0, 'OldChannel', 70)..unreadCount = 5;
|
||||
c.seedCachedChannelsForTest([stale]);
|
||||
|
||||
await c.getChannels(maxChannels: 1);
|
||||
// Same slot, different PSK: a different channel lives here now.
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'NewChannel', pskSeed: 10),
|
||||
);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(c.channels.single.name, 'NewChannel');
|
||||
expect(
|
||||
c.channels.single.unreadCount,
|
||||
0,
|
||||
reason: 'another identity\'s unread count must not ride the slot',
|
||||
);
|
||||
expect(c.slotIdentityChanges, isNotEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'unread count IS preserved when the slot keeps the same channel',
|
||||
() async {
|
||||
final c = _connector();
|
||||
final same = _channel(0, 'Keep', 10)..unreadCount = 7;
|
||||
c.seedCachedChannelsForTest([same]);
|
||||
|
||||
await c.getChannels(maxChannels: 1);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'Keep', pskSeed: 10),
|
||||
);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(c.channels.single.unreadCount, 7);
|
||||
expect(c.slotIdentityChanges, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'in-memory messages do not follow a slot across an identity change (#1063)',
|
||||
() async {
|
||||
final c = _connector();
|
||||
c.seedCachedChannelsForTest([_channel(0, 'OldChannel', 70)]);
|
||||
c.channelMessagesForTest[0] = [
|
||||
ChannelMessage(
|
||||
senderName: 'x',
|
||||
text: 'old occupant message',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000),
|
||||
isOutgoing: false,
|
||||
channelIndex: 0,
|
||||
messageId: 'old1',
|
||||
),
|
||||
];
|
||||
|
||||
await c.getChannels(maxChannels: 1);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'NewChannel', pskSeed: 10),
|
||||
);
|
||||
// Settle the sync completion and the unawaited history reload.
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(
|
||||
c.channelMessagesForTest[0] ?? const <ChannelMessage>[],
|
||||
isEmpty,
|
||||
reason:
|
||||
"the old occupant's conversation must not render under the new "
|
||||
'channel; the slot reloads from the NEW identity\'s (empty) store',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'in-memory messages stay when the slot keeps the same channel',
|
||||
() async {
|
||||
final c = _connector();
|
||||
c.seedCachedChannelsForTest([_channel(0, 'Keep', 10)]);
|
||||
c.channelMessagesForTest[0] = [
|
||||
ChannelMessage(
|
||||
senderName: 'x',
|
||||
text: 'kept',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000),
|
||||
isOutgoing: false,
|
||||
channelIndex: 0,
|
||||
messageId: 'k1',
|
||||
),
|
||||
];
|
||||
|
||||
await c.getChannels(maxChannels: 1);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'Keep', pskSeed: 10),
|
||||
);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(c.channelMessagesForTest[0]!.single.text, 'kept');
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a sync with unconfirmed slots does not overwrite the offline cache',
|
||||
() async {
|
||||
final c = _connector();
|
||||
c.seedCachedChannelsForTest([
|
||||
_channel(0, 'GoodCache0', 10),
|
||||
_channel(1, 'GoodCache1', 30),
|
||||
]);
|
||||
|
||||
await c.getChannels(maxChannels: 2);
|
||||
c.handleFrameForTest(
|
||||
_channelInfoFrame(index: 0, name: 'Fresh0', pskSeed: 10),
|
||||
);
|
||||
for (var i = 0; i <= 3; i++) {
|
||||
c.handleChannelSyncTimeoutForTest(1);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
|
||||
expect(c.unconfirmedChannelSlots, {1});
|
||||
// The confirmed slot is live; the unconfirmed one is a hole, and the last
|
||||
// fully-confirmed cache survives for the next attempt (slot 0 lookup still
|
||||
// resolves, slot 1 fails closed).
|
||||
expect(c.findChannelByIndexForTest(0)?.name, 'Fresh0');
|
||||
expect(c.findChannelByIndexForTest(1), isNull);
|
||||
},
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,128 @@
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/storage/channel_message_store.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';
|
||||
|
||||
/// #1063 (Epic B of #1061): slot reassignment must not move history between
|
||||
/// channel identities. Persisted history is PSK-keyed (#194); the remnants a
|
||||
/// reassignment has to deal with are the LEGACY slot-index keys, and only
|
||||
/// those - the outgoing occupant's PSK-keyed history survives so re-adding
|
||||
/// that channel brings its messages back.
|
||||
void main() {
|
||||
late OffbandDatabase db;
|
||||
late BlobStore blobs;
|
||||
|
||||
const pskA = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
|
||||
const pskB = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb';
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
db = OffbandDatabase(NativeDatabase.memory());
|
||||
blobs = BlobStore(db);
|
||||
BlobStore.overrideForTest(blobs);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await db.close();
|
||||
BlobStore.clearTestOverride();
|
||||
});
|
||||
|
||||
ChannelMessage chan(int i, {String? text}) => ChannelMessage(
|
||||
senderName: 's',
|
||||
text: text ?? 'm$i',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i),
|
||||
isOutgoing: false,
|
||||
channelIndex: 0,
|
||||
messageId: 'id$i',
|
||||
);
|
||||
|
||||
ChannelMessageStore store({String? psk}) => ChannelMessageStore()
|
||||
..setPublicKeyHex = 'd' * 20
|
||||
..channelPskResolver = (_) => psk;
|
||||
|
||||
test('clearLegacySlotHistory purges the legacy slot keys', () async {
|
||||
// Pre-#194 remnants: device-scoped index key and the unscoped one.
|
||||
await blobs.write(
|
||||
'channel_messages_dddddddddd0',
|
||||
ChannelMessageStore.encodeHistoryForTest([chan(1)]),
|
||||
);
|
||||
await blobs.write(
|
||||
'channel_messages_0',
|
||||
ChannelMessageStore.encodeHistoryForTest([chan(2)]),
|
||||
);
|
||||
|
||||
await store(psk: pskA).clearLegacySlotHistory(0);
|
||||
|
||||
expect(
|
||||
await blobs.readWithPrefsFallback('channel_messages_dddddddddd0'),
|
||||
isNull,
|
||||
);
|
||||
expect(await blobs.readWithPrefsFallback('channel_messages_0'), isNull);
|
||||
});
|
||||
|
||||
test('clearLegacySlotHistory keeps the PSK-keyed history', () async {
|
||||
final s = store(psk: pskA);
|
||||
await s.saveChannelMessages(0, [chan(1), chan(2)]);
|
||||
|
||||
await s.clearLegacySlotHistory(0);
|
||||
|
||||
final loaded = await s.loadChannelMessages(0);
|
||||
expect(loaded.map((m) => m.messageId), ['id1', 'id2']);
|
||||
});
|
||||
|
||||
test('after a reassignment clear, the new occupant does not adopt the old '
|
||||
'occupant\'s legacy slot history', () async {
|
||||
// Old occupant A left pre-#194 history under the slot-index key.
|
||||
await blobs.write(
|
||||
'channel_messages_dddddddddd0',
|
||||
ChannelMessageStore.encodeHistoryForTest([chan(1, text: 'old-A')]),
|
||||
);
|
||||
|
||||
// Slot 0 is reassigned to channel B: the connector purges the legacy
|
||||
// slot keys (setChannel, #1063).
|
||||
await store(psk: pskB).clearLegacySlotHistory(0);
|
||||
|
||||
// Channel B's first load must not inherit A's messages via the one-time
|
||||
// slot-index adoption.
|
||||
expect(await store(psk: pskB).loadChannelMessages(0), isEmpty);
|
||||
});
|
||||
|
||||
test('the outgoing occupant\'s history survives a reassignment and comes '
|
||||
'back when the channel is re-added', () async {
|
||||
// Channel A lives in slot 0 with PSK-keyed history.
|
||||
final asA = store(psk: pskA);
|
||||
await asA.saveChannelMessages(0, [chan(1, text: 'kept')]);
|
||||
|
||||
// Slot 0 is reassigned to channel B.
|
||||
await store(psk: pskB).clearLegacySlotHistory(0);
|
||||
await store(psk: pskB).saveChannelMessages(0, [chan(9, text: 'b-msg')]);
|
||||
|
||||
// Channel A is re-added (any slot; identity is the PSK, not the slot).
|
||||
final loaded = await store(psk: pskA).loadChannelMessages(5);
|
||||
expect(loaded.single.text, 'kept');
|
||||
});
|
||||
|
||||
test('clearChannelMessages (true delete) removes the PSK-keyed history '
|
||||
'and the legacy index key', () async {
|
||||
final s = store(psk: pskA);
|
||||
await s.saveChannelMessages(0, [chan(1)]);
|
||||
await blobs.write(
|
||||
'channel_messages_dddddddddd0',
|
||||
ChannelMessageStore.encodeHistoryForTest([chan(2)]),
|
||||
);
|
||||
|
||||
await s.clearChannelMessages(0);
|
||||
|
||||
expect(await s.loadChannelMessages(0), isEmpty);
|
||||
expect(
|
||||
await blobs.readWithPrefsFallback('channel_messages_dddddddddd0'),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
}
|
||||
Loading…
Reference in new issue