Repository navigation
Oj store: shared build cache across worktrees, with a wire - #503
Draft
raphamorim wants to merge 3 commits into
Draft
raphamorim wants to merge 3 commits into
raphamorim wants to merge 3 commits into
Conversation
raphamorim
force-pushed
the
rapha/pulp
branch
4 times, most recently
from
October 23, 2026 22:39
e11f245 to
5c3c679
Compare
raphamorim
force-pushed
the
rapha/pulp
branch
3 times, most recently
from
December 3, 2026 09:53
1ec8dca to
12eabcb
Compare
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.
raphamorim
force-pushed
the
rapha/pulp
branch
from
December 3, 2026 10:03
12eabcb to
9d94771
Compare
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
OJ_STORE_DIRis set.oj dev --store[=DIR]is the one switch: it setsOJ_STORE_DIRfor the server and every child (to DIR, else/oj/store, else~/.cache/oj/store) and turns the persistent module cache on. A plainoj devwrites nothing outside the tree. There is no--enable-cacheor--no-cacheany more (Remove the on-disk module cache and its --enable-cache / --no-cache flags #669 removed them).oj store serve: an HTTP substituter, withOJ_STORE_REMOTEread-through andOJ_STORE_PUSH.node:fsinterposition plus TracingFs under the engine's fs ops, are re-verified on warm hits.What the rebase changed, against the October branch:
--storeonly, 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. ThemoduleParsedreplay and the plugin-virtual re-transform check came back with it.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.keyed_by_files) are root-relative, generations and blobs live in the shared dir with per-rootcurrent/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_dependencies_of) in place of the process-wideOnceLock, which main's static-config path and the Start bundler's cache key also use now.start_dev_style_url, under the root-relative/@oj-start/fs/@ws/<rel>form.--configfile 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):
globcrate's: a brace pattern used to list nothing and keep a constant digest.tsconfig*.jsonat the root and the config's named tsconfig by content, nottsconfig.jsonalone (Vite's template keepspathsin tsconfig.app.json)./@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.OJ_STORE_DIRis set;--storesets it. The unusedOJ_DEBUG_SALTknob 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.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_persistentandwarm_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.store-concurrent.mjs: twooj dev --storeprocesses 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_compilertests,oj_serverlib tests, theojbin 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):
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../utiltoutil/index.ts, the importer untouched) was served as a hit whose import 404d. The check used to run only with a transform plugin active..browserslistrcare in the salt: a stylesheet entry persisted across a PostCSS config edit./kept every entry local.--storehelp, the knob doc and the changelog name$XDG_CACHE_HOME/oj/storeagain; 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 andimport.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.envedit and a--modeeach 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_keyfollows components, not string prefixes.oj_serversalt: every resolver setting is its own field (extensions against mainFields,ab|cagainsta|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_checkouton paths, route strings and/.keyed_by_filestells missing from empty and keeps file boundaries; the cold probe skips other salts' generations and still restores its own.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:
@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.--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./@fs/@mono/<rel>import has no file in the reader's workspace is a miss.URL,Bufferor 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).--max-bytes, 507);DELETEpurge under the write token; streaming handlers off the runtime;oj store servedefaults 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_PUSHis documented as sendingsourcesContent.--storeis the one switch, as the docs said:oj devwithout it now clears an inheritedOJ_STORE_DIRfor itself and its children (the variable alone used to share the Start bundle, codegen and bytecode while the module cache stayed off);--storewith 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:
node:fswhile 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@useand CSS@importsearches 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 declareddir-dependencystays a directory row.oj build,preview,lintandtypecheckclear an inheritedOJ_STORE_DIRtoo.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 (
.envdefines 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
nodeor a browser without a favicon.