Skip to content

mac: a superseded display-candidate hold carries its work forward, so the v2 frame isn't evicted (#799, supersedes #803) - #808

Merged
d-q222 merged 2 commits into
mainfrom
fix/799-helper-race
Sep 17, 2026
Merged

d-q222 merged 2 commits into
mainfrom
fix/799-helper-race

Conversation

@d-q222

@d-q222 d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Fixes #799. Supersedes #803: this branch contains #803's commit bce66857 (a real helper timeout fails instead of skipping), plus the product fix that makes that change safe to land.

Root cause

It wasn't a test-harness race. It's a real app bug.

  • The hold: after each preview, the app holds its completion-list fetch for up to 80 ms so the helper can emit the optional v2 frame first.
  • The bug: when a newer preview arrived during an older hold, displayCandidatesAfterSibling ran the older hold's work immediately.
  • The eviction: that fetch's required reply then reached the controller inside the newer revision's window. It evicted that revision's queued optional v2 frame, which display-forwarding.md documents as expected.
  • The evidence: FLASHTEX_CONTROLLER_DIAGNOSTIC_TIMINGS=1 showed a 35,697-byte frame admitted and then evicted_by_required 0.1 ms later by a 757-byte reply. There were no orphaned helpers between tests.

User impact: when two previews land within 80 ms (a startup preview followed by ⌘B, or opening includes followed by a recompile), the newer revision stays on the plain preview. It has no v2 navigation or exact click-to-source until the next compile.

Fix

A superseded hold moves its work, in order, into the new hold. The work runs when that hold ends (the v2 frame arrives or the timeout passes) and is still never dropped.

DisplayCandidateTests.testHeldWorkRunsOnCandidateTimeoutOrSupersessionNeverDropped now asserts that carried work doesn't run early and still runs after the timeout.

Tests

All runs were niced and sequential, with fresh release helpers.

Suite Result
NavigationMultiFileV2Tests, clusters test forced first (the failing order) Before the fix: failed 9 of 21 runs. After: 10/10 passed.
NavigationMultiFileV2Tests, default order 5 runs, 10/10 cases passed
DisplayCandidateTests 12/12
DocumentFilesTests 13/13

Not covered: the separate DocumentFilesTests:437 CI flake (a scripted fake project-files helper with a 0.4 s timeout). It's unrelated to this root cause and is tracked with the #800 timing work.

🤖 Generated with Claude Code

d-q222 and others added 2 commits September 17, 2026 08:26
…799)

Fixes the primary, unambiguous part of #799: a frame-wait timeout on a
helper `requireHelperAndRender` already confirmed present threw `XCTSkip`,
so `NavigationMultiFileV2Tests`'s second case could time out and be marked
skipped instead of failed — exactly the "CI run can show green without
running it" impact the issue describes. `waitUntil`'s timeout branch now
calls `XCTFail` with the same diagnostic state string instead.

Also added `waitForControllerExit`, called from each test's teardown right
after `detachController()` (with the `PreviewControllerClient` captured
before that call, since it nils `model.controller`): blocks until the
helper's process has actually exited (or a 5s timeout, itself an `XCTFail`)
rather than assuming `detachController()`'s SIGTERM-and-return is enough.
`PreviewControllerClient.terminate()` never calls `waitUntilExit`, so a
back-to-back test could previously start a new helper while the old one
was still shutting down.

Honest status on the underlying race, since I could not fully root-cause it
this session: with fresh, matching `flashtex-preview-controller`/
`flashtex-render` binaries and the machine otherwise idle, the second test
still failed in 3 of 5 runs even with `waitForControllerExit` in place —
this is NOT a rare flake, it reproduces roughly 60-100% of the time in a
clean back-to-back run, and in one run manifested as a *different* failure
shape (`XCTUnwrap failed: expected non-nil value of type "ClusterHit"`
rather than the `waitUntil` timeout), suggesting more than one thing is
wrong, not only teardown timing. `waitForControllerExit`'s own polling
never observed a still-running old process before the new attach in the
runs I captured, which argues against "the literal parent process outlives
detach" as the whole story. My best remaining lead, not yet checked:
`flashtex-preview-controller`'s own producer-process management (I found
where its `Command` is *built*, `producer_command`/`producer_command_with_
limit` in `crates/preview-controller/src/main.rs`, but not where it is
*spawned*+reaped — that lives in a worker abstraction I did not have time
to trace this session) may not be killing/reaping its own child
`flashtex-render` process on shutdown, leaving an orphan that the next
test's fresh helper contends with.

What I verified today, for whoever continues:
- `swift build --target FlashTeXMacTests`: clean.
- The `XCTFail` path fires correctly and reports the exact state string
  (confirmed via direct runs with both stale and fresh binaries).
- Reproduction rate with fresh binaries, machine otherwise idle: 3/5 and
  1/1 failed runs across two back-to-back sessions today (this PR's fix in
  place); 1/2 runs passed cleanly. Two distinct failure shapes observed.
- (Unrelated finding from today, already reported and resolved separately
  on issue #2: this Mac was under extreme, unrelated CPU contention for
  much of the day from 8 abandoned infinite busy-loop processes left by a
  different, already-fixed issue's repro script — killed before this
  investigation, not the cause of this race.)

Implementation-Agent: daniel-muse-lead (Claude Sonnet)
Commit-Executor: daniel-muse-lead (Claude Sonnet)
…tead of running it early (#799)

When a newer preview arrived during an earlier preview's 80 ms display-candidate
hold, displayCandidatesAfterSibling ran the older hold's work straight away. That
work was the completion fetch. Its required reply then reached the controller
inside the newer revision's window and evicted that revision's optional v2 frame,
which is documented as dropped when a required reply arrives. The newer revision
stayed on the plain preview, with no v2 navigation or exact click-to-source,
until the next compile.

A superseded hold now moves its work, in order, into the new hold, and it runs
when that hold ends (the v2 frame arrives or the timeout passes). The work is still
never dropped.

Diagnosis: FLASHTEX_CONTROLLER_DIAGNOSTIC_TIMINGS=1 showed the 35,697-byte frame
admitted to the optional slot and then evicted_by_required 0.1 ms later by a
757-byte reply. There were no orphaned helpers between tests.

Tests:
- NavigationMultiFileV2Tests run clusters-first failed 9 of 21 runs before the
  fix and passed 10/10 after.
- Default order passed 5/5.
- DisplayCandidateTests 12/12.
- DocumentFilesTests 13/13.

Implementation-Agent: Claude Opus 5 (daniel-parent subagent)
Commit-Executor: daniel-parent (Claude Opus 5)
Co-authored-by: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz
@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Commander (daniel-parent): independent Opus review of 2e5ac13f, APPROVE. No material findings. Correction to the PR body: DisplayCandidateTests locally ran 12 with 6 skipped (the helper paths weren't set). The follow-ups (waitUntil should throw, the 5 s helper-exit bound) are tracked below. Merging after the filtered tests run on the merged tree.

PR #808 review (head 2e5ac13, reviewer: opus, read-only)

Scope: git diff origin/main...HEAD. That covers ShellModel+DisplayCandidates.swift, DisplayCandidateTests.swift, and NavigationMultiFileV2Tests.swift (which includes #803's commit bce6685). I also read the surrounding hold, release and invalidate code and both call sites in ShellModel+Controller.swift (lines 503 and 551).

MATERIAL findings

None.

Adversarial checks (why nothing is material)

  • Exactly once, in order. All three exits clear deferred before running anything. releaseDeferred (.candidate/.timeout/.invalidated) and supersedeDeferred both set deferred = nil and cancel the timer first. Carried work is placed ahead of the new work (carried + [work]), so the original order holds across any chain of supersessions. The old hold's DispatchWorkItem is cancelled, and its closure also checks deferred?.requestID == requestID, so a late old timer can't fire a second release. displayCandidatesReleaseDeferred(for:) checks the request id both before and inside its main.async, so a late sibling of the older request doesn't release the newer hold. Work is dropped nowhere:
    • Candidate arrival, timeout and invalidation all run every carried closure.
    • Invalidation covers detachController, helper exit and reattach. Each piece of work then checks its own controller: the completion closure checks controller === controller && isRunning, and controllerReleaseInFlight finds a fresh ControllerState on detach.
    • If ShellModel is deallocated, the [weak self] timer is a no-op. That is the same as before.
  • Starvation. There is no hard cap. Each supersession restarts the 80 ms window, so in theory carried work waits as long as newer previews keep arriving less than 80 ms apart and none of their siblings arrives. In practice it is bounded:
    1. With the default hold (FLASHTEX_DISPLAY_CANDIDATES_HOLD≠0), the in-flight edit's release is itself held. The next edit-driven preview can't exist until this hold releases, so typing can't build a chain.
    2. A chain needs non-edit previews (⌘B, recompiles triggered by includes) arriving every <80 ms, each with a missing sibling.
    3. Any sibling that does arrive releases the whole chain.
    • Typing cost: at most one extra ≤80 ms before the edit release, and only in the rare supersession case.
    • Completion cost: the newest fetch runs ≤80 ms after its own preview (or at its candidate). That is the same bound as an un-superseded hold.
  • Actor isolation and reentrancy. Everything runs on main: the two call sites, the DispatchQueue.main timer and the main-async candidate release. supersedeDeferred takes the work without running it, which removes the only reentrant step the old .superseded path had. In releaseDeferred, deferred is nil before the closures run. A closure that started a new hold would get a fresh one, and the remaining old closures would still run. None of the current closures can do that synchronously, because previews arrive from helper I/O.
  • Tests. testHeldWorkRunsOnCandidateTimeoutOrSupersessionNeverDropped does exercise supersession at the model level:
    • pc-3 holds 3a and 3b, then pc-4 starts.
    • It asserts nothing ran, requestID == "pc-4", works.count == 3 and a supersession count of 1.
    • After the timeout it asserts the order ["3a","3b","4"] and a timeout count of exactly 1. That count also proves pc-3's cancelled timer never fired.
    • Before this PR, the held == [] assertion would fail, so the test really guards the fix. The helper-backed ordering regression is covered only by the NavigationMultiFileV2 runs the PR reports; I did not rerun them, as instructed.

Non-blocking notes

  1. Test gaps (DisplayCandidateTests.swift ~183–199). Nothing tests carried work released by candidate arrival (handleDisplayCandidate → .candidate). Nothing tests carried work released by invalidation: the pc-5 invalidation step holds only its own work. Either is a two-line addition, e.g. supersede pc-5 with pc-6 and then call invalidate(), or feed a pc-4 candidate.
  2. Redundant stale completion fetch (ShellModel+Controller.swift:551, Completion.swift:1462). The carried fetch for the older sourceVersions now runs right before the newer one. CompletionFetcher.request replaces query, so the older replies are discarded, and the older fetch only adds N+1 wasted required requests. Before the PR it also ran, just earlier. A later option: tag completion work so a newer fetch replaces a carried one. Holds carrying controllerReleaseInFlight must stay intact.
  3. Pre-existing ordering gap, not introduced here. A new call that fails the guard (not negotiated, or the newer preview's layoutCapabilities lacks display-list-v2) runs work() inline while an older hold is still pending. A newer completion fetch can then be followed by an older one, whose query wins, leaving the vocabulary one revision stale until the next preview. Suggested fix: run supersedeDeferred() work before an inline work(), or append to the existing hold. This PR doesn't make it worse.
  4. mac tests: a real helper timeout fails instead of silently skipping #803, waitUntil (NavigationMultiFileV2Tests.swift ~69–76). It now records XCTFail and then returns normally. The callers keep going:
    • currentFrame throws XCTSkip("no frame"), or proceeds with a frame that isn't current and piles up further assertion failures.
    • The run is still red, because the failure count is nonzero, so the intent is met.
    • The cleaner fix is to throw a plain Error (or XCTFail and then throw) so the test stops at the real cause.
  5. mac tests: a real helper timeout fails instead of silently skipping #803, CI red risk. CI's build-helpers.sh exports FLASHTEX_PREVIEW_CONTROLLER and FLASHTEX_RENDER, so these tests really run in CI. A slow runner that needs more than 40 s for negotiation or first frame on a two-file project will now go red instead of skipped. Given the product fix, that deadline is generous, and a skip there would hide real breakage (mac tests: NavigationMultiFileV2Tests second case times out waiting for a frame and is SKIPPED when run after the first (CI can pass green without running it) #799), so the change is acceptable. Two residual risks:
    • waitForControllerExit XCTFails if the helper hasn't exited within 5 s of SIGTERM. That would fail CI for a slow shutdown unrelated to this feature.
    • It busy-waits with Thread.sleep on the MainActor inside defer. That is fine only because Process.isRunning is updated off-main.
    • Consider a longer exit bound (e.g. 15 s), or a log line instead of XCTFail.
  6. PR body. It reports DisplayCandidateTests as 12/12. Without the helper env vars, 6 of the 12 skip (see below). Worth saying the helper-backed six ran only with helpers present.
  7. Comment accuracy. The doc comment on displayCandidatesAfterSibling matches the new behaviour. deferredReleasedBySupersession now counts carries, not releases. The name is slightly misleading but harmless.

Tests run

  • I waited until no other swift-test/swift-build/xctest process was running (another agent's run was active at first).
  • cd ~/flashtex-wt/review-808/apps/mac && nice -n 15 swift build --build-tests -j 3 → Build complete (60.5 s).
  • nice -n 15 swift test --skip-build --filter 'DisplayCandidateTests' → 12 executed, 6 skipped (the helper-backed cases; no FLASHTEX_PREVIEW_CONTROLLER/FLASHTEX_RENDER set), 0 failures. testHeldWorkRunsOnCandidateTimeoutOrSupersessionNeverDropped passed (0.142 s).
  • NavigationMultiFileV2 stress loop not rerun, per instructions.

VERDICT: APPROVE

@d-q222
d-q222 merged commit 8777a17 into main Sep 17, 2026
20 of 21 checks passed
ItsAkilesh pushed a commit to ItsAkilesh/flashtex that referenced this pull request Sep 18, 2026
Non-blocking follow-ups from the flash-tex#808 review: waitUntil now throws after
recording its XCTFail so a timeout stops the test instead of cascading;
the post-detach helper-exit bound is 20s (was 5s) and logs via
XCTContext instead of failing when a slow runner exceeds it, force-
killing the helper so it's never left running; DisplayCandidateTests
gains model-level cases for carried hold work released by a v2 frame
arriving and by invalidation (only the timeout path was covered).

Implementation-Agent: Claude Sonnet 5 (daniel-parent subagent)
Commit-Executor: daniel-parent subagent (Claude Sonnet 5)
Co-authored-by: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant