Batch per-frame persistence so busy meshes don't stall the UI isolate

Every received packet copy re-saved its channel's whole history, every
unread change re-saved the channel list, and adverts/path records re-saved
full contact and path-history blobs. Under load the SharedPreferences
backlog starved the Dart event loop (frames and timers stopped), the radio's
offline queue overflowed, and CPU stayed pinned after traffic ended.

- Add CoalescedWrites: keeps the latest write per key and runs them once
  per window (750 ms; 5 s for path history). Writes start synchronously so
  stores still read the current scoped key.
- Flush before the app is backgrounded, on disconnect, before switching
  radios, before the channel slot map changes, before channel history
  reloads, before deleteChannel drops a list, and before path history
  reloads an evicted contact.
- Cap in-memory channel history at ChannelMessageStore.maxStoredMessages;
  storage already kept only that many, but the list grew unbounded during a
  session and every save grew with it.
- Cache Contact.publicKeyHex and build pubKeyToHex from a hex-digit lookup; it was
  rebuilt on every equality/hash and per-advert contact scan.

Load test (fake TCP radio, 350 contacts, 17 channels, 10-150 packets/s,
Linux profile build): CPU at 10 packets/s 104% -> 45%, recovers to idle
after traffic instead of staying at 160%, and queued messages drained went
from 555 to 3237 over the same run.
This commit is contained in:
zjs81 committed 2026-10-24 23:38:28 -07:00
1 parent eab1ad2964
commit 603172b3ec
10 files changed
+365 -29

No files matched your search

