Merge: perf round 1 — chat streaming rebuilds only the live turn

This commit is contained in:
2026-11-02 00:00:09 +00:00
10 changed files with 722 additions and 63 deletions
@@ -0,0 +1,70 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_row_widgets.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_cache.dart';
void main() {
test('chatJsonEquals compares decoded JSON structurally', () {
expect(
chatJsonEquals(
{
'a': [
1,
'x',
{'b': true},
],
},
{
'a': [
1,
'x',
{'b': true},
],
},
),
isTrue,
);
expect(chatJsonEquals({'a': 1}, {'a': 2}), isFalse);
expect(chatJsonEquals({'a': 1}, {'b': 1}), isFalse);
expect(chatJsonEquals([1, 2], [1, 2, 3]), isFalse);
expect(chatJsonEquals({'a': null}, <String, dynamic>{}), isFalse);
});
test('ChatRowWidgets reuses a widget until its row or inputs change', () {
final rows = ChatRowWidgets();
var builds = 0;
Widget build() {
builds++;
return SizedBox(width: builds.toDouble());
}
final first = rows.widgetFor('k', {'text': 'a'}, [1], build);
expect(rows.widgetFor('k', {'text': 'a'}, [1], build), same(first));
expect(builds, 1);
expect(rows.widgetFor('k', {'text': 'b'}, [1], build), isNot(same(first)));
final second = rows.widgetFor('k', {'text': 'b'}, [2], build);
expect(builds, 3);
rows.prune();
// A row the last build did not ask for is forgotten.
rows.prune();
expect(rows.widgetFor('k', {'text': 'b'}, [2], build), isNot(same(second)));
expect(builds, 4);
});
test('ChatMarkdownCache parses a text once and stays bounded', () {
final cache = ChatMarkdownCache(maxEntries: 2, maxChars: 100);
final blocks = cache.blocksFor('# One');
expect(cache.blocksFor('# One'), same(blocks));
expect(cache.parses, 1);
cache.blocksFor('two');
cache.blocksFor('three');
// The least recently used text was evicted and parses again.
expect(cache.blocksFor('# One'), isNot(same(blocks)));
expect(cache.parses, 4);
// A text larger than the character budget is parsed but never held.
final long = 'x' * 200;
cache.blocksFor(long);
cache.blocksFor(long);
expect(cache.parses, 6);
});
}
@@ -0,0 +1,159 @@
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart' as widgets;
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_cache.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart';
import '../conversation/chat_thread_fixtures.dart';
/// Measurement harness: streams 200 text deltas into a 300-message transcript
/// and counts message builds, markdown builds/parses and per-delta frame time;
/// then scrolls the long transcript up and back down.
const _messages = 300;
const _deltas = 200;
String _answer(int index) =>
'## Answer $index\n\nSome **bold** text with `code` and a '
'[link](https://example.com/$index).\n\n'
'```dart\n'
'${List.generate(30, (line) => 'final v$line = $index * $line;').join('\n')}'
'\n```\n\n'
'- one\n- two\n- three\n';
List<JsonMap> _transcript() => [
for (var index = 0; index < _messages; index++)
// The newest message is the operator's, so the reply opens a new turn.
index.isOdd
? chatMessage(
'u$index',
'user',
parts: [
{'type': 'text', 'text': 'Question $index'},
],
)
: chatMessage(
'a$index',
'assistant',
parts: [
{'type': 'text', 'id': 't$index', 'text': _answer(index)},
],
),
];
Future<FakeChatGateway> _open(WidgetTester tester) async {
tester.view.physicalSize = const Size(1000, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(_transcript());
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
),
);
final watch = Stopwatch()..start();
await tester.pumpAndSettle();
watch.stop();
// ignore: avoid_print
print(
'PERF open: parses=${chatMarkdownCache.parses} '
'settleMs=${watch.elapsedMilliseconds}',
);
return gateway;
}
String _stats(List<int> samples) {
final sorted = [...samples]..sort();
final mean = sorted.reduce((a, b) => a + b) / sorted.length;
return 'meanUs=${mean.round()} p50Us=${sorted[sorted.length ~/ 2]} '
'p90Us=${sorted[sorted.length * 9 ~/ 10]} maxUs=${sorted.last}';
}
void main() {
setUp(chatMarkdownCache.clear);
testWidgets('streaming deltas rebuild only the live turn', (tester) async {
final gateway = await _open(tester);
var messageBuilds = 0;
var markdownBuilds = 0;
var totalBuilds = 0;
widgets.debugOnRebuildDirtyWidget = (element, _) {
final widget = element.widget;
if (widget is ChatMessageView) messageBuilds++;
if (widget is ChatMarkdownView) markdownBuilds++;
totalBuilds++;
};
addTearDown(() => widgets.debugOnRebuildDirtyWidget = null);
final parsesBefore = chatMarkdownCache.parses;
final perDelta = <int>[];
final watch = Stopwatch();
for (var index = 0; index < _deltas; index++) {
gateway.emitEvent(
chatTextFrame(
index == 0 ? 'Live reply ' : 'word$index ',
messageId: 'live',
),
);
await tester.idle();
watch
..reset()
..start();
await tester.pump();
watch.stop();
perDelta.add(watch.elapsedMicroseconds);
}
widgets.debugOnRebuildDirtyWidget = null;
final parses = chatMarkdownCache.parses - parsesBefore;
// ignore: avoid_print
print(
'PERF stream: deltas=$_deltas messages=$_messages '
'messageBuilds=$messageBuilds markdownBuilds=$markdownBuilds '
'markdownParses=$parses totalBuilds=$totalBuilds frame ${_stats(perDelta)}',
);
expect(
find.textContaining('word${_deltas - 1}', findRichText: true),
findsOneWidget,
);
// Only the live turn rebuilds per delta (plus slack for the turn that
// starts the stream); every finished message is left alone.
expect(messageBuilds, lessThanOrEqualTo(_deltas + 10));
expect(parses, lessThanOrEqualTo(_deltas + 10));
});
testWidgets('scrolling a long transcript reuses parsed markdown', (
tester,
) async {
await _open(tester);
final list = find.byKey(const ValueKey<String>('chat-thread-s'));
final parsesBefore = chatMarkdownCache.parses;
var parsesUp = 0;
final frames = <int>[];
final watch = Stopwatch();
// Up 40 drags and back down 40: the way back revisits parsed rows.
for (final dy in [...List.filled(40, 600.0), ...List.filled(40, -600.0)]) {
await tester.drag(list, Offset(0, dy));
watch
..reset()
..start();
await tester.pump(const Duration(milliseconds: 16));
watch.stop();
frames.add(watch.elapsedMicroseconds);
if (frames.length == 40) {
parsesUp = chatMarkdownCache.parses - parsesBefore;
}
}
await tester.pumpAndSettle();
final parses = chatMarkdownCache.parses - parsesBefore;
// ignore: avoid_print
print(
'PERF scroll: drags=${frames.length} markdownParses=$parses '
'(up=$parsesUp down=${parses - parsesUp}) '
'frame ${_stats(frames)}',
);
});
}