Skip to content

fix(#652): renderer bottom-output corruption — column-binding + renderSummary teardown order - #654

Closed
admarble wants to merge 4 commits into
feature/647-fix-cli-624-s-duplicate-header-fix-doesn-t-catch-rfrom
feature/652-fix-cli-renderer-bottom-output
Closed

admarble wants to merge 4 commits into
feature/647-fix-cli-624-s-duplicate-header-fix-doesn-t-catch-rfrom
feature/652-fix-cli-renderer-bottom-output

Conversation

@admarble

@admarble admarble commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Stacking callout (read first)

This PR is stacked on PR #653 / feature/647-… (issue #647).

Closes #652.

What this PR ships

Two defensive renderer fixes + two invariant tests.

1. log-update column binding (Symptom A)

The production TTYRenderer constructor previously delegated to the unbound logUpdate singleton, which reads process.stdout.columns directly. Under npx, that value is sometimes undefined → log-update falls back to its internal defaultColumns (~80) while the renderer falls back to 100 (getColumns()). The width disagreement makes log-update's previousLineCount desync from the actual terminal-row-count.

Fix: replace the singleton with createLogUpdate(boundStream), where the bound stream's columns/rows/isTTY getters delegate to the renderer's view of the world. Renderer and log-update now share a single source of truth.

Note: isTTY derives from process.stdout.isTTY (NOT hardcoded true). An earlier draft of this PR hardcoded true — caught by code review because it would cause log-update v7 to wrap every write in synchronized-output ANSI escapes (ESC[?2026h … ESC[?2026l) under redirects/pipes.

2. renderSummary teardown order (Symptom B)

The original PR comment claimed that a setInterval tick could fire between logUpdateClear and the subsequent clearInterval, allowing the live frame to redraw into the summary stream. That claim is false. JS is single-threaded; setInterval callbacks are macrotasks and cannot preempt synchronous code. The race window doesn't exist.

The reorder (move clearInterval to the top of renderSummary) is kept as structural cleanup: single-statement move, guards against future redraw() callers re-creating the live zone after teardown, and documents intent (when rendering summary, we are finished with the live zone). But it is NOT a fix for Symptom B in any defensible sense.

The likely real fix for Symptom B is #647's AC-3 grid-width math correction (-7 → -9), already shipped in this branch.

Tests

Two RED→GREEN invariant tests in scrollback-harness.test.ts:

  1. Symptom A: _boundStream exists and reports the renderer's view. Constructs a production-path renderer with process.stdout.columns = undefined and asserts _boundStream.columns === 200 (the renderer's configured value, not log-update's 80-col fallback). Also asserts _boundStream.isTTY correctly tracks process.stdout.isTTY (guards against the synchronized-output ANSI regression).

  2. Symptom B: clearInterval runs before logUpdateClear. Sets a real interval, asserts the precondition (liveTimer !== null before renderSummary), spies on logUpdateClear, and asserts that at the moment it ran, liveTimer was already null (proves clearInterval ran first via the renderSummary branch, not via a dispose shortcut).

RED→GREEN verified locally by reverting each fix:

  • Symptom A: set _boundStream = null → test fails with "expected null not to be null"
  • Symptom B: revert clearInterval to after clear/done → test fails with "expected true to be false"

Honest gap acknowledgements

These are documented limits, not blockers. Filed as follow-ups (recommended below).

  • Symptom A's column-mismatch hypothesis is partial. eraseLines clears whole lines and can't directly produce mid-string corruption (#505 loop → #5loop). That shape requires log-update's diff renderer overwriting from the first changed column, AND/OR SIGWINCH races, AND/OR subprocess stdout interleaving. The column-binding fix narrows the desync window but does not address SIGWINCH or subprocess interleaving.

  • Symptom B is likely already fixed by fix(cli): #624's duplicate-header fix doesn't catch real log-update/scrollback bug (v2.3.0 regression confirmed) #647's AC-3 grid-math correction. The U+FFFD and row-overlap are most plausibly the result of wrap-ansi hard-wrapping inside a multibyte box-drawing character because the rows were 2 chars wider than the terminal column count. The reorder in this PR is structural cleanup; fix(cli): #624's duplicate-header fix doesn't catch real log-update/scrollback bug (v2.3.0 regression confirmed) #647 is the substantive fix.

  • Tests are property invariants, not visible-symptom regressions. They prove the bound stream is configured correctly and the call order is correct. They do NOT prove the visible symptoms cannot occur via SIGWINCH/subprocess/etc. mechanisms.

  • No production replay performed. Running the original npx sequant run 504 505 -q transcript with SEQUANT_DEBUG_RENDERER=1 would validate (or refute) the column-mismatch hypothesis. Not done here because it requires live claude subprocess calls.

  • Commit history is messy. Three commits, including a revert-restore cycle. Squash-merge at merge time will collapse to a single clean commit.

Recommended follow-ups (not blocking)

  1. PTY-based harness for true visible-symptom regression coverage (instead of the synchronous VirtualTerminal model that fundamentally can't reproduce timing-dependent symptoms).
  2. Production replay with SEQUANT_DEBUG_RENDERER=1 against the original transcript to empirically validate the column-mismatch hypothesis.
  3. SIGWINCH race investigation — the column-binding fix doesn't address process.stdout.columns changing mid-render.

Test plan

  • npm run build passes
  • npm run lint passes (0 errors, 0 warnings)
  • All 91 cli-ui tests pass (npx vitest run src/lib/cli-ui/)
  • Symptom A invariant goes RED on pre-fix code (verified by setting _boundStream = null)
  • Symptom B invariant goes RED on pre-fix code (verified by reverting clearInterval to after clear/done)
  • Production replay with SEQUANT_DEBUG_RENDERER=1 (deferred — requires real claude subprocess; filed as follow-up)

admarble added 3 commits May 15, 2026 17:56
…rSummary teardown order

Closes #652.

## Summary

Two defensive fixes for the bottom-output corruption symptoms documented in
#652, plus reproduction scaffolding + a RED→GREEN invariant gate for the
renderSummary path.

## Fixes

1. **Bind log-update to a column-consistent stream wrapper** (`run-renderer.ts`)

   Symptom A (event-line char loss: `✔ #5loop` instead of `✔ #505 loop`) is
   most consistent with log-update wrapping at a different width than the
   real terminal renders, causing `previousLineCount` to disagree with the
   actual terminal-row-count. `eraseLines(previousLineCount)` then over- or
   under-clears, leaving partial frame rows that the next event-line write
   lands on top of.

   The production singleton `logUpdate` reads `process.stdout.columns`
   directly. Under `npx`, that value is sometimes undefined → log-update
   falls back to its internal `defaultColumns` (~80) while the renderer
   falls back to 100. Width disagreement is the root cause.

   Fix: replace the singleton with `createLogUpdate(boundStream)`, where
   `boundStream.columns` / `boundStream.rows` delegate to the renderer's
   `getColumns()` / `getRows()` getters. Renderer and log-update now share
   a single source of truth for width.

2. **Reorder `renderSummary` teardown** (`run-renderer.ts`)

   Symptom B (U+FFFD in the summary separator + row overlap) is most
   consistent with the live timer's tick firing between the log-update
   teardown and the summary write, re-rendering the live frame into the
   summary's output stream and splitting a multibyte box-drawing char at a
   byte boundary.

   Before: `logUpdateClear → logUpdateDone → clearInterval → write`.
   After:  `clearInterval → logUpdateClear → logUpdateDone → write`.

## Tests

`scrollback-harness.test.ts` gains three new specs:

- `#652 Symptom A — event-line mid-string char loss` (2 cases): drive the
  motivating `npx sequant run 504 505 -q` transcript with interleaved live
  ticks, and a second case forcing the `streamColumns < cols` mismatch.
- `#652 Symptom B — U+FFFD and row overlap in summary table` (2 cases):
  visible-output assertion (no `�`, no digits/letters in separator rows)
  plus a RED→GREEN call-order invariant — `liveTimer` must be `null` at
  the moment `logUpdateClear` runs. Reverting the renderSummary reorder
  flips this assertion RED.

The visible-output assertions pass on both the pre- and post-fix branches
because the harness is single-threaded and cannot model OS-level pipe
buffering or pending setInterval ticks. They are kept as scaffolding for
future reproduction (e.g. PTY-level harness) and to document the symptom
shape. The call-order invariant is the actual regression gate.

## AC-4 verdict (shared vs independent root cause)

Symptoms A and B **share a contributing mechanism** with #647 Mechanism #1
— column/row count mismatch between log-update's stream view and the
terminal's actual width under `npx`. But the **visible symptoms** are
independent of the duplicate-header bug that #647 addresses, so they are
shipped as a follow-up on top of #647 per the issue body's instructions.
Strengthens AC-5 for Symptom A. The earlier scaffolding tests pass on
both pre-fix and post-fix code because the synchronous VT harness cannot
model real OS-level cursor/erase interleaving.

This invariant test pins the *property* the fix enforces: when
`process.stdout.columns` is undefined (the `npx` case), log-update must
still wrap at the renderer's configured column count (200), not at its
own 80-col `defaultColumns` fallback.

Verification:
- Without the column-binding fix (singleton `logUpdate`): RED. The
  longest captured line is exactly 80 chars (log-update wrapped at its
  default).
- With the column-binding fix (`createLogUpdate(boundStream)`): GREEN.
  Lines exceed 80 chars (log-update reads the renderer's 200-col view
  through the bound stream's `columns` getter).

Method: temporarily mocks `process.stdout.columns = undefined` and spies
on `process.stdout.write` to capture what log-update emits. Restores all
overrides in a finally block.
Repairs commit 06271dd which inadvertently rolled back the run-renderer.ts
fixes from 50facf0. Cause: `git checkout HEAD~1 -- file` (used to verify
the new invariant test goes RED on pre-fix code) staged the reversion;
the subsequent `cp` restored the working tree but not the index, so the
commit captured the index (pre-fix) state.

Restores:
1. log-update column-binding via `createLogUpdate(boundStream)` (Symptom A)
2. `clearInterval` moved before `logUpdateClear/Done` in `renderSummary`
   (Symptom B)

All 7 scrollback-harness tests pass with the restored fix. The two new
RED→GREEN invariant tests now correctly hold GREEN.
…tests

Addresses HIGH-severity findings from the four-reviewer gap analysis on PR
#654. Changes per finding:

1. **isTTY no longer hardcoded.** `boundStream.isTTY` was previously
   `true` unconditionally, which would cause log-update v7 to wrap every
   write in synchronized-output ANSI escapes (`ESC[?2026h` … `ESC[?2026l`)
   even when stdout was piped/redirected (CI logs, `> file`, `npx | tee`).
   Now derives from `process.stdout.isTTY` via a getter — matches the
   pre-#652 singleton behaviour exactly while preserving the column-binding
   fix.

2. **Symptom B comment rewritten.** The original claim — that a setInterval
   tick could fire between `logUpdateClear` and `clearInterval` —
   misrepresents JS semantics. Macrotasks cannot preempt synchronous code.
   The reorder is kept as structural cleanup (single-statement move,
   guards against future `redraw()` callers re-creating the live zone) but
   the comment now names #647's AC-3 grid-width fix (`-7` → `-9`) as the
   likely real Symptom B mitigation.

3. **Misleading scaffolding tests deleted.** Two of the three earlier
   Symptom A tests took the harness's `logUpdateInstance` constructor
   branch, NOT the `else` branch where the bound-stream fix lives — they
   were testing the harness, not the fix. The Symptom B visible-output
   test passed on both pre- and post-fix code. All three were noise that
   would have misled future maintainers about regression coverage. Replaced
   with a single hardened invariant per symptom (see below).

4. **Symptom A invariant hardened.** Now reads `_boundStream` (a newly
   exposed private field) directly and asserts:
   - `_boundStream !== null` (production path was taken)
   - `boundStream.columns === 200` (delegates to `getColumns()`, NOT
     log-update's 80-col fallback)
   - `boundStream.isTTY` correctly tracks `process.stdout.isTTY` (guards
     against the synchronized-output ANSI regression from finding #1)
   The earlier `longestVisible > 80` assertion was fragile (only 30-char
   margin to the frame cap; direct event-line writes could cause false
   GREEN). Replaced with direct property assertion.

5. **Symptom B invariant hardened.** Now adds:
   - Precondition `expect(r.liveTimer).not.toBeNull()` before
     `renderSummary` (proves the test isn't vacuous)
   - Assertion that `logUpdateClear` was actually called (proves the
     `clearInterval`-then-`clear` branch was taken, not a dispose
     shortcut that bypasses both)

Both invariants verified RED on the matching pre-fix code by reverting
each fix locally:
- Symptom A: setting `_boundStream = null` → "expected null not to be null"
- Symptom B: reverting `clearInterval` to after `clear/done` → "expected
  true to be false"

All 91 cli-ui tests pass on the post-fix code. Lint and build clean.
@admarble
admarble deleted the branch feature/647-fix-cli-624-s-duplicate-header-fix-doesn-t-catch-r May 16, 2026 04:38
@admarble admarble closed this May 16, 2026
@admarble

Copy link
Copy Markdown
Contributor Author

Closing — investigation results invalidated the premise

Four parallel adversarial reviewers and four parallel diagnostic investigators (all spawned post-merge of #647) collectively established that the column-mismatch hypothesis underlying this PR is wrong.

Summary of findings:

Investigation Verdict
log-update v7 internals Cannot produce mid-string char drops. Line-level diff with full ESC[2K erase per changed line. No partial-overwrite code path.
claude subprocess output trace No subprocess in non-verbose mode (the user's case). SDK runs in-process; output is captured. No stdout fd sharing.
Real-terminal reproduction Symptom not reproducible in any combination of column mismatch, SIGWINCH, interleaved writes, or long error strings. wrapAnsi bakes \n into the output string, so previousLineCount always matches the terminal's actual row count.
Byte-level forensics Identified a precise pattern (complete_line[0:8 bytes] + failed_line[col 9 onward]), but attributed it to a mechanism (cross-process TTY interleaving) that doesn't apply in non-verbose mode.

Implication: The column-binding fix in this PR is defensive consistency, not a Symptom A fix. The renderSummary reorder is structural cleanup. Both were honestly framed in the latest PR description, but the substance no longer justifies the change.

Investigation continues in a new issue: tracks the unexplained byte pattern, asks for production replay with SEQUANT_DEBUG_RENDERER=1, and lists the four ruled-out hypotheses so future investigation doesn't relitigate them.

Side find: batch-executor.ts lines 548, 813, 966 never pass the spinner argument, so renderer.pause() / renderer.resume() are dead code in production (affects --verbose mode output integrity). Filed separately.

Branch feature/652-fix-cli-renderer-bottom-output preserved for reference; not deleting in case parts of the bound-stream design get revived once the actual cause is known.

admarble added a commit that referenced this pull request Sep 9, 2026
…tests

Addresses HIGH-severity findings from the four-reviewer gap analysis on PR
#654. Changes per finding:

1. **isTTY no longer hardcoded.** `boundStream.isTTY` was previously
   `true` unconditionally, which would cause log-update v7 to wrap every
   write in synchronized-output ANSI escapes (`ESC[?2026h` … `ESC[?2026l`)
   even when stdout was piped/redirected (CI logs, `> file`, `npx | tee`).
   Now derives from `process.stdout.isTTY` via a getter — matches the
   pre-#652 singleton behaviour exactly while preserving the column-binding
   fix.

2. **Symptom B comment rewritten.** The original claim — that a setInterval
   tick could fire between `logUpdateClear` and `clearInterval` —
   misrepresents JS semantics. Macrotasks cannot preempt synchronous code.
   The reorder is kept as structural cleanup (single-statement move,
   guards against future `redraw()` callers re-creating the live zone) but
   the comment now names #647's AC-3 grid-width fix (`-7` → `-9`) as the
   likely real Symptom B mitigation.

3. **Misleading scaffolding tests deleted.** Two of the three earlier
   Symptom A tests took the harness's `logUpdateInstance` constructor
   branch, NOT the `else` branch where the bound-stream fix lives — they
   were testing the harness, not the fix. The Symptom B visible-output
   test passed on both pre- and post-fix code. All three were noise that
   would have misled future maintainers about regression coverage. Replaced
   with a single hardened invariant per symptom (see below).

4. **Symptom A invariant hardened.** Now reads `_boundStream` (a newly
   exposed private field) directly and asserts:
   - `_boundStream !== null` (production path was taken)
   - `boundStream.columns === 200` (delegates to `getColumns()`, NOT
     log-update's 80-col fallback)
   - `boundStream.isTTY` correctly tracks `process.stdout.isTTY` (guards
     against the synchronized-output ANSI regression from finding #1)
   The earlier `longestVisible > 80` assertion was fragile (only 30-char
   margin to the frame cap; direct event-line writes could cause false
   GREEN). Replaced with direct property assertion.

5. **Symptom B invariant hardened.** Now adds:
   - Precondition `expect(r.liveTimer).not.toBeNull()` before
     `renderSummary` (proves the test isn't vacuous)
   - Assertion that `logUpdateClear` was actually called (proves the
     `clearInterval`-then-`clear` branch was taken, not a dispose
     shortcut that bypasses both)

Both invariants verified RED on the matching pre-fix code by reverting
each fix locally:
- Symptom A: setting `_boundStream = null` → "expected null not to be null"
- Symptom B: reverting `clearInterval` to after `clear/done` → "expected
  true to be false"

All 91 cli-ui tests pass on the post-fix code. Lint and build clean.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant