Repository navigation
Description
Summary
#5650 moved cell rendering to UTF-8 buffers (Utf8Buffer) and batches cursor moves with cell output on the UnixRaw path. A post-merge review found that rendered output is correct, but it also found:
- an undocumented API break that silently drops output for existing subclasses,
- no test that exercises the new batched path,
- buffers that stay large indefinitely after a big image,
- extra UTF-16/UTF-8 conversions in the .NET and Windows drivers,
- performance gains much smaller than the "zero-allocation" description suggests.
No release contains #5650 yet, so the API break can still be undone without a second break. Item 1 should land before the next release; otherwise #5650 should be reverted, which would be a clean revert.
What was verified
- Output is correct. The full rendered byte stream (
GetLastOutput()) through the forced UnixRaw batched path is byte-for-byte identical to the pre-perf: UTF-8 batch mode + Utf8Buffer eliminates char[] to UTF8 conversion #5650 base (59e6b4d) across 60 frames. The frames mixed combining marks, ZWJ emoji, CJK, RGB colors, text styles, OSC 8 links (including non-ASCII URLs) and sixels. - Write calls per frame halved: 80×25 full redraw went from about 50 to 25 byte writes.
- Performance (in-process, UnixRaw with no real I/O, 4 runs per revision):
| Scenario | Base 59e6b4d |
#5650 / develop |
|---|---|---|
| 80×25 time/frame | 434–536 µs | 312–323 µs |
| 80×25 alloc/frame | ~597–609 KB | ~558 KB |
| 240×70 time/frame | 2855–2993 µs | 2820–3080 µs (no change) |
| 240×70 alloc/frame | 4.94 MB | 4.65 MB |
- A separate probe through a capture-only
OutputBasesink measured 556,872 → 556,216 B/frame. - ~95% of the remaining per-frame allocation is
string.GetColumns (), which allocates 264 B on every cell inAppendCellAnsi. This predates perf: UTF-8 batch mode + Utf8Buffer eliminates char[] to UTF8 conversion #5650, but it means the render path is not allocation-free. - Tested on macOS arm64 with .NET 10. Windows paths were reviewed from source only.
Must fix before the next release
-
1. The
OutputBasesubclass contract is broken, sometimes silently.- Overrides of the old
AppendOrWriteAttribute (StringBuilder, …)hook no longer compile (CS0115). - A subclass that overrides only
Write (StringBuilder)still compiles but receives zero rendered cells, because cells now go throughWrite (ReadOnlySpan<byte>). - The in-repo benchmark sink
MeasuringOutput(Tests/Benchmarks/ConsoleDrivers/OutputBuffer/OutputWriteBenchmark.cs) has exactly this bug, so the benchmark measures nothing. Utf8Bufferbecame public only because protected signatures expose it.- Fix: Either restore compatibility (for example, a default
Write (ReadOnlySpan<byte>)that forwards to the old sink) and makeUtf8Bufferinternal, or document the break indocfx/docsbreaking changes. In either case, fixMeasuringOutputand assert that the rendered payload reaches the sink.
- Overrides of the old
-
2. The new batched path has no test coverage.
- Output tests run with
AnsiPlatform.Degraded, andSetCursorPositionImplreturns before the batching branch. - Nothing tests cursor-move batching,
AnsiOutput/NetOutput/WindowsOutputWrite (ReadOnlySpan<byte>), orUnixIOHelper.TryWriteStdout (buffer, count). - PR CI and the perf gate don't run the output benchmark.
- Fix: Add tests that force the UnixRaw path (injectable writer) and assert byte-exact output, including sixel/kitty and hyperlink interleaving. Add a parity test against the string-based encoder.
- Output tests run with
Should fix
-
3. Unix partial writes copy unused buffer capacity.
TryWriteAllretries withbuffer [offset..]instead of the remaining part ofcount.- Repro: 1 MB backing array, a 2-byte write, first write returns 1 → ~1,000,088 B allocated.
- Fix: Retry with an offset into the original array or span, without copying. Test with
countmuch smaller than the buffer size.
-
4. Reusable buffers stay large indefinitely.
- After one 4 MB sixel frame followed by a small frame, the output object still holds about 16 MB:
_unixWriteBuffer: 4 MB_pendingCursorMoves: 4 MB_utf16DecodeBuffer: 8 MB
- Fix: Shrink or release buffers above a threshold after use, or write large payloads (sixel/kitty) straight through without staging them.
- After one 4 MB sixel frame followed by a small frame, the output object still holds about 16 MB:
-
5.
GetLastOutput ()capture is always on and now decodes every write.- Every byte write is decoded from UTF-8 back to UTF-16 into the capture
StringBuilder, in production too. - Fix: Make the capture opt-in (tests and diagnostics only).
- Every byte write is decoded from UTF-8 back to UTF-16 into the capture
-
6. The .NET and Windows drivers add conversions.
NetOutput.Write (ReadOnlySpan<byte>)callsEncoding.UTF8.GetStringon every write. Text goes UTF-16 → UTF-8 → UTF-16 →string, thenConsolere-encodes it; the old path allocated no string.WindowsOutput.Write (ReadOnlySpan<byte>)decodes UTF-8 twice (once for capture, once forWriteConsoleW).- Fix: Write bytes directly (
Console.OpenStandardOutput ()or a stream), or keep a UTF-16 path for these drivers.
-
7.
WindowsOutputno longer reports write failures (regression).- The old
Write (StringBuilder)path checkedWriteConsoleand threwWin32Exception; the new byte path ignores afalsereturn. - Fix: Restore the same error handling on the byte path.
- The old
-
8.
AnsiOutput.Write (ReadOnlySpan<byte>)catches and ignores every exception (// ignore for unit tests).- Fix: Limit the catch to the I/O failures it is meant to ignore, or log them through
Logging.
- Fix: Limit the catch to the I/O failures it is meant to ignore, or log them through
-
9. A failed batch still sends its pending cursor moves.
AnsiOutput.Write (IOutputBuffer)sends_pendingCursorMovesinfinally, even after rendering throws.- Impact is low in practice: only a throwing subclass triggered it, and a leftover move is harmless.
- Fix: Send pending moves only after a successful render; on failure, discard them.
Low priority / cleanup
- 10.
Utf8Buffer.AppendInt (int.MinValue)emits"-"(negation overflow). Handle the fullintrange and add signed boundary tests. No current caller passes negative values. - 11.
Utf8Buffer.AppendAsciisilently corrupts non-ASCII input."é中"becomes the bytesE9 2D. AddDebug.Assert/validation, or fall back to the UTF-8 encoder. - 12.
Utf8Buffer.EnsureCapacityadds_length + additionalinintbefore itslongcheck. It only matters near 2 GB and ends in an exception, but do the math inlongfirst. - 13. Batching could go further.
- The row-start and run-start cursor moves are both queued; only the last move is needed.
- A frame could be sent in one write instead of one per row.
AnsiOutput.Write (ReadOnlySpan<char>)doesn't check_pendingCursorMoves, so a future string write in the middle of a frame would come out in the wrong order.
- 14. Remove minor waste:
- a new
Utf8Bufferper frame (make it a field); ToAnsi/BuildAnsiForRegion*encode to UTF-8 and then callGetString;- extra
byte[]copies because the P/Invoke calls take arrays (use pointers or spans); - hand-written ASCII loops (consider the vectorized
Encoding.UTF8/AsciiAPIs); - large sixel/kitty payloads are now copied about 4 times, up from 2.
- a new
Pre-existing issues, not caused by #5650 (track separately)
string.GetColumns ()allocates on every cell and dominates per-frame allocation.WindowsVTOutputHelperignoresWriteFile's result and written count.AnsiOutputignoresTryWriteStdoutreturningfalse.TryWriteAlldoesn't retry onEINTR/EAGAIN.- A cursor position match aborts the frame:
AnsiOutput.SetCursorPositionImplreturnsfalsewhen the cursor is already at the target position, andOutputBase.Writetreatsfalseas "abort the frame".- The remaining rows aren't drawn and
DirtyLinesstays set. DriverImpl.Refreshusually prevents this, but a hidden cursor that keeps aPositioncan still trigger it.
Acceptance criteria
- Existing
OutputBasesubclasses either receive every rendered cell, or the break is documented and all in-repo subclasses (including the benchmark) are migrated. - Tests run the real batched UnixRaw path and assert byte-exact output, including a parity check against the string encoder.
- Unix partial writes allocate nothing, and reusable buffers don't keep multi-MB capacity after large payloads.
NetOutput/WindowsOutputadd no per-write string or double decode;WindowsOutputreports write failures again.- The benchmark reports allocations and write calls per frame for base and head, and PR descriptions don't claim "zero-allocation" unless the benchmark shows it.
Activity
Fixes tui-cs#5695. Harden UTF-8 output rendering