+36
View File
@@ -13,6 +13,7 @@ import 'package:meshcore_open/review_mode/review_script.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:pointycastle/export.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -185,6 +186,7 @@ void main() {
expect(_channelAt(1).name, 'Hiking Group');
expect(_texts(1), isNot(contains('ghost message')));
await _connector.flushPendingWrites();
// The old channel's history is kept under its own ID.
expect(_storedTexts(ghostId), ['ghost message']);
expect(_storedTexts(hikingId), contains(_queuedHikingText));
@@ -218,6 +220,7 @@ void main() {
.firstWhere((m) => m.text == _queuedHikingText);
expect(restored.channelIndex, 6);
await _connector.deleteChannelMessage(restored);
await _connector.flushPendingWrites();
expect(_texts(6), isNot(contains(_queuedHikingText)));
expect(_storedTexts(hikingId), isNot(contains(_queuedHikingText)));
});
@@ -237,6 +240,7 @@ void main() {
test('deleting a channel clears its stored history', () async {
await _connect(_TestRadio());
await _waitFor(() => _texts(1).contains(_queuedHikingText));
await _connector.flushPendingWrites();
expect(_storedTexts(hikingId), isNotEmpty);
await _connector.deleteChannel(1);
@@ -273,6 +277,7 @@ void main() {
await _waitFor(() => _texts(1).contains(_queuedHikingText));
await _connector.deleteChannel(1);
await _connector.flushPendingWrites();
expect(_storedTexts(hikingId), contains(_queuedHikingText));
},
);
@@ -299,6 +304,7 @@ void main() {
seed: () => _seedSlotMap({0: _id(_psk(0)), 1: ghostId, 2: _id(_psk(2))}),
);
await _waitFor(() => _texts(1).contains('before the map'));
await _connector.flushPendingWrites();
expect(_storedTexts(hikingId), contains('before the map'));
expect(_storedTexts(ghostId), isNot(contains('before the map')));
});
@@ -382,6 +388,7 @@ void main() {
);
await _waitFor(() => _texts(1).contains('from the twin slot'));
expect(_texts(5), contains('from the twin slot'));
await _connector.flushPendingWrites();
expect(
_storedTexts(hikingId).where((t) => t == 'from the twin slot'),
hasLength(1),
@@ -400,7 +407,36 @@ void main() {
),
);
await _waitFor(() => _texts(2).contains('heard over the air'));
await _connector.flushPendingWrites();
expect(_storedTexts(localId), contains('heard over the air'));
expect(_texts(1), isNot(contains('heard over the air')));
});
test('a busy channel is capped at the stored-message limit in memory and '
'in storage', () async {
await _connect(_TestRadio());
await _waitFor(() => _texts(1).contains(_queuedHikingText));
const cap = ChannelMessageStore.maxStoredMessages;
final start = DateTime.now().millisecondsSinceEpoch ~/ 1000;
for (var i = 0; i < cap + 50; i++) {
_connector.handleFrameForTest(
ReviewFrames.channelMessage(
channelIndex: 1,
sender: 'Sam',
message: 'busy $i',
timestampSecs: start + i,
),
);
}
final texts = _texts(1);
expect(texts, hasLength(cap));
expect(texts.last, 'busy ${cap + 49}');
// Nothing is written per frame; the batch lands on flush.
await _connector.flushPendingWrites();
final stored = _storedTexts(hikingId);
expect(stored, hasLength(cap));
expect(stored.first, 'busy 50');
expect(stored.last, 'busy ${cap + 49}');
});
}
+48
View File
@@ -0,0 +1,48 @@
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/contact.dart';
String _reference(Uint8List bytes) =>
bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
void main() {
test('pubKeyToHex is lowercase, zero-padded hex for every byte value', () {
final all = Uint8List.fromList(List<int>.generate(256, (i) => i));
expect(pubKeyToHex(all), _reference(all));
expect(pubKeyToHex(Uint8List(0)), '');
expect(pubKeyToHex(Uint8List.fromList([0x00, 0x0a, 0xff])), '000aff');
});
test('pubKeyToHex round-trips random keys through hexToPubKey', () {
final random = Random(7);
for (var i = 0; i < 200; i++) {
final key = Uint8List.fromList(
List<int>.generate(32, (_) => random.nextInt(256)),
);
final hex = pubKeyToHex(key);
expect(hex, _reference(key));
expect(hexToPubKey(hex), key);
}
});
test('Contact.publicKeyHex is stable and drives equality', () {
final key = Uint8List.fromList(List<int>.generate(32, (i) => i * 7));
Contact make(String name) => Contact(
publicKey: key,
name: name,
type: 1,
pathLength: -1,
path: Uint8List(0),
lastSeen: DateTime(2026),
);
final a = make('a');
expect(a.publicKeyHex, _reference(key));
expect(identical(a.publicKeyHex, a.publicKeyHex), isTrue);
expect(a, make('renamed'));
expect(a.hashCode, make('renamed').hashCode);
expect(a.copyWith(name: 'b').publicKeyHex, a.publicKeyHex);
});
}
@@ -858,6 +858,8 @@ void main() {
svc.recordPathResult(pubKey, sel, success: true, successIncrement: 0.5);
}
await _flush();
// Saves are batched; a restart only follows a flush (app backgrounded).
await svc.flushPendingWrites();
final fresh = PathHistoryService(storage);
fresh.recordPathResult(pubKey, sel, success: true, successIncrement: 0.5);
@@ -871,6 +873,7 @@ void main() {
test('getRecentPaths load does not drop a concurrent add', () async {
final pubKey = _hex('k004');
await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0);
await svc.flushPendingWrites();
final fresh = PathHistoryService(storage);
fresh.getRecentPaths(pubKey);
+66
View File
@@ -0,0 +1,66 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/utils/coalesced_writes.dart';
const _delay = Duration(milliseconds: 40);
Future<void> _wait(int ms) => Future<void>.delayed(Duration(milliseconds: ms));
void main() {
test('repeated schedules for a key run only the latest write once', () async {
final writes = CoalescedWrites(delay: _delay);
final ran = <String>[];
for (var i = 0; i < 100; i++) {
writes.schedule('channel:a', () async => ran.add('a$i'));
}
writes.schedule('contacts', () async => ran.add('contacts'));
expect(ran, isEmpty);
await _wait(120);
expect(ran, ['a99', 'contacts']);
expect(writes.hasPending, isFalse);
});
test('a steady stream of schedules does not push the write back', () async {
final writes = CoalescedWrites(delay: _delay);
var count = 0;
final stop = DateTime.now().add(const Duration(milliseconds: 300));
while (DateTime.now().isBefore(stop)) {
writes.schedule('k', () async => count++);
await _wait(5);
}
// Persistence keeps landing while frames keep arriving.
expect(count, greaterThanOrEqualTo(3));
await writes.flush();
});
test('flush starts every write synchronously and clears the queue', () {
final writes = CoalescedWrites();
final ran = <String>[];
writes.schedule('a', () async => ran.add('a'));
writes.schedule('b', () async => ran.add('b'));
final done = writes.flush();
// Stores read their scoped key on entry, before any await.
expect(ran, ['a', 'b']);
expect(writes.hasPending, isFalse);
return done;
});
test('cancel drops a queued write', () async {
final writes = CoalescedWrites(delay: _delay);
var ran = false;
writes.schedule('channel:a', () async => ran = true);
writes.cancel('channel:a');
await _wait(120);
expect(ran, isFalse);
});
test('a failing write does not stop the others', () async {
final writes = CoalescedWrites();
var ran = false;
writes.schedule('bad', () => throw StateError('boom'));
writes.schedule('good', () async => ran = true);
await writes.flush();
expect(ran, isTrue);
});
}