Skip to content

engine: remote cache fixes — relocate module source references, keep a cached module's core API version, fewer lookups, exports without the Cloud's offers, module results per CPU architecture, faster cache-volume collection and network teardown at stop, graph-lock profiling — and remove the test fixture - #14828

Closed
sipsma wants to merge 273 commits into
mainfrom
sipsma/remote-cache-timing-wcprof

Conversation

@sipsma

@sipsma sipsma commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

This PR collects fixes to the engine's cache and its remote cache, each as its own commits. It fixes a bug on main in how module sources move between engines, fixes a bug in released engines where a module taken back from the cache was served the loading client's core API version instead of its own (this wipes every engine's local cache once on upgrade), fixes a module taken back from the cache losing its own entry, so a module that calls itself failed, makes a fresh engine ask the remote cache service far fewer questions, stops exports from carrying the Cloud's own offers back to it, says in telemetry which results the engine image ships, keeps module function results from crossing CPU architectures, lets the cache-volume directory free space when the disk is short, measure its volumes far faster and log what its collection measured and removed, lets a stopping engine leave its cache-volume deletions to the next one, tears an engine's network namespace pool down faster at stop, links only a lazy result's first evaluation in a session, names who holds the cache's graph lock in profiles, holds each layer of a blob-backed cache's stored chains once, lets a prune keep from freeing far more than it needs, decodes a cache restore's records as it reads them, keeps every live equivalence class's number across a compaction, frees a stored entry's empty holder maps, reads a blob-backed cache at its reader's clock and has its writes say what they changed, sends records as their sender holds them (bundle format 8), holds a blob-backed cache's stored records compressed, prepares a merge's records in parallel and renumbers them before its commit's lock, builds an export's chains together and frames the remote cache's large zstd layers, lets a blob-backed cache's writers and readers take its lock in fewer and shorter holds, holds the service's call frames compressed, streams a save row by row, drops two retries in the blob reader, builds an idle engine's export on all its cores, prices the outputs a stored bundle's merge carries, shares an offer's layers between its copies, reports when each claimed session started, fixes a flaky test, and removes the remote cache's test-only fixture.

On the engine line but deliberately not in this PR, each waiting for another PR: an engine-disk temp mount (withMountedTemp(disk: true)) is #15143's; the cache export's wait for busy results, its offer filtering and logging, and nested clients reaching engine.localCache change #15127's ExportBundle and wait for it; and a prepared merge warming and renumbering its targets before its commit, with a blob-backed cache's merge warming nothing, needs #15162's session binding and waits for it. A directory content digest that includes where the directory is rooted is held out as well: it changes the engine's own cache so that identical files under different subdirectories stop sharing results, which main's tests assert on purpose, and that behaviour change waits for a decision.

A module source's references move between engines

This fixes a bug on main. When cache records move from one engine to another (a transfer through the remote cache, or the merge of an engine image's pre-built entries), every reference a record holds to another row is renumbered for the receiving engine. Three references were never renumbered, so they kept the sending engine's row number, weren't counted as dependencies, and were left out of exports:

  • A module source's git origin. Since Fresh dagger check -l of dagger/dagger in under 5 s: per-package Go builds, a pre-warmed engine cache, and faster module loading and check planning #15080, a module served from a git workspace's tree records the git repository its contextual git comes from. On the receiving engine that reference named no row, and loading the module failed with load persisted module source dir origin git result: resolve result N: missing shared result; if the number happened to name another git repository's row, the module would get the wrong origin. This failed checks on fresh engines served from the remote cache, on reruns of a commit an earlier run had computed.
  • The workspaces of a selection's collection roots.
  • The collections an artifact view was filtered from.

No failure has been seen from the last two; a new test found them. Without the remote cache, the first is reachable only if the engine prunes the git row, or if an engine image's pre-built entries hold such a module; neither has been seen.

Each fix makes the family's visitor walk the reference. core: test that every persisted family's visitor walks its stored references is a guard for the whole class: it fills every row reference in every persisted family's payload and requires the family's visitor to report each one, so a family that adds a reference without walking it fails. That commit fails on its own by design, naming the two references the next two commits fix.

A module taken back from the cache keeps the core API version it declares

A bug in the engine's own cache, in v1.0.0-beta.26 and beta.27. A Module's dependencies serve the core API at the version the module declares. The stored Module kept its dependency modules but not that version, so when an engine took a module back from its cache instead of building it (after a restart with its state kept, for example), the core API was rebuilt at the version of whichever client loaded it. A Dang module declaring v1.0.0-beta.25 that names FunctionCachePolicy.PerSession then failed with field "PerSession" not found in FunctionCachePolicy, as dagger's own engine-dev module did on reruns of CI checks; Go, TypeScript and Python modules had their calls answered at the client's version, with no error. The stored Module now records the core API version of its dependencies and of its entrypoint's, and loading it restores that version.

Users notice one thing: this raises the cache's persistence schema version (cachePersistenceSchemaVersion, to 24), so every engine's local cache is wiped once when it upgrades.

Two cases in TestCachePersistence/TestDiskPersistenceAcrossRestart (a module from a git workspace keeps the version it declares after a restart; a module whose client declares no version is answered at its own) fail without the fix, including on released beta.27, and pass with it; TestPersistedDecodeDefaultDeps covers the saved version winning over the decoding server's.

A module taken back from the cache can still call itself

Another bug in the engine's own cache. A Dang module's API includes the module itself, so its code can call its own constructor. A module built fresh gets that entry when its result is attached, but a Module taken back from the engine's cache (after a restart, for a check planned from a git workspace at a commit the engine had already run) came back without it: the stored record leaves the entry out, since a record can't reference itself, and the cache doesn't run the attach step for a decoded payload. Any function of a module that calls itself then failed, a Dang module with "<module>" not found. The cache now gives a decoded object payload its own row as an object of its class, as a fresh result's attach step gets it, and a decoded Module puts itself back in its dependencies. It doesn't change the persistence schema version. A restart test in TestCachePersistence/TestDiskPersistenceAcrossRestart, a module that calls itself still calling itself after a restart, fails on main without the fix and passes with it.

A fresh engine asks the remote cache service only about calls it can know

The remote cache service learns about a call from the cache decision its telemetry span reports. A fresh engine still sent a lookup for every cache miss, including calls telemetry leaves out: building a module's type definitions, reflection and introspection, and calls under a hidden context. The service almost never knows those, so their lookups came back unknown and queued ahead of the ones it can answer. An engine now sends a lookup only for a call whose cache decision telemetry reports, so what the service learns and what the engine asks about follow one rule.

On a fresh engine served from the remote cache, a same-commit rerun of test-base sent 76 lookup misses instead of 3,403, with the same hits. On served same-commit reruns on today's main, where the checks run nothing, test-base took 4.3 s against 4.4 s and lint-all 2.9 s against 3.3 s, so the change costs nothing (one run each). TestRemoteLookupOnlyReportedCalls and TestAroundFuncMarksReportedCalls fail without the change.

Exports no longer send the Cloud its own offers

A row an engine imported from the Cloud carries the Cloud's offers of its parts: each a layer chain from the base up, with a signed download address per layer. When the engine sends such a row back in full, which it does after the Cloud has pruned values the engine still held, or after a reconnect, the export carried all of those offers, though the Cloud drops every offer in a bundle when it merges it. On test-base after an edit this made the fresh engine's exports run up to 24 KB a record and over the protocol's 64 MiB message limit, so they were refused, results never reached the Cloud, and the engine's stop timed out. Exports now leave those offers out. What the Cloud holds after a merge is unchanged, since it dropped them anyway. On test-base after an edit, the refused exports went from 49–166 to 0, the largest export after a prune from about 66 MB to 30 MB, and the fresh engine's peak Go heap from 9–12 GiB to 6 GiB. Its stop now settles. remote_cache_reexport_test.go sends 2,206 imported rows with 24-layer chains back in full and fails without the change.

The settle state says when each claimed session started

The remote cache's settle state lists each session that started under a claim. Each SessionClaim now also carries Started, when the session started on the engine's own clock, the clock its spans' times are on. The remote cache service uses it to time each call from its run's start without comparing different engines' clocks, and so sends a fresh engine a check's results in the order an earlier run first used them. With the service's side, after a one-line edit a fresh engine with the remote cache built test-base's binaries 8.3 s behind a warm engine, against 13.8 s without (two runs each); after two edits in a row, about 8 s against 19 s (two sequences each). TestRemoteCacheReportsWhenEachClaimedSessionStarted fails without the change.

Telemetry says when the engine image ships a result

An engine never exports a result its image ships, nor that result's parts, because every engine built from the image already has them. But its telemetry didn't say which results those were, so the remote cache service took them for the engine's own and kept asking for them: on test-base after an edit, the same empty export went out every two seconds for most of the run. A call span now carries dagger.io/cache.image when the result has an image holding, and a remote holding takes that fact from each call span, so a result stops counting as the image's once a newer image no longer ships it. TestCacheResultStateImage, TestRemoteHoldingFromTheImage and TestCacheStateAttrsImage fail without the change.

Module function results are no longer served across CPU architectures

A module function's cache key was its module, the function, its arguments and its cache policy. Its body can still depend on the engine's default platform: by reading defaultPlatform (as dagger/go's gomod.hostPlatform does), by creating a container without a platform, or by running on the engine. Through the remote cache, an arm64 engine could be served the result an amd64 engine computed, such as an amd64 binary from dagger/go. Every module function and constructor now carries the engine's default platform as an implicit input, as the core fields that read it already do since #13911. The Dang runtime needs no key of its own: it isn't a cached result, and compiled SDKs' runtime containers already carry the platform through container().

The cost. Module function results with no declared platform stop being shared between engines of different architectures, since the engine can't tell which function bodies read the platform. Results declared with Directory.withPlatform or File.withPlatform (#15080) stay shared, because their identity leaves the engine's platform out, including on the module function calls in their recipe: dagger/go's wrapper functions, for example, can rerun on an engine of another architecture while the outputs they declare still hit. Since #15134, withPlatform is visible only to modules targeting v1.0.0-beta.26 or later (dagger/go targets beta.26); a module on an older engine version can't declare its results, so none of its function results are shared across architectures. Organizations with a single architecture see no change in what hits. An engine's platform never changes, so the local cache behaves as before, but existing module function results miss once after the upgrade, because their keys change.

Tests. TestModuleFunctionCacheImplicitInputs requires the engine's default platform as an input of every module function under every cache policy, and dagql's own tests cover what an implicit input does to a cache key.

The cache-volume directory frees space below its reserve when the disk is short

When the cache-volume directory's filesystem is short of its free-space minimum, collection now frees what that minimum asks for, even if that takes the directory below its reserved space. Before, the free-space target was capped at the reserve, so on a nearly full disk with every volume inside the reserve, collection freed nothing. This matches the engine's dagql cache pruning, where the free-space minimum isn't capped by the reserve either. Pruning for the max-used threshold still keeps the reserve.

This affects engines with no cache-volume capacity set; an engine with a capacity has only a max-used limit, so nothing changes for it. TestCollectFreesSpaceBelowTheReserve fails without the fix. The comments on reservedSpace and minFreeSpace in the engine config, and in the published engine.json schema, now say that pruning for free space can reclaim usage below the reserve.

The cache-volume collection walks volumes in parallel, and says what it measured and removed

On engines using the remote cache, the stop's slowest phase was the cache-volume directory's collection, which walks the file tree of every volume written since its last measurement to learn its size: 4.5–9.6 s on engines that ran a full test-base check. The walk read one directory and examined one entry at a time. It now reads up to 16 directories at once, and counts exactly what it counted before: every entry, and each inode's space once, so a hard link takes no more space, even when a file's links change during the walk.

On a real CI engine filling the remote cache with test-base (one run each, on comparable fills): with the serial walk, the stop itself walked 1,807,594 files (54.65 GB) in 13.88 s, 13.9 s of a 14.0 s stop; with the parallel walk, the collection after the session ended walked 1,881,403 files (55.87 GB) in 1.40 s, leaving the stop nothing to walk, and the whole graceful stop took about 0.5 s. In one simulated run of the released v1.0.0-beta.27 engine configured with cache volumes in a directory, its state kept and a 60 s stop grace, after a full test-base fill, the stop spent 58.5 s waiting for this collection's serial walk and was killed 2 s into closing its cache, before the cache was marked cleanly saved: without the parallel walk, an engine set up this way can spend its whole grace walking and lose its saved cache. (Engines that set no cache-volume directory keep cache volumes as snapshots and are unaffected.) On one machine with real cache volumes (36.7 GB, about 800,000 entries), the walk took 1.3 s instead of 39 s with the page cache emptied, and 0.37 s instead of 3.2 s with it warm; a Go compile running beside the cold parallel walk was 1.5–2.2% slower. Tests pin down what a walk counts, including a hard-linked file losing a link mid-walk.

The collection's report and log line now also say how many volumes it walked, their bytes and entries, how long the walk took, and the directory's usage against its cap; at stop the engine logs how long it waited for removals, and each removed volume gets a line with its key, namespace, size, and when it was created and last used.

A stopping engine doesn't wait for its cache-volume deletions

A collection removes cache volumes by moving them into the directory's trash at once, then deleting the files in the background. A stopping engine used to wait for that deletion, up to its stop budget, and the next engine to open the directory deleted any leftovers before it served anything. At Namespace's cache-volume cap, test-base crosses the cap every other run, and those stops removed about 50 GB, which takes about 65 s to delete; a stop that came during it waited up to 25 s. Deletion is bound by the filesystem's journal, so it can't be made to fit.

Now the stop exits without waiting. Whatever is still in the trash, the next engine that opens the directory deletes in the background right after it starts, counting it as space being freed until it's gone so collection doesn't remove more meanwhile; this is how the engine already treats its own discarded state. Its checks see nothing different: the trash takes disk space for up to about a minute while it's deleted, and if that engine also stops first, the one after it keeps deleting and counting it. A failed deletion is logged as a warning when it happens, and what survives stays counted until a later engine deletes it. The engine logs how many leftovers it found, their recorded bytes, and when their deletion ended.

In the simulator, with the cap lowered to 60 GB in both arms so stops delete (two series of 3 pairs each), the stop's cache-volume phase went from 0.0005–24.6 s to about 0.24 ms, and fresh engines' stops went from up to 25 s to 0–1 s. These stop times come from the engine wrapper's own log lines, not the simulator's verdicts, which include about 15 s of harness overhead. In the series without the service's pruning, the fresh engine that starts on the leftovers passed every check, except one run lost to a known flaky test, and its time before the tests and its check time matched the baseline (309–317 s against 313–320 s). Not tested: the next engine's start after a stop cut off mid-deletion. That an engine really starts on a previous engine's unfinished deletion is inferred from timings until the new log line shows it on a real run. Each behaviour has a test that fails without it.

An engine's stop tears its network namespace pool down 16 at a time

At every stop, an engine that keeps its state tears down its pool of container network namespaces, at least 128 of them, and did so one at a time: about 41 ms each on an idle engine and 160–190 ms inside a busy one. A CI engine on dagger main spent 23.3 s of its 24.5 s graceful stop there. The close now tears down up to 16 at once, with the same end state: every namespace is released, and one whose teardown fails keeps its file for the next start to retry. Nothing else runs on the engine then: the pool closes after the server stopped listening and every session was removed. It also logs one line at close with how many namespaces were released and failed, the pool's peak and the time taken. Engines that discard their state skip this phase.

Measured on dagger main's published engine, idle: 128 namespaces took 5.2 s one at a time and 0.35 s sixteen at a time; 512 took 21.7 s against 1.8 s. In simulated warm stops on the per-package workload with 128 namespaces in the pool (not one interleaved series), network close took 20.5 and 24.0 s without the change and 5.5–7.1 s over four stops with it, and the restart's whole graceful stop went from 36.9 s to 24.2 s; 14 other stops on today's code took 21–26 s.

Two things this doesn't show. It's 3–4× faster in a busy engine, not the 15× the idle bench suggests: part of each teardown doesn't overlap, most likely the kernel's deletion of each network device (inferred, not measured). And the pool's size at stop on a production CI engine isn't known: that engine's 23.3 s fits 128 namespaces at about 180 ms as well as 550 at 41 ms, so the gain there is an estimate until the new log line reports it. The tests run unprivileged in the package tests.

Only a lazy result's first evaluation in a session carries its cause links

On test-base, a fresh remote-cache engine was killed twice at about 15.9 GB, against about 3 GB for seed and warm engines, because every lazy evaluation repeated cause links to every module call owning its result. With #14884 alone it peaked at 6.0–6.1 GB; with this change too, at 5.01 GB (one fresh test-base run). Only a result's first evaluation in a session now carries the links; later evaluations link only that first one, marked dagger.io/lazy.anchor, and the CLI (since v1.0.0-beta.22, #14874) and Dagger Cloud follow them back. A CLI older than beta.22 on a newer engine can show some calls as pending forever. Timed against main on a cold test-base fill of the per-package workload, the change is no slower: the check took 1,083.5 s against 1,152.5 and 1,135.4 s, and the median time to publish a result was 0.068 ms against 0.082 and 0.079 ms. The install-span gathering is also a profile step now, and a regression test pins that an install-span lookup costs only what is above its result.

The cache's graph lock names who holds it in profiles

When the engine records a wall-clock profile, a wait on the cache's graph lock names who held the lock, but the engine's own passes (a session's release, a prune's measurement, snapshot and edge removal, a metadata prune's estimate and compaction, and a save) took it directly, with no name, and a writer waiting behind overlapping readers recorded an unknown holder too. On a recorded test-base run, about three quarters of the time spent waiting on the graph lock was behind holders the profile could not name. Those passes now take the lock as named profile steps, a save's and a prune's long snapshot reads are named too, and while a recorder is active the lock counts its readers, so a writer waiting behind them names them. This changes no lock boundaries and no cache behaviour. An engine that isn't recording has no recorder; on one machine, alternating before and after with no allocations, an uncontended write lock took 35 ns directly and 39 ns through the new path, a contended one 188–194 ns against 189–198 ns before, a read lock 18.3 ns either way, and parallel readers 31–34 ns against 35–37 ns, within noise.

A blob-backed cache holds each layer of its stored parts' chains once

dagql's blob-backed cache, the kind that stores parts (an engine's cache doesn't), kept a deep copy of every stored part's whole layer chain, from the base up, so each base layer's descriptor, annotations and pack entry were held once for every part built on it. It now holds each distinct layer once, in a table that holds layers weakly, and a stored part points to its layers; every reader gets exactly the offer it got before. The wire format, the saved format and SetStoredPart's signature don't change, and nothing changes in an engine's behaviour. With the same store contents (236 MB, about 37,800 values) and one run each, the cache's live heap at rest went from 946 to 538 MiB, its peak live heap from 1,218 to 916 MiB, and its process's resident memory from 2.24 to 1.57 GiB at rest and from 2.64 to 2.19 GiB at peak. A heap test stores 200 parts on a 40-layer base and fails without the change; another checks that a closed cache with stored parts is freed.

Copies of a part offer share its layers

Every copy of a part offer deep-copied its chain's layers: each layer's descriptor annotations, URLs, data and platform. A result's chain lists every layer from its base up, so copies repeated the same base layers for every result, and every merge, export and persistence pass makes copies. Decoding a merge also gave each chain its own copy of every layer the merge lists once. An offered layer is never written after it's built; the copy exists so that relocating references and removing addresses can't reach the original, and neither touches a layer. A copy (clonePartOffer) now shares the chain's layers and still copies the offer's address, value, owner, and its chain's addresses and packs; decoding a merge (resolveSharedLayers) gives the chains that name a listed layer that layer. Nothing on the wire changes. TestClonePartOffersShareOnlyLayers walks every field of an offer by reflection, so a new field is copied unless it is a layer, and TestValueBundleWireListsLayersOnce checks that decoded chains share the listed layers. On a fresh engine after a one-line edit to test-base, one heap-profiled run each way, offer copies held fell from 170 to 55 MB, and from 548 to 156 MB while exports ran; the engine process peaked at 3.98 GiB against 4.40 GiB, which rests on that one pair, where the fresh engine's peak moves by about 0.17 GiB from pair to pair.

Every live equivalence class keeps its number across a compaction

dagql's e-graph compaction renumbered the live equivalence classes 1..n. It now frees only the classes nothing uses and the slots of classes merged into another, and every live class keeps its number; freed numbers below the highest live class are taken again by new classes, lowest first, and free slots above it are trimmed. A restore keeps the numbers it was saved under. No cache rule changes: the same classes stay live with the same digests, terms and entries, and lookups answer as before. So a class number names its class for as long as the class lives, and anything that keeps a number outside the e-graph's tables, such as a saved row of a persisted cache written as it changes, stays right across a compaction. An engine compacts only in a prune; afterwards its class arrays keep the length of its highest live class rather than the live count until new classes take the freed slots (8 bytes of parent and 1 of rank a slot), and the slots the metadata estimate charges still count only classes that hold a number. On dagql's benchmarks, one run each: the metadata churn and sparse forced-compaction cases end at the same 2,000 slots and the same 65.9 MB compacted heap; a cache that stores entries for remote engines, 175,000 live entries through 20,000 churn cycles, ends at 524,996 slots instead of 295,000 (295,000 in use either way), about 4 MB more. A new test fails without the change.

A cache restore decodes its records as it reads them

dagql's restore, which every engine runs at start and a cache that stores entries for remote engines runs when it opens its store, listed the whole results table into memory, decoded every row, and kept the raw rows until its locked section ended, so for a while it held each record twice. It now reads the table 64 rows at a time, decodes each batch on all cores while the next is read, and drops a row's raw bytes once it's decoded. What is restored, the order rows are applied in, and which bad row's error is reported don't change, nor does the saved format. Measured with Go's default collector (live peak from a heap profile after a forced collection at each phase, one run each; resident memory and time from two runs each, alternating on one machine): on an engine's own store of 26,087 entries, the live peak went from 205 to 160 MiB (the restored cache itself is 154 MiB), resident memory from 632–661 to 441–500 MiB, and the restore took 0.43 s instead of 0.44 s; on a 4.26 GB store of 224,298 entries, the live peak went from 8.4 to 4.6 GB and resident memory from 22.3–22.5 to 13.4–13.8 GB, in 50 s instead of 51 s. On three large stores the restored cache was byte-identical with and without the change. TestCachePersistenceImportHoldsRawRowsOnlyUntilDecoded fails without it (125 MB held beyond the restored cache against a 32 MB bound, 11 MB with it), and TestCachePersistenceImportReportsFirstInvalidRow pins which bad row's error is reported.

A stored entry holds nothing for holdings that are gone

A cache that stores entries for remote engines keeps a holding for each result an engine holds, in maps on each stored entry and one on the cache. Removing a holding deleted the map key but left the map allocated, and a Go map keeps its memory after its last key goes; since a stored entry outlives its holdings, every stored entry an engine had held kept two empty maps, about 0.67 KB a stored record. Each map is now dropped when it empties. On a cache at rest with 50,733 stored records, the 32.2 MiB those maps held, 4.2% of its live heap, is gone (one run each). Only a cache that stores entries reaches this path; an engine's own cache doesn't. TestStoredEntryHoldsNothingForHoldingsGone fails without the change: 654 bytes an entry stayed on the live heap after every holding of 2,000 stored entries went.

A blob-backed cache's reads take the reader's clock, and its writes say what they changed

These change only dagql's blob-backed cache, the kind that stores entries for remote engines; an engine's own cache marks nothing and reads its clock as before.

The reader's clock. AvailablePart, PlaceOffer, StoredBundle, StoredSizes, MeasuredStoredSizes and StoredLowerHalf take the reader's clock (nowUnix) and judge every expiry they read at it; HeldBy no longer carries a clock. Before, a reader that judged entries' and holdings' expiries at one moment could read their parts at another and get answers describing states the cache never held at one instant, one bundle could borrow a part by one moment and leave out held rows by another, and a replay of a recorded run was answered by the wall clock. Each has a test that fails on the wall clock.

Change reports. A reader that keeps a blob-backed cache's answers had no way to tell which of them a write changed, short of asking every one again. Every write now returns a RemoteChange naming the holdings and entries whose answers may differ after it (Holdings, Entries): SetStoredPart, DropStoredParts and DropStoredPack, AddRemoteHold, ReleaseRemoteSession, EndRemoteProcess and ReleaseRemoteCache, ObserveRemoteRetention, CollectRemoteHolding and CollectRemoteHoldings, and the prune reports. A part answer gains ValidUntilUnix, before which only a write can change it. The commit that adds the marks gives the reasoning for what each kind of change marks. A completeness test drives every kind of write, reads every holding, entry and part answer at one clock before and after each, and fails on any change that wasn't named. What marking costs a blob-backed cache's writes (BenchmarkChangeMarks, three runs each way): a row 7 to 13% more, a merge commit's hold 7% (the whole merge 1%), a metadata prune 27%, a collected holding 40% (1.5 to 2.1 µs). An engine's own merge, prune and collection benchmarks don't differ beyond their noise.

Records travel as their sender holds them

Inside a bundle, a record (its own number, its payloads' references and its call frame's) now names rows by the sender's own entry numbers, exactly as the sender holds it; everything else in the bundle still names rows by ordinal, and the receiver maps a record's references through the bundle's table of sender numbers. So the remote cache service sends stored records without decoding, renumbering and re-encoding them, and an engine's export no longer rewrites them either. The references a stored record names are collected in the walk that already normalizes it. A record naming a number outside its bundle is refused.

The bundle format goes from version 7 to 8 (valueBundleVersion), so engines and the service move together: an engine and a service of different versions refuse each other's bundles, so every remote cache lookup misses and nothing is stored, and no pipeline fails. No saved store format changes.

In four simulated pairs of test-base, read up to its tests' start, against the same engine without the change: the service built a record in 0.054 ms instead of 0.081 ms (34% less), and a fresh engine received 102,032 records in its first 10 s instead of 77,043 (32% more); the fresh engine's gap to warm at the tests' start stayed within the pairs' spread, and a same-commit rerun was served whole. A round trip from an engine through the service to a second engine leaves the second engine's state identical, entry by entry, to the previous format's. The two new format tests fail without the change.

A blob-backed cache holds its stored records compressed

Only on dagql's blob-backed cache, the kind that stores entries for remote engines: each stored record's envelope is held as zstd-compressed transfer-form JSON, beside the facts its readers need without it (the entries its references name, and the parts it declares absent or pending), and the normalized copy it also kept of each record goes. Part answers and pricing never decompress a record; a bundle carries the compressed bytes and its JSON encoding writes them out byte-identical to the uncompressed form, so building a bundle neither decodes nor encodes a record. A merge installs a record whole as before, and a background worker compresses it afterwards, outside every lock. Saves write records compressed and restores read them back without decoding. The call frame stays decoded. Such a cache saves under a store format name of its own, so its existing store is wiped once; engines' own caches, their schema version and their stores don't change.

In simulated runs against the same line without the change: the cache's live heap at rest fell from 15.8 to 11.0 KB a stored record (one pair), building a record took 39% and 43% less (two pairs), a fresh engine received 38% and 45% more records in its first 10 s, and the fresh engine's gap to warm before the tests stayed within the pairs' spread. On a whole pull request's restored store of 137,601 records, a record once priced went from 24.7 KB (17.2 KB as restored) to 13.3 KB, pricing every root cold from 40.0 to 4.4 s, and the restore from 8.5 to 6.0 s. Three new tests fail without the change.

A stored bundle's price counts the outputs a merge's message carries

When the remote cache service places stored records on a fresh engine, it sends them as merges, each under a 64 MiB message limit, and decides what goes in a merge from the stored sizes dagql's blob-backed cache gives it. Those sizes counted only records. A merge's message also carries its outputs: each stored part's chain, its packs and its download addresses. One root's closure of 17,000 to 35,000 records came to 71 to 137 MB, so its merge was built, its addresses signed and its message encoded, then refused as over the limit and split, sometimes more than once.

StoredSize.OutputBytes now prices the outputs as the message carries them after ShareChainLayers: each closure entry's own stored parts without their layers, each layer the bundle doesn't list yet, and an allowance for each download address (one for each blob, and one more for each output that names a blob in another pack). Each stored part's and each layer's wire size is computed once, when the cache first holds it, and parts are priced in the order a bundle adds them. Cache.StoredLowerHalf gives the split a refused merge gets, the lower half of a root's closure, its kept calls' inputs included, so the service can split a root before building its merge. Two things stay unpriced: parts an entry borrows from another entry of its class, and kept calls' encodings. A merge refused as over the limit is still split, as before. An engine's own cache doesn't reach this code.

In two simulated pairs of test-base after an edit, on fresh engines, a fresh engine received about 24% more records in its first 10 s, sat idle a third less, and no merge was refused. The check itself was unharmed: the gap from fresh to warm on its binaries was 2 s smaller over the two pairs. These runs measured the version before review, which then made the price count every address of a blob held in more than one pack, made the lower half count kept calls' inputs, and priced parts in the bundle's order. Four tests fail without the change: TestStoredSizesPriceOutputsAsTheWireCarriesThem, TestStoredLowerHalfIsTheFirstHalfBelowTheRoot, TestStoredLowerHalfCountsWhatABundleOfTheRootCarries and TestStoredSizesAllowForEachAddressOfABlobInDifferentPacks.

A prune can keep from freeing far more than it needs

A prune removes roots oldest first until it has freed enough. When most of a cache is one closure that many roots share, as a remote cache's store can be after a check, the root that releases that closure can free nearly everything: one store went from 142.3 MB to 2.3 MB against a 96 MiB target. A prune can now take an overshoot allowance (CachePrunePolicy.OvershootAllowance, and WithOvershootAllowance for PruneMetadataEstimate): a root whose removal would free more than the prune needs plus the allowance is passed over and the next oldest is tried, and if passing over can't get under the maximum, the prune runs plain oldest first, so everything stays prunable. Engines pass no allowance, so their prune is unchanged. In three simulated pairs of test-base after an edit, a 128 MiB store fell under 50 MB in 12 of 28 prunes without the allowance, three times to empty, and in none of 33 with it; replaying 14 stores saved just before real prunes, it collapsed none where the plain prune collapsed 6. A test checks that a root passed over leaves no trace of its simulated release.

A merge prepares its records' payloads in parallel

Every merge into a cache prepares each record with its payload (decoding it, validating its references and relocating them) before it takes the graph lock. That ran one record after another; it now runs on up to GOMAXPROCS goroutines and applies the prepared records in dependency order. A merge that refuses records reports the first refused in that order, and a cancellation answers as before; nothing under the graph lock changes. An engine's merge of its image's built-in entries at start went from 0.84 to 0.41 s, so every engine boots about 0.4 s sooner, and the remote cache's merges into a busy engine cost 23–27% less per 1,000 records in simulated pairs. Across four simulated pairs a fresh engine's gap to warm up to the tests' start showed no slowdown (mean -0.5 s, from -7.1 to +2.8 s). TestMergeValuesPreparesPayloadsInParallel fails without the change.

An export at an engine's stop builds its chains together and frames large layers

A File's own-content chain in an export used to build alone, one after another, before the other chains began; it now builds alongside them under the same build gate, and none begins after another has failed. The export's last step finds each output's owners once per row and routes only parts a chain walked (3.0–3.6 s at a test-base seed's stop to 0.13 s); the bundle is unchanged, which a golden test checks at one and eight CPUs. Parts that are the same File share one chain. The remote cache's exports (only exportRefConfig sets compression.Config.Framed) compress a zstd layer over 8 MiB as fixed 8 MiB frames, four at a time: the bytes depend on the content alone, and blobs grow 0.7–0.8%. In the simulator, one run each, a seed stop that carried the big content went from timing out at 20 s with two blobs unstored to 14.5 s, all content landed, and a 365 MB layer from 7.15 to 4.62 s.

Every zstd layer, not only the remote cache's. Every zstd layer the engine writes is now framed above 8 MiB, not only the remote cache's exports, so a zstd image published by the new engine gets new digests, once, for those layers; a layer that already has a blob keeps it, and every zstd reader, older engines and containerd included, reads them as before. compression.Config.Framed is gone: a layer of up to 8 MiB is one frame with its size, byte for byte as before, and gzip and uncompressed layers don't change.

Once after upgrading: a zstd layer over 8 MiB that the engine compresses gets new bytes and a new digest, so its first export or publish after this change uploads it again; blobs already stored stay valid.

A blob-backed cache's remote writes can apply in one hold of its lock

A caller that keeps a blob-backed cache, such as the remote cache service, can now apply many remote writes in one hold of the cache's write lock (Cache.HoldRemoteWrites), instead of one hold per write. Readers that walk the cache hold its read lock for their whole walk, and a writer waiting for the lock stops new readers, so each write waited for every walk in progress. In a service test, 2,000 telemetry rows applied beside such readers went from 65 a second to about 110,000; with no readers the cost is unchanged. The hold's methods (AttachRemoteHolding, UpdateRemoteHolding, AddRemoteHold, ObserveRemoteRetention, ReleaseRemoteSession, ReleaseRemoteCache, CollectRemoteHoldings, and the reads RemoteHoldingInfo, HolderClosure and EntryClassEntries) run the same code as the Cache's own and return the same changes; TestRemoteWritesApplyAsTheCacheDoes checks that on a scripted series, and TestRemoteWritesHoldTheCache that a hold keeps readers out until Release. Engines don't use it.

The rules for a caller: while a goroutine holds a RemoteWrites it calls nothing else on that Cache, only the hold's methods, since the Cache's methods take the same lock; it calls Release exactly once and doesn't use the hold afterwards; Release runs what the hold's collections released after the lock is dropped and returns their error, so a hold's CollectRemoteHoldings doesn't report those itself; and a hold keeps every reader waiting for its whole length, so it stays short.

Cache.ApplyMergedReply is split into checks and preparation before the lock and a locked body, and RemoteWrites.ApplyMergedReply runs that body inside a hold, so a run of merged replies takes the cache's write lock once instead of once per reply. Behaviour is unchanged: a test runs merged replies through the hold and through the Cache one by one and requires the same change and holdings.

A blob-backed cache holds stored call frames compressed, and a prune names only what it removes

A prune no longer computes a call label for every prunable entry under the graph lock, only for the entries it removes, which are the only ones it reports or logs; the report and log name the same calls. BenchmarkCachePruneSnapshot/disk, four interleaved rounds: 547 to 483 ms for 200,000 entries and 3.48 to 3.09 s for a million (11–12% less), one allocation fewer per entry. On a blob-backed cache only, each stored record's call frame is held compressed inside its compressed body with its recipe digest, and no decoded copy is kept: on a whole pull request's store of 137,601 entries the live heap at rest fell from 13.6 to 8.0 KB a stored record (three runs), building every root's bundle took 4m07–4m25 instead of 5m12–5m43, and every bundle, size and saved row was byte-identical. A restore compresses the frames at its end (about 1–2 s, 0.3 GB more allocation; live heap after restore 3.44 to 1.88 GB on the largest store). The saved format, the bundle's JSON and engines' stores don't change.

A merge's commit warms its targets in a few holds of the graph lock, and a holding's closure is read in pieces

A merge's commit warmed each target's parts with two write holds of the graph lock per target; it now takes many targets in write holds of 256, each checked and owned exactly as one is taken alone, and skips targets whose capture is current, so N targets take the write lock 2x(N/256, rounded up) times instead of 2N. Nothing decided or reported changes; tests compare against warming one by one, including a target changed between prepare and commit. A holding's closure (HolderClosure) is walked holding the read lock for 1,024 steps at a time, letting writers in between; a walk restarts if that engine cache's holdings or dependencies changed between pieces, so its result is always one state's closure, and after three tries it walks in one hold. A merge's reply also counts its records by what the commit did (MergeReply.Rows) and times its targets' warming (MergeReply.Warm). On a whole pull request's fill, the closure walks had held the read lock for 150 s, up to 2.45 s at once; on a replay of a kept fill against its rerun's same six minutes, the worst export reply took 3.6 s instead of 27.0 s and lookups' median wait 9.3 s instead of 11.8 s.

A save encodes each row just before writing it

dagql's whole save encodes each result's row just before its insert and lets it go once written, instead of holding every row's encoding until the transaction commits; the saved store is identical row for row. On an engine's 26,087-result store the save's rise in live heap went from 80 to 36 MiB (2.71 vs 2.89 s, one save each, within noise); on a blob-backed cache from 1,284 to 313 MiB (137,601 results, 1.86 GB) and from 2,541 to 577 MiB (224,298 results, 4.26 GB), save time within about 3%. TestCachePersistenceSaveHoldsOneRowEncodingAtATime and TestCachePersistenceFailedSaveKeepsPreviousSave.

A ranged chunk that fails on the network fails the read

A large offered blob is read in parallel ranged chunks; a chunk whose request failed with a network error, or whose response broke off, was requested again up to twice. A failed read is already handled (the install fails as a content failure, that source is dropped for the demand, and with no other source the engine computes the part itself), so the retry only made a failing blob store look like a working one and held the install while it did. A chunk's network error now fails the read without a retry (a read goes in order, so it can still finish the chunks before the failed one first). The renewal of an address the store refused (401, 403, 404, 410) is unchanged. Two tests fail without the change.

Imports waiting on a shared download, or a shared read of a pack, that failed now fail with it instead of downloading again. A blob-store failure is a content failure, so the source is dropped and the engine computes the part itself; a failure of the engine's own content store fails every import waiting on it, without a second attempt. A waiter fails with the shared download even when its own offer names another address for the blob; the engine then computes the part, rather than downloading it a second time. Three tests fail without the change.

A blob-backed cache doesn't re-teach an identity it already holds

Applying a remote telemetry row whose call identity a blob-backed cache already holds now skips the identity's rewrite, about three rows in four in a fill or a rerun; a read-only check of the same kind the local cache uses for repeat hits (hitTeachesNothingLocked) finds them. On a replay of a whole pull request's fill, applying rows took 39% less time, the cost having been a class merge that changed nothing and its congruence repair. Nine replayed slices of three pushes (18.4 million rows) ended identical at all 44 checkpoints. It removes work only; an engine's own cache is unchanged.

A merge renumbers its records before its commit takes the graph lock

A merge's commit decoded and re-encoded the records it moved under the graph lock. They are now renumbered before the lock, in parallel, and the commit takes each only if every number it used still holds, renumbering under the lock as before otherwise; the cache ends in the same state. In two simulated pairs, a commit held the lock 26.4-26.7 ms instead of 35.0-38.6 ms per 1,000 records, its longest hold 313-356 ms instead of 514-531 ms, and a fresh check's summed waits on the graph lock 4.7-4.8 s instead of 6.9-8.3 s, with its critical-path share unchanged within noise. TestMergeValuesRelocatesBeforeTheGraphLock fails without the change.

An idle engine's export builds its layers on all its cores

While no session is live, as when an engine is stopping, an export's layer blobs build on runtime.NumCPU() slots through a gate of their own, instead of 4 engine-wide; compression is unchanged, so the blobs are the same. A stopping engine's last export had built 113 layers four at a time in 8.5 s on a ten-check stack, and its last blob upload was cut at the 20 s bound. TestExportLayerBuildsWhileNoSessionIsLive fails without the change.

A session that is tearing down now counts as idle for build slots, since a stopping engine's last export was asked 0.6 s into the session's teardown and still built four layers at a time; with the change it built about ten at once. The settle and its 20 s bound are unchanged. Each layer an export builds also logs export layer built at debug level, with its blob, size, raw size, diff start and ready time (reused layers log nothing), to measure what uploading a stopping engine's ready blobs while its other layers still build could save. The remote cache export's log line also gains bundle_passes, bundle_known, bundle_check, bundle_settle, bundle_recipes and bundle_values, the steps of the capture's bundle phase summed over its passes: on a whole pull request's fill, test-base's stop export spent 3.3 s in that phase, against 0.2 s on a ten-check stack, and the line couldn't say which step.

A zstd layer's compression keeps its encoders and buffers between layers

Each layer an engine compressed with zstd made a new encoder, with its tables and a history of up to 16 MB for each encoder that compressed a frame of it, and new 8 MB buffers for every frame. An engine exporting to the remote cache compresses thousands of layers in a check: with it on, test-base's engine allocated 341 GB against 70 GB with it off, most of it there. The encoders now go back to a pool, by level and framing, once their layer is written, and the frames' and held layers' buffers to pools of their own. Each frame or stream an encoder starts resets its state as a new one would, so every blob is byte-identical, which the tests pin against what the writer made before; an encoder whose layer failed isn't kept. For every engine, compressing layers allocates far less, so the collector has less to do.

A stored-size walk reads in pieces

StoredSizes walked each root's stored closure in one hold of the graph's read lock, which reached seconds, and every writer waited behind it, including an upload's part writes. It now reads in pieces of 1,024 steps, as a holding's closure does, and also lets the lock go on the way back up a deep closure. Each entry is read whole within a piece and re-read by its number after a yield. With no concurrent write a walk counts exactly what one hold would; a walk that spans a write counts each entry as the cache held it when the walk reached it. Two existing tests now prove the lock free by taking it for writing.

An upload's stored parts take the graph lock once

A blob-backed cache stored an upload's parts one call at a time, each taking the graph lock for writing on its own and waiting for whichever reader held it then. On a whole pull request's fill, an execution trace caught 238 such waits in 5 s, 0.5 s in all, 72% of it behind the walk that counts a root's records; near engines' stops, applying uploads waited seconds. SetStoredParts now stores an upload's parts as SetStoredPart stores each, in order, under one take of the lock, answering each part as it would have been answered alone; SetStoredPart is its one-part case.

A call names the cached call it was made under

Each cached call's telemetry span now names, as dagger.io/cache.caller, the recipe digest of the nearest enclosing reported cached call, including through a module function's calls back into the engine, and a remote cache lookup's miss carries the same (LookupMiss.Caller, JSON caller, left out when empty). A process in an exec also makes its calls under the exec's call: before, a process inside an exec made its calls with no caller unless the exec was a function runtime's own, which left a whole pull request's test-base engine naming a caller on 14,469 of 286,270 call rows; an exec now captures the cached call it was made under, and its nested client makes the process's calls under it (TestEngine/TestNestedExecCallsNameTheExecAsCaller). An exec loaded from the cache names none, as before. The remote cache service uses it to send a check's results top-down by call depth, and one level deeper where an engine misses. No cache decision changes.

A blob-backed cache answers entries' facts without describing their holdings

A caller that needed only an entry's stored facts, or those and a few of its holders' keys, read EntryInfo, which describes every engine's holding of it. Cache.EntriesHeld(numbers, limit) answers those for many entries under one hold, in EntryInfo's order, and describes no holding; the remote cache service's absent-part marks and lookups read it. A test checks that it answers as EntryInfo does. Cache.EntriesFacts(numbers) likewise reads entries' own facts (number, whether stored, expiry, sorted recipes) without describing any holding, through the same code RemoteHoldingInfo uses, and a test checks it answers as that does.

An export leaves out a running root at once, and a merge can leave a root unretained

A root whose own evaluation is in flight can't be captured whatever its closure holds, but the capture still walked its whole closure under the graph lock and copied every record below it before leaving it out: on a ten-check stack's test-base engine, each of the remote cache service's 13 asks for a running test's root took 2.7 to 7.1 s, 57 s in all, while the tests ran. The capture now reads each root's lazy state before the walk and leaves such a root out busy at once, with nothing below it walked or copied; a root the selection already knows still goes as a held row. The one difference in what is exported: an output selected only below such a root is now left out with it. Separately, PreparedValueMerge.Unretained(ordinals...) lets a merging caller give chosen bundle roots no retention edge. Each has a test that fails without it.

A merged reply can apply to a blob-backed cache in pieces

PrepareMergedReply and RemoteWrites.ApplyMergedReplyPiece let the remote cache service apply a large merged reply a bounded number of records at a time, letting the cache's readers in between pieces; a reader between pieces sees fewer of the engine's holdings than it has, never wrong ones, with dependencies still to come shown as unknown. The whole-reply path behaves as before. A merge reply's hold of the cache's lock had reached about 1.2 s with 30 readers waiting. On a whole pull request's rerun with the change, 653 of 3,062 merge replies were over 512 records and went in pieces; the longest single hold over the fill and the rerun was 146.1 ms, and goroutine dumps that caught a merge reply's hold showed 2 and 4 goroutines waiting on the lock. An entry also keeps its kept calls' grouping by term until its calls or an input's class change, so pricing a root again with nothing changed doesn't group them again.

The collection after a session ends waits for the remote cache's settle

With the remote cache attached, the containerd collection the engine runs after a session ends now waits while the engine settles with the service: no session live, and the idle period neither settled nor timed out. The settle's own bound limits the wait, with no timer of its own; without the remote cache, or once settled, the pass runs at once, as before. That collection holds containerd's metadata write lock and then the snapshotter's lock while it removes what the session released, and the stop's last export needs both for its lease writes and diff mounts. On test-base's stop on a ten-check stack, the export's chains took 0.50 s instead of 3.9 s (about 2.7 s of which had waited on a collection removing 42,475 snapshots), its capture 2.33 s instead of 7.6 s, and the time from the session's end to the last export landing 4.1 s instead of 9.4 s; one run each, on different hosts. A test fails without the change.

An engine restores its check's own results from a file when it connects

When an engine is claimed for a check, the remote cache service can now tell it to fetch and merge a file of records the service published, instead of placing those records one merge at a time. Today the service builds one small file per check, its own results, and the engine restores it when it connects. A set file is a JSON header line followed by parts, each one zstd frame of a closed bundle with its layers listed once and no download addresses, which come in the restore message. The engine downloads a file as soon as the restore arrives, checks its size and digest, and merges its parts one at a time through the same path as a merge (RestoreValues), behind the merges that answer lookups. The engine's code can also restore a check's whole set, in parts merged on a lane of their own, with roots a later part carries merged unretained and held until the file ends; restoring whole sets is not part of this PR's behaviour yet, since the service doesn't build those files outside trials. Each part is decoded with a decoder of its own, closed once the part is decoded (a shared one had kept 236 MB of an engine's heap in such a trial). An engine's hello lists the files it merged whole, so a reconnect isn't offered them again, and an engine refuses a file of another bundle version before decoding any part.

To send only what changed after a file was built, a blob-backed cache's entries keep the count of the last write that changed what a bundle of them carries; a bundle returns the count it was built at (Position), and ChangedSince says which entries changed since. A recipient's HeldBy.Also names entries it holds from a restored file before its own rows name them, which a bundle then carries as held rows. A merge's reply says which records its commit stored. Each entry keeps the cause of its last change, for diagnostics (StampCauses), and the stop event counts the parts read with no source, by reason.

A merged chain of mounts is copied once per mount

Natively, a container's part is copied from the nearest layer below it that doesn't pass the part through, so through a chain of n mounts each mount is copied once. The walk stopped at the first container with an acquired output, one merged from another engine's record or with an offer installed on it, so past that point each mount was fetched through every layer above it: about n³ work. On a CI engine with the remote cache, the exec of dagger/go's module proxy, a chain of about 571 withMountedDirectory calls, stopped the engine serving requests, and two checks were cancelled at their time limit. Concurrent demands of one row's parts also refused each other's source scans, about n² times (7,102 scans at the top of a merged chain of 64 mounts). The walk now goes through such a container where its recorded operation routes the part to its own copy group, and never past a merged import or builtin container; scans of one row take turns; and a merged row's record is decoded once per payload, not once per pending part. In the tests: 64 merged mounts took 48,654 lazy tasks and 5.6 s before, about 500 tasks and 0.3 s after; 571 merged mounts never finished before and take 16.6 s now; 585 mounts an engine built and then had offered, about 15 s; a natively restored chain, about 1 s.

A content digest taught after a record was stored travels with it

On an engine, a result's content digest goes on its own frame, which an export carries. On a blob-backed cache, a content digest a later span reported was taught to the entry's class only, and the record it sent kept its frame as stored, so a fresh engine held that record apart from its own result of the same content and every call over it ran again (on a docs-only edit, Go.module over the engine-dev workspace and everything over dagger/go after it). The entry now keeps the digests its spans teach it, in order, and the stored-body worker gives its frame those digests off the lock, as an engine would; a replaced, pruned or restored entry keeps them as an engine's would, and a cache's save keeps them in a result_taught table (the store's schema version doesn't change). A pruned entry's taught digests go with its value, since another engine's run of the recipe may have other bytes. A rewritten record's size grows with its frame. A record also carries the content-preferred digest its engine computed, so a fresh engine names a service as its producer did instead of giving it a new hostname, and every call below the service no longer runs again; a row whose identity the cache already holds still records a re-taught digest for its frame. TaughtContentStats counts what the rewrites did.

Blob-backed cache holdings

  • Holdings take about a third of the memory. A holding's sets (dependencies, sessions, parts) are now sorted copy-on-write slices, its repeated strings unique handles, and an entry's holders one sorted slice. On a whole pull request's telemetry (1.13 million holdings), about 735 B a holding instead of about 2,440 B, 1.93 GB less live heap at the peak, and a row 4–8% faster; every holding reader answered byte for byte the same over the whole fill. HoldingFacts reads a holding's facts.
  • HolderEntry reads which entry a holding sits on without describing the holding, which a telemetry row needs on every apply.
  • An entry is keyed by its own recipe only. A call answered with an entry of another recipe also made its request digest a key of the recipe index, which an engine's cache never does; rows above it then landed with frames naming another recipe and were answered stale again after every full merge (151 refusals for one engine on a whole fill). The request digest stays an equivalence only.
  • An engine's held row teaches the cache its holding when the row's recipe has a live value, instead of being refused as stale until the engine's telemetry named the holding.

An entry's parts reach the remote cache when a span could only report some

When a span's read of an entry's complete parts couldn't read its record (another read held it), it reported only the parts already settled, and nothing reported the rest: the remote cache took the engine to lack them, never asked for them, and a part only that engine held was never stored. Such an entry now owes a report of the parts its spans left out, with their raw sizes, made once its record can be read and at close before the cache refuses reads; a later span that reads the record settles it. Each fallback is logged at debug.

An export's stale refusal forgets only the rows it names

When the remote cache refused an export as stale, the engine forgot every row that export held, so its next export carried them all in full. On a whole pull request's fill, test-base's engine had 40 such refusals and its held rows fell to a few hundred; a test run's 44,000-record export then no longer fit in a message, and 16 test runs were never stored. The refusal now names the stale rows (protocol.Upload.Stale, KnownRows.Stale), and the engine forgets only those.

Less work encoding and keying

  • A merge's message is encoded once, in place (MarshalJSONTo, EncodeEnvelope): a merge of 2,000 records allocated 10.3 times its message before and 2.5 times after.
  • A plain part address (fs, metadata) is keyed without the JSON encoder, byte for byte the same key: a fresh engine's call row attached in 8.7 µs instead of 10.3 µs on recipes others already hold.

Diagnostics

  • While wcprof records, an engine logs its own CPU every 10 s by kind of remote cache work (merges, captures, layer diffs and compression, sends, lookups, part fetches), from pprof labels the remote cache's goroutines now carry; the sampler yields the profiler to wcprof's own profiles, and nothing samples while wcprof is off.
  • At its remote cache's stop, an engine logs what fetching parts ahead downloaded and how much of it an install read, released unread or still held, split by tenth of the order its offers were accepted in.
  • A lazy evaluation's install-span walk reads the graph lock as a profiling step of its own, dagql.installSpans.walk, empty when nothing records.
  • The rebuild of a part no source supplies logs how many of the entry's other parts stay from the first execution and how many merged entries depend on it.
  • A read in pieces lets go at its end only of a hold it has, so a check failing between pieces no longer unlocks an unlocked lock and crashes the test binary; the blob cache usage's piece test runs with the stored-body worker stopped. The service tunnel tests overlap their two clients and keep their services listening.

A blob cache's usage reads in pieces

A blob-backed cache's usage (BlobCacheUsage), which the remote cache service asks for on every status request and metrics scrape, walked the whole pool in one hold of the graph's read lock, about 0.3 s per walk on a whole pull request's rerun, and every writer and the readers queued behind it waited. It now reads in pieces of 1,024 steps per hold, so a writer waits for one piece. The unread RecordBytes field goes with its walk of every entry.

Removing the remote cache test fixture

The remote cache's cross-engine tests now run against the real service, in the remote cache service's own end-to-end suite, so the test-only machinery that simulated it here goes:

  • the Query._remoteCacheFixture field and its _DAGGER_TEST_REMOTE_CACHE_FIXTURE_ROOT environment gate;
  • the cache's observation hooks that only the fixture used;
  • the fixture's integration suites (the remote cache transfer and module-definition suites) and the testModuleDefinitions CI check.

For users: nothing changes in an engine that has a remote cache, and there is no runtime cost. An engine without one no longer turns on early snapshot sharing when the test variable is set: sharing now needs a real remote-cache integration. The core schema loses a field that only a test variable switched on.

Tests that never used the fixture move: ChangesetSuite.TestMergeConflictAtCall and CacheSuite.TestImageEntriesAreUncompressed. Package tests that observed through the fixture now read the cache's debug snapshot, the snapshot manager or the engine's logs instead. The generated-client tests in GeneratorsSuite read the nested engine's cache snapshot.

Not covered end to end after this change:

  1. LLM tools bound to an object from another engine, on a client that never served its module. Schema selection is unit-tested, and cold-engine LLM restore is tested here, but neither goes through tool dispatch on an imported object.
  2. A real exec's metadata computed by a private run over a downloaded filesystem. The mechanism is covered by package tests.
  3. An engine that ships image entries receiving remote cache results. Package tests cover the merge rule.
  4. Two engines of different default platforms exchanging a module function result. The platform input is covered at package level, above.

A session-release timing margin in a dagql test

TestCacheReportsPartsRead checked, right after ReleaseSession, that the released entries' reads were forgotten, and failed on CI with all three still held. ReleaseSession returns before its cleanup when another operation of the session is still ending: a lazy evaluation's goroutine completes its value, which lets the caller go on, and only then finishes its session operation, which runs the release's cleanup. Under CPU contention with -race, 58 of 50,000 runs found the entries still in the cache with their reads, and none once the release had completed, so it's a timing margin, not a leak. The test now waits for WaitSessionRelease, the release's completion: 0 of 50,000 under the same contention. This change is test-only.

History

This PR first carried the whole remote-cache engine line. That line reached main through #15080, and its decoder reuse test fix through #15123; after rebasing onto main this PR holds only the changes above, and further fixes join it as they are ready.

@sipsma
sipsma marked this pull request as draft October 23, 2026 05:07
@sipsma sipsma changed the title remotecache, wcprof: time and profile the remote cache, images and nested clients remotecache: speed up fresh engines, and record where their time goes Oct 23, 2026
@sipsma
sipsma force-pushed the sipsma/remote-cache-timing-wcprof branch from 58ea590 to dc4f3b4 Compare October 29, 2026 20:44
@sipsma sipsma changed the title remotecache: speed up fresh engines, and record where their time goes remotecache: send fresh engines what they lack, and record where their time goes Oct 29, 2026
@sipsma
sipsma marked this pull request as ready for review October 29, 2026 20:45
@sipsma
sipsma force-pushed the sipsma/remote-cache-timing-wcprof branch 3 times, most recently from ffa3d7f to c249eb2 Compare November 5, 2026 07:19
@sipsma
sipsma requested a review from a team as a code owner November 5, 2026 07:19
@sipsma sipsma changed the title remotecache: send fresh engines what they lack, and record where their time goes remotecache: give a fresh engine what a warm one has, sooner and for less Nov 5, 2026
@sipsma

sipsma commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

This branch was rebuilt as the whole remote-cache engine line on current main; it replaces the earlier 69 commits, which are all inside it, now as its first group.

sipsma added a commit that referenced this pull request Nov 5, 2026
…er's signatures

#14828's module path test still passed a context to the comparisons this
branch stopped giving one, and the engine/client test connector lacks the
ClaimID method #14828 added.

Signed-off-by: Erik Sipsma <[email protected]>
sipsma added a commit that referenced this pull request Nov 5, 2026
…er's signatures

#14828's module path test still passed a context to the comparisons this
branch stopped giving one, and the engine/client test connector lacks the
ClaimID method #14828 added.

Signed-off-by: Erik Sipsma <[email protected]>
sipsma added a commit that referenced this pull request Nov 5, 2026
…er's signatures

branch stopped giving one, and the engine/client test connector lacks the
ClaimID method #14828 added.

Signed-off-by: Erik Sipsma <[email protected]>
@sipsma
sipsma force-pushed the sipsma/remote-cache-timing-wcprof branch 2 times, most recently from 9d8892c to 5f7d58e Compare November 9, 2026 20:48
@sipsma sipsma changed the title remotecache: give a fresh engine what a warm one has, sooner and for less core: never serve a module function's result to an engine of another CPU architecture Nov 9, 2026
@sipsma
sipsma force-pushed the sipsma/remote-cache-timing-wcprof branch 3 times, most recently from 29c7b52 to 0b9a9ac Compare November 10, 2026 19:32
@sipsma sipsma changed the title core: never serve a module function's result to an engine of another CPU architecture engine: scope module function results by CPU architecture, and free cache-volume space below the reserve Nov 10, 2026
@sipsma
sipsma force-pushed the sipsma/remote-cache-timing-wcprof branch from 46cc920 to e9951a1 Compare November 11, 2026 00:28
@sipsma sipsma changed the title engine: scope module function results by CPU architecture, and free cache-volume space below the reserve engine: scope module function results by CPU architecture, free cache-volume space below the reserve, and remove the remote cache test fixture Nov 11, 2026
@sipsma sipsma changed the title engine: scope module function results by CPU architecture, free cache-volume space below the reserve, and remove the remote cache test fixture engine: remote cache fixes — relocate module source references, fewer lookups, module results per CPU architecture, cache-volume GC — and remove the test fixture Nov 11, 2026
@sipsma sipsma changed the title engine: remote cache fixes — relocate module source references, fewer lookups, module results per CPU architecture, cache-volume GC — and remove the test fixture engine: remote cache fixes — relocate module source references, fewer lookups, exports without the Cloud's offers, module results per CPU architecture, cache-volume GC — and remove the test fixture Nov 11, 2026
@sipsma sipsma changed the title engine: remote cache fixes — relocate module source references, fewer lookups, exports without the Cloud's offers, module results per CPU architecture, cache-volume GC — and remove the test fixture engine: remote cache fixes — relocate module source references, fewer lookups, exports without the Cloud's offers, module results per CPU architecture, faster cache-volume collection — and remove the test fixture Nov 11, 2026
@sipsma sipsma changed the title engine: remote cache fixes — relocate module source references, fewer lookups, exports without the Cloud's offers, module results per CPU architecture, faster cache-volume collection — and remove the test fixture engine: remote cache fixes — relocate module source references, fewer lookups, exports without the Cloud's offers, module results per CPU architecture, faster cache-volume collection, graph-lock profiling — and remove the test fixture Nov 11, 2026
An engine claimed for a check is told, by restore, where the service
published the check's set files: the head, its own results and what its
runs used before them, and the whole set. It downloads each as soon as
the restore arrives, checks its size and digest, and merges its parts one
at a time through the path a merge takes, behind the merges that answer
lookups, with the rows they land on known to the connection. Each part is
decoded, given its download addresses from the file's table and merged
before the next is decoded. Heads and wholes merge on lanes of their own,
each in arrival order, so a head never waits for a whole, even another
check's that started first.

Nothing in a restore fails it or the engine: a file that can't be
fetched, isn't the file named, is of another bundle version, or has a
part that doesn't decode or merge leaves what merged of it, and the reply
says where it stopped. A download the store stops sending is given up as
a part's read is. A file the process merged whole isn't fetched again,
and each hello names it.

The engine's stop event says, for each file, when its restore arrived
and its download ran, each part's records, commit, wait for the cache's
lock and hold of it, the process's peak memory around it, and how many
lookups had missed before a part committed that it would have served:
each miss now carries its time, and the cache redoes its lookup on the
entries the part landed on. The count is an upper bound of the misses a
connection keeps, the newest 16,384; the stop event says how many it
dropped uncounted. A merge's reply now says how long its commit waited
for the lock. The stop event also carries the process's peak memory.

Signed-off-by: Erik Sipsma <[email protected]>
A restore's lane kept one zstd decoder for its connection, and the
decoder kept the last part's decompressed bytes: after a part's last
compressed block, the block decoder it keeps for reuse still points into
the part's output. On an engine that restored test-base's whole set that
was 236 MB, for as long as the engine was connected, and about 400 MB of
the restore's peak. Each part is now decoded with a decoder closed once
the part is decoded.

Measured on test-base's real file restored through a session: 236 MB of
heap left behind before, none after. A synthetic part shows it only when
it is large enough and its last block is a compressed one, 380,000
records here, which takes 90 s under the race detector test-split's
package run uses, so the check isn't kept as a test.

Signed-off-by: Erik Sipsma <[email protected]>
The service cuts a whole set into parts of bounded size, and a root
whose closure alone exceeds the bound has its closure sent first, in parts
of its own, with the root in the last. Those records are no root of their
own: the engine merges them unretained, as the part's header says, and a
later part names them as held rows. On an engine an unretained root is
released at the end of its own commit, so the hold must be the commit's:
RestoreValues now takes a part's unretained roots and holds every entry
its commit lands on, before it collects anything, until the reply's
Release. The restore keeps each part's release until its file ends, by
completing, by a part that stops it or by the connection ending, and then
releases them all, so nothing outlives what the file's roots retain.

Signed-off-by: Erik Sipsma <[email protected]>
A part work reads with nothing to read it from is made again, and the
engine logs each one. With whole sets restored at an engine's start, how
many there were over the engine's life is what says how much content a
restored engine had to make again; the stop event now gives it by
reason: no offer, a download that failed, an offer unavailable, or its
holder busy.

Signed-off-by: Erik Sipsma <[email protected]>
…elease a restore test's hold

A part with no source and no operation of its value that makes it has
its call run again, and isn't logged as a part without a source: the
stop event's count missed it, so an engine could make content again and
report none. It is now counted, as call_run.

A restore's hold is released when the connection ends mid-file too, now
tested beside a completed file and one a part stopped; and the test that
a restore merges as a merge does releases the hold its restore took.

Signed-off-by: Erik Sipsma <[email protected]>
A file's reader sees which of its records changed since the file was
built, not why. Each Cloud entry now keeps the cause of its last stamp:
the write that changed what a bundle of it carries, with whether the
write was to another entry of its class, and kept calls told apart by
whether they give the entry a new term a bundle can send. StampCauses
counts them for a list of entries.

Signed-off-by: Erik Sipsma <[email protected]>
The stop event now carries the engine's peak resident memory and its
restores, so the graceful-stop test compares only what it is about:
that the stop was unclean and saved nothing. commitValueMergeLocked and a
lookup test take the repository's lint exceptions.

Signed-off-by: Erik Sipsma <[email protected]>
@sipsma
sipsma force-pushed the sipsma/remote-cache-timing-wcprof branch from 28cd5a2 to 6399a66 Compare November 14, 2026 03:28
… payload

Decoding a row from its record checks whether any pending part is a
recorded delegation (markRestoredPartDelegation). It routed each pending
part with routePartRecord, which walks the record and decodes its payload
again for every part: a container with k pending mounts decoded its
payload k times, and a merged chain of n mounts decoded about n³/3 mounts
on the way. On a merged chain of 571 mounts demanded at once, that was
most of 73 s.

It now walks the record once and routes each payload's pending parts
together, through a router that decodes the payload once
(PersistedPartsRouter, which core's Container, Directory and File codec
implements with its partRouter). The test checks that routing parts
together gives each part exactly the route and error routing it alone
gives. The merged 571-mount chain now takes 17 s, and 256 mounts 3.7 s
against 7.5 s.

Signed-off-by: Erik Sipsma <[email protected]>
…call

The marker's test codecs count their routing calls: each payload with
pending parts is routed in one batch call, a family without batches part
by part, a failing route doesn't stop the others, and a payload whose parts
can't be mapped keeps the record from marking. Before the batch, the
batch-path cases fail.

A batch routes without write sets: building a part's write set reads
every part of the payload, which for a container with n mounts made each
batch n² again, and the marker reads only delegations. A second test holds
that four times the mounts allocate under six times as much.

Signed-off-by: Erik Sipsma <[email protected]>
…t be mapped

The marker mapped every payload in a first walk and routed in a second,
and its second walk's callback swallowed a mapping error the first walk
had already ruled out, which lint reports (nilerr). One walk now does
both: a payload whose parts can't be mapped ends the walk with its error,
and the record is marked only when the walk completes with a delegation
found, wherever the failing payload is. Payloads after a delegation is
found are still mapped, so a later mapping error still keeps the mark
off; they aren't routed.

Signed-off-by: Erik Sipsma <[email protected]>
The test held the chain's demand to its total lazy tasks and record
captures, which count how often a task runs again, and that depends on
scheduling: on a busy machine 64 merged mounts ran 966 tasks where a quiet
one runs about 500, over the same 385 distinct tasks. It now holds the
distinct tasks, a result and a task key each, which copying each mount
through every layer above it multiplies: on the line, 64 mounts run 4,291
of them, against 385 with the walk through merged layers. The totals are
logged.

Signed-off-by: Erik Sipsma <[email protected]>
…' stamps

A file the service offers is a stored bundle built at one position, and a
record it carries counts as current while no stamp has moved past that
position. Stamps were applied when a write handed its marks back. Two
writes on the Cloud make class marks and hand none back: the body worker
giving an entry's frame a taught content digest, whose identity can join
classes, and a merge taking back an entry whose replaced value failed to
release. Their marks waited for the next write that hands marks back.

So between such a write and the next, a record whose bundle the write had
changed read as current. A placement read in that window left it out, and a
restored engine could keep the record without a part offer it should have
had, and make that content itself: a miss, never a failed pipeline.

Each of those writes now applies the stamps of the marks it made before it
ends. The marks themselves stay for the next write that hands them back, so
what the readers of the changes learn, and when, is as before.

Signed-off-by: Erik Sipsma <[email protected]>
…ck go

A prune drops its retention edges each in a hold of the graph lock of its
own, and hands its marks back only once it ends. A stored bundle built
between two drops read an entry as current though a later drop changed what
it borrows: the walk of a leaving entry's classes was remembered across
holds, so a class an earlier drop had walked was skipped, and by the end the
collected entries named no class to widen to. So a placement read could
leave the record out, and a restored engine keep it without a part offer it
should have had: a miss, never a failed pipeline.

Each drop's hold now applies its stamps before it ends, while its classes
still name their entries, and the next hold walks leaving entries' classes
afresh.

Signed-off-by: Erik Sipsma <[email protected]>
… never other

A merged reply of thousands of records applies in one hold of the Cloud
cache's write lock, tens of milliseconds, while every reader of the cache
waits. The test prepares a reply of twelve records, each over the one
before it and some over the one after, applies it a record at a time, the
hold let go between pieces, and at every gap reads every holding the
reply lands on: each one seen is one the whole reply lands, in its final
value state but for dependencies on records still to come, named as
unknown, and none it hasn't applied yet is seen. At the end the cache
reads as the whole reply leaves it, with the same candidates.

It doesn't build here: there is no MergedReplyApply.

Signed-off-by: Erik Sipsma <[email protected]>
PrepareMergedReply checks and prepares a merged reply, as
ApplyMergedReply does before its lock, into a MergedReplyApply, which
RemoteWrites.ApplyMergedReplyPiece applies at most n records at a time,
in the hold, and the reply's roots' retention with its last records. A
hold let go between pieces lets the cache's readers in. A reader between
two pieces sees the holdings of the records applied so far, each in its
final value state but for its dependencies on records still to come,
which it names as unknown until they land, its dependents, and its
retention: less than the engine holds, never other, so a build that reads
it treats what's missing as not held and sends it. ApplyMergedReply and
the pieces share their body (applyMergedTargetsLocked,
applyMergedRootsLocked).

On a whole pull request's rerun, merged replies ran to 17,412 records,
about 77 ms in one hold at 4.4 us a record.

Signed-off-by: Erik Sipsma <[email protected]>
…s or an input's class change

Signed-off-by: Erik Sipsma <[email protected]>
The second way an engine runs a chain's mounts through every layer: it
builds dagger/go's module proxy itself, the service then merges records
offering the rootfs of those same entries, and installing an offer gives
each container an acquired output, where the native walk stopped. The
test builds the chain on one cache, offers it from another, installs each
layer's offered rootfs, and demands every mount of the top. On the line
before the walk through merged containers, 64 mounts ran 48,312 lazy tasks
over 4,289 distinct; with it, 385 distinct, as for a merged chain. At 585
mounts it takes about 15 s.

Signed-off-by: Erik Sipsma <[email protected]>
…ding

RemoteChange's Entries names an entry whose own facts, holders, classes or
part answers may have changed; the descriptions of the holdings on it
don't change with it. A reader that keeps those descriptions can read the
entry's facts alone, once an entry, instead of each holding's description.
The change's comment said a holding's description is asked again when its
entry is named; its test checks the opposite, that every changed
description is named in Holdings.

Signed-off-by: Erik Sipsma <[email protected]>
@sipsma

sipsma commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

We're continuing to iterate on the remote cache in our own branches, rather than keep this PR maintained. We'll reopen it once everything is ready.

@sipsma sipsma closed this Nov 19, 2026
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