Skip to content

Follow-up to PR #5650: fix the UTF-8 output path's compatibility, reliability and test gaps #5695

Closed

Description

@harder

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 OutputBase sink measured 556,872 → 556,216 B/frame.
  • ~95% of the remaining per-frame allocation is string.GetColumns (), which allocates 264 B on every cell in AppendCellAnsi. 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 OutputBase subclass 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 through Write (ReadOnlySpan<byte>).
    • The in-repo benchmark sink MeasuringOutput (Tests/Benchmarks/ConsoleDrivers/OutputBuffer/OutputWriteBenchmark.cs) has exactly this bug, so the benchmark measures nothing.
    • Utf8Buffer became 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 make Utf8Buffer internal, or document the break in docfx/docs breaking changes. In either case, fix MeasuringOutput and assert that the rendered payload reaches the sink.
  • 2. The new batched path has no test coverage.

    • Output tests run with AnsiPlatform.Degraded, and SetCursorPositionImpl returns before the batching branch.
    • Nothing tests cursor-move batching, AnsiOutput/NetOutput/WindowsOutput Write (ReadOnlySpan<byte>), or UnixIOHelper.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.

Should fix

  • 3. Unix partial writes copy unused buffer capacity.

    • TryWriteAll retries with buffer [offset..] instead of the remaining part of count.
    • 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 count much 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.
  • 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).
  • 6. The .NET and Windows drivers add conversions.

    • NetOutput.Write (ReadOnlySpan<byte>) calls Encoding.UTF8.GetString on every write. Text goes UTF-16 → UTF-8 → UTF-16 → string, then Console re-encodes it; the old path allocated no string.
    • WindowsOutput.Write (ReadOnlySpan<byte>) decodes UTF-8 twice (once for capture, once for WriteConsoleW).
    • Fix: Write bytes directly (Console.OpenStandardOutput () or a stream), or keep a UTF-16 path for these drivers.
  • 7. WindowsOutput no longer reports write failures (regression).

    • The old Write (StringBuilder) path checked WriteConsole and threw Win32Exception; the new byte path ignores a false return.
    • Fix: Restore the same error handling on the byte path.
  • 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.
  • 9. A failed batch still sends its pending cursor moves.

    • AnsiOutput.Write (IOutputBuffer) sends _pendingCursorMoves in finally, 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 full int range and add signed boundary tests. No current caller passes negative values.
  • 11. Utf8Buffer.AppendAscii silently corrupts non-ASCII input. "é中" becomes the bytes E9 2D. Add Debug.Assert/validation, or fall back to the UTF-8 encoder.
  • 12. Utf8Buffer.EnsureCapacity adds _length + additional in int before its long check. It only matters near 2 GB and ends in an exception, but do the math in long first.
  • 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 Utf8Buffer per frame (make it a field);
    • ToAnsi/BuildAnsiForRegion* encode to UTF-8 and then call GetString;
    • extra byte[] copies because the P/Invoke calls take arrays (use pointers or spans);
    • hand-written ASCII loops (consider the vectorized Encoding.UTF8/Ascii APIs);
    • large sixel/kitty payloads are now copied about 4 times, up from 2.

Pre-existing issues, not caused by #5650 (track separately)

  • string.GetColumns () allocates on every cell and dominates per-frame allocation.
  • WindowsVTOutputHelper ignores WriteFile's result and written count. AnsiOutput ignores TryWriteStdout returning false. TryWriteAll doesn't retry on EINTR/EAGAIN.
  • A cursor position match aborts the frame:
    • AnsiOutput.SetCursorPositionImpl returns false when the cursor is already at the target position, and OutputBase.Write treats false as "abort the frame".
    • The remaining rows aren't drawn and DirtyLines stays set.
    • DriverImpl.Refresh usually prevents this, but a hidden cursor that keeps a Position can still trigger it.

Acceptance criteria

  1. Existing OutputBase subclasses either receive every rendered cell, or the break is documented and all in-repo subclasses (including the benchmark) are migrated.
  2. Tests run the real batched UnixRaw path and assert byte-exact output, including a parity check against the string encoder.
  3. Unix partial writes allocate nothing, and reusable buffers don't keep multi-MB capacity after large payloads.
  4. NetOutput/WindowsOutput add no per-write string or double decode; WindowsOutput reports write failures again.
  5. 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

  1. added a commit that references this issue on Oct 6, 2026
    02236a1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions