task(#919): A5 Epic A verification: isolate gate + block-time benchmark

Two things the Epic needed and did not have: a gate that fails if the work
comes back to the UI isolate, and a number for how much it was blocking.

The gate is structural, not timed. The merge callback reports the isolate it
ran on, and the test asserts that is not "main". `compute` names the worker
it spawns after the callback, so the recorded name also says which worker.
A wall-clock threshold would have been flaky on CI and would not say why it
passed.

The benchmark runs a 1 ms heartbeat on the main isolate and reports the worst
gap between beats, which is the UI freeze an ANR is. It is named `_bench`,
not `_test`, so a bare `flutter test` skips it: it needs a local copy of a
real database and the numbers are machine-dependent.

Measured against the owner's real largest channel, 5,650,194 chars (5.39
MiB), 9,230 messages, on this desktop:

                            UI blocked   wall     heartbeats
  1 save, inline (pre-919)      381 ms   381 ms            1
  1 save, off-thread             44 ms   297 ms          174
  5 saves, inline             1,385 ms  1,385 ms           1
  5 saves, off-thread            66 ms  1,496 ms         964

8.7x less blocking on one save, 21x on a burst of five. Wall time barely
moves, which is the plan's point: the work is not cheaper, it is elsewhere.
Inline, UI-blocked equals wall and one heartbeat lands in 1.4 seconds; the
UI isolate was gone for the whole operation. Off-thread it beats 964 times
through the same burst.

The first measured support for the burst claim, which until now was
arithmetic. Still desktop, not a phone: that is the owner's device check.

The heartbeat needed a fix before it could be trusted. A periodic timer
cannot fire while the isolate is blocked, so cancelling it the moment the
action returns discards the tick that would have shown the gap, and the
first run of this benchmark duly reported the inline path blocking 0 ms.
Verified on a bare 200 ms busy-wait: no trailing yield gives fires=0,
worst=0 ms; with a yield it gives 200 ms. It now yields before cancelling
and reports the heartbeat count so a dead instrument cannot read as a clean
result.

Citadel: meshcore-open-xxc
Refs #919, #917, #334

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
feat/920-message-rows
diffwireauto 1 month ago committed by Benjamin Wiechel
parent 1ed7581a51
commit d791c58fea

