Repository navigation
Lazy members: --lazy-auto, background prefetch, and in-place decode of large files - #16
Merged
Merged
Conversation
…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.
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.
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.
This PR builds on the lazy members from #15.
--lazy-automakes 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
--lazy-auto/CAXA_LAZY_AUTO=1.--lazy/CAXA_LAZYmatches.#!scripts are never auto-selected. Interpreters read them (node cli.js,sh run.sh,require()), and npm sets an exec bit on every packagebinscript. An explicit--lazyglob still selects them.{{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, <size> bytes)in the build's lazy member list.CAXA_PREFETCH_APP=<app dir>: its own process group,nice 10, stdio on/dev/null, and every other inherited fd closed.<temp>/apps/<its identifier>/<attempt>. Anything else makes it exit 0 silently. The app never sees the variable.locks/<id>/<attempt>.prefetchkeeps one prefetcher per app dir. It is replaced when its writer is gone or its mtime is 10 minutes old..caxa-prefetched, and a warm start that sees that marker skips the scan.CAXA_PREFETCH=0restores the pure on-demand behaviour.commentrecord 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 ignorecomment: 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.posix_fallocate,F_PREALLOCATE), so a full disk fails here and not as a SIGBUS later.experimentalfeature), 1 MiB of compressed input at a time, hashing the input as it goes.write(), into a fresh file.alignedarray of{ frame, size }, which old stubs ignore; they extract the frames with tar. Builds whose files are all smaller keep their bytes (e2e againstcacb50f).safe_join) with the entry's mode. macOS gets the samewrite()copy as lazy members. These frames no longer count against the extraction's memory budget. Footer entries are validated like lazy ones.Results
Full
cdxgentarget, darwin-arm64, bench harness, same globs as #15 plusCAXA_LAZY_AUTO=1:6502616, #15 globs)CAXA_PREFETCH=0)--versionpeak RSS (20 ms sampler)prefetch-materializes), no regressions, also with the in-place decodePrefetcher memory (it runs alongside the app):
/usr/bin/time -l)RssAnonBuffer 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:
RssAnondrops 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.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-materializeswaits for the marker, requires atom and trivy to be real, and comparesatom -t coutput with an on-demand run on a fresh cache.Compatibility
--lazy-autobinary runs on the pre-lazy stub (cacb50f), which extracts everything. A binary built bycacb50f's packager runs on this stub.--lazy-autopayloads are byte-identical acrossCAXA_ZSTD_WORKERSvalues, andCAXA_LAZY_AUTO=1gives the same bytes as the flag.Limits
RUN cdxgen --versionwarm-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_APPset 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:lazy|prefetch|Windows|hot:: 5 pass, 14 Unix-only skipsx86_64-pc-windows-gnu,aarch64-pc-windows-gnullvmandaarch64-unknown-linux-musl.CAXA_PREFETCH_APPvalidation: unset, empty, outside the root, wrong identifier,.., a symlinked dir, a file.../entry and a FIFO entry.--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-autodeterminism, plus both directions againstcacb50f.CAXA_PREFETCH=0; two concurrent cold starts.pathrecord survives the alignment, and the system tar (bsdtar on macOS, GNU tar on Linux CI) extracts each frame byte-identically.cacb50fextracts the same payload.npm run formatand the lint check now covertest/andbench/too, andtest/e2e.test.mjsis prettier-formatted.rmSyncdoesn't retry that for a file.Follow-ups
build-standalone.shcan pass--lazy-auto(or setCAXA_LAZY_AUTO=1) after a caxa release.