Fix timeout observations, drop the last-rx feature and evict weak paths

- Record delivery observations with the path of the attempt the ACK
  belongs to, and skip ambiguous ACKs, so a late direct ACK is not
  learned as a flood delivery.
- Remove secondsSinceLastRx from the timeout model: it measured time
  since any companion frame, which was near zero at train and predict.
- When a contact's path history is full, evict the lowest-scoring path
  instead of silently dropping new discoveries.
This commit is contained in:
zjs81 committed 2026-10-25 11:36:13 -07:00
1 parent 6bc6143c4e
commit 82dcab1d92
8 files changed
+70 -31

No files matched your search

-14
View File
@@ -334,12 +334,6 @@ class MeshCoreConnector extends ChangeNotifier {
ReceivedImageStore? _receivedImageStore; ReceivedImageStore? _receivedImageStore;
void Function(ImageChunkOutcome outcome)? _onImageChunk; void Function(ImageChunkOutcome outcome)? _onImageChunk;
void Function(int senderPrefix)? _onImageSenderPrefix; void Function(int senderPrefix)? _onImageSenderPrefix;
// Intentionally global (not per-contact): tracks overall network activity.
// Frequent RX from any source indicates a busy network with more collisions.
DateTime _lastRxTime = DateTime.now();
// Snapshot of _lastRxTime taken before the ACK frame updates it, so that
// onDeliveryObserved records the pre-ACK elapsed time (matching prediction).
DateTime _lastRxBeforeFrame = DateTime.fromMillisecondsSinceEpoch(0);
DateTime _lastRadioRxTime = DateTime.fromMillisecondsSinceEpoch(0); DateTime _lastRadioRxTime = DateTime.fromMillisecondsSinceEpoch(0);
DateTime _lastContactMsgRxTime = DateTime.fromMillisecondsSinceEpoch(0); DateTime _lastContactMsgRxTime = DateTime.fromMillisecondsSinceEpoch(0);
DateTime _lastChannelMsgRxTime = DateTime.fromMillisecondsSinceEpoch(0); DateTime _lastChannelMsgRxTime = DateTime.fromMillisecondsSinceEpoch(0);
@@ -1810,15 +1804,11 @@ class MeshCoreConnector extends ChangeNotifier {
recentSelections: recentSelections, recentSelections: recentSelections,
), ),
onDeliveryObserved: (contactKey, pathLength, messageBytes, tripTimeMs) { onDeliveryObserved: (contactKey, pathLength, messageBytes, tripTimeMs) {
final secSinceRx = DateTime.now()
.difference(_lastRxBeforeFrame)
.inSeconds;
_timeoutPredictionService?.recordObservation( _timeoutPredictionService?.recordObservation(
contactKey: contactKey, contactKey: contactKey,
pathLength: pathLength, pathLength: pathLength,
messageBytes: messageBytes, messageBytes: messageBytes,
tripTimeMs: tripTimeMs, tripTimeMs: tripTimeMs,
secondsSinceLastRx: secSinceRx,
); );
}, },
), ),
@@ -6073,8 +6063,6 @@ class MeshCoreConnector extends ChangeNotifier {
void _handleFrame(List<int> data) { void _handleFrame(List<int> data) {
if (data.isEmpty) return; if (data.isEmpty) return;
_lastRxBeforeFrame = _lastRxTime;
_lastRxTime = DateTime.now();
final frame = Uint8List.fromList(data); final frame = Uint8List.fromList(data);
_receivedFramesController.add(frame); _receivedFramesController.add(frame);
@@ -6834,12 +6822,10 @@ class MeshCoreConnector extends ChangeNotifier {
final physicsMax = _physicsMaxTimeout(pathLength, airtime); final physicsMax = _physicsMaxTimeout(pathLength, airtime);
// Try ML-based prediction // Try ML-based prediction
final secSinceRx = DateTime.now().difference(_lastRxTime).inSeconds;
final mlTimeout = _timeoutPredictionService?.predictTimeout( final mlTimeout = _timeoutPredictionService?.predictTimeout(
contactKey: contactKey, contactKey: contactKey,
pathLength: pathLength, pathLength: pathLength,
messageBytes: messageBytes, messageBytes: messageBytes,
secondsSinceLastRx: secSinceRx,
); );
if (mlTimeout != null) { if (mlTimeout != null) {
// Use device est_timeout as a baseline floor when available — // Use device est_timeout as a baseline floor when available —
-4
View File
@@ -2,7 +2,6 @@ class DeliveryObservation {
final String contactKey; final String contactKey;
final int pathLength; final int pathLength;
final int messageBytes; final int messageBytes;
final int secondsSinceLastRx;
final bool isFlood; final bool isFlood;
final int deliveryMs; final int deliveryMs;
final DateTime timestamp; final DateTime timestamp;
@@ -11,7 +10,6 @@ class DeliveryObservation {
required this.contactKey, required this.contactKey,
required this.pathLength, required this.pathLength,
required this.messageBytes, required this.messageBytes,
required this.secondsSinceLastRx,
required this.isFlood, required this.isFlood,
required this.deliveryMs, required this.deliveryMs,
required this.timestamp, required this.timestamp,
@@ -22,7 +20,6 @@ class DeliveryObservation {
'contact_key': contactKey, 'contact_key': contactKey,
'path_length': pathLength, 'path_length': pathLength,
'message_bytes': messageBytes, 'message_bytes': messageBytes,
'seconds_since_last_rx': secondsSinceLastRx,
'is_flood': isFlood, 'is_flood': isFlood,
'delivery_ms': deliveryMs, 'delivery_ms': deliveryMs,
'timestamp': timestamp.toIso8601String(), 'timestamp': timestamp.toIso8601String(),
@@ -34,7 +31,6 @@ class DeliveryObservation {
contactKey: json['contact_key'] as String, contactKey: json['contact_key'] as String,
pathLength: json['path_length'] as int, pathLength: json['path_length'] as int,
messageBytes: json['message_bytes'] as int, messageBytes: json['message_bytes'] as int,
secondsSinceLastRx: json['seconds_since_last_rx'] as int? ?? 0,
isFlood: json['is_flood'] as bool? ?? false, isFlood: json['is_flood'] as bool? ?? false,
deliveryMs: json['delivery_ms'] as int, deliveryMs: json['delivery_ms'] as int,
timestamp: DateTime.parse(json['timestamp'] as String), timestamp: DateTime.parse(json['timestamp'] as String),
+5 -2
View File
@@ -843,9 +843,12 @@ class MessageRetryService extends ChangeNotifier {
tripTimeMs, tripTimeMs,
); );
} }
// Learn from the attempt this ACK belongs to, not the latest one: a
// late ACK for a direct attempt can land after a retry went flood.
if (config?.onDeliveryObserved != null && if (config?.onDeliveryObserved != null &&
tripTimeMs > 0 && tripTimeMs > 0 &&
message.pathLength != null) { selection != null &&
!ambiguousPath) {
final outboundTextForObserved = final outboundTextForObserved =
config!.prepareContactOutboundText?.call(contact, message.text) ?? config!.prepareContactOutboundText?.call(contact, message.text) ??
message.text; message.text;
@@ -854,7 +857,7 @@ class MessageRetryService extends ChangeNotifier {
.length; .length;
config.onDeliveryObserved!( config.onDeliveryObserved!(
contact.publicKeyHex, contact.publicKeyHex,
message.pathLength!, selection.useFlood ? -1 : selection.hopCount,
messageBytesForObserved, messageBytesForObserved,
tripTimeMs, tripTimeMs,
); );
+13 -1
View File
@@ -357,8 +357,9 @@ class PathHistoryService extends ChangeNotifier {
updatedPaths.removeWhere((p) => _pathsEqual(p.pathBytes, pathBytes)); updatedPaths.removeWhere((p) => _pathsEqual(p.pathBytes, pathBytes));
// Make room by dropping the weakest path so new discoveries still land.
if (existing == null && updatedPaths.length >= _maxHistoryEntries) { if (existing == null && updatedPaths.length >= _maxHistoryEntries) {
return; updatedPaths.remove(_lowestScoredPath(updatedPaths));
} }
updatedPaths.insert(0, newRecord); updatedPaths.insert(0, newRecord);
@@ -540,6 +541,17 @@ class PathHistoryService extends ChangeNotifier {
return ranked; return ranked;
} }
PathRecord _lowestScoredPath(List<PathRecord> paths) {
final fastestTripMs = _getFastestKnownTripMs(paths);
final highestRouteWeight = _getHighestKnownRouteWeight(paths);
double score(PathRecord p) => _scorePathRecord(
p,
fastestTripMs: fastestTripMs,
highestRouteWeight: highestRouteWeight,
);
return paths.reduce((a, b) => score(b) < score(a) ? b : a);
}
int? _getFastestKnownTripMs(List<PathRecord> paths) { int? _getFastestKnownTripMs(List<PathRecord> paths) {
final knownTrips = paths final knownTrips = paths
.where((path) => path.tripTimeMs > 0) .where((path) => path.tripTimeMs > 0)
+1 -6
View File
@@ -65,7 +65,6 @@ class TimeoutPredictionService extends ChangeNotifier {
required int pathLength, required int pathLength,
required int messageBytes, required int messageBytes,
required int tripTimeMs, required int tripTimeMs,
int secondsSinceLastRx = 0,
}) { }) {
if (recordingSuspended) return; if (recordingSuspended) return;
final isFlood = pathLength < 0; final isFlood = pathLength < 0;
@@ -75,7 +74,6 @@ class TimeoutPredictionService extends ChangeNotifier {
// only; isFlood carries the flood signal as a separate feature. // only; isFlood carries the flood signal as a separate feature.
pathLength: isFlood ? 0 : pathLength, pathLength: isFlood ? 0 : pathLength,
messageBytes: messageBytes, messageBytes: messageBytes,
secondsSinceLastRx: secondsSinceLastRx,
isFlood: isFlood, isFlood: isFlood,
deliveryMs: tripTimeMs, deliveryMs: tripTimeMs,
timestamp: DateTime.now(), timestamp: DateTime.now(),
@@ -110,7 +108,6 @@ class TimeoutPredictionService extends ChangeNotifier {
String? contactKey, String? contactKey,
required int pathLength, required int pathLength,
required int messageBytes, required int messageBytes,
int secondsSinceLastRx = 0,
}) { }) {
if (_model == null) return null; if (_model == null) return null;
@@ -123,7 +120,6 @@ class TimeoutPredictionService extends ChangeNotifier {
// prediction see the same pathLength values; isFlood carries the signal. // prediction see the same pathLength values; isFlood carries the signal.
'pathLength': flood ? 0.0 : pathLength.toDouble(), 'pathLength': flood ? 0.0 : pathLength.toDouble(),
'messageBytes': messageBytes.toDouble(), 'messageBytes': messageBytes.toDouble(),
'secSinceRx': secondsSinceLastRx.toDouble(),
'isFlood': flood ? 1.0 : 0.0, 'isFlood': flood ? 1.0 : 0.0,
}; };
final row = _activeFeatures.map((f) => allFeatures[f]!).toList(); final row = _activeFeatures.map((f) => allFeatures[f]!).toList();
@@ -174,13 +170,12 @@ class TimeoutPredictionService extends ChangeNotifier {
try { try {
// Build feature columns, then exclude any with zero variance // Build feature columns, then exclude any with zero variance
// (ml_algo's OLS produces all-zero coefficients for singular matrices) // (ml_algo's OLS produces all-zero coefficients for singular matrices)
final allNames = ['pathLength', 'messageBytes', 'secSinceRx', 'isFlood']; final allNames = ['pathLength', 'messageBytes', 'isFlood'];
final allExtractors = <double Function(DeliveryObservation)>[ final allExtractors = <double Function(DeliveryObservation)>[
// pathLength is already clamped to >=0 in recordObservation, but guard // pathLength is already clamped to >=0 in recordObservation, but guard
// here as well for any observations loaded from older persisted data. // here as well for any observations loaded from older persisted data.
(o) => o.pathLength < 0 ? 0.0 : o.pathLength.toDouble(), (o) => o.pathLength < 0 ? 0.0 : o.pathLength.toDouble(),
(o) => o.messageBytes.toDouble(), (o) => o.messageBytes.toDouble(),
(o) => o.secondsSinceLastRx.toDouble(),
(o) => o.isFlood ? 1.0 : 0.0, (o) => o.isFlood ? 1.0 : 0.0,
]; ];
+24 -3
View File
@@ -5,12 +5,12 @@ import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/message.dart'; import 'package:meshcore_open/models/message.dart';
import 'package:meshcore_open/services/message_retry_service.dart'; import 'package:meshcore_open/services/message_retry_service.dart';
Contact _contact() => Contact( Contact _contact({int pathLength = -1, List<int> path = const []}) => Contact(
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => 0xAA + i)), publicKey: Uint8List.fromList(List<int>.generate(32, (i) => 0xAA + i)),
name: 'Test', name: 'Test',
type: 1, type: 1,
pathLength: -1, pathLength: pathLength,
path: Uint8List(0), path: Uint8List.fromList(path),
lastSeen: DateTime.now(), lastSeen: DateTime.now(),
); );
@@ -19,6 +19,7 @@ void main() {
late Map<String, Message> latest; late Map<String, Message> latest;
late List<({int attempt, int timestamp})> sends; late List<({int attempt, int timestamp})> sends;
late int timeoutMs; late int timeoutMs;
late List<({int pathLength, int tripTimeMs})> observed;
final selfKey = Uint8List(32); final selfKey = Uint8List(32);
setUp(() { setUp(() {
@@ -28,6 +29,7 @@ void main() {
latest = {}; latest = {};
sends = []; sends = [];
timeoutMs = 20; timeoutMs = 20;
observed = [];
service.initialize( service.initialize(
RetryServiceConfig( RetryServiceConfig(
sendMessage: (_, _, attempt, timestamp) async { sendMessage: (_, _, attempt, timestamp) async {
@@ -38,6 +40,8 @@ void main() {
getSelfPublicKey: () => selfKey, getSelfPublicKey: () => selfKey,
calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) => calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) =>
timeoutMs, timeoutMs,
onDeliveryObserved: (_, pathLength, _, tripTimeMs) =>
observed.add((pathLength: pathLength, tripTimeMs: tripTimeMs)),
), ),
); );
}); });
@@ -92,4 +96,21 @@ void main() {
await Future<void>.delayed(const Duration(milliseconds: 1100)); await Future<void>.delayed(const Duration(milliseconds: 1100));
expect(sends, hasLength(1)); expect(sends, hasLength(1));
}); });
test('late ACK is observed with the path of the attempt it acks', () async {
final direct = _contact(pathLength: 2, path: [0x11, 0x22]);
await service.sendMessageWithRetry(contact: direct, text: 'hello');
await pumpEventQueue();
// Attempt 0 times out; the retry then goes out as a flood.
await Future<void>.delayed(const Duration(milliseconds: 100));
service.updatePendingContact(_contact());
await Future<void>.delayed(const Duration(milliseconds: 1100));
expect(sends.map((s) => s.attempt), [0, 1]);
service.handleAckReceived(ackHashFor(0), 700);
expect(latest.values.single.status, MessageStatus.delivered);
expect(observed, [(pathLength: 2, tripTimeMs: 700)]);
});
} }
@@ -602,6 +602,33 @@ void main() {
// Group 4: handlePathUpdated // Group 4: handlePathUpdated
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
group('handlePathUpdated', () { group('handlePathUpdated', () {
test('full history evicts the weakest path for a new one', () async {
final pubKey = _hex('full');
for (int i = 0; i < 100; i++) {
svc.handlePathUpdated(
_makeContact(publicKeyHex: pubKey, pathLength: 2, path: [i, 0xEE]),
);
await _flush();
}
const weak = PathSelection(
pathBytes: [7, 0xEE],
hopCount: 2,
useFlood: false,
);
svc.recordPathResult(pubKey, weak, success: false);
svc.recordPathResult(pubKey, weak, success: false);
svc.handlePathUpdated(
_makeContact(publicKeyHex: pubKey, pathLength: 2, path: [0xFF, 0xEE]),
);
await _flush();
final paths = svc.getRecentPaths(pubKey).map((p) => p.pathBytes);
expect(paths, hasLength(100));
expect(paths, contains(equals([0xFF, 0xEE])));
expect(paths, isNot(contains(equals([7, 0xEE]))));
});
test( test(
'pathLength >= 0 with path bytes → records path using pathLength', 'pathLength >= 0 with path bytes → records path using pathLength',
() async { () async {
@@ -156,7 +156,6 @@ DeliveryObservation _obs({
contactKey: contactKey, contactKey: contactKey,
pathLength: pathLength, pathLength: pathLength,
messageBytes: messageBytes, messageBytes: messageBytes,
secondsSinceLastRx: 5,
isFlood: pathLength < 0, isFlood: pathLength < 0,
deliveryMs: deliveryMs, deliveryMs: deliveryMs,
timestamp: DateTime.now(), timestamp: DateTime.now(),