Skip to content

dagql, core, engine: cut allocations in cache state, the schema digest, snapshot namespaces and hot paths - #14989

Closed
sipsma wants to merge 17 commits into
mainfrom
sipsma/engine-allocation-cuts
Closed

sipsma wants to merge 17 commits into
mainfrom
sipsma/engine-allocation-cuts

Conversation

@sipsma

@sipsma sipsma commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Profiling the engine through a cold first build and the edits of dagger's CLI shows it allocating about 4 GiB per first build at the default GC target, and garbage collection is a large share of its CPU. Much of that allocation is the engine redoing work it has already done:

  • re-encoding a value to JSON just to read back a field it already holds;
  • hashing a schema's whole JSON encoding in every session;
  • re-attaching a context's namespace on every call;
  • making a fresh buffer per file or per stream where a pooled one would do.

This PR removes those in four areas, each change its own commit. Measured separately and added up, they save roughly 3 engine CPU-s per cold first build of dagger's CLI, out of about 35. One-line edits get 0.1 s faster. Behavior is unchanged except for the two points under What changes for users.

1. Complete parts from the live value (2 commits)

The engine reports which of a result's parts are complete, on each cache-state span attribute and in result-state queries. completePartKeys worked that out by capturing the result's persisted record, which encoded each object's payload to JSON and copied the record. Then it decoded each payload again, only to read its parts' states. The answer is cached, but each lazy operation that completes changes a part, so most calls found the cache out of date for a real reason. In a cold first build this was 468 MiB, a tenth of everything the engine allocated.

The first commit adds an optional interface in dagql, PersistedPartsDescriber, for an object to describe its parts from its live value.

  • Who implements it: File, Directory and Container. Each builds the payload its encoder builds, with the same code and under the same locks, then runs its family's part mapping and routing on it. Only the JSON, the decode and the record copy are skipped.
  • What's kept from the capture: the result is held and refused exactly as a capture holds and refuses it, including while an evaluation or sync is in flight. Its output versions are recorded before each object is read, and checked after.
  • Fallbacks: an acquired container output, a file or directory with a transfer pending, and a result that hasn't been decoded take the record path, as before.

The second commit removes what was left. Describing a container's parts still encoded its recipe to JSON, and decoded it once per part, to read a single field: for a withExec recipe, whether it replays a volatile exec's cache hit.

  • withExec: its two recipes now build the value they encode in one place. Routing reads the field from that value directly. Building it runs the encoder's checks, so a description fails exactly where encoding would.
  • Other recipes: they're still encoded, and decoded once per container rather than once per part.

2. The schema digest without JSON (1 commit)

The schema digest scopes per-schema calls in dagql's cache keys. It was the hash of the whole schema's JSON encoding: every type, each object again as a possible type and as an implementation, and every description, grown into one buffer. Each session builds its schemas' digests anew, so every dagger invocation paid for it while loading its module, before running any calls. A one-line edit of dagger's CLI spent 112 MiB on it, 7% of all the engine allocated.

schemaDigest now writes each part of the schema straight into the hash, in a fixed order.

  • Framing: every value is written with its length or a presence flag first, so no two schemas write the same bytes.
  • Reuse: each definition is hashed once, and its hash stands for it wherever it appears again.
  • Coverage: it covers every field the JSON encoding held, except positions, which the encoding also left out. A nil list or map hashes the same as an empty one, since both describe the same schema.
  • A guard against drift: a reflection test fills every field of every part of a schema. It checks that changing any one field changes the digest, and that changing a position doesn't. So a field gqlparser adds later fails the test until the digest covers it.

3. Snapshot namespaces and trace log fields (5 commits)

Every call through the engine's containerd wrappers (snapshotter, content store, leases, metadata) called namespaces.WithNamespace. That copies the context's outgoing gRPC and ttrpc metadata, even when the caller had attached the same namespace already.

What changes:

  • One WithNamespace: engine/snapshots now has one, used by every wrapper, and a snapshot walk attaches the namespace once rather than once per call.
  • What it checks: it re-attaches the namespace only when namespaces.Namespace doesn't already find it, which is what the engine's in-process containerd stores (snapshots, leases, content) read. Checking the outgoing headers too would copy the context's whole outgoing metadata on every call, so it doesn't.
  • The proxied snapshotter: the one store reached over gRPC is a proxied snapshotter, configured with proxySnapshotterPath. It needs the namespace on each call's headers, so its client is wrapped to put it there, as containerd's own daemon does for proxy plugins. The wrapper covers every context-taking snapshotter method, and passes Cleanup through, which containerd's metadata store calls after garbage collection.
  • The wcprof ops: each wrapper keeps its op, with the namespace attached before the op begins.
  • ttrpc: nothing in the engine uses it, so it stays an indirect requirement.

The snapshot cache also built its trace log fields on every call. It now builds them only when trace logs are on.

4. Small cuts in hot paths (6 commits, plus 2 test commits)

Each replaces an allocation made per file, per stream or per read with a pooled or shared one:

  • content hashing uses its existing pooled copy buffer, not a new 32 KiB one per file;
  • zip extraction reads entries through pooled bufio.Readers and the zip package's pooled decompressor;
  • the secret scrubber steps its trie without allocating;
  • a client scope's clones share its sealed metadata instead of copying it;
  • reading a result's value no longer copies its snapshot links: every read loaded the whole payload state, links included, and now reads the value alone;
  • container output is copied through a pooled buffer, not a new 32 KiB one for each stream of every exec.

What changes for users

  • Faster builds: the engine does less work, with no change to what builds produce.
  • New cache keys, once: the schema digests change, so calls scoped to a schema get new cache keys, once, at the upgrade.
  • Platformless containers: a container built with no platform used to encode its platform as "unknown", which doesn't decode. So the old part description fell back to the parts already settled. The live description reports the container's actual parts instead. Every container the engine builds has a platform, so only hand-built containers in tests reach this.

Numbers

These come from building dagger's CLI with dagger/go's per-package Go builds, where each package compiles in its own exec.

  • Each run: a fresh engine, a cold first build, its unchanged rebuild, and two one-line edits.
  • Machines: c8gd.4xlarge spot machines (16 Graviton4 vCPUs) in us-east-1, at the default GC target.
  • Not main: each change was measured on a development branch that carries other pending engine changes, against that branch without it. The code each one removes is the same on main.
Change Cold first build Edits
1, first commit (8 paired rounds) −1.5 engine CPU-s, lower in every round, 0.9 of it GC; −275 MiB, −1.5 M objects −0.2 CPU-s on the edit inside dagger
1, second commit (8 paired rounds) −0.5 engine CPU-s, mostly GC; −50 to −55 MiB over a whole run, −0.3 CPU-s, lower in 7 of 8 rounds
2 (8 paired rounds) −0.3 engine CPU-s; −122 MiB both edits 0.11 and 0.10 s faster, and the unchanged rebuild 0.06 s faster, every round; −0.3 to −0.4 CPU-s and −116 MiB per edit
3's namespace attached once per walk, with 4's last two cuts (8 paired rounds) about −0.3 engine CPU-s; −0.15 GiB for the three −0.3 CPU-s on the edit inside dagger
3's check of the context only (4 runs per arm, alternating, plus heap profiles) the namespace helper's allocations 65 → 47.5 MiB, its gRPC metadata copies 28 → 4 MiB; no change in wall time or engine CPU beyond noise no change beyond noise
3's trace fields, and 4's first four cuts (allocation census, with other small cuts: 6 paired rounds) about 350 MiB together; the arm they were part of saved 0.7 engine CPU-s —
  • Wall time: apart from the schema digest's edits, wall time doesn't resolve. The first commit of part 1 was 0.18 s faster on the first build in 7 of 8 rounds, but within the spread.
  • Peak memory: unchanged for every change.

Tests

  • Part 1:
    • For each family, the live answer must equal what capture and decode give, on the persistence tests' values. That covers pending, computed and absent parts, mounts, services, routing failures, and the fallbacks.
    • The capture's refusals, and an output that changes while it's read.
    • Routing from a live withExec recipe gives the same groups, write sets and failures as routing from its JSON, for every recipe kind.
  • Part 2: the reflection test above.
  • Part 3:
    • A context that already carries the namespace, including one with replaced outgoing headers or incoming metadata only, is returned as it is. Any other gets the namespace.
    • A proxied snapshotter is built through the engine's own constructor, against a real snapshots gRPC server on a unix socket. That server must receive the namespace for a bare context, one with replaced outgoing headers, and one with incoming metadata only. The test fails with the wrapper removed.
  • Part 4:
    • a pooled zip decompressor that hit a corrupt entry decodes the next entry whole;
    • container output arrives whole.

The core, dagql, engine, engine/contenthash, engine/engineutil, engine/snapshots and engine/server tests pass on main.

@sipsma
sipsma force-pushed the sipsma/engine-allocation-cuts branch from 9096fbf to b3b980e Compare October 30, 2026 19:02
sipsma added 17 commits October 30, 2026 20:53
poolsCopy passed the opened *os.File to io.CopyBuffer, which hands the
copy to the file's WriteTo when it has one. A hash has no fast path to
take, so WriteTo fell back to a copy with its own new buffer for every
file, and the pooled 32 KiB buffer went unused. Hiding WriteTo makes
CopyBuffer use the pooled buffer, as #14949 did for
ReadFrom in zip extraction.

Signed-off-by: Erik Sipsma <[email protected]>
flate decompresses from an io.ByteReader, and wraps any reader that
isn't one, such as a zip entry's section of the archive, in a new 4 KiB
bufio.Reader. extractZip opened every entry that way. It now registers
its own deflate decompressor on the archive's reader: the zip package's
pooled one, with the bufio.Reader it reads through pooled too.

Signed-off-by: Erik Sipsma <[email protected]>
The censor stepped through its trie once for every byte it read, and
each step, and each return to the root, allocated a new TrieIter. Trie
iterators are now values, with the zero TrieIter for no node, so
stepping allocates nothing. The censor keeps its current node and its
last match by value.

Signed-off-by: Erik Sipsma <[email protected]>
Clone and Delegate copied the scope's encoded metadata. It's never
modified once the scope is made, so clones now share it.

Signed-off-by: Erik Sipsma <[email protected]>
Result's Type, Unwrap and DerefValue, and ObjectResult's DerefValue,
loaded the result's whole payload state to read its value, and
loadPayloadState copies the snapshot owner links every time: most of
the bytes cloneSnapshotRefLinks allocated in a build. They now read the
value alone through loadSelf, like loadResultCall reads the call.

Signed-off-by: Erik Sipsma <[email protected]>
forwardIO gave the container runtime's process its stdout and stderr
writers as they were. They aren't files, so os/exec copied each stream
with io.Copy, which allocated a 32 KiB buffer for each stream of every
container run. The writers now get a ReadFrom that copies through a
pooled buffer, which io.Copy uses; nil and *os.File writers are left
for os/exec to handle as before.

Signed-off-by: Erik Sipsma <[email protected]>
sync.Pool may hand out a fresh decompressor instead of the one the
corrupt entry broke, and drops some under the race detector, so the
test could pass without reusing one. It now retries until the reader
that failed comes back from the pool, and fails if it never does.

Signed-off-by: Erik Sipsma <[email protected]>
Acquiring and releasing a ref, and removing a record, built a map of
log fields, and a logger entry around them, for trace logs that are
usually off. Each now checks the level first.

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

Every call through the namespace wrappers for containerd's snapshotter,
content store and lease manager attached the namespace again, and
attaching it copies the context's gRPC and ttrpc metadata. AttachLease
and attachOwnerContent make such a call for every snapshot and blob in
a chain. The wrappers now leave a context that already carries their
namespace as it is, and those two walks attach it once at the start.

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

