diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index e9b1942e..332b40a9 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -3183,7 +3183,7 @@ class MeshCoreConnector extends ChangeNotifier { }, ), ); - final maxRetries = _appSettingsService?.settings.maxMessageRetries ?? 5; + final maxRetries = _appSettingsService?.settings.maxMessageRetries ?? 3; _retryService?.setMaxRetries(maxRetries); } @@ -10190,6 +10190,12 @@ class MeshCoreConnector extends ChangeNotifier { /// Calculate timeout for a message based on radio settings and path length. /// Returns timeout in milliseconds, considering number of hops. + /// + /// This is the airtime formula and nothing more. The measured floor on a DM's + /// ACK window lives in [MessageRetryService.minAckWindowMs] rather than here, + /// because this method also feeds [calculateCliTimeout], and a floor applied + /// here added 11.5 s to every repeater CLI command: a surface with its own + /// issue, its own budget arithmetic and its own tests (#530/#533). (#316) int calculateTimeout({ required int pathLength, int messageBytes = 100, diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 04f2df05..c142f6f8 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -228,7 +228,7 @@ class AppSettings { this.initialRouteWeight = 3.0, this.routeWeightSuccessIncrement = 0.5, this.routeWeightFailureDecrement = 0.2, - this.maxMessageRetries = 5, + this.maxMessageRetries = 3, this.themeMode = 'system', this.languageOverride, this.appDebugLogEnabled = false, @@ -404,7 +404,7 @@ class AppSettings { (json['route_weight_success_increment'] as num?)?.toDouble() ?? 0.5, routeWeightFailureDecrement: (json['route_weight_failure_decrement'] as num?)?.toDouble() ?? 0.2, - maxMessageRetries: json['max_message_retries'] as int? ?? 5, + maxMessageRetries: json['max_message_retries'] as int? ?? 3, themeMode: json['theme_mode'] as String? ?? 'system', languageOverride: json['language_override'] as String?, appDebugLogEnabled: json['app_debug_log_enabled'] as bool? ?? false, diff --git a/lib/services/message_retry_service.dart b/lib/services/message_retry_service.dart index e91fe901..f3302a06 100644 --- a/lib/services/message_retry_service.dart +++ b/lib/services/message_retry_service.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:uuid/uuid.dart'; import 'package:crypto/crypto.dart'; @@ -77,11 +78,50 @@ class RetryServiceConfig { } class MessageRetryService extends ChangeNotifier { + /// Never wait less than this for a DM's ACK, whatever the formula says. + /// + /// Measured, not chosen. Upload OB-ZRNBY (2026-11-27) carries 24 completed + /// round trips as reported by the radio in `PUSH_CODE_SEND_CONFIRMED`: median + /// 6771 ms, 90th percentile 12394 ms, against windows this code armed with a + /// median of 4884 ms. Over half of all ACKs were arriving after the attempt + /// that earned them had already timed out, and 83 DMs cost 311 + /// transmissions. The owner ruled the 90th percentile, rounded up. + /// + /// `calculateTimeout` derives a window from airtime, which is the wrong + /// dominant term: on a multi-hop mesh the time goes into repeater forwarding + /// delay and `TXT_ACK_DELAY`, not onto the air, so an airtime-derived value + /// under-predicts and no coefficient fixes that. This floor is the measured + /// reality; the formula still governs anything slower. + /// + /// The floor lives here, not in `calculateTimeout`, because that method also + /// feeds the repeater CLI budget, where a floor added 11.5 s to every command + /// (#530/#533). + /// + /// Those 24 samples exist only for messages that were eventually confirmed, + /// so they are conditioned on success: the true 90th percentile is higher + /// than 12394 ms, not lower. This is a lower bound. (#316) + static const int minAckWindowMs = 12500; + + int _minAckWindowMs = minAckWindowMs; + + /// 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 + void setMinAckWindowForTest(int ms) => _minAckWindowMs = ms; + 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; + // Three attempts, not five. With the ACK window raised to the measured 90th + // percentile, five attempts spent the same total wait on transmissions that + // mostly fired before an answer could arrive: 83 DMs cost 311 of them in + // OB-ZRNBY. Three attempts at the wider window give up after about the same + // elapsed time as five at the old one, while putting roughly 40% less traffic + // on a shared mesh. It also keeps every attempt's ACK hash distinct, since + // the firmware masks `attempt & 3` and attempt 4 collided with attempt 0. + // (#316) + int _maxRetries = 3; int get maxRetries => _maxRetries; final Map _timeoutTimers = {}; @@ -602,14 +642,24 @@ class MessageRetryService extends ChangeNotifier { // Calculate timeout: prefer ML prediction, then device-provided, then physics fallback final pathLengthValue = message.pathLength ?? contact.pathLength; + // The radio's own estimate, carried in RESP_CODE_SENT, is not a second + // opinion to be discarded. It is derived from the packet that actually went + // on air, which this side only approximates: `calculateTimeout` is handed + // `message.text.length`, 7 bytes for "Dm test", where the wire frame was 21 + // bytes before LoRa framing. Overwriting the radio outright is how a 3252 ms + // estimate became a shorter local window and lost an ACK that came back at + // 3448 ms. Take whichever is longer. (#316) int actualTimeout = timeoutMs; if (config.calculateTimeout != null) { - actualTimeout = config.calculateTimeout!( + final computed = config.calculateTimeout!( pathLengthValue, message.text.length, contactKey: contact.publicKeyHex, ); + actualTimeout = math.max(timeoutMs, computed); } + // And never below the measured floor, whichever of the two won. + actualTimeout = math.max(actualTimeout, _minAckWindowMs); final updatedMessage = message.copyWith( status: MessageStatus.sent, diff --git a/test/connector/ack_window_test.dart b/test/connector/ack_window_test.dart new file mode 100644 index 00000000..6498795b --- /dev/null +++ b/test/connector/ack_window_test.dart @@ -0,0 +1,112 @@ +// #316: the ACK window was smaller than the median round trip. +// +// Upload OB-ZRNBY (2026-11-27) carries 24 completed round trips as measured by +// the radio: median 6771 ms, 90th percentile 12394 ms, against windows this +// code armed with a median of 4884 ms. Over half of all ACKs arrived after the +// attempt that earned them had timed out, and 83 DMs cost 311 transmissions. +// +// The owner ruled the 90th percentile rounded up, 12.5 s, with three attempts +// rather than five. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late MeshCoreConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + connector = MeshCoreConnector(); + }); + + group('the ACK window never drops below the measured 90th percentile', () { + // 12500 is written as a literal on purpose. The owner ruled this number + // from the OB-ZRNBY distribution, so a test that read it back off the + // constant would keep passing if someone quietly changed the constant. + test('the floor is the ruled 12.5 s', () { + expect(MessageRetryService.minAckWindowMs, equals(12500)); + }); + + // The airtime formula is deliberately NOT floored. It also feeds + // calculateCliTimeout, and flooring it there added 11.5 s to every repeater + // CLI command, which is a separate surface with its own budget arithmetic + // and its own tests (#530/#533). These are the small values the field + // capture armed, against measured round trips of 3.1 s to 16.3 s. + test( + 'the formula itself is left alone, so the CLI budget is untouched', + () { + expect( + connector.calculateTimeout(pathLength: -1, messageBytes: 7), + lessThan(12500), + reason: 'about 1.3 s for a flood', + ); + expect( + connector.calculateTimeout(pathLength: 0, messageBytes: 7), + lessThan(12500), + reason: 'about 1.05 s for a zero-hop direct send', + ); + }, + ); + + test('a long path still exceeds the floor: it is a minimum, not a cap', () { + expect( + connector.calculateTimeout(pathLength: 30, messageBytes: 100), + greaterThan(12500), + ); + }); + }); + + group('three attempts, not five (#316)', () { + test('the retry service defaults to 3', () { + expect(MessageRetryService().maxRetries, equals(3)); + }); + + test( + 'settings default to 3, and so does a stored blob without the key', + () { + expect(AppSettings().maxMessageRetries, equals(3)); + expect(AppSettings.fromJson(const {}).maxMessageRetries, equals(3)); + }, + ); + + test('every attempt keeps a distinct ACK hash, unlike five', () { + // The firmware masks `attempt & 3`, so attempt 4 reused attempt 0's hash + // and the first and last attempts were indistinguishable. Three attempts + // cannot collide. + final senderKey = Uint8List.fromList( + List.generate(32, (i) => i + 1), + ); + final hashes = List.generate( + 3, + (i) => MessageRetryService.computeExpectedAckHash( + 1700000000, + i, + 'Dm test', + senderKey, + ), + ); + expect(hashes.toSet().length, equals(3)); + + // And the collision five attempts had, shown rather than asserted from + // memory: attempt 4 masks to the same value as attempt 0. + expect( + MessageRetryService.computeExpectedAckHash( + 1700000000, + 4, + 'Dm test', + senderKey, + ), + equals(hashes.first), + ); + }); + }); +} diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index 5f3d76ab..d3711730 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -275,7 +275,10 @@ void main() { expect(settings.initialRouteWeight, equals(3.0)); expect(settings.routeWeightSuccessIncrement, equals(0.5)); expect(settings.routeWeightFailureDecrement, equals(0.2)); - expect(settings.maxMessageRetries, equals(5)); + // Three attempts, not five: #316 raised the ACK window to the measured + // 90th percentile, so five attempts spent the same total wait on + // transmissions that mostly fired before an answer could arrive. + expect(settings.maxMessageRetries, equals(3)); }); test('experimentalUnlocked defaults off and round-trips (#509)', () { @@ -304,7 +307,7 @@ void main() { expect(json['initial_route_weight'], equals(3.0)); expect(json['route_weight_success_increment'], equals(0.5)); expect(json['route_weight_failure_decrement'], equals(0.2)); - expect(json['max_message_retries'], equals(5)); + expect(json['max_message_retries'], equals(3)); }); test('fromJson reads all new fields', () { @@ -333,7 +336,7 @@ void main() { expect(settings.initialRouteWeight, equals(3.0)); expect(settings.routeWeightSuccessIncrement, equals(0.5)); expect(settings.routeWeightFailureDecrement, equals(0.2)); - expect(settings.maxMessageRetries, equals(5)); + expect(settings.maxMessageRetries, equals(3)); }, ); diff --git a/test/services/retry_and_protocol_test.dart b/test/services/retry_and_protocol_test.dart index b4fc41ee..fa55a789 100644 --- a/test/services/retry_and_protocol_test.dart +++ b/test/services/retry_and_protocol_test.dart @@ -1163,7 +1163,11 @@ void main() { test('a manual path override floods on the final attempt instead of ' 'failing on a route that is not working', () async { - final retryService = MessageRetryService()..setMaxRetries(2); + final retryService = MessageRetryService() + ..setMaxRetries(2) + // Without this the 12.5 s ACK floor (#316) would make the retry fire + // long after this test finishes waiting. + ..setMinAckWindowForTest(1); // A multi-hop route the user picked by hand in path management. final contact = _makeContact( publicKey: recipientKey, @@ -1225,6 +1229,81 @@ void main() { retryService.dispose(); }); + test('the radio\'s own ACK estimate is a floor, not a second opinion ' + '(#316)', () async { + final retryService = MessageRetryService(); + final contact = _makeContact(publicKey: recipientKey, pathLength: -1); + final armed = []; + + retryService.initialize( + RetryServiceConfig( + sendMessage: (_, _, _, _) async {}, + addMessage: (_, _) {}, + updateMessage: (m) => armed.add(m.estimatedTimeoutMs), + clearContactPath: (_) {}, + // Stands in for a local computation that comes out SHORTER than the + // radio's. Before this change it replaced the radio's number + // outright, which is how a 3252 ms estimate became a window too + // small for an ACK that returned at 3448 ms. + calculateTimeout: (_, _, {String? contactKey}) => 1200, + ), + ); + + await retryService.sendMessageWithRetry(contact: contact, text: 'hi'); + await Future.delayed(const Duration(milliseconds: 20)); + // Above the 12.5 s floor, so this test is about max() and not the floor. + retryService.updateMessageFromSent(0x1234, 14000); + + expect( + armed.whereType(), + contains(14000), + reason: + 'the radio said 14000 ms and the local guess said 1200 ms, so ' + 'the armed window must be 14000 ms', + ); + expect( + armed.whereType(), + isNot(contains(1200)), + reason: 'the shorter local guess must never win', + ); + + retryService.dispose(); + }); + + test('and the window never drops below the measured floor, whichever ' + 'of the two won (#316)', () async { + final retryService = MessageRetryService(); + final contact = _makeContact(publicKey: recipientKey, pathLength: -1); + final armed = []; + + retryService.initialize( + RetryServiceConfig( + sendMessage: (_, _, _, _) async {}, + addMessage: (_, _) {}, + updateMessage: (m) => armed.add(m.estimatedTimeoutMs), + clearContactPath: (_) {}, + // Both sources small, as they were in the field: the radio reported + // 3252 ms and the formula computed about 1300 ms for a flood, while + // measured round trips ran from 3115 ms to 16266 ms. + calculateTimeout: (_, _, {String? contactKey}) => 1300, + ), + ); + + await retryService.sendMessageWithRetry(contact: contact, text: 'hi'); + await Future.delayed(const Duration(milliseconds: 20)); + retryService.updateMessageFromSent(0x1234, 3252); + + expect( + armed.whereType(), + contains(MessageRetryService.minAckWindowMs), + reason: + 'neither 3252 ms nor 1300 ms covers a median round trip of ' + '6771 ms, so the floor has to win', + ); + + retryService.dispose(); + }); + test('a pinned route is re-established once per send, at the width it ' 'was captured at', () async { final retryService = MessageRetryService();