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>
This commit is contained in:
2026-11-26 02:52:41 +00:00
parent f7ef4d1445
commit ae07fe14db
8 changed files with 328 additions and 21 deletions
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:collection';
import 'chat_shell_terminal_yield.dart';
/// UTF-16 units one emulator write takes at most.
const int chatShellFeedSlice = 16 * 1024;
@@ -8,32 +9,66 @@ const int chatShellFeedSlice = 16 * 1024;
/// large replay or burst never holds a UI frame for long.
const Duration chatShellFeedBudget = Duration(milliseconds: 6);
/// While output waits after a turn, the view is shown the emulator's state
/// at most this often (about 30 frames a second), so a flood spends its
/// time parsing rather than drawing screens nobody can read.
const Duration chatShellFeedShowGap = Duration(milliseconds: 32);
/// The fewest units a write takes while more waits, however slow the
/// output has been to write.
const int _minimumSlice = 1024;
/// The units the first write takes, before the speed is known.
const int _firstSlice = 4096;
/// Output on its way into one emulator, in order: written in slices of at
/// most [slice] units, and after [budget] of writing the rest waits for the
/// next turn of the event loop. Each piece carries the server's absolute
/// byte offset its text ends at; [drawn] is the end of the last piece
/// written whole (what a terminal acknowledges as consumed).
/// next turn of the event loop ([chatShellYield]). A slice is cut to what
/// the measured speed writes in the budget left, so a turn ends close to
/// the budget however costly the output is to parse. Each piece carries
/// the server's absolute byte offset its text ends at; [drawn] is the end
/// of the last piece written whole (what a terminal acknowledges as
/// consumed).
///
/// With [show], writes do not notify the view themselves: [show] is called
/// once everything queued is written, and while output still waits after
/// a turn at most every [showGap], so a burst draws its final state per
/// frame instead of one frame per turn.
class ChatShellTerminalFeed {
ChatShellTerminalFeed(
this._write, {
this.show,
this.budget = chatShellFeedBudget,
this.slice = chatShellFeedSlice,
this.showGap = chatShellFeedShowGap,
});
/// Writes [text] into the emulator; [replay] marks a redraw of old output.
final void Function(String text, bool replay) _write;
/// Lets the view show what was written (the emulator's listeners).
final void Function()? show;
final Duration budget;
final int slice;
final Duration showGap;
/// Since [show] was last called; whether anything was written since.
final Stopwatch _sinceShown = Stopwatch()..start();
bool _unshown = false;
/// Called with a piece's end once it is drawn.
void Function(int end)? onDrawn;
final Queue<_Piece> _pieces = Queue();
Timer? _timer;
void Function()? _cancel;
bool _pumping = false;
int _drawn = 0;
int _end = 0;
/// Units written per millisecond, as last measured (0 before a write
/// took measurable time).
double _speed = 0;
/// The end of the output drawn so far.
int get drawn => _drawn;
@@ -46,8 +81,8 @@ class ChatShellTerminalFeed {
/// Drops what waits: the emulator is redrawn and continues from [end].
void restart(int end) {
_pieces.clear();
_timer?.cancel();
_timer = null;
_cancel?.call();
_cancel = null;
_drawn = end;
_end = end;
}
@@ -71,23 +106,35 @@ class ChatShellTerminalFeed {
void dispose() {
_pieces.clear();
_timer?.cancel();
_timer = null;
_cancel?.call();
_cancel = null;
}
void _schedule() {
if (_timer == null && !_pumping) _pump();
if (_cancel == null && !_pumping) _pump();
}
/// Units the next write takes, [elapsed] microseconds into the turn.
int _sliceAt(int elapsed) {
// Unmeasured (the first write, cold code): a small slice to measure.
if (_speed <= 0) return slice < _firstSlice ? slice : _firstSlice;
final left = (budget.inMicroseconds - elapsed) / 1000;
final fits = (_speed * left).floor();
if (fits >= slice) return slice;
final least = slice < _minimumSlice ? slice : _minimumSlice;
return fits < least ? least : fits;
}
void _pump() {
_timer = null;
_cancel = null;
_pumping = true;
final clock = Stopwatch()..start();
try {
while (_pieces.isNotEmpty) {
final piece = _pieces.first;
if (piece.at < piece.text.length) {
var cut = piece.at + slice;
final started = clock.elapsedMicroseconds;
var cut = piece.at + _sliceAt(started);
if (cut >= piece.text.length) {
cut = piece.text.length;
} else if (_highSurrogate(piece.text.codeUnitAt(cut - 1))) {
@@ -95,11 +142,17 @@ class ChatShellTerminalFeed {
cut++;
}
_write(piece.text.substring(piece.at, cut), piece.replay);
_unshown = true;
final took = clock.elapsedMicroseconds - started;
// Small writes (an echo) say little about the speed.
final units = cut - piece.at;
if (took > 0 && units >= _minimumSlice) _speed = units * 1000 / took;
piece.at = cut;
}
if (piece.at >= piece.text.length) {
_pieces.removeFirst();
if (piece.action != null) {
_show();
piece.action!();
} else {
_drawn = piece.end;
@@ -107,14 +160,23 @@ class ChatShellTerminalFeed {
}
}
if (_pieces.isNotEmpty && clock.elapsed >= budget) {
_timer = Timer(Duration.zero, _pump);
if (_sinceShown.elapsed >= showGap) _show();
_cancel = chatShellYield(_pump);
return;
}
}
_show();
} finally {
_pumping = false;
}
}
void _show() {
if (!_unshown) return;
_unshown = false;
_sinceShown.reset();
show?.call();
}
}
class _Piece {
@@ -47,7 +47,7 @@ class ChatShellTerminalSession {
ChatShellInputHandler(optionAsMeta: this.optionAsMeta),
defaultInputHandler,
]);
_feed = ChatShellTerminalFeed(_write);
_feed = ChatShellTerminalFeed(_write, show: terminal.notifyListeners);
// Drawn at the process's own size until a view lays it out at its own.
if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows);
terminal.onOutput = _output;
@@ -185,7 +185,7 @@ class ChatShellTerminalSession {
_replaying = replay;
_drawing = !replay;
try {
terminal.write(text);
terminal.write(text, notify: false);
} finally {
_replaying = false;
_drawing = false;
@@ -0,0 +1,11 @@
import 'chat_shell_terminal_yield_stub.dart'
if (dart.library.js_interop) 'chat_shell_terminal_yield_web.dart'
as impl;
/// Runs [callback] in a later turn of the event loop, after which the UI
/// may have drawn a frame; the returned function cancels it if it has not
/// run. On the web this is a message task: a chain of zero-length timers
/// is clamped to 4 ms each after a few, which left the emulator idle for
/// a third of a large burst. Elsewhere it is a zero-length timer.
void Function() chatShellYield(void Function() callback) =>
impl.chatShellYield(callback);
@@ -0,0 +1,4 @@
import 'dart:async';
void Function() chatShellYield(void Function() callback) =>
Timer(Duration.zero, callback).cancel;
@@ -0,0 +1,32 @@
import 'dart:async';
import 'dart:collection';
import 'dart:js_interop';
import 'package:web/web.dart' as web;
/// One channel for every terminal: each message runs the oldest waiting
/// callback, in order.
final _waiting = Queue<_Turn>();
web.MessageChannel? _channel;
void Function() chatShellYield(void Function() callback) {
final channel = _channel ??= web.MessageChannel()
..port1.onmessage = _next.toJS;
final turn = _Turn(Zone.current.bindCallbackGuarded(callback));
_waiting.add(turn);
channel.port2.postMessage(null);
return () => turn.cancelled = true;
}
void _next(web.MessageEvent _) {
if (_waiting.isEmpty) return;
final turn = _waiting.removeFirst();
if (!turn.cancelled) turn.callback();
}
class _Turn {
_Turn(this.callback);
final void Function() callback;
bool cancelled = false;
}
@@ -55,6 +55,84 @@ void main() {
},
);
test('the view is shown once what waits is written, and while a burst '
'is behind at most every show gap', () async {
var shown = 0;
final writes = <String>[];
final feed = ChatShellTerminalFeed(
(text, _) => writes.add(text),
show: () => shown++,
budget: Duration.zero,
slice: 10,
showGap: const Duration(hours: 1),
);
feed.add('abc', 3);
// Written whole at once: shown at once.
expect(writes, ['abc']);
expect(shown, 1);
feed.add('x' * 35, 38);
await turn();
await turn();
// Behind, within the gap: not shown again.
expect(writes.length, 4);
expect(shown, 1);
await turn();
await turn();
// Caught up: the final state is shown.
expect(writes.skip(1).join(), 'x' * 35);
expect(feed.idle, isTrue);
expect(shown, 2);
// An action waiting behind output sees it shown first.
feed.add('y' * 25, 63);
var shownForAction = -1;
feed.then(() => shownForAction = shown);
for (var i = 0; i < 5; i++) {
await turn();
}
expect(shownForAction, 3);
expect(shown, 3);
});
test('every turn shows its state with no show gap', () async {
var shown = 0;
final feed = ChatShellTerminalFeed(
(_, _) {},
show: () => shown++,
budget: Duration.zero,
slice: 10,
showGap: Duration.zero,
);
feed.add('x' * 30, 30);
for (var i = 0; i < 5; i++) {
await turn();
}
expect(feed.idle, isTrue);
expect(shown, 3);
});
test('slices follow the measured speed within the slice', () async {
final sizes = <int>[];
final feed = ChatShellTerminalFeed(
(text, _) {
sizes.add(text.length);
// About 1 ms per 1000 units.
final until = Stopwatch()..start();
while (until.elapsedMicroseconds < text.length) {}
},
budget: const Duration(milliseconds: 6),
slice: 16 * 1024,
);
feed.add('y' * 100000, 100000);
while (!feed.idle) {
await turn();
}
expect(sizes.reduce((a, b) => a + b), 100000);
expect(sizes.every((s) => s <= 16 * 1024), isTrue);
// After the first slice measured the speed, no write takes much more
// than a turn's budget (6 ms, about 6000 units here).
expect(sizes.skip(1).every((s) => s <= 8000), isTrue, reason: '$sizes');
});
test('a surrogate pair is never split between two writes', () {
final writes = <String>[];
final feed = ChatShellTerminalFeed((text, _) => writes.add(text), slice: 3);
+41 -6
View File
@@ -6,7 +6,10 @@
// 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` (the window size sets the grid).
// `?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.
@@ -40,14 +43,27 @@ class _Bench extends StatefulWidget {
class _BenchState extends State<_Bench> {
late final Terminal _terminal = Terminal(maxLines: 10000);
// Wired as ChatShellTerminalSession wires its feed.
late final ChatShellTerminalFeed _feed = ChatShellTerminalFeed(
(text, _) => _terminal.write(text),
(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;
@@ -76,19 +92,35 @@ class _BenchState extends State<_Bench> {
_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);
final perTick = (_rate * 1e6 * tick.inMicroseconds / 1e6).round();
_producer = Timer.periodic(tick, (_) {
if (_written >= _megabytes * 1e6) {
_producer?.cancel();
_feed.then(_finish);
return;
}
final chunk = _chunk(perTick);
_written += chunk.length;
_feed.add(chunk, _written);
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);
}
});
}
@@ -164,6 +196,9 @@ class _BenchState extends State<_Bench> {
'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
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env node
// CPU profile of one terminal bench workload (tool/perf/terminal_stream_bench.dart)
// in headless Chrome: prints the functions with the most self and total
// time while the stream runs, and the bench's own summary line.
//
// node tool/perf/terminal_stream_profile.mjs --build build/terminal-bench \
// [--workload seq] [--mb 8] [--top 40] [--out profile.cpuprofile]
import { parseArgs } from 'node:util';
import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
import { openBrowser } from '../capture/browser.mjs';
import { serveBuild } from '../capture/serve.mjs';
const { values: options } = parseArgs({
options: {
build: { type: 'string' },
workload: { type: 'string', default: 'seq' },
mb: { type: 'string', default: '8' },
rate: { type: 'string', default: '30' },
top: { type: 'string', default: '40' },
out: { type: 'string' },
size: { type: 'string', default: '1280x800' },
},
});
if (!options.build) throw new Error('--build required');
const [width, height] = options.size.split('x').map(Number);
const server = await serveBuild(options.build);
const browser = await openBrowser();
const evaluate = async (expression) =>
(await browser.send('Runtime.evaluate', { expression, returnByValue: true })).result.value;
try {
await browser.send('Page.enable');
await browser.send('Runtime.enable');
await browser.send('Profiler.enable');
await browser.send('Profiler.setSamplingInterval', { interval: 200 });
await browser.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
const url = new URL('/', server.origin);
url.searchParams.set('workload', options.workload);
url.searchParams.set('mb', options.mb);
url.searchParams.set('rate', options.rate);
await browser.send('Page.navigate', { url: url.href });
// The bench streams 1.5 s after start-up; profile from then on.
await delay(1500);
await browser.send('Profiler.start');
let result = null;
for (let i = 0; i < 600 && !result; i++) {
await delay(250);
result = await evaluate('window.__benchResult ?? null');
}
const { profile } = await browser.send('Profiler.stop');
if (options.out) await writeFile(options.out, JSON.stringify(profile));
const byId = new Map(profile.nodes.map((n) => [n.id, n]));
const parent = new Map();
for (const n of profile.nodes) for (const c of n.children ?? []) parent.set(c, n.id);
const hits = new Map();
for (const s of profile.samples) hits.set(s, (hits.get(s) ?? 0) + 1);
const name = (n) => `${n.callFrame.functionName || '(anonymous)'} ${n.callFrame.url.split('/').pop()}:${n.callFrame.lineNumber}`;
const self = new Map();
const total = new Map();
let all = 0;
for (const [id, count] of hits) {
all += count;
const key = name(byId.get(id));
self.set(key, (self.get(key) ?? 0) + count);
const seen = new Set();
for (let at = id; at !== undefined; at = parent.get(at)) {
const k = name(byId.get(at));
if (seen.has(k)) continue;
seen.add(k);
total.set(k, (total.get(k) ?? 0) + count);
}
}
const pct = (v) => (100 * v / all).toFixed(1).padStart(5);
const top = Number(options.top);
console.log(`samples ${all}`);
console.log('--- self');
for (const [k, v] of [...self].sort((a, b) => b[1] - a[1]).slice(0, top)) console.log(pct(v), pct(total.get(k)), k);
console.log('--- total');
for (const [k, v] of [...total].sort((a, b) => b[1] - a[1]).slice(0, top)) console.log(pct(self.get(k) ?? 0), pct(v), k);
console.log(result);
} finally {
await browser.close?.();
await server.close?.();
}