@ -0,0 +1,201 @@
// Epic A verification benchmark (#919 / #917): how long does saving one
// channel message block the isolate that draws the UI?
//
// The filename ends in `_bench`, not `_test`, so a bare `flutter test` does
// not collect it: the numbers depend on the machine and on a local copy of a
// real database, which makes this a measurement tool rather than a gate. It
// lives under test/ anyway so the analyzer treats it as test code. The
// non-flaky gate is test/storage/blob_merge_runs_off_main_isolate_test.dart.
//
// Run it:
// 1. copy a real database somewhere local, e.g.
// cp "$APPDATA/Offband MeshCore/offband_store.sqlite" /tmp/live_copy.sqlite
// 2. flutter test test/benchmarks/anr_block_time_bench.dart \
// --dart-define=BENCH_DB=/tmp/live_copy.sqlite
//
// Without BENCH_DB it synthesises a payload of a comparable size, which is
// fine for a regression check and useless as evidence about real data.
//
// What it measures: a 1 ms heartbeat timer runs on the main isolate while the
// save happens. The largest gap between heartbeats IS the UI freeze, which is
// what Android's input-dispatch watchdog kills an app for. Wall-clock duration
// of the save is reported too, because the point of Epic A is that those two
// numbers come apart: the work still takes just as long, it just stops
// happening where the UI lives.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const String _benchDb = String.fromEnvironment('BENCH_DB');
/// Records the worst gap between 1 ms heartbeats while [action] runs. A gap is
/// time the main isolate was not free to do anything, UI included.
///
/// The yield before `cancel` is load-bearing. A periodic timer cannot fire
/// while the isolate is blocked, so the gap only becomes visible on the first
/// tick *after* the block; cancelling the moment the action returns throws that
/// tick away and reports a block of 0 ms. Verified: a bare 200 ms busy-wait
/// with no trailing yield measured `fires=0, worst=0ms`, and the same block
/// with a yield measured 200 ms.
///
/// [fires] is reported for the same reason. A run with few fires has not
/// proven anything, whatever its gap says.
Future<({int maxGapMs, int wallMs, int fires})> _withHeartbeat(
Future<void> Function() action,
) async {
var last = DateTime.now();
var worst = 0;
var fires = 0;
final beat = Timer.periodic(const Duration(milliseconds: 1), (_) {
final now = DateTime.now();
final gap = now.difference(last).inMilliseconds;
if (gap > worst) worst = gap;
last = now;
fires++;
});
final sw = Stopwatch()..start();
last = DateTime.now();
await action();
final wall = sw.elapsedMilliseconds;
// Let the overdue tick land before the timer goes away.
for (var i = 0; i < 3; i++) {
await Future<void>.delayed(Duration.zero);
}
beat.cancel();
return (maxGapMs: worst, wallMs: wall, fires: fires);
}
void main() {
test(
'one save: UI-isolate block time, old path vs new path',
() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
String payload;
if (_benchDb.isNotEmpty && File(_benchDb).existsSync()) {
final source = OffbandDatabase(NativeDatabase(File(_benchDb)));
final rows = await source
.customSelect(
'select value from stored_blobs '
'order by length(value) desc limit 1',
)
.get();
payload = rows.single.data['value'] as String;
await source.close();
// ignore: avoid_print
print('payload: real, from $_benchDb');
} else {
// ignore: avoid_print
print(
'payload: SYNTHETIC (pass --dart-define=BENCH_DB=... for real '
'data; these numbers are not evidence about production)',
);
final one = jsonEncode({
'senderName': 'synthetic',
'text': 'x' * 120,
'timestamp': 1700000000000,
'isOutgoing': false,
'channelIndex': 0,
'messageId': 'id',
'status': 0,
});
payload = '[${List.filled(9230, one).join(',')}]';
}
// ignore: avoid_print
print(
'payload size: ${payload.length} chars '
'(${(payload.length / 1048576).toStringAsFixed(2)} MiB)',
);
final db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
final blobs = BlobStore.instance;
// One more message arriving, encoded the way the store encodes it.
final incoming = jsonEncode([
{
'senderName': 'bench',
'text': 'the message that just arrived',
'timestamp': 1800000000000,
'isOutgoing': false,
'channelIndex': 0,
'messageId': 'bench-1',
'status': 0,
},
]);
// OLD path: exactly what the store did before #919, calling the very
// same merge function inline instead of through compute. Not a strawman:
// the only difference is where it runs.
await blobs.write('old', payload);
final old = await _withHeartbeat(() async {
final stored = await blobs.readWithPrefsFallback('old');
final merged = mergeChannelHistoryJson((stored, incoming));
await blobs.write('old', merged);
});
// NEW path.
await blobs.write('new', payload);
final fresh = await _withHeartbeat(
() => blobs.mergeOffThread('new', incoming, mergeChannelHistoryJson),
);
// A burst of five, which is the case that crosses the watchdog.
await blobs.write('burst_old', payload);
final burstOld = await _withHeartbeat(() async {
for (var i = 0; i < 5; i++) {
final stored = await blobs.readWithPrefsFallback('burst_old');
await blobs.write(
'burst_old',
mergeChannelHistoryJson((stored, incoming)),
);
}
});
await blobs.write('burst_new', payload);
final burstNew = await _withHeartbeat(() async {
for (var i = 0; i < 5; i++) {
await blobs.mergeOffThread(
'burst_new',
incoming,
mergeChannelHistoryJson,
);
}
});
void report(String label, ({int maxGapMs, int wallMs, int fires}) r) {
// ignore: avoid_print
print(
'${label.padRight(26)} UI blocked ${r.maxGapMs}ms '
'wall ${r.wallMs}ms (heartbeats ${r.fires})',
);
}
// ignore: avoid_print
print('');
report('1 save, inline (pre-#919)', old);
report('1 save, off-thread (#919)', fresh);
report('5 saves, inline', burstOld);
report('5 saves, off-thread', burstNew);
await db.close();
BlobStore.clearTestOverride();
// Sanity, not a threshold: the off-thread path must not block longer
// than the inline one. Real thresholds are the owner's device check.
expect(fresh.maxGapMs, lessThanOrEqualTo(old.maxGapMs));
expect(burstNew.maxGapMs, lessThanOrEqualTo(burstOld.maxGapMs));
},
timeout: const Timeout(Duration(minutes: 5)),
);
}

@ -0,0 +1,72 @@
import 'dart:isolate';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// The one property Epic A (#919) delivers: the decode / merge / re-encode does
/// not run on the isolate that draws the UI.
///
/// Asserted structurally rather than by timing, because a wall-clock threshold
/// would be flaky on CI and would not say *why* it passed. If someone later
/// "simplifies" `mergeOffThread` back to an inline call, every other test in
/// this directory still passes and only this one fails.
void main() {
late OffbandDatabase db;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
});
tearDown(() async {
await db.close();
BlobStore.clearTestOverride();
});
test('the merge callback does not run on the main isolate', () async {
final mainName = Isolate.current.debugName;
expect(
mainName,
'main',
reason: 'sanity check on the premise of this test',
);
await BlobStore.instance.write('k', 'ignored');
final wrote = await BlobStore.instance.mergeOffThread(
'k',
'ignored',
_reportIsolateName,
);
expect(wrote, isTrue);
final ranOn = await BlobStore.instance.read('k');
// `compute` names the isolate it spawns after the callback it was handed,
// so the recorded name both proves this was not the main isolate and says
// which worker it was. Observed: "Closure: ((String?, String)) => String
// from Function '_reportIsolateName@...': static."
expect(
ranOn,
isNot('main'),
reason: 'the whole point of #919: this work must leave the UI isolate',
);
expect(
ranOn,
contains('_reportIsolateName'),
reason:
'a spawned compute worker is named after its callback; anything '
'else means the merge ran somewhere unexpected',
);
});
}
/// Writes the name of the isolate it ran on, so the caller can check it.
String _reportIsolateName((String?, String) input) =>
Isolate.current.debugName ?? 'unnamed';
Loading…
Cancel
Save

Powered by TurnKey Linux.