Skip to content

Lazy members: --lazy-auto, background prefetch, and in-place decode of large files - #16

Merged
prabhu merged 14 commits into
mainfrom
feat/lazy-prefetch
Sep 28, 2026
Merged

prabhu merged 14 commits into
mainfrom
feat/lazy-prefetch

Conversation

@prabhu

@prabhu prabhu commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

This PR builds on the lazy members from #15. --lazy-auto makes every large native executable lazy with no globs. A background prefetcher then materializes the placeholders after the app starts, so later spawns usually find real files. Lazy members and large hot files are now decoded straight into their destination file, so neither a cold start nor a materialization needs a buffer the size of a large file.

On the full cdxgen binary, auto-selection takes atom, trivy, golem, cdxrs, trustinspector, rusi and cdxui off the cold path. Together with #15's kosi, dosai and osqueryd globs, cold-start writes fall from 320.9 MB to 187.5 MB (−41.6%). The binary grows by 0.41%.

What changes

  • Packager: --lazy-auto / CAXA_LAZY_AUTO=1.
    • It adds every native executable (ELF, Mach-O, PE) of at least 1 MiB to the --lazy/CAXA_LAZY matches.
    • #! scripts are never auto-selected. Interpreters read them (node cli.js, sh run.sh, require()), and npm sets an exec bit on every package bin script. An explicit --lazy glob still selects them.
    • Every {{caxa}}/… file that any command token names stays eager: the executable, so its first run doesn't exec a placeholder, and its arguments, which it may read. The bundled Node never goes through the file collection.
    • Auto members are marked (auto, <size> bytes) in the build's lazy member list.
  • Stub on Unix: background prefetch.
    • Before it execs the app, the stub spawns one detached copy of itself with CAXA_PREFETCH_APP=<app dir>: its own process group, nice 10, stdio on /dev/null, and every other inherited fd closed.
    • The prefetcher accepts only <temp>/apps/<its identifier>/<attempt>. Anything else makes it exit 0 silently. The app never sees the variable.
    • A pid lock at locks/<id>/<attempt>.prefetch keeps one prefetcher per app dir. It is replaced when its writer is gone or its mtime is 10 minutes old.
    • The prefetcher materializes the remaining placeholders of its own identifier in frame order, through the same verified write-and-rename path as the on-demand run. It then writes .caxa-prefetched, and a warm start that sees that marker skips the scan.
    • Any error, including the cache being deleted mid-run, cleans up and exits 0. CAXA_PREFETCH=0 restores the pure on-demand behaviour.
    • Memory: one pair of buffers, sized for the largest pending frame, serves every member.
    • Temp files: every writer holds an flock on its temp file until the rename. Leftover temps are removed only when their pid is gone and their lock is free, since a writer in another PID namespace sharing the cache looks dead by pid.
  • In-place decode of lazy members.
    • Packager: every lazy frame starts with a pax header. It carries the entry's own pax records plus a comment record padded so the member's data starts at a 64 KiB-aligned offset, and the frame ends right after the data's padding. tar readers ignore comment: old stubs, the Windows stub, bsdtar and GNU tar extract the frame as before (e2e and unit tests). Builds without lazy members keep their bytes.
    • Stub on Unix:
      1. Preallocates the member's temp file (posix_fallocate, F_PREALLOCATE), so a full disk fails here and not as a SIGBUS later.
      2. Maps the file at the data offset, under anonymous pages for the header.
      3. Streams zstd into the mapping with a stable output buffer (zstd's experimental feature), 1 MiB of compressed input at a time, hashing the input as it goes.
      4. Renames the temp file over the placeholder only after the sha256, the decoded size and the tar entry (path, type, size, data offset) all match.
    • macOS: it kills a signed binary whose pages were written through a writable mapping. osqueryd got SIGKILL at exec even though its bytes were identical. So on macOS the verified bytes are written once more, with write(), into a fresh file.
    • Fallback: unaligned frames, and filesystems that can't preallocate or map, keep the buffered path. On-demand runs and the prefetcher share this code.
  • In-place decode of large hot files.
    • Packager: in the hot stream, every regular file of at least 8 MiB gets a frame of its own, laid out like a lazy frame. The frame before it ends at its first pax or long-name record, so cuts remain a function of the tar bytes alone. The footer lists these frames in an aligned array of { frame, size }, which old stubs ignore; they extract the frames with tar. Builds whose files are all smaller keep their bytes (e2e against cacb50f).
    • Stub on Unix: a cold start decodes each aligned frame into a temp file in the app dir. Once the decoded size and the single regular entry check out, the file moves to the entry's own path (through safe_join) with the entry's mode. macOS gets the same write() copy as lazy members. These frames no longer count against the extraction's memory budget. Footer entries are validated like lazy ones.
  • Windows: no change. Lazy frames are still extracted eagerly, aligned frames take the buffered path, and no prefetcher is spawned.

Results

Full cdxgen target, darwin-arm64, bench harness, same globs as #15 plus CAXA_LAZY_AUTO=1:

main (6502616, #15 globs) this branch
Binary 143,181,431 B 143,765,341 B (+0.408%); with the aligned lazy and hot frames: 137.14 MB (+0.4%) in the harness
Written on a cold start (CAXA_PREFETCH=0) 320,927,416 B 187,456,234 B (−41.6%)
Files on a cold start 3572 3572 (placeholders replace members 1:1)
Cold --version peak RSS (20 ms sampler) 357,328 KB 224,032 KB; with hot in-place: 196.5 MB (includes the aligned files' page cache)
Smoke 6/6 + 2/2 7/7 + 2/2 (new prefetch-materializes), no regressions, also with the in-place decode
  • Prefetcher memory (it runs alongside the app):

    Before this PR's fixes Buffers reused In-place decode
    Full cdxgen binary, darwin-arm64: peak footprint (/usr/bin/time -l) 301.4 MB 161.8 MB 3.0–4.3 MB
    120 MB incompressible member, Linux x86_64: peak RssAnon – 234,692 KB 1,264 KB

    Buffer reuse alone stopped at kosi's frame: 34.1 MiB compressed plus 118.3 MiB decoded. With the in-place decode, peak RSS still includes the mapped member's page cache (128 MB on darwin, VmHWM 120,704 KB on Linux); that memory is reclaimable, not heap. Every materialized member is byte-identical to its source.

  • Cold-start memory, hot in-place:

    • Linux x86_64: a fixture with the Node runtime bundled, which is one 121 MiB aligned frame. The same payload runs on the stub before and after this change, three runs each. Peak RssAnon drops from 155,844 KB to 8,116–10,300 KB, while VmHWM goes from 158,412 KB to 128,128 KB; what remains is now the runtime's page cache.
    • darwin-arm64, full cdxgen: libnode (53.8 MiB), libicudata (31.7 MiB) and typescript.js (8.7 MiB) get aligned frames, and smoke passes 9/9.
  • Read safety: every smoke case of both targets was traced with preload.cjs. Across 34,524 events, no member path was ever read; there were 13 execs and 7 stats. The trace was taken before the rule was narrowed to native executables; the review build selected the same 7 files.

  • Parity: prefetch-materializes waits for the marker, requires atom and trivy to be real, and compares atom -t c output with an on-demand run on a fresh cache.

Compatibility

  • Old stubs: a --lazy-auto binary runs on the pre-lazy stub (cacb50f), which extracts everything. A binary built by cacb50f's packager runs on this stub.
  • Determinism: --lazy-auto payloads are byte-identical across CAXA_ZSTD_WORKERS values, and CAXA_LAZY_AUTO=1 gives the same bytes as the flag.
  • The cache protocol is unchanged. The lock and marker are new files next to the existing ones.

Limits

  • Hot files under 8 MiB still share frames and decode into memory, as before. Those frames are at most about 8 MiB each.
  • On macOS the in-place path writes each large file twice through the page cache, which is the code-signing workaround above.
  • Prefetching is best effort. A container that stops right after a short command, such as a RUN cdxgen --version warm-up in a Docker build, kills it mid-way. The next start resumes it: the dead lock is replaced and orphaned temps are swept. There is no synchronous "materialize everything now" mode yet.
  • CAXA_PREFETCH_APP set to anything invalid in the user's environment makes the binary exit 0 without running the app. It never runs the app detached with null stdio.

Testing

CAXA_STUBS=host npm test (prettier, cargo fmt --check, clippy -D warnings, stub tests, e2e) passes on:

Host Stub tests e2e
macOS arm64 65/65 27 pass, 2 Windows-only skips
Linux x86_64 (Ubuntu 24.04, btrfs, Node 24) 66/66 27 pass, 2 Windows-only skips
Windows 11 ARM64 VM (Node 24 x64) 36/36 (aarch64-pc-windows-gnullvm test binary, run natively) lazy|prefetch|Windows|hot:: 5 pass, 14 Unix-only skips
  • Cross-compilation and lint: all seven stubs cross-compile with zigbuild. Clippy is clean for x86_64-pc-windows-gnu, aarch64-pc-windows-gnullvm and aarch64-unknown-linux-musl.
  • New stub tests:
    • CAXA_PREFETCH_APP validation: unset, empty, outside the root, wrong identifier, .., a symlinked dir, a file.
    • Lock handling: live, stale, dead writer, garbage content, pid 0 and −1, and a deleted cache that is not recreated.
    • Replacement rules; buffer reuse across members of different sizes; mode preservation.
    • The temp sweep: a dead writer is swept, and a live or lock-holding writer is kept.
    • In-place decode: an aligned member, long names, unaligned and empty frames on the buffered path, and several failure cases, none of which leave a file or temp behind:
      • a name mismatch, a one-byte size mismatch at the same data offset, and a sha256 mismatch;
      • a truncated frame whose index and hash match the truncated bytes;
      • a ../ entry and a FIFO entry.
    • The aligned frames also extract through the tar reader that the Windows stub and old stubs use.
    • Hot aligned frames:
      • one extracts in place (the test asserts the in-place path ran), with its mode, and leaves no temp;
      • a missing or misaligned footer entry falls back to the buffered path;
      • a size mismatch, or an entry escaping the app dir, fails with nothing left behind;
      • bad footer entries (a missing frame, a duplicate, a size larger than the frame) are rejected.
  • New e2e tests:
    • --lazy-auto, one fixture file per selection rule: the fixtures are real native executables, small caxa binaries on the host stub. The size floor, the command's executable and arguments, shared-library names, #! scripts and checksums are all left eager.
    • --lazy-auto determinism, plus both directions against cacb50f.
    • Windows eager extraction.
    • Prefetch: a cold run returns while prefetch continues; 8 spawns during prefetch; a killed prefetcher is replaced by the next start; a cache deleted mid-run is not recreated; CAXA_PREFETCH=0; two concurrent cold starts.
    • A caller waiting for EOF on an extra pipe is not held. This test fails on the stub before this branch's fixes.
    • Lazy frames are 64 KiB-aligned, a long-name path record survives the alignment, and the system tar (bsdtar on macOS, GNU tar on Linux CI) extracts each frame byte-identically.
    • A 9 MiB hot file gets an aligned frame listed in the footer, and the payload is byte-identical across worker counts. The system tar extracts that frame, a cold start restores the file's contents and mode, and the stub from cacb50f extracts the same payload.
  • Formatting: npm run format and the lint check now cover test/ and bench/ too, and test/e2e.test.mjs is prettier-formatted.
  • ETXTBSY fix: a CI run on Linux arm64 caught one bug of my own. The temp file's writable fd stayed open across the rename, so a concurrent exec got ETXTBSY. The flock now lives on a read-only fd.
  • e2e cleanup now retries a just-run exe on Windows. The Windows VM holds a new exe for about 200 ms after it exits, and rmSync doesn't retry that for a file.

Follow-ups

  • cdxgen's build-standalone.sh can pass --lazy-auto (or set CAXA_LAZY_AUTO=1) after a caxa release.

…able of at least 1 MiB

The command's own executable ({{caxa}}-prefixed command[0]) and its
portable-node -real twin stay eager; the bundled Node runtime is added
to the archive from outside the collected files, so it can never be
selected. Auto matches are a union with --lazy/CAXA_LAZY, sorted as
before and listed with sizes in the build output. Formats without v2
zstd frames fail the flag and report the env var, like --lazy.

Also updates the e2e main reference to 6502616 (the #15 merge) and
covers selection, the self-executable rule, determinism across worker
counts, the old-stub and old-packager combinations.
Before exec'ing the app on Unix, the stub spawns itself detached with
CAXA_PREFETCH_APP=<app dir>: its own process group, stdio on /dev/null,
nice 10. The prefetcher validates the app dir against the temp root and
its own identifier, takes a pid lock at locks/<id>/<attempt>.prefetch
(stale or dead-writer locks are replaced), materializes the members
still sitting as placeholders of this identifier in frame order with
the existing verified path, writes .caxa-prefetched and removes the
lock. Any error exits 0 silently and cleans up. Real files and foreign
placeholders are never replaced; the race with a first exec is the same
temp-file-and-rename argument as #15. The app never sees the variable.

CAXA_PREFETCH=0 keeps the pure on-demand behaviour. Windows has no
placeholders and never spawns a prefetcher. Warm starts with the marker
skip the placeholder scan; otherwise the scan is a stat plus an 8-byte
read per footer member path, never a directory walk.

Tests: cargo unit tests for validation, lock handling, replacement
rules, error cleanup, temp sweeps; e2e tests for cold-return, spawn
races, killed prefetcher, deleted cache, CAXA_PREFETCH=0, concurrent
cold starts and Windows eagerness.
The payload measurement and the placeholder-asserting smoke cases
(kosi-help, osquery-runtime, include-runtime-osquery) run with
CAXA_PREFETCH=0, so payload bytes are what the cold start itself
writes and the placeholder contracts do not race the prefetcher.
Cases may now be async. The new cdxgen/prefetch-materializes case
keeps prefetch on: it polls for the .caxa-prefetched marker (120 s),
requires atom and trivy to be real files by then, and checks the
atom -t c output matches a CAXA_PREFETCH=0 run on a fresh copy of the
same fixture.
MAIN_REF must stay the pre-lazy commit: its stub has no lazy support,
so a --lazy or --lazy-auto binary on it proves eager extraction, and
its packager is what byte-identity without the options compares
against. 6502616 (the #15 merge) honours lazy footers and would make
the reference identical to the code under test.

test/.main-ref is now stamped with the commit it was built from and
rebuilt when MAIN_REF changes: a stale cache from a different branch
silently tested the wrong reference, which a fresh clone on the Linux
host caught.
…ed fds, and sweeps only unlocked temps

- One pair of buffers, sized for the largest pending frame, serves every
  member. The prefetcher's peak on the full cdxgen binary drops from
  301 MB to 162 MB, the floor set by kosi's frame (34 MiB compressed,
  118 MiB decoded); macOS malloc kept earlier members' buffers resident.
- Descriptors above stderr are closed at prefetcher start. A caller that
  passed the app an extra pipe (Node's stdio[3]) otherwise waited for EOF
  until the prefetcher finished.
- Every writer holds an flock on its temp file until the rename, and the
  sweep removes a temp only when its pid is gone and its lock is free: a
  writer in another PID namespace sharing the cache looks dead by pid.
- Zero and negative lock pids no longer count as alive (kill(0/-1, 0)
  addresses process groups).
- The lock directory is created one level at a time, so a prefetcher never
  recreates a cache deleted after its app dir was validated.
…y file the command names eager

#! scripts are no longer auto-selected: interpreters read them (node
cli.js, sh run.sh, require()), and npm sets an exec bit on every package
bin script, so a large bundled CLI would have become a placeholder that
its readers get as stub bytes. Explicit --lazy globs still select scripts.

Every {{caxa}}/... path in any command token stays eager, not only
command[0]: an argument may name a file the executable reads.

Auto members are marked (auto, <size> bytes) in the one lazy member list
instead of being listed twice.
…t that runs nothing, concurrent and fd prefetch tests

- The file is main's formatting again: the earlier commits ran prettier
  over the whole file, which lint does not cover (source/ only).
- lazy-auto fixtures are real native executables (small caxa binaries on
  the host stub), with one file per selection rule: size floor, command
  executable, command argument, shared-library name, #! script, checksum.
- The Windows lazy-auto test spawned #! scripts, which Windows cannot run;
  it now uses PE-header files and only checks they are extracted eagerly.
- "two cold starts at once" ran them one after the other; they now run
  concurrently, and every attempt dir is checked.
- New: a caller waiting for EOF on an extra pipe is not held by the
  prefetcher (fails on the previous stub, passes now).
- Prefetch tests use the lazy skip like the other lazy tests, and a
  shared noise helper; the fixture scripts exit before their padding.
The CAXA_PREFETCH=0 run shared the cache that had just been prefetched,
so both runs used the real atom. It now gets its own cache, where atom
starts as a placeholder and materializes on demand.
Windows builds warned that five of them were never used, which fails the
Windows runner's clippy -D warnings. Checked with clippy for
x86_64-pc-windows-gnu and aarch64-pc-windows-gnullvm through zig's cc.
Windows can hold a new exe for a moment after it exits (EPERM, ~200 ms on
the ARM64 VM), and rmSync does not retry that for a file whatever its
maxRetries. Both Windows lazy tests failed in cleanup on the VM, the one
from main included.
…nux arm64)

b457cc7 kept the temp file's writable descriptor open through the rename
to hold its flock. For that moment the member path named a file open for
writing, and a concurrent first run's exec failed with ETXTBSY: 4 of 8
spawns in the prefetch race test on the ubuntu arm64 runners. The flock
now lives on a read-only descriptor; the writable one is closed first.
…g decode into the mapped member file

Packager: every lazy frame starts with a pax header, carrying the entry's
own pax records plus a comment record padded so the member's data starts
at a 64 KiB-aligned offset of the decoded frame, which then ends right
after the data's padding. tar readers ignore comment: old stubs, the
Windows stub, bsdtar and GNU tar extract the frame as before. Builds
without lazy members keep their bytes.

Stub (Unix): the data offset follows from the frame and member sizes.
The member's temp file is preallocated (posix_fallocate, F_PREALLOCATE)
and mapped at that offset under an anonymous header page range, and zstd
streams into the mapping with a stable output buffer (zstd's
experimental feature), 1 MiB of compressed input at a time, hashed on
the way in. The temp file becomes the member only after the sha256, the
decoded size and the tar entry (path, type, size, data offset) match.
macOS kills a signed binary whose pages were written through a writable
mapping (osqueryd: SIGKILL at exec with identical bytes), so there the
verified bytes are written once more, with write(), into a fresh file.
Unaligned frames, and filesystems that cannot preallocate or map, keep
the buffered path; on-demand runs and the prefetcher share the code.

Prefetcher peak on the full cdxgen binary (darwin-arm64, /usr/bin/time
-l): 161.8 MB -> 3.0-4.3 MB peak footprint (max RSS 128 MB, the mapped
file's page cache). Linux, 120 MB incompressible member: peak RssAnon
234,692 -> 1,264 KB (VmHWM 120,704 KB, file-backed).

Also: TempMember removes a temp file on every failure path, and entry
data is skipped by seeking when a frame's entries are checked.
test/e2e.test.mjs was never formatted, since the lint and the format
script only covered source/. It is now, formatting only, and both
scripts include test/*.mjs and bench/*.mjs so it stays that way.
@prabhu prabhu changed the title Lazy members: --lazy-auto and background prefetch Lazy members: --lazy-auto, background prefetch, and in-place decode Sep 28, 2026
@prabhu prabhu added the ai-auto A person set the task, and AI agents carried it through to completion label Sep 28, 2026
Packager: in the hot stream, every regular file of at least 8 MiB gets a
v2 frame of its own (the frame before it ends at its first pax/long-name
record), laid out like a lazy frame for in-place decoding, and the footer
lists those frames in an `aligned` array of { frame, size }. Cuts remain
a function of the tar bytes alone. Builds whose files are all smaller keep
their bytes; old stubs ignore `aligned` and extract the frames with tar.

Stub (Unix): a cold start decodes each aligned frame straight into a temp
file in the app dir, then renames it to the tar entry's own path (checked
by safe_join) with the entry's mode, after the decoded size and the entry
(single regular entry, size, data offset) check out; macOS keeps the
write() copy for code signing. Such frames no longer count against
FRAME_MEMORY_BUDGET. Frames the stub cannot decode in place, and Windows,
take the buffered path. The footer entries are validated like lazy ones.

The in-place decoder is shared with lazy members: Expected carries the
member's path, mode and sha256, or none of them for a hot frame.

Cold start, Linux x86_64, Node runtime bundled (one 121 MiB aligned
frame), same payload on the stub before and after: peak RssAnon
155,844 KB -> 8,116-10,300 KB (VmHWM 158,412 -> 128,128 KB, now the
runtime's page cache). Full cdxgen, darwin-arm64: libnode (53.8 MiB),
libicudata (31.7 MiB) and typescript.js (8.7 MiB) are aligned; cold
--version peak RSS (20 ms sampler) 224.4 -> 196.5 MB, smoke 9/9.
@prabhu prabhu changed the title Lazy members: --lazy-auto, background prefetch, and in-place decode Lazy members: --lazy-auto, background prefetch, and in-place decode of large files Sep 28, 2026
@prabhu
prabhu merged commit ffe868e into main Sep 28, 2026
34 checks passed
@prabhu
prabhu deleted the feat/lazy-prefetch branch September 28, 2026 12:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-auto A person set the task, and AI agents carried it through to completion

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant