Skip to content

fix(build): build xterm's source once per content, so parallel builds never read it half written - #2138

Merged
devswha merged 3 commits into
mainfrom
fix/demo-build-xterm-cache-race
Oct 28, 2026
Merged

devswha merged 3 commits into
mainfrom
fix/demo-build-xterm-cache-race

Conversation

@devswha

@devswha devswha commented Oct 28, 2026

Copy link
Copy Markdown
Owner

Change

Fixes #2021. buildXtermSource (scripts/build-xterm.ts, called by vite.config.ts on every config load) re-emitted xterm's patched source in place into node_modules/.cache/herdr-xterm on every build. Two builds at once in one checkout (the browser lane's parallel workers, 58 scripts that build the demo themselves) could then read a module while the other rewrote it and fail with MISSING_EXPORT.

Now the source is built into node_modules/.cache/herdr-xterm/<key>, where the key hashes TypeScript's version, the compiler options and every .ts file of xterm's src/ and typings/ (both patched). A finished directory is never written again:

  • a build whose key exists reuses it without emitting;
  • a new key is emitted into a private mkdtemp directory and renamed into place whole; a build that loses the rename uses the winner's;
  • an emit with any error diagnostic is not published (TypeScript reports a failed write, e.g. ENOSPC, only as a diagnostic with emitSkipped false);
  • on Windows, a rename a scanner (Defender, the indexer) briefly refuses is retried until a 10 s deadline.

Old key directories stay until node_modules is reinstalled; they are only disk.

Validation

  • scripts/build-xterm.test.ts (new, mkdtemp checkouts, never the repo's cache): a second build returns the same directory with its files unwritten (inode and mtime); changed source gets a new directory and leaves the old one as it was; a write error publishes nothing and the next build emits again. The first two fail on main (mtime rewritten; same directory for changed source), the third fails without the error-diagnostic guard.
  • Real surface: 3 rounds of 4 concurrent taskset -c 0,1 bun scripts/demo-build.ts <dir> in one checkout, first round on a cold cache: 12/12 exit 0, one cache entry.
  • bun run check fast: green (7875 pass). A first run failed only scripts/ci-browser.test.ts on two 5 s spawn timeouts at host load ~117; alternating 3 runs each, this branch passed 3/3 and main failed once, and that lane stubs the demo build.
  • Reviews: omo-native-code-reviewer PASS (its MEDIUM, the Windows rename retry, is fixed here); Codex Sol 6.1 Fast xhigh found a reproduced MEDIUM (failed writes published a broken cache), fixed in 3efdadf and re-reviewed PASS.
  • Server, shared and the remote bundle are untouched, so REMOTE_BUNDLE_VERSION does not change.

… never read it half written

Every build re-emitted xterm's source in place into node_modules/.cache/herdr-xterm, so a build running at the same time in the same checkout (the browser lane's parallel workers) could read a module while it was being rewritten and fail with MISSING_EXPORT. buildXtermSource now emits into a directory named after a hash of the patched source, TypeScript's version and the options, reuses a finished one without emitting, and emits a new one into a private directory renamed into place whole.

Fixes #2021
…uild on its typings too

Review follow-ups for #2021: Defender or the indexer can briefly refuse renaming a fresh build on Windows, so the move into the cache retries until a deadline; the patched typings the emit type-checks against are part of the key; the test copies xterm's package by value.
… not write

A failed write (ENOSPC) is only an emit diagnostic with emitSkipped false; the staged build was renamed into place and stayed cached with an empty module. Review follow-up for #2021 (Codex).
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between c5d9555 and 3efdadf.

Files selected for processing: 3
  • changelog.d/xterm-build-cache-race.md
  • scripts/build-xterm.test.ts
  • scripts/build-xterm.ts

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.

📝 Summary

Summary by CodeRabbit

  • Bug Fixes
    • Fixed intermittent build failures that could occur when multiple builds ran from the same checkout. Builds now reuse completed outputs and avoid interfering with one another, helping ensure the required xterm module is available. Failed or incomplete builds are not treated as successful, and transient file-move issues on Windows are retried.

Concurrent demo builds could read xterm files while another build rewrote the shared cache, causing a missing export. The build now stages output and publishes it to a cache directory keyed by compiler settings and source contents.

Changes: xterm build cache

Layer / File(s) Summary
Build and publish xterm cache
scripts/build-xterm.ts, scripts/build-xterm.test.ts, changelog.d/xterm-build-cache-race.md
buildXtermSource keys output by TypeScript version, compiler options, and xterm source and typings. It emits to a temporary directory and publishes by rename. Tests cover cache reuse, changed source, and write failure recovery. The changelog records the concurrent-build issue.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Minimal · up to 3efda

The inspected build paths use the new cache location correctly. No actionable issue remains before merge.

Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title clearly states the primary change: cache xterm source builds by content to prevent parallel builds from reading partially written output.
Description check Passed The description includes the required Change and Validation sections. It explains the race, the implementation, failure handling, Windows behavior, tests, concurrency results, and check results.
Linked Issues check Passed Issue #2021 requires safe concurrent builds in one checkout. buildXtermSource keys output by TypeScript inputs and patched xterm files, reuses completed directories, emits into a private staging dir…
Out of Scope Changes check Passed The changes are limited to the xterm build cache implementation, focused regression tests, and a changelog entry. Hashing inputs, failed-diagnostic handling, atomic publication, and Windows rename ret…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Linked Issues check

Explanation