Review found that namespaces.Namespace also reads incoming gRPC metadata,
so the wrappers could skip WithNamespace for a server-side context whose
outgoing headers carry no namespace, and a proxied snapshotter would get
none; replaced outgoing metadata had the same effect. There's now one
WithNamespace in engine/snapshots, used by every wrapper, that skips
only when the context value and both outgoing headers, gRPC and ttrpc,
name the namespace. A test covers bare, other-namespace, incoming-only
and replaced-header contexts. go.mod now requires ttrpc directly.

Signed-off-by: Erik Sipsma <[email protected]>
completePartKeys captured the row's persisted record, encoding each
object's payload to JSON, then copied the record and decoded each
payload again only to read its parts' states: 468 MiB of allocations in
a cold first build of dagger's CLI, 7.5% of the engine's.

An object can now describe its parts from its live value
(PersistedPartsDescriber). File, Directory and Container build the
payload their encoders build, under the same locks, and run their
family's part mapping and routing on it, skipping only the JSON. The
row is held and refused as a capture holds and refuses it, and its
output versions are recorded and checked the same way. An object that
can't describe itself (an acquired container output, a File or
Directory with a transfer pending) and an undecoded row take the
record's path, as before.

One difference: a container built with no platform encodes its platform
as "unknown", which doesn't decode, so the record's path fell back to
the parts the row's gate settled. Its live description reports its
actual parts. Every container the engine builds has a platform.

Signed-off-by: Erik Sipsma <[email protected]>
Describing a container's parts from its live value (completePartKeys)
encoded the container's recipe to JSON, then decoded it again for each
part it routed, only to read a field or two. In a cold first build of
dagger's CLI that was about 54 MiB of allocations, most of it withExec's
recipe.

A withExec recipe now gives routing what it reads from its encoding,
with its encoder's checks and failures, without encoding it. Any other
recipe is still encoded, and a router decodes what it reads from the
recipe's JSON once rather than once per part.

Signed-off-by: Erik Sipsma <[email protected]>
The schema digest was the hash of the whole schema's JSON encoding: every
type, each object again as a possible type and as an implementation,
and every description. Each session builds its schemas' digests anew,
so every invocation paid for it. A one-line edit of dagger's CLI
allocated 112 MiB for it, 7% of what the engine allocated, and a cold
first build as much.

schemaDigest now writes each part of the schema straight into the hash,
in a fixed order, every value with its length or a presence flag first.
It covers every field the JSON encoding held, except positions, which
the encoding left out too; a nil list or map hashes as an empty one,
since both describe the same schema. Each definition is hashed once,
and its hash stands for it wherever it appears. A test fills every
field of every part of a schema and checks that changing any one
changes the digest and changing a position doesn't, so a field
gqlparser adds fails it until it's hashed.

The digests change, so calls scoped to a schema get new cache keys once.

Signed-off-by: Erik Sipsma <[email protected]>
The namespace wrappers skipped re-attaching the namespace only when the
context carried it in its value and on both outgoing headers, gRPC and
ttrpc. Checking the gRPC header copies the context's whole outgoing
metadata, so every call through the wrappers on an already-namespaced
context paid that copy, about 21 MiB of a cold build of dagger's CLI,
and a context whose headers had been replaced was attached again.

The engine's containerd stores run in process and read the namespace
from the context value. The headers matter only to a proxied
snapshotter, the one store reached over gRPC, so its client is now
wrapped to put the namespace on each call's headers, as containerd's own
daemon does for its proxy plugins. WithNamespace checks only the value.

go.mod takes ttrpc back as an indirect requirement.

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

The test now builds the proxy through newSnapshotter and reads the header a
snapshots server receives, so it also fails if the proxy isn't wrapped. The
WithNamespace comment says what it checks: what namespaces.Namespace finds,
incoming headers included, which is what the in-process stores read.

Signed-off-by: Erik Sipsma <[email protected]>
Describing a row's complete parts from its live value took over the one
use of the revision captureRowRecord returned, so it returns only the
record and its error now.

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

sipsma commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Combined into #15007, which carries these commits unchanged with the rest of the engine performance batch.

@sipsma sipsma closed this Oct 30, 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