Skip to content

Oj store: shared build cache across worktrees, with a wire - #503

Draft
raphamorim wants to merge 3 commits into
mainfrom
rapha/pulp
Draft

raphamorim wants to merge 3 commits into
mainfrom
rapha/pulp

Conversation

@raphamorim

@raphamorim raphamorim commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

The oj store: a shared per-user content store so a second worktree of an app (or a second app on the same deps, or a fresh sandbox) starts warm. Rebased onto main on 2026-12-02 (the October branch was 388 commits behind, with 29 conflicting files), as one commit.

What's in it:

  • The store is off unless OJ_STORE_DIR is set. oj dev --store[=DIR] is the one switch: it sets OJ_STORE_DIR for the server and every child (to DIR, else /oj/store, else ~/.cache/oj/store) and turns the persistent module cache on. A plain oj dev writes nothing outside the tree. There is no --enable-cache or --no-cache any more (Remove the on-disk module cache and its --enable-cache / --no-cache flags #669 removed them).
  • oj store serve: an HTTP substituter, with OJ_STORE_REMOTE read-through and OJ_STORE_PUSH.
  • Worktree-independent keys and artifacts for the module cache, the V8 code cache, Start codegen and the Start client bundle.
  • Constructive traces: plugin side-file reads, recorded through node:fs interposition plus TracingFs under the engine's fs ops, are re-verified on warm hits.
  • Content-derived dep URL versions through a write-once ledger, so worktrees and restarts over the same bytes mint the same URLs.

What the rebase changed, against the October branch:

  • Main removed the persistent module cache in Remove the on-disk module cache and its --enable-cache / --no-cache flags #669 (nothing turned it on). The store is the reason to have it, so it is back, under --store only, built on main's pipeline: the on-disk name of an entry is the memory key (oj_cache::ModuleKey) under the process salt (PersistentCache::disk_key), a hit is served only under the HMR import stamps it baked in (Dev server cache: a cached compile serves only under the import stamps it bakes in #661's rule, now on the disk path too), a stamped compile is never persisted (a later session's stamps start over, so it could never hit), and a sheet that inlined an asset is never persisted either. The moduleParsed replay and the plugin-virtual re-transform check came back with it.
  • A read from the shared directory refuses an entry that still names a checkout, whatever wrote it (a copied store, another oj), and removes it. A shared directory that cannot be written keeps entries in the app's own cache instead of dropping them.
  • The dep ledger records the hash of the bundled file's bytes. Main's Rust prebundler reports Vite's fileHash (the entry's name and imports, never its code), which the October ledger took for a content hash: an edited dependency would have kept its URL.
  • A root never replaces a stored generation that another root's fresh pin names (same sources, other chunks: a nondeterministic plugin, another machine); it serves its own build dir and the next boot restores the stored one. Replacing it would have swept the chunks from under the other root's running server.
  • The Start bundle store is main's rewritten one (as-built persists, restored inputs, the route-tree and config keys of Start client bundle cache keys on the route trees #629/Config extraction cache keys on the env vars the config read #632) with the sharing layered on: closure ids and the inputs outside the closure (keyed_by_files) are root-relative, generations and blobs live in the shared dir with per-root current/memo and pins, a cold worktree probes recent generations. The October branch's own config salt is gone, since main already keys the bundle by the config and its imports. A generation's StyleX rules and its plugin-served-stylesheet mark are attachments, so a worktree that restores it has them.
  • Config-file dependencies are recorded per config file (config_dependencies_of) in place of the process-wide OnceLock, which main's static-config path and the Start bundler's cache key also use now.
  • Start dev asset URLs go through main's svg inlining and start_dev_style_url, under the root-relative /@oj-start/fs/@ws/<rel> form.
  • The V8 code cache keeps main's held-write batching and consume-only mode with the root-relative keys.
  • The --config file is on the server state, so the watcher reads that config's dependencies.

From the second review round (findings of the review pass, each with a test):

  • A side file a plugin looked for and did not find gets a trace row too (no digest), so creating it later is a miss instead of a warm hit on the fallback.
  • Glob trace rows list files with the expansion's own matcher (globset, picomatch's dialect), not the glob crate's: a brace pattern used to list nothing and keep a constant digest.
  • The module-cache salt hashes every tsconfig*.json at the root and the config's named tsconfig by content, not tsconfig.json alone (Vite's template keeps paths in tsconfig.app.json).
  • A plugin that collects state from every transform (UnoCSS, WindiCSS, detected by name) keeps app modules out of the persistent cache for the session; dependencies still serve from it. Other collectors are a known limit of a transform cache, as they are of any.
  • A file outside the root but in the workspace is named by its /@fs/@mono/<rel> url in its debug info; an entry whose code or map still names the checkout stays in the app's own cache.
  • The wire's write-once links a per-request temp file into place, so racing pushers of one key cannot mix bodies; its body limit is the declared 64 MB, not axum's 2 MiB default.
  • The remote read-through has a 2 s connect and 5 s fetch timeout and gives up on a substituter after three failures in a row.
  • The store is off unless OJ_STORE_DIR is set; --store sets it. The unused OJ_DEBUG_SALT knob is gone.

