Files
pipelines/app/tool/perf/terminal_stream_bench.dart
T
alan ae07fe14db Terminal feed: message-task yields, slices sized to speed, one show per frame
- On the web a turn yields through a MessageChannel task: a chain of
  zero-length timers is clamped to 4 ms each, which left the emulator
  idle for a third of a burst.
- Slices are cut to what the measured speed writes in the budget left,
  so a turn ends near 6 ms however costly the output is to parse; the
  first write takes 4 Ki units to measure.
- Writes no longer notify the view each: the feed shows the emulator's
  state once everything queued is written, and while output still waits
  after a turn at most every 32 ms, so a flood draws its final state per
  frame instead of a frame per turn.
- Stream bench: producer follows a flow window (256 KiB past drawn, 32 KiB
  frames, rate by elapsed time), reports time spent parsing, ?show=each
  for the old per-write notify; tool/perf/terminal_stream_profile.mjs
  prints a CPU profile of one workload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 02:52:41 +00:00

251 lines
8.4 KiB
Dart

// Terminal rendering bench: the app's emulator view (theme, text style and
// the sliced output feed the terminals use) streaming generated output at a
// fixed rate, with Flutter frame timings and rAF intervals recorded.
//
// Build (from app/):
// flutter build web --profile --target tool/perf/terminal_stream_bench.dart \
// --output build/terminal-bench
// Run with tool/perf/terminal_stream_bench.mjs, or open the page with
// `?workload=seq|yes|unicode|colors|screen|progress&mb=30&rate=30&window=256`
// (the window size sets the grid; `rate` MB/s caps the producer and
// `window` KiB is how far it may run ahead of what is drawn, as the
// server's flow control, 0 for no limit).
// When the stream ends `window.__benchResult` holds a JSON summary:
// frames, build/raster/total quantiles (ms), rAF interval quantiles (ms),
// MB written, seconds and MB/s.
import 'dart:async';
import 'dart:convert';
import 'dart:js_interop';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_feed.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_theme.dart';
import 'package:xterm/xterm.dart';
@JS('__benchResult')
external set _benchResult(JSString value);
void main() {
final params = Uri.base.queryParameters;
runApp(_Bench(params));
}
class _Bench extends StatefulWidget {
const _Bench(this.params);
final Map<String, String> params;
@override
State<_Bench> createState() => _BenchState();
}
class _BenchState extends State<_Bench> {
late final Terminal _terminal = Terminal(maxLines: 10000);
// Wired as ChatShellTerminalSession wires its feed.
late final ChatShellTerminalFeed _feed = ChatShellTerminalFeed(
(text, _) {
_parsing.start();
_terminal.write(text, notify: _notifyEachWrite);
_parsing.stop();
},
show: _notifyEachWrite ? null : _terminal.notifyListeners,
);
/// `?show=each`: every write notifies the view, as before frames were
/// coalesced.
bool get _notifyEachWrite => widget.params['show'] == 'each';
final List<FrameTiming> _timings = [];
final List<double> _intervals = [];
Duration? _lastFrame;
Timer? _producer;
final Stopwatch _clock = Stopwatch();
/// Time spent in the emulator's writes (parsing into the buffer).
final Stopwatch _parsing = Stopwatch();
int _written = 0;
int _counter = 0;
bool _done = false;
String get _workload => widget.params['workload'] ?? 'seq';
double get _megabytes => double.tryParse(widget.params['mb'] ?? '') ?? 30;
double get _rate => double.tryParse(widget.params['rate'] ?? '') ?? 30;
@override
void initState() {
super.initState();
SchedulerBinding.instance.addTimingsCallback(_onTimings);
SchedulerBinding.instance.addPersistentFrameCallback(_onFrame);
// Let the first frames settle before streaming.
Timer(const Duration(milliseconds: 1500), _start);
}
void _onTimings(List<FrameTiming> timings) {
if (_clock.isRunning) _timings.addAll(timings);
}
void _onFrame(Duration stamp) {
if (_clock.isRunning && _lastFrame != null) {
_intervals.add((stamp - _lastFrame!).inMicroseconds / 1000);
}
_lastFrame = stamp;
}
/// KiB the producer may run ahead of what the feed has drawn, as the
/// server's flow window (256 KiB); 0 for no limit.
double get _window => double.tryParse(widget.params['window'] ?? '') ?? 256;
void _start() {
_clock.start();
// Every tick tops the output up to what the rate allows by now, at most
// a flow window past what is drawn: late ticks (a long frame) catch up,
// and a slow emulator holds the producer back as the server's flow
// control does.
const tick = Duration(milliseconds: 4);
_producer = Timer.periodic(tick, (_) {
if (_written >= _megabytes * 1e6) {
_producer?.cancel();
_feed.then(_finish);
return;
}
var allowed = _rate * 1e6 * _clock.elapsedMicroseconds / 1e6;
if (_window > 0) {
final ahead = _feed.drawn + _window * 1024;
if (ahead < allowed) allowed = ahead;
}
// In frames of at most 32 KiB, as the server sends a PTY's reads.
while (allowed - _written >= 1024) {
final size = allowed - _written;
final chunk = _chunk(size < 32768 ? size.round() : 32768);
_written += chunk.length;
_feed.add(chunk, _written);
}
});
}
String _chunk(int size) {
final out = StringBuffer();
while (out.length < size) {
_counter++;
switch (_workload) {
case 'yes':
out.write('y\r\n');
case 'unicode':
out.write(
'$_counter e\u0301 \u00F1 \u4E2D\u6587 \u{1F600} \u{1F44D}\u{1F3FD} \u{1F1F5}\u{1F1F9} \u2502 \u256D\u2500\u256E \u2593\u2592\u2591 \u{E0B0} done\r\n',
);
case 'colors':
final c = 31 + _counter % 7;
out.write(
'\x1b[${c}m$_counter\x1b[0m \x1b[1mbold\x1b[0m '
'plain text line with some words\r\n',
);
case 'screen':
// A full-screen program redrawing every row (top, an editor).
out.write('\x1b[H');
for (var row = 0; row < 48; row++) {
final c = 31 + (row + _counter) % 7;
out.write(
'\x1b[${c}m${(_counter + row).toString().padLeft(8)}'
'\x1b[0m \x1b[7m cpu ${row % 100}% \x1b[0m '
'${'process name and arguments ' * 4}\x1b[K\r\n',
);
}
case 'progress':
// A screen of text, then one status line rewritten in place (a
// progress bar, a build counter): one row changes per frame.
if (_counter == 1) {
for (var row = 0; row < 47; row++) {
out.write(
'\x1b[3${row % 7 + 1}mline $row\x1b[0m '
'${'static output that does not change ' * 3}\r\n',
);
}
}
final done = _counter % 50;
out.write(
'\r\x1b[1m[${'#' * done}${'.' * (50 - done)}]\x1b[0m '
'$_counter files',
);
default:
out.write('$_counter\r\n');
}
}
return out.toString();
}
void _finish() {
if (_done) return;
_done = true;
// A last frame flushes the engine's batched timings.
SchedulerBinding.instance.scheduleFrame();
Timer(const Duration(milliseconds: 600), () {
_clock.stop();
final seconds = _clock.elapsedMicroseconds / 1e6;
List<double> ms(Duration Function(FrameTiming t) pick) => [
for (final t in _timings) pick(t).inMicroseconds / 1000,
];
final result = {
'workload': _workload,
'frames': _timings.length,
'build': _quantiles(ms((t) => t.buildDuration)),
'raster': _quantiles(ms((t) => t.rasterDuration)),
'total': _quantiles(ms((t) => t.totalSpan)),
'interval': _quantiles(_intervals),
'mb': _written / 1e6,
'seconds': seconds,
'mbPerSecond': _written / 1e6 / seconds,
'parseSeconds': _parsing.elapsedMicroseconds / 1e6,
'parseMbPerSecond':
_written / 1e6 / (_parsing.elapsedMicroseconds / 1e6),
};
_benchResult = jsonEncode(result).toJS;
// ignore: avoid_print
print('BENCH_RESULT ${jsonEncode(result)}');
});
}
static Map<String, double> _quantiles(List<double> values) {
if (values.isEmpty) return const {};
final sorted = [...values]..sort();
double at(double q) =>
sorted[(q * (sorted.length - 1)).round().clamp(0, sorted.length - 1)];
double round(double v) => (v * 100).roundToDouble() / 100;
return {
'p50': round(at(0.5)),
'p90': round(at(0.9)),
'p99': round(at(0.99)),
'max': round(sorted.last),
'mean': round(sorted.reduce((a, b) => a + b) / sorted.length),
};
}
@override
void dispose() {
_producer?.cancel();
_feed.dispose();
SchedulerBinding.instance.removeTimingsCallback(_onTimings);
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(brightness: Brightness.dark),
home: Builder(
builder: (context) => Scaffold(
body: TerminalView(
_terminal,
theme: chatShellTerminalTheme(context),
textStyle: chatShellTerminalStyle(context),
padding: const EdgeInsets.all(8),
readOnly: true,
),
),
),
);
}
}