feat(#919): move the channel-history merge off the UI isolate

BlobStore.mergeOffThread runs the whole read-modify-write through compute(): stored JSON and incoming JSON in, merged JSON out, so only strings cross the isolate boundary and the object graph never does. Keeps the per-key serialisation that stops concurrent saves clobbering each other.

channel_message_store.saveChannelMessages now encodes only the INCOMING messages on the UI isolate (normally one message, measured 0.002 ms) and hands the 5.38 MB decode-merge-encode to another isolate, where it measured 134 ms per save and crossed Android's 5s input-dispatch watchdog in a burst (#334).

Fails closed: a stored blob that will not decode throws out of the merge, is logged, and the key is NOT written, which is the same refusal the inline code made. compute runs inline on web, which has no isolates; that is documented behaviour, not a silent fallback, and #920 removes the cost for every platform.

_messageToJson, _messageFromJson, _mergeKey, _repeatToJson and _repeatFromJson became static so the top-level merge can call them; none touched instance state.

9 new tests cover merge equivalence, timestamp ordering, empty/absent blobs, the throw on corrupt JSON, fail-closed leaving the blob byte-identical, and three concurrent saves all surviving. Fixtures go through the store's own encoder rather than hand-written maps, after a hand-rolled fixture rotted on a non-null field.

Refs #334, #917

Agent: TealGlen (session c61ce804)

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

@ -8,6 +8,45 @@ import '../helpers/reaction_helper.dart';
import '../helpers/smaz.dart';
import 'drift/blob_store.dart';
/// Merges `incomingJson` into the stored channel history, off the UI isolate.
///
/// Top-level because `compute` sends it to another isolate; a closure capturing
/// the store would not be sendable. Visible (not `_`-private) only so the test
/// can call it directly and assert the merge semantics without an isolate.
///
/// Semantics are deliberately identical to the inline merge this replaced:
/// upsert by [ChannelMessageStore._mergeKey], the incoming copy wins so edits,
/// reactions and status updates are captured, and the result is sorted by
/// timestamp. Deletion has its own path, so this never resurrects a deleted
/// message.
///
/// **Throws** when the stored JSON will not decode, rather than merging into an
/// empty base. [BlobStore.mergeOffThread] logs and declines to write, so a
/// blob that cannot be read is never replaced by a truncated one (#334's
/// original inline behaviour, preserved).
String mergeChannelHistoryJson((String?, String) input) {
final (stored, incomingJson) = input;
final byKey = <String, ChannelMessage>{};
if (stored != null && stored.isNotEmpty) {
// No try/catch: a decode failure must propagate so the caller refuses the
// write. Swallowing it here would silently truncate the history.
for (final e in jsonDecode(stored) as List<dynamic>) {
final m = ChannelMessageStore._messageFromJson(e as Map<String, dynamic>);
byKey[ChannelMessageStore._mergeKey(m)] = m;
}
}
for (final e in jsonDecode(incomingJson) as List<dynamic>) {
final m = ChannelMessageStore._messageFromJson(e as Map<String, dynamic>);
byKey[ChannelMessageStore._mergeKey(m)] = m;
}
final merged = byKey.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
return jsonEncode(merged.map(ChannelMessageStore._messageToJson).toList());
}
class ChannelMessageStore {
static const String _keyPrefix = 'channel_messages_';
@ -75,39 +114,22 @@ class ChannelMessageStore {
// resurrects a message the user deleted.
final key = _storageKey(channelIndex);
final blobs = BlobStore.instance;
// Serialise the whole read-modify-write against other saves/deletes on this
// key so two concurrent saves cannot clobber each other (Gemini review).
await blobs.synchronized(key, () async {
final byKey = <String, ChannelMessage>{};
final existing = await blobs.readWithPrefsFallback(key);
if (existing != null && existing.isNotEmpty) {
try {
for (final e in jsonDecode(existing) as List<dynamic>) {
final m = _messageFromJson(e as Map<String, dynamic>);
byKey[_mergeKey(m)] = m;
}
} catch (e) {
// SAFELANE 6: never merge into an empty base and truncate silently.
appLogger.error(
'Failed to decode existing channel $channelIndex history before '
'merge; aborting save to avoid truncation: $e',
tag: 'Storage',
);
return;
}
}
for (final m in messages) {
byKey[_mergeKey(m)] = m;
}
final merged = byKey.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
await blobs.write(key, jsonEncode(merged.map(_messageToJson).toList()));
});
// Only the INCOMING messages are encoded here, on the UI isolate: that is
// normally one message and costs microseconds. Decoding the stored history,
// merging and re-encoding it runs on another isolate (#919), because at the
// owner's largest channel (5.38 MB, 9,230 messages) that work measured
// 134 ms per save and a burst of them crossed Android's five-second
// watchdog (#334). `mergeOffThread` keeps the per-key serialisation that
// stops two saves clobbering each other, and fails closed: if the stored
// JSON will not decode, the key is not written, which is the same refusal
// this code made inline.
final incoming = jsonEncode(messages.map(_messageToJson).toList());
await blobs.mergeOffThread(key, incoming, mergeChannelHistoryJson);
}
/// Stable identity for merge/dedupe. messageId when present, else a composite
/// that distinguishes distinct messages that share no id.
String _mergeKey(ChannelMessage m) {
static String _mergeKey(ChannelMessage m) {
if (m.messageId.isNotEmpty) return 'id:${m.messageId}';
// Include the sender: two different senders can post identical text at the
// same timestamp without a messageId, and would otherwise collide and lose
@ -242,7 +264,7 @@ class ChannelMessageStore {
}
/// Convert ChannelMessage to JSON map
Map<String, dynamic> _messageToJson(ChannelMessage msg) {
static Map<String, dynamic> _messageToJson(ChannelMessage msg) {
return {
'senderKey': msg.senderKey != null ? base64Encode(msg.senderKey!) : null,
'senderName': msg.senderName,
@ -273,7 +295,7 @@ class ChannelMessageStore {
}
/// Convert JSON map to ChannelMessage
ChannelMessage _messageFromJson(Map<String, dynamic> json) {
static ChannelMessage _messageFromJson(Map<String, dynamic> json) {
final rawText = json['text'] as String;
final decodedText = Smaz.tryDecodePrefixed(rawText) ?? rawText;
return ChannelMessage(
@ -325,7 +347,7 @@ class ChannelMessageStore {
);
}
Map<String, dynamic> _repeatToJson(Repeat repeat) {
static Map<String, dynamic> _repeatToJson(Repeat repeat) {
return {
'repeaterKey': repeat.repeaterKey != null
? base64Encode(repeat.repeaterKey!)
@ -336,7 +358,7 @@ class ChannelMessageStore {
};
}
Repeat _repeatFromJson(Map<String, dynamic> json) {
static Repeat _repeatFromJson(Map<String, dynamic> json) {
return Repeat(
repeaterKey: json['repeaterKey'] != null
? Uint8List.fromList(base64Decode(json['repeaterKey']))

@ -138,6 +138,66 @@ class BlobStore {
await (_db.delete(_db.storedBlobs)..where((t) => t.key.equals(key))).go();
}
/// Read-modify-write for a bulk key with the decode, merge and re-encode run
/// **off the UI isolate** (#919).
///
/// Why this exists: the stores hold one JSON blob per key, so saving a single
/// message decodes, rebuilds and re-encodes the entire history. Measured on
/// the owner's live database, the largest channel is 5.38 MB holding 9,230
/// messages, and one save costs **134 ms** on a desktop CPU (decode 50,
/// rebuild 38, encode 51), scaling about 14 ms per 1,000 records. Saves on a
/// key are serialised by [synchronized], so a burst of arriving messages pays
/// that cost once each, back to back. Five messages on a phone five to ten
/// times slower than a desktop crosses Android's five-second input-dispatch
/// watchdog, which is what 25 ANR clusters on Play reported (#334).
///
/// This does not make the work cheaper, only concurrent: the ~11 MB of string
/// and map allocation per save still happens, on another isolate. Removing
/// the cost needs one row per message (#920).
///
/// [merge] **must be a top-level or static function**: `compute` sends it to
/// another isolate, and a closure capturing `this` is not sendable. It
/// receives `(storedJson, incomingJson)` and returns the JSON to store, or
/// null to leave the key untouched.
///
/// Fails closed. If [merge] throws, including on malformed stored JSON, the
/// error is logged and **the key is not written**, so a corrupt or
/// undecodable blob can never be overwritten by a truncated one. This is the
/// same refusal the stores already made inline; it does not fall back to
/// merging on the UI isolate.
///
/// On web `compute` runs [merge] inline, because web has no isolates. That is
/// documented `compute` behaviour, not a silent degradation: web keeps the
/// cost it has today and gains nothing here, which #920 fixes for every
/// platform at once.
///
/// Returns true when the key was written.
Future<bool> mergeOffThread(
String key,
String incomingJson,
BlobMergeCallback merge,
) {
return synchronized(key, () async {
final stored = await readWithPrefsFallback(key);
final String? merged;
try {
merged = await compute(merge, (stored, incomingJson));
} catch (e, stack) {
appLogger.error(
'Off-thread merge FAILED for $key (stored '
'${stored?.length ?? "null"} chars, incoming '
'${incomingJson.length} chars): $e. The key was NOT written, so '
'nothing was truncated.\n$stack',
tag: 'Storage',
);
return false;
}
if (merged == null) return false;
await write(key, merged);
return true;
});
}
/// Unions an [incoming] bulk value into the stored value for [key] by element
/// identity (message id / public key), keeping the stored copy on conflict and
/// adding only what is missing. Used to consolidate stores found in old
@ -347,6 +407,14 @@ class BlobStore {
}
}
/// Merge step for [BlobStore.mergeOffThread], run on another isolate.
///
/// Takes `(storedJson, incomingJson)` and returns the JSON to store, or null to
/// leave the key untouched. Must be a top-level or static function so `compute`
/// can send it; a record of strings is the payload so sendability is not in
/// question.
typedef BlobMergeCallback = String? Function((String?, String) input);
/// Mutable tally of a migration run; surfaced in the log and used by tests.
class MigrationReport {
int migrated = 0;

@ -0,0 +1,220 @@
import 'dart:convert';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/channel_message.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';
/// #919: the blob read-modify-write moved off the UI isolate. These tests pin
/// the two things that must not change with it: the merge is semantically what
/// it was, and a blob that cannot be decoded is never overwritten.
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();
});
ChannelMessage msg(int i, {String? text}) => ChannelMessage(
senderName: 's',
text: text ?? 'm$i',
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i),
isOutgoing: false,
channelIndex: 0,
messageId: 'id$i',
);
// Fixtures go through the store's OWN encoder rather than a hand-written map.
// A hand-rolled fixture silently rots the moment a non-null field is added to
// the schema, which is exactly how the first run of this test failed.
Future<String> encodeVia(List<ChannelMessage> ms) async {
final fixtureDb = OffbandDatabase(NativeDatabase.memory());
final previous = BlobStore.instance;
BlobStore.overrideForTest(BlobStore(fixtureDb));
try {
final store = ChannelMessageStore()..setPublicKeyHex = 'f' * 20;
await store.saveChannelMessages(0, ms);
final keys = await BlobStore.instance.keysWithPrefix('channel_messages_');
return (await BlobStore.instance.read(keys.single))!;
} finally {
BlobStore.overrideForTest(previous);
await fixtureDb.close();
}
}
group('mergeChannelHistoryJson', () {
test('adds incoming messages to the stored history', () async {
final stored = await encodeVia([msg(1), msg(2)]);
final incoming = await encodeVia([msg(3)]);
final out =
jsonDecode(mergeChannelHistoryJson((stored, incoming)))
as List<dynamic>;
expect(out.length, 3);
expect(
out.map((e) => (e as Map<String, dynamic>)['messageId']),
containsAll(['id1', 'id2', 'id3']),
);
});
test('incoming wins on the same id, so edits are captured', () async {
final stored = await encodeVia([msg(1, text: 'original')]);
final incoming = await encodeVia([msg(1, text: 'edited')]);
final out =
jsonDecode(mergeChannelHistoryJson((stored, incoming)))
as List<dynamic>;
expect(
out.length,
1,
reason: 'same messageId must upsert, not duplicate',
);
expect((out.single as Map<String, dynamic>)['text'], 'edited');
});
test('result is sorted by timestamp regardless of input order', () async {
final stored = await encodeVia([msg(9), msg(3)]);
final incoming = await encodeVia([msg(5)]);
final out =
jsonDecode(mergeChannelHistoryJson((stored, incoming)))
as List<dynamic>;
final stamps = out
.map((e) => (e as Map<String, dynamic>)['timestamp'] as int)
.toList();
expect(stamps, [...stamps]..sort());
});
test(
'an empty or absent stored blob merges into just the incoming',
() async {
final incoming = await encodeVia([msg(1)]);
for (final stored in <String?>[null, '']) {
final out =
jsonDecode(mergeChannelHistoryJson((stored, incoming)))
as List<dynamic>;
expect(out.length, 1, reason: 'stored=$stored');
}
},
);
test(
'THROWS on an undecodable stored blob rather than truncating',
() async {
final incoming = await encodeVia([msg(1)]);
// The whole point: swallowing this would merge into an empty base and
// silently replace real history with one message.
expect(
() => mergeChannelHistoryJson(('{not json at all', incoming)),
throwsA(anything),
);
},
);
});
group('BlobStore.mergeOffThread', () {
test('writes the merged result', () async {
final blobs = BlobStore.instance;
await blobs.write('k', await encodeVia([msg(1)]));
final wrote = await blobs.mergeOffThread(
'k',
await encodeVia([msg(2)]),
mergeChannelHistoryJson,
);
expect(wrote, isTrue);
final out = jsonDecode((await blobs.read('k'))!) as List<dynamic>;
expect(out.length, 2);
});
test(
'FAILS CLOSED on a corrupt stored blob: returns false and leaves it byte-identical',
() async {
final blobs = BlobStore.instance;
const corrupt = '{not json at all';
await blobs.write('k', corrupt);
final wrote = await blobs.mergeOffThread(
'k',
await encodeVia([msg(1)]),
mergeChannelHistoryJson,
);
expect(
wrote,
isFalse,
reason: 'a failed merge must not report success',
);
expect(
await blobs.read('k'),
corrupt,
reason: 'the unreadable blob must survive untouched, not be replaced',
);
},
);
test('a merge returning null leaves the key untouched', () async {
final blobs = BlobStore.instance;
await blobs.write('k', 'original');
final wrote = await blobs.mergeOffThread('k', 'x', _alwaysNull);
expect(wrote, isFalse);
expect(await blobs.read('k'), 'original');
});
test('concurrent merges on one key do not clobber each other', () async {
final blobs = BlobStore.instance;
await blobs.write('k', await encodeVia([msg(0)]));
// Fired together: without the per-key serialisation one read-modify-write
// would overwrite the other and a message would vanish.
await Future.wait([
blobs.mergeOffThread(
'k',
await encodeVia([msg(1)]),
mergeChannelHistoryJson,
),
blobs.mergeOffThread(
'k',
await encodeVia([msg(2)]),
mergeChannelHistoryJson,
),
blobs.mergeOffThread(
'k',
await encodeVia([msg(3)]),
mergeChannelHistoryJson,
),
]);
final out = jsonDecode((await blobs.read('k'))!) as List<dynamic>;
expect(
out.length,
4,
reason: 'all three concurrent saves plus the original must survive',
);
});
});
}
/// Top-level so `compute` can send it.
String? _alwaysNull((String?, String) input) => null;
Loading…
Cancel
Save

Powered by TurnKey Linux.