fix(#316): bound the ACK window, and write a pin when it changes mid-send

Both from the adversarial review gate, both regressions this branch
introduced rather than pre-existing faults.

1. `timeoutMs` reaches updateMessageFromSent as a raw readUInt32LE off the
   RESP_CODE_SENT frame with nothing bounding it. While the local
   computation overwrote that value it did not matter; making the radio's
   estimate a floor meant a garbage frame could arm a timer 49 days long,
   and one message in flight per contact is a queue invariant, so that
   wedged every later DM to that contact until an app restart. Clamped to
   60 s, about four times the longest real round trip in OB-ZRNBY.

2. The pinned-route write was gated on `message.retryCount == 0`, so a user
   changing the override between attempts left the radio transmitting the
   old pin while this side had already re-armed its timeout and its
   path-weight bookkeeping for the new one. `updatePendingContact` hands the
   new override to the retry in flight, so attempt 0 is the wrong key. Now
   keyed on the route itself: a change is written, an unchanged pin is not.
   That keeps it from becoming the per-attempt re-assert #1198 removed.

Tests, both proven to fail first: 4294967295 ms armed where 60000 was
required, and the new pin never reaching the radio. The unchanged-pin case
is covered too, at maxRetries 3 so the retry under test is an ordinary
attempt rather than the final flooding one, which would have passed for the
wrong reason.

Third review finding, not fixed, justified: existing installs without a
stored `max_message_retries` move from 5 attempts to 3 on upgrade. That is
the ruling, it applies to everyone by design, the slider still spans 2 to
10, and the total time to failure is comparable because the window widened.
feat/1198-dm-path-ownership
diffwireauto 7 hours ago
parent ba4713e559
commit 710b299d6d

@ -102,8 +102,31 @@ class MessageRetryService extends ChangeNotifier {
/// than 12394 ms, not lower. This is a lower bound. (#316)
static const int minAckWindowMs = 12500;
/// Ceiling on a single attempt's ACK window.
///
/// `timeoutMs` reaches [updateMessageFromSent] as a raw `readUInt32LE` off
/// the RESP_CODE_SENT frame, with nothing bounding it. While the local
/// computation overwrote that value this did not matter; now that the radio's
/// estimate is a floor, a garbage frame could arm a timer days long. One
/// message in flight per contact is a queue invariant, so that would wedge
/// every later DM to that contact until the app restarted.
///
/// 60 s is about four times the longest real round trip in the OB-ZRNBY
/// capture (16266 ms), so it cannot clip a legitimate wait. (#316)
static const int maxAckWindowMs = 60000;
int _minAckWindowMs = minAckWindowMs;
/// The path last written to the radio for a message, by message id.
///
/// A hand-picked route is pushed once per send, but "once" cannot mean "only
/// on attempt 0": the user can change the override between attempts, and
/// `updatePendingContact` hands the new one to the retry in flight. Keyed on
/// the route itself so a change is written and an unchanged pin is not,
/// which is what keeps this from becoming the per-attempt re-assert that
/// #1198 removed. (#1223)
final Map<String, String> _lastPushedPath = {};
/// Lowers the ACK floor so a test can drive a retry without a 12.5 s
/// wall-clock wait per attempt. Production never calls this.
@visibleForTesting
@ -248,6 +271,12 @@ class MessageRetryService extends ChangeNotifier {
_pendingMessages[messageId] = failed;
_config?.updateMessage(failed);
}
// This path does not run _cleanupMessage, because the other pending
// maps still have to be reachable for a late ACK from an earlier
// attempt. `_lastPushedPath` only records what we last told the
// radio and ACK matching never reads it, so it is dropped here
// rather than left to accumulate. (#1223, review round 2)
_lastPushedPath.remove(messageId);
_onMessageResolved(messageId, contactKey);
});
return;
@ -365,26 +394,39 @@ class MessageRetryService extends ChangeNotifier {
if (config.clearContactPath != null) {
await config.clearContactPath!(contact);
}
} else if (message.retryCount == 0 && (contact.pathOverride ?? 0) > 0) {
// One write per send, and only for a route the user chose by hand.
} else if ((contact.pathOverride ?? 0) > 0) {
// A route the user chose by hand, written when it is not already what we
// told the radio.
//
// This is not the defect above. That was a client-side snapshot of a
// path the RADIO had learned, re-asserted before every attempt, which
// could overwrite a fresher route the radio had just picked up off the
// air. This is the user's own explicit choice, written once, at the
// start of a send, and it has to be written because the previous send's
// final attempt may have cleared it: the fallback floods, and flooding
// means clearing the stored path. Without this a pinned route stops
// being honoured after one bad send while the UI still claims it, which
// is the silent failure that got "Direct" removed. (#1223 R4)
// air. This is the user's own explicit choice, and it has to be written
// at all because the previous send's final attempt may have cleared it:
// the fallback floods, and flooding means clearing the stored path.
// Without it a pinned route stops being honoured after one bad send
// while the UI still claims it, which is the silent failure that got
// "Direct" removed. (#1223 R4)
//
// Keyed on the route rather than on `retryCount == 0`, because the user
// can change the override between attempts and `updatePendingContact`
// hands the new one to the retry in flight. Gating on attempt 0 left the
// radio transmitting the old pin while this side had already re-armed
// its timeout and its path-weight bookkeeping for the new one.
final resolved = resolvePathSelection(contact);
if (config.setContactPath != null && resolved.pathBytes.isNotEmpty) {
final signature =
'${resolved.hopCount}:${resolved.hashWidth}:'
'${resolved.pathBytes.join(",")}';
if (config.setContactPath != null &&
resolved.pathBytes.isNotEmpty &&
_lastPushedPath[messageId] != signature) {
await config.setContactPath!(
contact,
Uint8List.fromList(resolved.pathBytes),
resolved.hopCount,
hashWidth: resolved.hashWidth,
);
_lastPushedPath[messageId] = signature;
}
}
@ -658,8 +700,12 @@ class MessageRetryService extends ChangeNotifier {
);
actualTimeout = math.max(timeoutMs, computed);
}
// And never below the measured floor, whichever of the two won.
actualTimeout = math.max(actualTimeout, _minAckWindowMs);
// Never below the measured floor, and never above the ceiling: the radio's
// value is unvalidated, and an absurd one would park this message in the
// per-contact queue forever.
actualTimeout = math
.max(actualTimeout, _minAckWindowMs)
.clamp(_minAckWindowMs, maxAckWindowMs);
final updatedMessage = message.copyWith(
status: MessageStatus.sent,
@ -707,6 +753,7 @@ class MessageRetryService extends ChangeNotifier {
_pendingMessages.remove(messageId);
_pendingContacts.remove(messageId);
_attemptPathHistory.remove(messageId);
_lastPushedPath.remove(messageId);
_timeoutTimers.remove(messageId);
_sentConfirmationTimers.remove(messageId)?.cancel();
_resolvedMessages.remove(messageId);

@ -1304,6 +1304,136 @@ void main() {
retryService.dispose();
});
test('an absurd window from the radio is clamped, so one bad frame '
'cannot park the contact\'s queue forever (#316)', () async {
final retryService = MessageRetryService();
final contact = _makeContact(publicKey: recipientKey, pathLength: -1);
final armed = <int?>[];
retryService.initialize(
RetryServiceConfig(
sendMessage: (_, _, _, _) async {},
addMessage: (_, _) {},
updateMessage: (m) => armed.add(m.estimatedTimeoutMs),
clearContactPath: (_) {},
),
);
await retryService.sendMessageWithRetry(contact: contact, text: 'hi');
await Future<void>.delayed(const Duration(milliseconds: 20));
// `timeoutMs` is a raw readUInt32LE off the frame with nothing bounding
// it. One message is in flight per contact, so an unclamped value here
// would wedge every later DM to this contact until an app restart.
retryService.updateMessageFromSent(0x1234, 0xFFFFFFFF);
expect(
armed.whereType<int>(),
contains(MessageRetryService.maxAckWindowMs),
reason: '49 days is not a send timeout',
);
retryService.dispose();
});
test('a mid-flight override change is written to the radio, because the '
'radio would otherwise keep transmitting the old pin', () async {
// Three attempts, so attempt 1 is an ordinary retry rather than the
// final one. At maxRetries 2 the retry IS the final attempt, which
// floods and clears instead of writing, and the test would pass for
// the wrong reason.
final retryService = MessageRetryService()
..setMaxRetries(3)
..setMinAckWindowForTest(1);
var contact = _makeContact(
publicKey: recipientKey,
pathLength: 2,
path: const [0x10, 0x20],
pathOverride: 2,
pathOverrideBytes: const [0x10, 0x20],
);
final writes = <String>[];
retryService.initialize(
RetryServiceConfig(
sendMessage: (_, _, _, _) async {},
addMessage: (_, _) {},
updateMessage: (_) {},
setContactPath: (_, bytes, hops, {hashWidth = 1}) =>
writes.add(bytes.join(',')),
clearContactPath: (_) {},
),
);
await retryService.sendMessageWithRetry(contact: contact, text: 'hi');
await Future<void>.delayed(const Duration(milliseconds: 20));
expect(writes, equals(['16,32']), reason: 'attempt 1 writes the pin');
// The user picks a different route while the send is still retrying.
contact = _makeContact(
publicKey: recipientKey,
pathLength: 3,
path: const [0x10, 0x20, 0x30],
pathOverride: 3,
pathOverrideBytes: const [0x10, 0x20, 0x30],
);
retryService.updatePendingContact(contact);
retryService.updateMessageFromSent(0x1234, 1);
await Future<void>.delayed(const Duration(milliseconds: 1400));
expect(
writes,
equals(['16,32', '16,32,48']),
reason:
'the new pin reaches the radio; gating on attempt 0 left the '
'radio sending the old route while this side had already '
're-armed its timeout for the new one',
);
retryService.dispose();
});
test('an unchanged pin is not rewritten on a retry, which is the '
'per-attempt re-assert #1198 removed', () async {
// Three attempts, so the retry below is an ordinary one and genuinely
// had the chance to rewrite the pin.
final retryService = MessageRetryService()
..setMaxRetries(3)
..setMinAckWindowForTest(1);
final contact = _makeContact(
publicKey: recipientKey,
pathLength: 2,
path: const [0x10, 0x20],
pathOverride: 2,
pathOverrideBytes: const [0x10, 0x20],
);
final writes = <String>[];
retryService.initialize(
RetryServiceConfig(
sendMessage: (_, _, _, _) async {},
addMessage: (_, _) {},
updateMessage: (_) {},
setContactPath: (_, bytes, hops, {hashWidth = 1}) =>
writes.add(bytes.join(',')),
clearContactPath: (_) {},
),
);
await retryService.sendMessageWithRetry(contact: contact, text: 'hi');
await Future<void>.delayed(const Duration(milliseconds: 20));
retryService.updateMessageFromSent(0x1234, 1);
await Future<void>.delayed(const Duration(milliseconds: 1400));
expect(
writes,
equals(['16,32']),
reason: 'written once, not once per attempt',
);
retryService.dispose();
});
test('a pinned route is re-established once per send, at the width it '
'was captured at', () async {
final retryService = MessageRetryService();

Loading…
Cancel
Save

Powered by TurnKey Linux.