Tester feedback: routing, bulk select, notifications, map crash
Routing - Auto routing picks routes by Thompson sampling over faded delivery stats (24 h half-life, capped evidence), weighted by what the radio currently hears; retries prefer a different route; last attempt floods. - Route failures are held until a message's fate is known, so an offline contact no longer wrecks its route history; failing routes are only deleted after a week without a delivery. - Direct (zero-hop) path is a rotation candidate (#643) and a new Direct mode in the routing sheet; history routes are used for repeater logins. - Remove the route-weight sliders the new chooser no longer uses. Chats - Bulk selection in channel chats (spam / not spam / delete / copy) and in the Filtered messages list. - Tapping a search result jumps to the message. - Swipe-to-reply ignores vertical scrolls. - Active conversation follows route lifecycle, so covered chats count unread again. Notifications - Tapping a notification opens its conversation. - Per-conversation coalescing and one alert per queued-message sync. - Monochrome status-bar icon; background service stops when the app is swiped away; stale notifications cleared on radio or slot change. Other - Online map: opaque links and painted dots for dense areas to avoid an Impeller GPU crash; expandable hop list on path maps. - Contact share: clipboard import of shared contacts, "Add again". - Android: enableEdgeToEdge and scrolling-screenshot support. - Translations for all new strings; fix mistranslated routing labels.
This commit is contained in:
1 parent
f81f2686a7
commit
5ea44d6ce9
85 files changed
+6520
-1716
No files matched your search
@@ -323,6 +323,26 @@ void main() {
|
||||
expect(service.notSpamExampleCount, 1);
|
||||
});
|
||||
|
||||
test('bulk spam and not-spam store every example and persist', () async {
|
||||
await service.markSpamMany([
|
||||
(sender: 'a', text: 'Buy now'),
|
||||
(sender: 'b', text: 'Free crypto'),
|
||||
(sender: 'c', text: ' '),
|
||||
]);
|
||||
expect(service.spamExampleCount, 2);
|
||||
|
||||
await service.markNotSpamMany([
|
||||
(channelId: _channel, sender: 'a', text: 'buy now'),
|
||||
(channelId: _channel, sender: 'd', text: 'Hello all'),
|
||||
]);
|
||||
expect(service.spamExampleCount, 1);
|
||||
expect(service.notSpamExampleCount, 2);
|
||||
|
||||
final reloaded = await create();
|
||||
expect(reloaded.spamExampleCount, 1);
|
||||
expect(reloaded.notSpamExampleCount, 2);
|
||||
});
|
||||
|
||||
test('state persists across instances and reset keeps rules', () async {
|
||||
await service.addRule(const FilterRule(id: 'r1', pattern: 'promo'));
|
||||
await service.updateSettings(
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/models/message.dart';
|
||||
import 'package:meshcore_open/models/path_selection.dart';
|
||||
import 'package:meshcore_open/services/message_retry_service.dart';
|
||||
|
||||
Contact _contact({int pathLength = -1, List<int> path = const []}) => Contact(
|
||||
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => 0xAA + i)),
|
||||
name: 'Test',
|
||||
type: 1,
|
||||
pathLength: pathLength,
|
||||
path: Uint8List.fromList(path),
|
||||
lastSeen: DateTime.now(),
|
||||
);
|
||||
|
||||
/// Route failures only count once the contact proved reachable: a message
|
||||
/// that never gets through must not wreck the routes' history.
|
||||
void main() {
|
||||
late MessageRetryService service;
|
||||
late Map<String, Message> latest;
|
||||
late List<({int attempt, int timestamp})> sends;
|
||||
late List<({List<int> path, bool flood, bool success})> results;
|
||||
final selfKey = Uint8List(32);
|
||||
|
||||
setUp(() {
|
||||
service = MessageRetryService(
|
||||
sentWatchdogGrace: const Duration(milliseconds: 10),
|
||||
);
|
||||
service.setMaxRetries(2);
|
||||
latest = {};
|
||||
sends = [];
|
||||
results = [];
|
||||
service.initialize(
|
||||
RetryServiceConfig(
|
||||
sendMessage: (_, _, attempt, timestamp) async {
|
||||
sends.add((attempt: attempt, timestamp: timestamp));
|
||||
},
|
||||
addMessage: (_, m) => latest[m.messageId] = m,
|
||||
updateMessage: (m) => latest[m.messageId] = m,
|
||||
getSelfPublicKey: () => selfKey,
|
||||
calculateTimeout: (_, _, {String? contactKey, int? deviceTimeoutMs}) =>
|
||||
20,
|
||||
recordPathResult: (_, PathSelection selection, success, _) =>
|
||||
results.add((
|
||||
path: List<int>.of(selection.pathBytes),
|
||||
flood: selection.useFlood,
|
||||
success: success,
|
||||
)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() => service.dispose());
|
||||
|
||||
// Lists inside records compare by identity, so compare readable strings.
|
||||
List<String> recorded() => [
|
||||
for (final r in results)
|
||||
'${r.flood ? 'flood' : r.path}:${r.success ? 'ok' : 'fail'}',
|
||||
];
|
||||
|
||||
int ackHashFor(int attempt) => MessageRetryService.computeExpectedAckHash(
|
||||
sends.firstWhere((s) => s.attempt == attempt).timestamp,
|
||||
attempt,
|
||||
'hello',
|
||||
selfKey,
|
||||
);
|
||||
|
||||
test('a message that never gets through blames no route', () async {
|
||||
await service.sendMessageWithRetry(
|
||||
contact: _contact(pathLength: 2, path: [0x11, 0x22]),
|
||||
text: 'hello',
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
// Attempt 0 times out, the 1 s backoff runs, attempt 1 times out too.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1300));
|
||||
|
||||
expect(latest.values.single.status, MessageStatus.failed);
|
||||
expect(results.where((r) => !r.flood), isEmpty);
|
||||
});
|
||||
|
||||
test('once delivered, the routes that timed out are blamed', () async {
|
||||
await service.sendMessageWithRetry(
|
||||
contact: _contact(pathLength: 2, path: [0x11, 0x22]),
|
||||
text: 'hello',
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
// Attempt 0 times out; the retry goes out on another route.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
service.updatePendingContact(_contact(pathLength: 1, path: [0x33]));
|
||||
// Act as soon as attempt 1 goes out, before its own 30 ms watchdog.
|
||||
for (var i = 0; i < 300 && sends.length < 2; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
}
|
||||
expect(sends.map((s) => s.attempt), [0, 1]);
|
||||
|
||||
// The radio confirms the send (so the ACK maps to attempt 1), then ACKs.
|
||||
expect(service.updateMessageFromSent(ackHashFor(1), 60000), isTrue);
|
||||
service.handleAckReceived(ackHashFor(1), 400);
|
||||
|
||||
expect(latest.values.single.status, MessageStatus.delivered);
|
||||
expect(recorded(), ['[17, 34]:fail', '[51]:ok']);
|
||||
});
|
||||
|
||||
test(
|
||||
'a late ACK for a timed-out attempt credits it, not blames it',
|
||||
() async {
|
||||
await service.sendMessageWithRetry(
|
||||
contact: _contact(pathLength: 2, path: [0x11, 0x22]),
|
||||
text: 'hello',
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
// Attempt 0 times out and its failure is held back...
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
expect(latest.values.single.retryCount, 1);
|
||||
|
||||
// ...then its ACK arrives after all.
|
||||
service.handleAckReceived(ackHashFor(0), 900);
|
||||
|
||||
expect(recorded(), ['[17, 34]:ok']);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a late ACK after the final timeout still blames earlier routes',
|
||||
() async {
|
||||
await service.sendMessageWithRetry(
|
||||
contact: _contact(pathLength: 2, path: [0x11, 0x22]),
|
||||
text: 'hello',
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
// Attempt 0 times out; attempt 1 goes out on another route and also
|
||||
// times out, so the message is marked failed.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
service.updatePendingContact(_contact(pathLength: 1, path: [0x33]));
|
||||
for (var i = 0; i < 300 && sends.length < 2; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
}
|
||||
expect(service.updateMessageFromSent(ackHashFor(1), 20), isTrue);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
expect(latest.values.single.status, MessageStatus.failed);
|
||||
expect(recorded(), isEmpty);
|
||||
|
||||
// Within the grace period, attempt 1's ACK arrives after all.
|
||||
service.handleAckReceived(ackHashFor(1), 1500);
|
||||
|
||||
expect(latest.values.single.status, MessageStatus.delivered);
|
||||
expect(recorded(), ['[17, 34]:fail', '[51]:ok']);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
@@ -104,9 +105,33 @@ void main() {
|
||||
|
||||
setUp(() {
|
||||
storage = FakeStorageService();
|
||||
svc = PathHistoryService(storage);
|
||||
// Picks are random by design (Thompson sampling); seed for repeatability.
|
||||
svc = PathHistoryService(storage, random: math.Random(1));
|
||||
});
|
||||
|
||||
/// How often each route is picked over [n] selections, keyed by hex bytes.
|
||||
Map<String, int> tally(
|
||||
String pubKey, {
|
||||
int n = 400,
|
||||
int attemptIndex = 0,
|
||||
List<PathSelection> recent = const [],
|
||||
}) {
|
||||
final counts = <String, int>{};
|
||||
for (var i = 0; i < n; i++) {
|
||||
final pick = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: attemptIndex,
|
||||
maxRetries: 5,
|
||||
recentSelections: recent,
|
||||
);
|
||||
final key = pick.useFlood
|
||||
? 'flood'
|
||||
: pick.pathBytes.map((b) => b.toRadixString(16)).join(',');
|
||||
counts[key] = (counts[key] ?? 0) + 1;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
group('path selection', () {
|
||||
test('empty path history returns flood', () {
|
||||
const pubKey =
|
||||
@@ -149,135 +174,129 @@ void main() {
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'retries avoid immediately repeating the same path when possible',
|
||||
() async {
|
||||
final pubKey = _hex('rot1');
|
||||
await _seed(svc, pubKey, pathBytes: [0xAA], hopCount: 1, weight: 1.0);
|
||||
test('retries usually move to a different path', () async {
|
||||
final pubKey = _hex('rot1');
|
||||
await _seed(svc, pubKey, pathBytes: [0xAA], hopCount: 1, weight: 1.0);
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xBB], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 0.0,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
// After [0xBB] missed, the retry should mostly try [0xAA].
|
||||
final counts = tally(
|
||||
pubKey,
|
||||
attemptIndex: 1,
|
||||
recent: const [
|
||||
PathSelection(pathBytes: [0xBB], hopCount: 1, useFlood: false),
|
||||
],
|
||||
);
|
||||
expect(counts['flood'], isNull);
|
||||
expect(counts['aa']!, greaterThan(counts['bb'] ?? 0));
|
||||
});
|
||||
|
||||
test('a third retry favours the path not yet tried', () async {
|
||||
final pubKey = _hex('rot2');
|
||||
await _seed(svc, pubKey, pathBytes: [0xA1], hopCount: 1, weight: 3.0);
|
||||
for (final bytes in const [
|
||||
[0xB2],
|
||||
[0xC3],
|
||||
]) {
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xBB], hopCount: 1, useFlood: false),
|
||||
PathSelection(pathBytes: bytes, hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 0.0,
|
||||
);
|
||||
await _flush();
|
||||
}
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final second = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 1,
|
||||
maxRetries: 5,
|
||||
recentSelections: [first],
|
||||
);
|
||||
final counts = tally(
|
||||
pubKey,
|
||||
attemptIndex: 2,
|
||||
recent: const [
|
||||
PathSelection(pathBytes: [0xB2], hopCount: 1, useFlood: false),
|
||||
PathSelection(pathBytes: [0xC3], hopCount: 1, useFlood: false),
|
||||
],
|
||||
);
|
||||
// [0xA1] is untested (no results) yet still the most likely pick,
|
||||
// because both others just missed for this message.
|
||||
expect(counts['a1']!, greaterThan(counts['b2'] ?? 0));
|
||||
expect(counts['a1']!, greaterThan(counts['c3'] ?? 0));
|
||||
});
|
||||
|
||||
expect(first.useFlood, isFalse);
|
||||
expect(second.useFlood, isFalse);
|
||||
expect(second.pathBytes, isNot(equals(first.pathBytes)));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'retries avoid the last two paths when a third option exists',
|
||||
() async {
|
||||
final pubKey = _hex('rot2');
|
||||
await _seed(svc, pubKey, pathBytes: [0xA1], hopCount: 1, weight: 3.0);
|
||||
test('first attempts favour the best path but still try others', () async {
|
||||
final pubKey = _hex('rot3');
|
||||
await _seed(svc, pubKey, pathBytes: [0xA1], hopCount: 1, weight: 4.0);
|
||||
for (var i = 0; i < 6; i++) {
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xB2], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 1.0,
|
||||
);
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xC3], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 0.0,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final second = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 1,
|
||||
maxRetries: 5,
|
||||
recentSelections: [first],
|
||||
);
|
||||
final third = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 2,
|
||||
maxRetries: 5,
|
||||
recentSelections: [first, second],
|
||||
);
|
||||
|
||||
final chosenPaths = [
|
||||
first.pathBytes,
|
||||
second.pathBytes,
|
||||
third.pathBytes,
|
||||
];
|
||||
expect(
|
||||
chosenPaths
|
||||
.map((path) => path.map((b) => b.toRadixString(16)).join(','))
|
||||
.toSet()
|
||||
.length,
|
||||
equals(3),
|
||||
);
|
||||
expect(
|
||||
chosenPaths,
|
||||
everyElement(anyOf(equals([0xA1]), equals([0xB2]), equals([0xC3]))),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('first-attempt selection rotates across ranked candidates', () async {
|
||||
final pubKey = _hex('rot3');
|
||||
await _seed(svc, pubKey, pathBytes: [0xA1], hopCount: 1, weight: 4.0);
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xB2], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 1.0,
|
||||
);
|
||||
}
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xC3], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
successIncrement: 0.5,
|
||||
success: false,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final second = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final third = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
final counts = tally(pubKey);
|
||||
expect(counts['b2']!, greaterThan(counts['a1'] ?? 0));
|
||||
expect(counts['b2']!, greaterThan(counts['c3'] ?? 0));
|
||||
// Exploration: the untested path is still tried now and then.
|
||||
expect(counts['a1'] ?? 0, greaterThan(0));
|
||||
});
|
||||
|
||||
expect(first.pathBytes, isNot(equals(second.pathBytes)));
|
||||
expect(second.pathBytes, isNot(equals(third.pathBytes)));
|
||||
expect(
|
||||
[first.pathBytes, second.pathBytes, third.pathBytes]
|
||||
.map((path) => path.map((b) => b.toRadixString(16)).join(','))
|
||||
.toSet()
|
||||
.length,
|
||||
equals(3),
|
||||
// Issue #643: the direct path (zero hops, no bytes) must be a rotation
|
||||
// candidate alongside saved multi-hop routes.
|
||||
test('direct path is a candidate alongside other routes', () async {
|
||||
final pubKey = _hex('dir1');
|
||||
await _seed(svc, pubKey, pathBytes: const [], hopCount: 0, weight: 2.0);
|
||||
svc.recordPathResult(
|
||||
pubKey,
|
||||
const PathSelection(pathBytes: [0xA1], hopCount: 1, useFlood: false),
|
||||
success: true,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final counts = tally(pubKey);
|
||||
expect(counts['flood'], isNull);
|
||||
expect(counts[''] ?? 0, greaterThan(0), reason: 'direct must be tried');
|
||||
expect(counts['a1'] ?? 0, greaterThan(0));
|
||||
});
|
||||
|
||||
test('a lone direct path is used instead of flooding', () async {
|
||||
final pubKey = _hex('dir2');
|
||||
await _seed(svc, pubKey, pathBytes: const [], hopCount: 0);
|
||||
final pick = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(pick.useFlood, isFalse);
|
||||
expect(pick.hopCount, 0);
|
||||
});
|
||||
|
||||
test('resolvePathSelection keeps a direct auto selection', () {
|
||||
final contact = _makeContact(
|
||||
publicKeyHex: _hex('dir3'),
|
||||
pathLength: 2,
|
||||
path: const [0x01, 0x02],
|
||||
);
|
||||
final resolved = resolvePathSelection(
|
||||
contact,
|
||||
selection: const PathSelection(
|
||||
pathBytes: [],
|
||||
hopCount: 0,
|
||||
useFlood: false,
|
||||
),
|
||||
);
|
||||
expect(resolved.useFlood, isFalse);
|
||||
expect(resolved.hopCount, 0);
|
||||
expect(resolved.pathBytes, isEmpty);
|
||||
});
|
||||
|
||||
test('final attempt is always flood regardless of known paths', () async {
|
||||
@@ -330,12 +349,8 @@ void main() {
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(first.pathBytes, equals([0x02]));
|
||||
final counts = tally(pubKey);
|
||||
expect(counts['2']!, greaterThan(counts['1'] ?? 0));
|
||||
});
|
||||
|
||||
test('lower latency wins when reliability is tied', () async {
|
||||
@@ -356,12 +371,8 @@ void main() {
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(first.pathBytes, equals([0x20]));
|
||||
final counts = tally(pubKey, n: 1000);
|
||||
expect(counts['20']!, greaterThan(counts['10'] ?? 0));
|
||||
});
|
||||
|
||||
test('fresher path wins when reliability and latency are tied', () async {
|
||||
@@ -396,57 +407,47 @@ void main() {
|
||||
svc.getRecentPaths(pubKey);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(first.pathBytes, equals([0x02]));
|
||||
final counts = tally(pubKey, n: 1000);
|
||||
expect(counts['2']!, greaterThan(counts['1'] ?? 0));
|
||||
});
|
||||
|
||||
test(
|
||||
'higher route weight wins when other factors are effectively tied',
|
||||
() async {
|
||||
final pubKey = _hex('rank4');
|
||||
final sharedTimestamp = DateTime.now().subtract(
|
||||
const Duration(minutes: 30),
|
||||
);
|
||||
storage._store[pubKey] = ContactPathHistory(
|
||||
contactPubKeyHex: pubKey,
|
||||
recentPaths: [
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 750,
|
||||
timestamp: sharedTimestamp,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: const [0x01],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
routeWeight: 4.0,
|
||||
),
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 750,
|
||||
timestamp: sharedTimestamp,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: const [0x02],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
routeWeight: 1.0,
|
||||
),
|
||||
],
|
||||
);
|
||||
svc.getRecentPaths(pubKey);
|
||||
await _flush();
|
||||
test('route weight alone does not decide between equal routes', () async {
|
||||
final pubKey = _hex('rank4');
|
||||
final sharedTimestamp = DateTime.now().subtract(
|
||||
const Duration(minutes: 30),
|
||||
);
|
||||
storage._store[pubKey] = ContactPathHistory(
|
||||
contactPubKeyHex: pubKey,
|
||||
recentPaths: [
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 750,
|
||||
timestamp: sharedTimestamp,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: const [0x01],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
routeWeight: 4.0,
|
||||
),
|
||||
PathRecord(
|
||||
hopCount: 1,
|
||||
tripTimeMs: 750,
|
||||
timestamp: sharedTimestamp,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: const [0x02],
|
||||
successCount: 1,
|
||||
failureCount: 0,
|
||||
routeWeight: 1.0,
|
||||
),
|
||||
],
|
||||
);
|
||||
svc.getRecentPaths(pubKey);
|
||||
await _flush();
|
||||
|
||||
final first = svc.selectPathForAttempt(
|
||||
pubKey,
|
||||
attemptIndex: 0,
|
||||
maxRetries: 5,
|
||||
);
|
||||
expect(first.pathBytes, equals([0x01]));
|
||||
},
|
||||
);
|
||||
// Choice follows delivery results; weight only guards deletion.
|
||||
final counts = tally(pubKey, n: 1000);
|
||||
expect(counts['1']!, inInclusiveRange(350, 650));
|
||||
});
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -545,6 +546,48 @@ void main() {
|
||||
expect(paths.first.routeWeight, closeTo(1.5, 0.001));
|
||||
});
|
||||
|
||||
test('a route that delivered this week survives a run of failures', () {
|
||||
// e.g. a repeater down for a day: the route must still be there when
|
||||
// it comes back. Faded stats keep it out of use meanwhile.
|
||||
var clock = DateTime(2026, 11, 1);
|
||||
final timed = PathHistoryService(
|
||||
FakeStorageService(),
|
||||
random: math.Random(1),
|
||||
clock: () => clock,
|
||||
);
|
||||
final pubKey = _hex('w0a1');
|
||||
const route = PathSelection(
|
||||
pathBytes: [0x01],
|
||||
hopCount: 1,
|
||||
useFlood: false,
|
||||
);
|
||||
return () async {
|
||||
timed.getRecentPaths(pubKey);
|
||||
await _flush();
|
||||
timed.recordPathResult(pubKey, route, success: true);
|
||||
clock = clock.add(const Duration(days: 1));
|
||||
for (var i = 0; i < 6; i++) {
|
||||
timed.recordPathResult(
|
||||
pubKey,
|
||||
route,
|
||||
success: false,
|
||||
failureDecrement: 0.5,
|
||||
);
|
||||
}
|
||||
expect(timed.getRecentPaths(pubKey), hasLength(1));
|
||||
|
||||
// A week without a delivery: the next failure removes it.
|
||||
clock = clock.add(const Duration(days: 8));
|
||||
timed.recordPathResult(
|
||||
pubKey,
|
||||
route,
|
||||
success: false,
|
||||
failureDecrement: 0.5,
|
||||
);
|
||||
expect(timed.getRecentPaths(pubKey), isEmpty);
|
||||
}();
|
||||
});
|
||||
|
||||
test('failure to 0 removes the path', () async {
|
||||
final pubKey = _hex('w004');
|
||||
await _seed(svc, pubKey, pathBytes: [0x01], hopCount: 1, weight: 0.3);
|
||||
@@ -735,6 +778,27 @@ void main() {
|
||||
expect(credited.tripTimeMs, equals(3000));
|
||||
});
|
||||
|
||||
test('a flood answered directly credits the direct path', () async {
|
||||
final pubKey = _hex('fa0d');
|
||||
await _seed(svc, pubKey, pathBytes: [0xAA], hopCount: 1, weight: 1.0);
|
||||
|
||||
svc.recordFloodPathAttribution(
|
||||
contactPubKeyHex: pubKey,
|
||||
pathBytes: const [],
|
||||
hopCount: 0,
|
||||
tripTimeMs: 800,
|
||||
successIncrement: 0.5,
|
||||
maxWeight: 5.0,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final direct = svc
|
||||
.getRecentPaths(pubKey)
|
||||
.firstWhere((p) => p.pathBytes.isEmpty && p.hopCount == 0);
|
||||
expect(direct.successCount, 1);
|
||||
expect(direct.routeWeight, closeTo(1.5, 0.001));
|
||||
});
|
||||
|
||||
test('creates new path record when path is unknown', () async {
|
||||
final pubKey = _hex('fa02');
|
||||
// Seed with a different path so the cache is warm.
|
||||
@@ -777,24 +841,27 @@ void main() {
|
||||
expect(paths.first.routeWeight, closeTo(5.0, 0.001));
|
||||
});
|
||||
|
||||
test('ignores empty pathBytes', () async {
|
||||
test('ignores empty pathBytes for a multi-hop path', () async {
|
||||
final pubKey = _hex('fa04');
|
||||
await _seed(svc, pubKey, pathBytes: [0x01], hopCount: 1, weight: 1.0);
|
||||
|
||||
final pathsBefore = svc.getRecentPaths(pubKey);
|
||||
final weightBefore = pathsBefore.first.routeWeight;
|
||||
|
||||
// Hops without their bytes can't be replayed; only zero hops (the
|
||||
// direct path) may be recorded without bytes.
|
||||
svc.recordFloodPathAttribution(
|
||||
contactPubKeyHex: pubKey,
|
||||
pathBytes: [],
|
||||
hopCount: 0,
|
||||
hopCount: 2,
|
||||
successIncrement: 0.5,
|
||||
maxWeight: 5.0,
|
||||
);
|
||||
await _flush();
|
||||
|
||||
// Existing path should be untouched.
|
||||
// Existing path should be untouched and nothing new recorded.
|
||||
final pathsAfter = svc.getRecentPaths(pubKey);
|
||||
expect(pathsAfter, hasLength(1));
|
||||
expect(pathsAfter.first.routeWeight, equals(weightBefore));
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/path_history.dart';
|
||||
import 'package:meshcore_open/models/path_selection.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/route_chooser.dart';
|
||||
|
||||
import 'path_history_service_test.dart' show FakeStorageService;
|
||||
|
||||
final _now = DateTime(2026, 11, 8, 12);
|
||||
|
||||
PathRecord _route(
|
||||
List<int> bytes, {
|
||||
double success = 0,
|
||||
double failure = 0,
|
||||
DateTime? statsAt,
|
||||
int tripTimeMs = 0,
|
||||
}) => PathRecord(
|
||||
hopCount: bytes.length,
|
||||
tripTimeMs: tripTimeMs,
|
||||
timestamp: null,
|
||||
wasFloodDiscovery: false,
|
||||
pathBytes: bytes,
|
||||
successCount: success.round(),
|
||||
failureCount: failure.round(),
|
||||
recentSuccess: success,
|
||||
recentFailure: failure,
|
||||
statsAt: statsAt ?? _now,
|
||||
);
|
||||
|
||||
Map<List<int>, int> _tally(
|
||||
List<PathRecord> routes, {
|
||||
int draws = 2000,
|
||||
RouteContext context = RouteContext.unknown,
|
||||
}) {
|
||||
final random = math.Random(42);
|
||||
final counts = {for (final r in routes) r.pathBytes: 0};
|
||||
for (var i = 0; i < draws; i++) {
|
||||
final pick = pickRoute(routes, random: random, now: _now, context: context);
|
||||
counts[pick.pathBytes] = counts[pick.pathBytes]! + 1;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
RouteContext _hearing(Set<int> firstHops, {bool contactDirect = false}) =>
|
||||
RouteContext(
|
||||
hasNeighbourInfo: true,
|
||||
contactHeardDirectly: contactDirect,
|
||||
firstHopHeard: (bytes, width) =>
|
||||
bytes.isNotEmpty && firstHops.contains(bytes.first),
|
||||
);
|
||||
|
||||
void main() {
|
||||
group('fading', () {
|
||||
test('results lose half their weight per half-life', () {
|
||||
expect(routeDecayFactor(_now, _now), 1.0);
|
||||
expect(
|
||||
routeDecayFactor(_now.subtract(routeStatsHalfLife), _now),
|
||||
closeTo(0.5, 1e-9),
|
||||
);
|
||||
expect(
|
||||
routeDecayFactor(_now.subtract(routeStatsHalfLife * 3), _now),
|
||||
closeTo(0.125, 1e-9),
|
||||
);
|
||||
expect(routeDecayFactor(null, _now), 1.0);
|
||||
});
|
||||
|
||||
test('a new result is added on top of the faded old ones', () {
|
||||
final old = _route(
|
||||
[1],
|
||||
success: 4,
|
||||
failure: 2,
|
||||
statsAt: _now.subtract(routeStatsHalfLife),
|
||||
);
|
||||
final next = addRouteResult(old, success: false, now: _now);
|
||||
expect(next.success, closeTo(2, 1e-9));
|
||||
expect(next.failure, closeTo(2, 1e-9));
|
||||
});
|
||||
|
||||
test('a route proven long ago ranks below one working today', () {
|
||||
final stale = _route(
|
||||
[1],
|
||||
success: 20,
|
||||
statsAt: _now.subtract(const Duration(days: 10)),
|
||||
);
|
||||
final fresh = _route([2], success: 3);
|
||||
double score(PathRecord r) =>
|
||||
routeExpectedScore(r, now: _now, fastestTripMs: null);
|
||||
expect(score(fresh), greaterThan(score(stale)));
|
||||
});
|
||||
|
||||
test('history saved before fading existed seeds from capped counts', () {
|
||||
final legacy = PathRecord.fromJson({
|
||||
'hop_count': 1,
|
||||
'trip_time_ms': 0,
|
||||
'timestamp': _now.toIso8601String(),
|
||||
'was_flood': false,
|
||||
'path_bytes': [1],
|
||||
'success_count': 40,
|
||||
'failure_count': 1,
|
||||
});
|
||||
expect(legacy.recentSuccess, 5);
|
||||
expect(legacy.recentFailure, 1);
|
||||
expect(legacy.statsAt, _now);
|
||||
});
|
||||
});
|
||||
|
||||
group('sampling', () {
|
||||
test('Beta samples average a / (a + b)', () {
|
||||
final random = math.Random(7);
|
||||
for (final (a, b) in [(1.0, 1.0), (8.0, 2.0), (0.6, 3.5)]) {
|
||||
var sum = 0.0;
|
||||
const n = 6000;
|
||||
for (var i = 0; i < n; i++) {
|
||||
final x = sampleBeta(random, a, b);
|
||||
expect(x, inInclusiveRange(0, 1));
|
||||
sum += x;
|
||||
}
|
||||
expect(sum / n, closeTo(a / (a + b), 0.02), reason: 'Beta($a, $b)');
|
||||
}
|
||||
});
|
||||
|
||||
test('a proven route wins most picks but others still get tried', () {
|
||||
final strong = _route([1], success: 20, failure: 1);
|
||||
final weak = _route([2], success: 1, failure: 10);
|
||||
final unknown = _route([3]);
|
||||
final counts = _tally([strong, weak, unknown]);
|
||||
expect(counts[strong.pathBytes]!, greaterThan(1700));
|
||||
// Exploration: an untested route is still tried now and then.
|
||||
expect(counts[unknown.pathBytes]!, greaterThan(20));
|
||||
expect(counts[weak.pathBytes]!, lessThan(counts[unknown.pathBytes]!));
|
||||
});
|
||||
});
|
||||
|
||||
group('context', () {
|
||||
test('a route whose first hop is heard beats an equal one that is not', () {
|
||||
final viaA = _route([0xA0, 0x10], success: 3, failure: 1);
|
||||
final viaB = _route([0xB0, 0x10], success: 3, failure: 1);
|
||||
final counts = _tally([viaA, viaB], context: _hearing({0xA0}));
|
||||
expect(counts[viaA.pathBytes]!, greaterThan(1300));
|
||||
});
|
||||
|
||||
test('direct is preferred when the contact was heard directly', () {
|
||||
final direct = _route([], success: 3, failure: 1);
|
||||
final relayed = _route([0xA0], success: 3, failure: 1);
|
||||
final heard = _tally([
|
||||
direct,
|
||||
relayed,
|
||||
], context: _hearing({0xA0}, contactDirect: true));
|
||||
final notHeard = _tally([direct, relayed], context: _hearing({0xA0}));
|
||||
expect(
|
||||
heard[direct.pathBytes]!,
|
||||
greaterThan(notHeard[direct.pathBytes]!),
|
||||
);
|
||||
expect(notHeard[relayed.pathBytes]!, greaterThan(1000));
|
||||
});
|
||||
|
||||
test('with nothing heard, context changes nothing', () {
|
||||
final route = _route([0xA0], success: 1);
|
||||
expect(routeContextFactor(route, RouteContext.unknown), 1.0);
|
||||
});
|
||||
});
|
||||
|
||||
// A tiny simulated mesh: each route delivers with a fixed probability.
|
||||
// Each message gets up to [maxRetries] attempts, the last one a flood.
|
||||
group('simulation', () {
|
||||
late PathHistoryService svc;
|
||||
late DateTime clock;
|
||||
const contact =
|
||||
'00000000000000000000000000000000000000000000000000000000000000aa';
|
||||
const maxRetries = 4;
|
||||
|
||||
setUp(() async {
|
||||
clock = _now;
|
||||
svc = PathHistoryService(
|
||||
FakeStorageService(),
|
||||
random: math.Random(1),
|
||||
clock: () => clock,
|
||||
);
|
||||
svc.getRecentPaths(contact);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
});
|
||||
|
||||
void seed(List<int> bytes) => svc.recordPathAttempt(
|
||||
contact,
|
||||
PathSelection(pathBytes: bytes, hopCount: bytes.length, useFlood: false),
|
||||
);
|
||||
|
||||
/// Sends [messages] messages; returns the average number of route
|
||||
/// attempts before delivery (flood counts as one more).
|
||||
double run(
|
||||
int messages,
|
||||
double Function(List<int> bytes) deliveryRate, {
|
||||
RouteContext context = RouteContext.unknown,
|
||||
math.Random? rng,
|
||||
}) {
|
||||
final random = rng ?? math.Random(99);
|
||||
var attempts = 0;
|
||||
for (var m = 0; m < messages; m++) {
|
||||
clock = clock.add(const Duration(minutes: 10));
|
||||
final used = <PathSelection>[];
|
||||
for (var attempt = 0; attempt < maxRetries; attempt++) {
|
||||
attempts++;
|
||||
final pick = svc.selectPathForAttempt(
|
||||
contact,
|
||||
attemptIndex: attempt,
|
||||
maxRetries: maxRetries,
|
||||
recentSelections: used,
|
||||
context: context,
|
||||
);
|
||||
if (pick.useFlood) break; // flood always gets through here
|
||||
final ok = random.nextDouble() < deliveryRate(pick.pathBytes);
|
||||
svc.recordPathResult(contact, pick, success: ok);
|
||||
if (ok) break;
|
||||
used.add(pick);
|
||||
}
|
||||
}
|
||||
return attempts / messages;
|
||||
}
|
||||
|
||||
test('settles on the reliable route', () {
|
||||
seed([0x01]);
|
||||
seed([0x02]);
|
||||
seed([0x03]);
|
||||
final rates = {0x01: 0.95, 0x02: 0.5, 0x03: 0.1};
|
||||
run(100, (b) => rates[b.first]!); // learn
|
||||
final avg = run(200, (b) => rates[b.first]!);
|
||||
expect(avg, lessThan(1.25));
|
||||
});
|
||||
|
||||
test('moves off a route that stops working', () {
|
||||
seed([0x01]);
|
||||
seed([0x02]);
|
||||
var rates = {0x01: 0.95, 0x02: 0.8};
|
||||
run(100, (b) => rates[b.first]!);
|
||||
// The best repeater goes offline.
|
||||
rates = {0x01: 0.0, 0x02: 0.8};
|
||||
run(10, (b) => rates[b.first]!); // a few messages to notice
|
||||
final avg = run(100, (b) => rates[b.first]!);
|
||||
expect(avg, lessThan(1.5));
|
||||
});
|
||||
|
||||
test('home and work routes follow what the radio hears', () {
|
||||
seed([0xA0, 0x10]); // via the home repeater
|
||||
seed([0xB0, 0x10]); // via the work repeater
|
||||
double homeRates(List<int> b) => b.first == 0xA0 ? 0.9 : 0.05;
|
||||
double workRates(List<int> b) => b.first == 0xB0 ? 0.9 : 0.05;
|
||||
|
||||
run(60, homeRates, context: _hearing({0xA0}));
|
||||
final atWork = run(60, workRates, context: _hearing({0xB0}));
|
||||
final backHome = run(60, homeRates, context: _hearing({0xA0}));
|
||||
expect(atWork, lessThan(1.6));
|
||||
expect(backHome, lessThan(1.6));
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user