From ee32e2e38e8426f20251a724e055faf93be1a1de Mon Sep 17 00:00:00 2001 From: Strycher Date: Mon, 27 Jul 2026 12:34:50 -0400 Subject: [PATCH] fix(#395): MTU-aware size cap + de-wedge DM/channel send on failed write A max-length DM built a 170-byte frame but this BLE link only writes ATT_MTU-3 (=169) bytes, so writeCharacteristic threw. The DM path swallowed the throw and never resolved the message, leaving it "active" forever and silently blocking every later DM to that contact until force-stop+reconnect. - Size: maxContact/ChannelMessageBytes take an MTU-aware frame budget (BLE = mtuNow-3, USB/TCP = maxFrameSize); composers pass connector.effectiveMaxFrameSize. The channel cap now also subtracts the "Name: " prefix so a small-MTU link can't overflow. - DM wedge: _sendMessageDirect propagates the failure and the retry callback is awaited, so a failed send marks the message failed and drains the per-contact queue. Added a RESP_CODE_SENT safety timeout. - Channel wedge: sendChannelMessage clears the stuck queue id and marks the message failed on a failed write. - Tests: MTU-aware caps + failed-send-does-not-wedge regression. Co-Authored-By: Claude Opus 4.8 --- lib/connector/meshcore_connector.dart | 83 +++++++++++++++--- lib/connector/meshcore_protocol.dart | 18 +++- lib/screens/channel_chat_screen.dart | 15 +++- lib/screens/chat_screen.dart | 8 +- lib/services/message_retry_service.dart | 51 +++++++++++- test/services/retry_and_protocol_test.dart | 97 +++++++++++++++++++++- 6 files changed, 249 insertions(+), 23 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index a48f8345..7a470c5e 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -431,6 +431,23 @@ class MeshCoreConnector extends ChangeNotifier { // Getters MeshCoreConnectionState get state => _state; BluetoothDevice? get device => _device; + + /// Largest frame (in bytes) the active transport can write in a single + /// operation. BLE caps one characteristic write at ATT_MTU - 3 (ATT opcode + + /// handle); a device that negotiates a smaller MTU than [maxFrameSize] assumes + /// would otherwise reject a max-length message and wedge the send path (#395). + /// USB/TCP have no such per-write cap, so they take the full [maxFrameSize]. + int get effectiveMaxFrameSize { + if (_activeTransport != MeshCoreTransportType.bluetooth) { + return maxFrameSize; + } + final mtu = _device?.mtuNow ?? 0; + if (mtu <= 0) return maxFrameSize; + final writable = mtu - 3; + if (writable >= maxFrameSize) return maxFrameSize; + return writable < 23 ? 23 : writable; + } + String? get deviceId => _deviceId; String get deviceIdLabel => _deviceId ?? 'Unknown'; @@ -1381,6 +1398,10 @@ class MeshCoreConnector extends ChangeNotifier { ); } catch (e) { appLogger.error('Failed to send message: $e', tag: 'Connector'); + // Propagate so MessageRetryService marks the message failed and drains the + // per-contact queue. Swallowing here left the message "active" forever and + // silently blocked every later DM to the contact until reconnect (#395). + rethrow; } } @@ -3638,11 +3659,22 @@ class MeshCoreConnector extends ChangeNotifier { final reactionQueueId = _nextReactionSendQueueId(); _pendingChannelSentQueue.add(reactionQueueId); await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); - await sendFrame( - buildSendChannelTextMsgFrame(channel.index, text), - channelSendQueueId: reactionQueueId, - expectsGenericAck: true, - ); + try { + await sendFrame( + buildSendChannelTextMsgFrame(channel.index, text), + channelSendQueueId: reactionQueueId, + expectsGenericAck: true, + ); + } catch (e) { + // A failed write must not leave a stale id at the head of the FIFO + // queue, or the next channel message's OK would be credited to it and + // the real message would never clear (#395). + _pendingChannelSentQueue.remove(reactionQueueId); + appLogger.error( + 'Failed to send channel reaction: $e', + tag: 'Connector', + ); + } return; } @@ -3660,11 +3692,19 @@ class MeshCoreConnector extends ChangeNotifier { final outboundText = prepareChannelOutboundText(channel.index, text); await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); - await sendFrame( - buildSendChannelTextMsgFrame(channel.index, outboundText), - channelSendQueueId: message.messageId, - expectsGenericAck: true, - ); + try { + await sendFrame( + buildSendChannelTextMsgFrame(channel.index, outboundText), + channelSendQueueId: message.messageId, + expectsGenericAck: true, + ); + } catch (e) { + // Clear the stuck queue id and surface the failure in the chat bubble + // instead of leaving the message pending and blocking the queue (#395). + _pendingChannelSentQueue.remove(message.messageId); + _markChannelMessageFailed(channel.index, message.messageId); + appLogger.error('Failed to send channel message: $e', tag: 'Connector'); + } } Future removeContact(Contact contact) async { @@ -6448,6 +6488,29 @@ class MeshCoreConnector extends ChangeNotifier { return false; } + void _markChannelMessageFailed(int channelIndex, String messageId) { + final channelMessages = _channelMessages[channelIndex]; + if (channelMessages == null) return; + for (int i = channelMessages.length - 1; i >= 0; i--) { + final message = channelMessages[i]; + if (message.messageId != messageId) { + continue; + } + if (!message.isOutgoing || + message.status != ChannelMessageStatus.pending) { + return; + } + channelMessages[i] = message.copyWith( + status: ChannelMessageStatus.failed, + ); + unawaited( + _channelMessageStore.saveChannelMessages(channelIndex, channelMessages), + ); + notifyListeners(); + return; + } + } + void _handleOk() { if (_pendingGenericAckQueue.isEmpty) { return; diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index f18413e4..c19b910d 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -587,16 +587,26 @@ const int _sendTextMsgOverheadBytes = const int _sendChannelTextMsgOverheadBytes = 1 + 1 + 1 + 4 + 1 + 2; // +2 safety margin -int maxContactMessageBytes() { - final byFrame = maxFrameSize - _sendTextMsgOverheadBytes; +// [maxFrameBytes] is the largest frame the active transport can write in one +// operation. On BLE that is ATT_MTU - 3, which can be smaller than [maxFrameSize]; +// pass it so a max-length message never overflows the characteristic write (#395). +// Defaults to [maxFrameSize] for callers without a live transport (USB/TCP, tests). +int maxContactMessageBytes({int? maxFrameBytes}) { + final frameBudget = maxFrameBytes ?? maxFrameSize; + final byFrame = frameBudget - _sendTextMsgOverheadBytes; return _minPositive(byFrame, maxTextPayloadBytes); } -int maxChannelMessageBytes(String? senderName) { +int maxChannelMessageBytes(String? senderName, {int? maxFrameBytes}) { + final frameBudget = maxFrameBytes ?? maxFrameSize; final nameLength = _senderNameBytes(senderName); final prefixBytes = nameLength + 2; // ": " final byPayload = maxTextPayloadBytes - prefixBytes; - final byFrame = maxFrameSize - _sendChannelTextMsgOverheadBytes; + // The wire text is ": ", so the prefix eats into the frame + // budget too. At maxFrameSize the payload limit always governed and this went + // unnoticed; with a smaller BLE budget the frame limit can govern, so the + // prefix must be subtracted here or a channel frame can still overflow (#395). + final byFrame = frameBudget - _sendChannelTextMsgOverheadBytes - prefixBytes; return _minPositive(byPayload, byFrame); } diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 1cac5815..1007fa3c 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1155,7 +1155,10 @@ class _ChannelChatScreenState extends State { Widget _buildMessageComposer() { final connector = context.watch(); - final maxBytes = maxChannelMessageBytes(connector.selfName); + final maxBytes = maxChannelMessageBytes( + connector.selfName, + maxFrameBytes: connector.effectiveMaxFrameSize, + ); final settings = context.watch().settings; return Column( mainAxisSize: MainAxisSize.min, @@ -1388,7 +1391,10 @@ class _ChannelChatScreenState extends State { messageText = '@[${_replyingToMessage!.senderName}] $messageText'; } - final maxBytes = maxChannelMessageBytes(connector.selfName); + final maxBytes = maxChannelMessageBytes( + connector.selfName, + maxFrameBytes: connector.effectiveMaxFrameSize, + ); final outboundText = connector.prepareChannelOutboundText( _currentChannel.index, messageText, @@ -1430,7 +1436,10 @@ class _ChannelChatScreenState extends State { final hops = message.pathBytes.length ~/ (w < 1 ? 1 : w); final prefix = '@[${message.senderName}] ↩ ${context.l10n.chat_hopsCount(hops)} · via '; - final maxBytes = maxChannelMessageBytes(connector.selfName); + final maxBytes = maxChannelMessageBytes( + connector.selfName, + maxFrameBytes: connector.effectiveMaxFrameSize, + ); var path = _formatPathPrefixes(message.pathBytes, w); var truncated = false; diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 0e733503..dfe0be79 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -595,7 +595,9 @@ class _ChatScreenState extends State { if (context.watch().isBlocked(widget.contact.publicKeyHex)) { return _buildBlockedBar(); } - final maxBytes = maxContactMessageBytes(); + final maxBytes = maxContactMessageBytes( + maxFrameBytes: connector.effectiveMaxFrameSize, + ); final colorScheme = Theme.of(context).colorScheme; final settings = context.watch().settings; return Container( @@ -815,7 +817,9 @@ class _ChatScreenState extends State { } } } - final maxBytes = maxContactMessageBytes(); + final maxBytes = maxContactMessageBytes( + maxFrameBytes: connector.effectiveMaxFrameSize, + ); final outboundText = connector.prepareContactOutboundText( _resolveContact(connector), outgoingText, diff --git a/lib/services/message_retry_service.dart b/lib/services/message_retry_service.dart index 733dfc59..ae81a68c 100644 --- a/lib/services/message_retry_service.dart +++ b/lib/services/message_retry_service.dart @@ -34,7 +34,7 @@ typedef AckHashMapping = ({ }); class RetryServiceConfig { - final void Function(Contact, String, int, int) sendMessage; + final Future Function(Contact, String, int, int) sendMessage; final void Function(String, Message) addMessage; final void Function(Message) updateMessage; final Function(Contact)? clearContactPath; @@ -74,10 +74,14 @@ class RetryServiceConfig { class MessageRetryService extends ChangeNotifier { static const int maxAckHistorySize = 100; + // How long to wait for the radio's RESP_CODE_SENT before treating an + // apparently-sent message as failed so it can't wedge the queue (#395). + static const int _sentConfirmationTimeoutMs = 8000; int _maxRetries = 5; int get maxRetries => _maxRetries; final Map _timeoutTimers = {}; + final Map _sentConfirmationTimers = {}; final Map _pendingMessages = {}; final Map _pendingContacts = {}; final Map> _attemptPathHistory = {}; @@ -348,7 +352,43 @@ class MessageRetryService extends ChangeNotifier { ); } - config.sendMessage(contact, message.text, attempt, timestampSeconds); + // Await so a send failure (e.g. an oversized BLE write) propagates to the + // catchError in _sendNextForContact, which marks the message failed and + // drains the per-contact queue instead of wedging it (#395). + await config.sendMessage(contact, message.text, attempt, timestampSeconds); + + // The write reached the transport; now guard the window until the radio + // returns RESP_CODE_SENT. If it never does (frame dropped on the wire), this + // message would otherwise stay "active" forever and block the queue (#395). + _startSentConfirmationTimer(messageId); + } + + void _startSentConfirmationTimer(String messageId) { + _sentConfirmationTimers[messageId]?.cancel(); + _sentConfirmationTimers[messageId] = Timer( + const Duration(milliseconds: _sentConfirmationTimeoutMs), + () => _handleSentConfirmationTimeout(messageId), + ); + } + + void _handleSentConfirmationTimeout(String messageId) { + _sentConfirmationTimers.remove(messageId); + final message = _pendingMessages[messageId]; + final contact = _pendingContacts[messageId]; + if (message == null || contact == null) return; + // RESP_CODE_SENT would have moved the status to sent (and cancelled this + // timer); still-pending here means the radio never confirmed the send. + if (message.status != MessageStatus.pending) return; + + final failed = message.copyWith(status: MessageStatus.failed); + _pendingMessages[messageId] = failed; + _config?.updateMessage(failed); + _config?.debugLogService?.warn( + 'No RESP_CODE_SENT within ${_sentConfirmationTimeoutMs}ms — marking send failed', + tag: 'AckHash', + ); + notifyListeners(); + _onMessageResolved(messageId, contact.publicKeyHex); } bool updateMessageFromSent(int ackHash, int timeoutMs) { @@ -424,6 +464,8 @@ class MessageRetryService extends ChangeNotifier { _pendingMessages[messageId] = updatedMessage; config.updateMessage(updatedMessage); + // Radio confirmed the send — the delivery-ack timer takes over from here. + _sentConfirmationTimers.remove(messageId)?.cancel(); _startTimeoutTimer(messageId, actualTimeout); return true; } @@ -459,6 +501,7 @@ class MessageRetryService extends ChangeNotifier { _pendingContacts.remove(messageId); _attemptPathHistory.remove(messageId); _timeoutTimers.remove(messageId); + _sentConfirmationTimers.remove(messageId)?.cancel(); _resolvedMessages.remove(messageId); } @@ -747,6 +790,10 @@ class MessageRetryService extends ChangeNotifier { timer.cancel(); } _timeoutTimers.clear(); + for (var timer in _sentConfirmationTimers.values) { + timer.cancel(); + } + _sentConfirmationTimers.clear(); _pendingMessages.clear(); _pendingContacts.clear(); _attemptPathHistory.clear(); diff --git a/test/services/retry_and_protocol_test.dart b/test/services/retry_and_protocol_test.dart index b6c53b6c..b019859e 100644 --- a/test/services/retry_and_protocol_test.dart +++ b/test/services/retry_and_protocol_test.dart @@ -567,7 +567,7 @@ void main() { retryService.initialize( RetryServiceConfig( - sendMessage: (_, _, _, _) {}, + sendMessage: (_, _, _, _) async {}, addMessage: (_, message) => addedMessage = message, updateMessage: (_) {}, clearContactPath: (_) {}, @@ -601,7 +601,7 @@ void main() { retryService.initialize( RetryServiceConfig( - sendMessage: (_, _, _, _) {}, + sendMessage: (_, _, _, _) async {}, addMessage: (_, message) => addedMessage = message, updateMessage: (_) {}, clearContactPath: (_) {}, @@ -616,4 +616,97 @@ void main() { expect(addedMessage!.pathBytes, isEmpty); }); }); + + group('MTU-aware message size caps (#395)', () { + test('maxContactMessageBytes shrinks with a smaller frame budget and the ' + 'built frame fits the budget', () { + // Omitting the budget matches passing maxFrameSize explicitly. + expect( + maxContactMessageBytes(), + equals(maxContactMessageBytes(maxFrameBytes: maxFrameSize)), + ); + // A 169-byte writable budget (ATT_MTU 172 - 3) caps below the default. + final cap169 = maxContactMessageBytes(maxFrameBytes: 169); + expect(cap169, lessThan(maxContactMessageBytes())); + // Real DM frame overhead is 14 bytes; the built frame must fit 169. + expect(14 + cap169, lessThanOrEqualTo(169)); + }); + + test( + 'maxChannelMessageBytes subtracts the sender prefix so the frame never ' + 'exceeds a small budget', + () { + const name = 'Bob'; + const budget = 120; + final cap = maxChannelMessageBytes(name, maxFrameBytes: budget); + expect(cap, lessThan(maxChannelMessageBytes(name))); + // Wire text = "Bob: " (5 bytes) + userText; real channel overhead = 8. + const realOverhead = 8; + const prefix = 5; // "Bob: " + expect(realOverhead + prefix + cap, lessThanOrEqualTo(budget)); + }, + ); + }); + + group('send failure does not wedge the contact queue (#395)', () { + test( + 'a throwing send marks the message failed and lets later sends proceed', + () async { + final retryService = MessageRetryService(); + final contact = _makeContact( + publicKey: recipientKey, + pathLength: 2, + path: const [0x10, 0x20], + ); + final updates = []; + var sendCalls = 0; + var failNext = true; + + retryService.initialize( + RetryServiceConfig( + sendMessage: (_, _, _, _) async { + sendCalls++; + if (failNext) { + failNext = false; + throw Exception( + 'data longer than allowed, datalen: 170 > max: 169', + ); + } + }, + addMessage: (_, _) {}, + updateMessage: updates.add, + clearContactPath: (_) {}, + setContactPath: (_, _, _) {}, + ), + ); + + await retryService.sendMessageWithRetry( + contact: contact, + text: 'too long', + ); + await Future.delayed(const Duration(milliseconds: 20)); + + expect( + updates.any((m) => m.status == MessageStatus.failed), + isTrue, + reason: 'a failed send must mark the message failed, not swallow it', + ); + + // The prior failure must not block a later DM to the same contact. + await retryService.sendMessageWithRetry( + contact: contact, + text: 'ok now', + ); + await Future.delayed(const Duration(milliseconds: 20)); + + expect( + sendCalls, + greaterThanOrEqualTo(2), + reason: 'the per-contact queue must drain after a failed send', + ); + + retryService.dispose(); + }, + ); + }); }