Issue #2021 requires safe concurrent builds in one checkout. buildXtermSource keys output by TypeScript inputs and patched xterm files, reuses completed directories, emits into a private staging directory, and publishes with a directory rename. A losing concurrent publisher uses the existing output. The new tests cover reuse, changed input isolation, and failed-write cleanup. These changes prevent readers from observing an in-place rewrite.

Full details: Out of Scope Changes check

Explanation

The changes are limited to the xterm build cache implementation, focused regression tests, and a changelog entry. Hashing inputs, failed-diagnostic handling, atomic publication, and Windows rename retries directly support the concurrency fix. No unrelated product or server changes are present in the reviewed summary.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 2 functions across 2 files. (1 skipped: 1 unsupported.)

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@devswha

devswha commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

Merging 3efdadf: omo-native-code-reviewer and Codex both pass this head, and the required checks are green. CodeRabbit did not review this head. Eight concurrent builds, and four on a cold cache, produced identical, complete output. The emitted JS matches main byte for byte. Codex's two MEDIUMs need the source or xterm's package.json changed by hand between hashing and compiling. They go to a follow-up issue with omo's LOW notes.

@devswha
devswha merged commit c2be708 into main Oct 28, 2026
11 checks passed
@devswha
devswha deleted the fix/demo-build-xterm-cache-race branch October 28, 2026 02:53
devswha added a commit that referenced this pull request Oct 28, 2026
…ole Windows test results (#2242)

Closes #2148
Closes #2165
Closes #2104

Follow-ups from the #2138 review and two flaky Windows-native tests.
Build script and tests only: nothing the server or the client ships
changes.

## #2148: xterm build cache (`scripts/build-xterm.ts`)
- **Hash/compile race (Codex MEDIUM).** The key was made from the files
on disk, and TypeScript then read the files again. A source edited in
between was compiled and published under the old source's key, and
restoring the old source reused it. The build now gives TypeScript a
compiler host that serves the very bytes it hashed for everything inside
xterm's package, so what is published under a key is always what the key
names.
- **Resolution metadata (Codex MEDIUM).** xterm's `package.json` is now
part of the key: its `types` entry picks the typings `@xterm/xterm`
imports resolve to, so changing it alone emits again.
- **Symlinked checkouts.** The package is reached through its real path
and the compiler host keeps paths inside it as they are, so imports
never resolve out of the hashed copy to the disk (macOS's `tmpdir()`, a
symlinked `node_modules` or worktree).
- **Leftover staging.** Staging directories are named
`<key>.tmp-<pid>-XXXXXX`; a fresh emit removes those whose process no
longer runs (a build killed by SIGKILL, OOM or Ctrl-C) once they have
not changed for 10 minutes, so a build in another pid namespace that
only looks dead keeps its own. Before publishing, a build checks that
every file it emitted is still in its staging directory, and publishes
nothing otherwise.
- **0700 output.** The staging directory is `chmod 0755` before it is
renamed into place, so another user of the checkout can read the
published build.

## #2165: half-written result in `windows-native.test.ts`
The desktop child now writes its result under another name and renames
it into place, and the waiter (`watchJson`) treats a result that does
not parse yet as not there, looking again on the next change within the
same 15 s deadline.

## #2104: Restart Manager timeout
Every Windows-only case now carries an explicit 30 s budget instead of
bun's default 5 s. A Linux test parses the file with the TypeScript API
and fails if a Windows-only case is added without one.

## Tests
Each new test fails on the code before this PR and passes after it (`bun
test scripts/build-xterm.test.ts server/windows-native.test.ts`):

| Test | Before | After |
| --- | --- | --- |
| compiles the source it hashed, even when the file changes while
TypeScript reads | output contains the post-hash edit | pass |
| reads none of xterm's package from the disk while compiling, even
through a symlinked checkout | 95 reads from disk | pass |
| publishes nothing when an emitted module vanishes from the staging
directory before the rename | incomplete build published | pass |
| emits again when only the manifest's typings entry changes | same key
| pass |
| removes the staging directories killed builds left behind, not one a
build may still write | dead staging kept | pass |
| publishes a build other users of the checkout can read | mode 0700 |
pass |
| waits past a half-written result until the whole file is renamed into
place (#2165) | result settles on the half-written file (`SyntaxError:
JSON Parse error: Unexpected EOF`) | pass |
| gives every Windows-only case a budget sized for a busy hosted runner
(#2104) | Restart Manager case has no budget | pass |

For the "before" run the new tests ran on origin/main's
`build-xterm.ts`, with `completeJson` rethrowing parse errors as the old
watcher did and the Restart Manager case back on the default budget. The
Windows-only cases themselves run in CI's "Native Windows install" job.

## Review
Test and build-script changes only, so per the review policy this got
omo-native-code-reviewer only (no Codex). Verdict PASS, no
CRITICAL/HIGH. Its three MEDIUMs are fixed in the second commit, each
with a test that fails on the first commit:
- symlinked checkout let imports escape the hashed copy (reproduced: a
const-enum edit published under the old key);
- the #2165 test did not exercise the watcher (the old logic passed it);
- a build in another pid namespace looks dead, so its staging could be
removed mid-emit and a partial build published.

LOWs, not fixed and not filed (per the follow-up bar):
- the #2104 guard checks only the budgets' numbers and could live in
`server/conventions.test.ts`;
- the dead-pid fixture (`Bun.spawnSync`'s reaped pid) could in theory be
reused by another process.

Two other LOWs were cheap and are fixed: a result held for a moment by a
Windows scanner (EBUSY/EPERM) reads as not there yet, and staging
directories from before names carried a pid are cleared by age.
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.

Concurrent demo builds race on the shared xterm cache (MISSING_EXPORT)

1 participant