Tests added for the parts that have to hold under abuse, beyond the October branch's:

  • oj_cache: racing writers (two worktrees' caches, many threads) on one key leave one whole entry and no temp file while readers never see torn bytes; a torn entry is removed and misses; a pinned entry planted in the shared dir is refused on read; relocation round-trips 500 generated path mixes and admits only path-free entries.
  • Start bundle store: two worktrees persisting one closure at once commit one whole generation with every blob; a root restoring in a loop never loses its generation or blobs to another root's eviction (pins).
  • Dep ledger: 32 racing records of one URL pick one hash for every process, no temp file left.
  • Dev server (tests/dev/store.rs): garbage, a torn file and a checkout-pinned entry under a live key are recompiled and replaced; a read-only store still serves and gets nothing; a store deleted while serving is recreated on the next write; two servers on one store serve identical bytes under parallel load and write no duplicate; a tsconfig edit between sessions is a miss. hmr_stamp_persistent and warm_transform_virtual (Remove the on-disk module cache and its --enable-cache / --no-cache flags #669 removed them with the cache) are back under --store.
  • e2e store-concurrent.mjs: two oj dev --store processes on one empty store, hammered in parallel; one killed mid-burst; a third boots over the same store; every entry whole, no temp files, identical bytes throughout.

Checks: cargo fmt --check, clippy on the touched crates, oj_cache/oj_js/oj_stylex/oj_compiler tests, oj_server lib tests, the oj bin tests (the preview-driven build tests need Chrome and do not run on the box this was done on), the store dev tests and the five store e2e scripts.

From the third review round (each with a test):

  • An oj.plugins.mjs (run in a vite config's place) is in the module-cache salt by content: an edit to it between sessions was a hit on the old plugin's output.
  • A persistent hit whose import names a file with no file there now is a miss whatever the plugin chain: a file moved on a branch switch (./util to util/index.ts, the importer untouched) was served as a hit whose import 404d. The check used to run only with a transform plugin active.
  • The PostCSS config a plain stylesheet compiles through and .browserslistrc are in the salt: a stylesheet entry persisted across a PostCSS config edit.
  • A side file written while the transform that read it ran (its mtime at or after the compile's start) keeps the entry in memory: it was persisted with the new file's digest next to output built from the old content.
  • The V8 code cache keys an app's own modules with its package name: two apps on one store at the same relative path evicted each other's bytecode on every boot. An edit still overwrites in place, and a dependency's file is one entry under any app.
  • Glob trace rows are listed on the compile path only: every request for a globbing module re-expanded its patterns, memory hits included.
  • The writer's checkout check matches a directory as a path (with its separator) and never a directory with no name: a short root matched route strings and a workspace of / kept every entry local.
  • The cold worktree's Start-bundle probe tries only generations under its own store salt (recorded in the manifest), so another app's recent generations no longer crowd its candidates.
  • Docs: --store help, the knob doc and the changelog name $XDG_CACHE_HOME/oj/store again; the store-flag e2e message interpolates its count.

Tests added for hashing and deterministic output:

  • tests/dev/determinism.rs: a matrix of module kinds (TypeScript under tsconfig semantics, TSX with a pre-bundled runtime, a CSS module, JSON, assets by import and import.meta.url, ?raw/?url, an inlined svg, env, a hot module, a dynamic import and a glob, a worker) served in a second checkout byte for byte from the first's entries, sourcemaps decoded and checked for served paths, every entry admissible, the second checkout writing nothing; the same bytes a server without the store compiles and a second session's hits; an .env edit and a --mode each compiling their own entry; an import from outside the root and workspace served under /@fs/<abs> and never shared.
  • oj_cache: disk keys over a corpus of near inputs (sources a byte apart, prefix urls, modes shifted across the field boundary) are distinct digests and agree between caches of one salt; rel_key follows components, not string prefixes.
  • oj_server salt: every resolver setting is its own field (extensions against mainFields, ab|c against a|bc); tsconfig files by name whatever the listing order, nested ones excluded unless named; the plugin file, PostCSS config, browserslist and config imports by content, the same in a twin checkout; names_checkout on paths, route strings and /.
  • Start bundle store: keyed_by_files tells missing from empty and keeps file boundaries; the cold probe skips other salts' generations and still restores its own.
  • V8 code cache: two apps' own modules coexist; a dependency overwrites in place.

From the fourth review round (three reviewers: cache semantics; concurrency, security and operations; and a research pass on the idea against prior art), each fix with a test:

  • Stale hit, reproduced: a stylesheet's @imported files were graph imports but not trace rows, so an edit to the imported file between sessions served the sheet with the old file inlined. CSS deps (imports, Sass partials, PostCSS dependencies) are trace rows now.
  • The default path did store work without --store: the dependency ledger was opened and every pre-bundled file hashed on each commit; the engine's fs tracing opened a window per transform and the pipeline digested every traced read; the module salt (lockfile, every tsconfig, the config graph) and the cache writer thread ran on every boot. All of it is gated on the store now; a read in the engine costs one atomic load when it is off.
  • Keys: the tool build (version plus a source digest, so two builds of one version never share), the root's place in its workspace, linked packages' manifests and entry files, patch files by content (not the directory's mtime). An entry whose /@fs/@mono/<rel> import has no file in the reader's workspace is a miss.
  • Tracing: directory listings, existence checks, reads by file URL, Buffer or descriptor, and relative paths are rows. A whole-second mtime within two seconds before a compile counts as racy; a stamp with nanoseconds compares exactly (a fresh checkout persists from its first boot).
  • Trust and growth: the store directory must be owned by the user and not writable by others (else refused, one stderr line, the app's own cache is used); it is created 0700; temp files are exclusive with a random suffix; the modules directory has a 2 GiB budget and a stale-temp sweep; the shared bytecode directory a 1 GiB budget (it was 128 MiB per app, so each boot evicted the rest) and a V8-flags digest in its name; Start pins are per process (two sandboxes at the same path no longer share one pin) and the generation window is per app and config.
  • The wire: constant-time token compare; server-side admission (relocatable module JSON only, else 422); a byte quota (--max-bytes, 507); DELETE purge under the write token; streaming handlers off the runtime; oj store serve defaults to the user's store directory. The client's breaker counts slow answers (over 500 ms) as failures and probes again after 30 s; pushes are bounded (256 entries or 64 MiB) and stop while tripped; bodies are capped; stamped keys never ask the remote. OJ_STORE_PUSH is documented as sending sourcesContent.
  • --store is the one switch, as the docs said: oj dev without it now clears an inherited OJ_STORE_DIR for itself and its children (the variable alone used to share the Start bundle, codegen and bytecode while the module cache stayed off); --store with no resolvable dir exits with an error.

Measured on this branch's release binary (56-core box, synthetic 1,000-component React app, medians of three): with no plugin host, a crawl of 1,001 modules takes about 330 ms whether the store is off, cold, warm in the same root or warm from another worktree; an entry hit costs about what an oxc compile costs. With a hosted plugin, a fresh worktree boots to the port in 0.52 s with the store against 0.73 s without (the plugin host's bytecode), and the crawl differs by about 50 ms. The TanStack Start fixture boots to the port in 1.2 s with the store in a fresh worktree against 1.6 s without, first GET 1.55 s against 2.3 s. No difference between this branch with the store off and main.

Not changed, design decisions for the reviewer: entries are keyed under one salt that includes the lockfile and package.json, dependency modules too, so sharing across apps is limited to template-identical ones; the dependency prebundle itself is not in the store (only its URL ledger); wire entries are not signed (a bearer token is the boundary). The research notes with sources are kept outside the repo.

From the fifth round (a second double review of the round-four result, and a second research pass that measured the binary), each with a test:

  • The dependency ledger's epoch, a per-store nonce, reached every module key through the dep URL version, so two sandboxes with their own stores shared no module key at all (0 of 1,001 measured) and a substituter could never hit for modules. With a ledger, versions now come from the inputs alone (the pre-bundle hash and the dependency names: Vite's own committed browserHash scheme), so two stores that bundled one plan mint the same URLs and share the modules compiled against them, from a checkout's first boot on; the ledger's byte records still re-mint and reload when other bytes land under a recorded URL. (A first attempt derived the version from the bundled bytes instead; that made a cold boot's version provisional until the bundle finished, so its compiles were keyed under a version no later session restored. The store dev tests caught it as a doubled entry count.)
  • Trace rows: the host's exact per-hook account is the trace, plus what the engine's shared window saw that no hook in flight read through the host (each reply lists the reads made through the patched node:fs while it ran, and those are dropped from its window share). A file-reading plugin no longer makes a warm boot cost 2.8x the compile's CPU through cross-charged rows, and an entry over 256 rows stays in memory. Sass @use and CSS @import searches record the candidates they did not find, so a partial added later that shadows the hit is a miss (reproduced as a stale hit). PostCSS plugin reads are traced through the CSS engine's own window and a declared dir-dependency stays a directory row.
  • The racy-mtime rule counts a stamp within 20 ms before the compile's start (the kernel's file clock lags the wall clock by up to a tick). A module hard-invalidated by an edit this session is not persisted under its session-only key. The tool build id reaches Start bundles, codegen, the ledger and the pre-seed stamp, and covers embedded assets and the bundler fork. Packages linked above the app are salted. oj build, preview, lint and typecheck clear an inherited OJ_STORE_DIR too.
  • The substituter probe is a lease that clears itself if the request is dropped mid-flight and expires after the fetch timeout (it could stick the breaker open for the session); at most 16 fetches are in flight. The wire sweeps crashed PUTs' temp files, caps the missing-digest query at 4,096, and every remaining temp file (wire, ledger, touch files) is exclusive. Start bundle pins name the boot and the process, age out after an hour, are refreshed every ten minutes and ignored once the process is gone; the pins directory is read once per persist.

The second research pass confirms the first's direction with measurements: for plain TSX a hit saves about 0.1 ms CPU per module against a 0.3 ms compile and no wall time; the plugin host's bytecode and host transforms are what pay; the memory footprint is the consistent win (66 vs 76 MB plain, 180 vs 270 MB hosted). It also demonstrated that an entry edited on a substituter's disk reaches the browser: wire entries are unsigned, by decision, and that decision stands with this PR; a substituter must be as trusted as the store directory. The remaining design items are unchanged: one salt for app and dependency entries (.env defines included), the dependency prebundle outside the store.

CI note: the unit-tests job has failed on each of this branch's runs on a different test (a dependency reload test, a racing-persist test, the config-evaluation crash check whose SIGABRT child waits on a core dump), while every other job passes; the local full dev suite passes apart from the tests that need node or a browser without a favicon.

@raphamorim
raphamorim force-pushed the rapha/pulp branch 4 times, most recently from e11f245 to 5c3c679 Compare October 23, 2026 22:39
@raphamorim
raphamorim force-pushed the rapha/pulp branch 3 times, most recently from 1ec8dca to 12eabcb Compare December 3, 2026 09:53
A shared per-user content store (`$OJ_STORE_DIR`, which `oj dev --store` sets
to a DIR or the user's cache dir; off otherwise) for the cache entries whose
keys and artifacts are worktree-independent, so a second worktree of an app, a second app on the same
dependencies or a fresh sandbox starts warm: the persistent module cache, back
under `oj dev --store` after #669 removed it with nothing to turn it on, the V8
code cache, Start codegen and the Start client bundle. `oj store serve` is an
HTTP substituter dev servers read through and push to.

Entries are path-free: the compiler names an in-root module by its served path,
metadata and `?importer=` params encode root- or workspace-relative, files
outside the root but in the workspace serve at `/@fs/@mono/<rel>`, and Start's
dev asset URLs are `/@oj-start/fs/@ws/<rel>`. A module's key covers the
dependency epoch, the config graph, tsconfig, the resolver settings, the
defines, the JSX runtime and the asset URL settings. A cached module records
the side files a plugin read (node:fs interposition and a TracingFs under the
engine's fs ops) and its `import.meta.glob` listings, re-verified on a hit. An
entry is served only under the HMR import stamps it baked in; a stamped
compile is never persisted, nor is an app module where a plugin collects
state from transforms (UnoCSS, by name). A read from the shared directory
refuses an entry that still names a checkout; a file outside the root but in
the workspace is named by its `/@fs/@mono/<rel>` url in its debug info. The
wire's write-once links a per-request temp file into place, and a substituter
that does not answer is given up on for the session.

Dep URL versions are content-derived through a write-once ledger salted with
its epoch, so worktrees and restarts over the same bytes mint the same URLs,
and other bytes under a served URL move every URL and reload.

The Start bundle store keeps generations and blobs in the shared directory
with per-root pointers and pins, keys closures and the inputs outside them
root-relative, probes recent generations for a cold worktree, and carries a
generation's StyleX rules and generated-sheet mark as attachments.

Tests cover the store under abuse: racing writers of one key, torn and
poisoned entries, racing bundle persists and a restore against another root's
eviction, racing ledger records, a read-only or deleted store under a live
server, two servers on one store, a config edit between sessions, and an e2e
with two `oj dev --store` processes where one is killed mid-burst.
…ing of the store's work without it, a trust boundary and budgets

A stylesheet's @imported files were graph imports and not trace rows, so
an edit to one between sessions served the sheet with the old file
inlined; they are rows now, with Sass partials and PostCSS deps. The
directories a plugin listed, its existence checks, reads by URL, Buffer
or descriptor, and relative paths are rows too, and a `/@fs/@mono/`
import must name a file in the reader's workspace.

Without --store a server did the store's work anyway: the dep ledger
hashed every bundled file on each commit, the engine traced every read,
the pipeline digested every row, the salt read the config graph and the
writer thread ran. All of it is behind the flag now, and `oj dev` without
it clears an inherited OJ_STORE_DIR for itself and its children.

The key covers the tool build (version plus a source digest), the root's
place in its workspace, linked packages by content and patch files by
content. A whole-second mtime within two seconds before a compile counts
as racy; a stamp with nanoseconds compares exactly.

The store directory must be the user's own and not writable by others;
temp files are exclusive with a random suffix; the modules directory has
a 2 GiB budget and a stale-temp sweep, the shared bytecode directory a
1 GiB one and the V8 flags in its name; Start pins name the process and
the generation window is per app and config. The wire compares tokens
in constant time, admits only servable entries, keeps a quota, purges on
DELETE, streams off the runtime; its client trips on slow answers,
probes after a cooldown, bounds its push queue and never asks for a
stamped key.
…e build id everywhere it keys

The dependency ledger's epoch, a nonce minted per store, reached every
module key through the dependency URL version, so two stores never
shared a module entry and a substituter could never answer for one.
With a ledger a version now comes from the pre-bundle hash and the
dependency names alone, as Vite's committed browserHash, so two stores
that bundle one plan mint one URL from the first boot on. The ledger
still records what each URL served, and other bytes under a recorded
URL re-mint a version from the bytes and reload. A first attempt
derived every version from the bundled bytes; that left a cold boot's
compiles under a version no later session computed.

The trace is the host's own per-hook account, plus what the engine's
shared window saw that no hook in flight read through the host: each
reply lists the reads it made through the patched node:fs, and those
leave its window share. A file-reading plugin no longer cross-charges
its reads to every module compiled while it ran. An entry over 256 rows
stays in memory. Sass @use and CSS @import searches record the
candidates they missed, so a partial or sheet added later that shadows
the hit is a miss; PostCSS plugin reads are traced through the CSS
engine's own window and a declared dir-dependency stays a directory row.

A stamp within 20 ms before the compile's start counts as racy. A module
hard-invalidated by an edit this session compiles under a key with the
invalidation counter and is not persisted. The tool build id reaches
Start bundles, codegen, the ledger and the pre-seed stamp, and covers
the embedded assets and the bundler fork; packages linked above the app
are in the salt; build, preview, lint and typecheck clear an inherited
OJ_STORE_DIR.

The substituter probe is a lease that clears itself when its request is
dropped and expires after the fetch timeout; at most 16 fetches are in
flight. The wire sweeps a crashed PUT's temp files, caps the missing
query at 4,096 digests, and every temp file is exclusive. Start bundle
pins name the boot and the process, age out after an hour, are refreshed
every ten minutes and ignored once the process is gone.
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