Skip to content

engine: a batch of performance changes: cache hits, allocations, Go 1.27, faster engine start, image import and services - #15007

Merged
sipsma merged 98 commits into
mainfrom
sipsma/engine-perf-batch
Nov 2, 2026
Merged

sipsma merged 98 commits into
mainfrom
sipsma/engine-perf-batch

Conversation

@sipsma

@sipsma sipsma commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

The engine redoes a lot of work it has already done, and some of what it does on every start, import and service is slower than it needs to be. This PR combines the engine's pending performance changes so they go through CI and review once instead of more than twenty times. Each was reviewed and measured on its own, and keeps its own commits.

It is #15007's fourteen changes, plus Go 1.27 (#14954), the engine startup-race fix (#14975), a per-exec opt-in to transparent huge pages (#14981) and content-keyed withDirectory (#14999), plus four changes first opened here: a faster engine start, parallel layer extraction, a diffID check on image import, and services noticed as soon as they listen.

Two additions to the public API:

  • File.extract gains two optional arguments, include and exclude, so a caller can leave archive entries out of the extraction itself.
  • withExec(transparentHugePages:), in views from v1.0.0-beta.22, lets an exec use the kernel's transparent huge pages. Every other exec starts with them off.

The SDKs and the API docs are regenerated for both, and each has a changelog entry. Nothing else changes the API. The in-memory store for containerd's metadata, which was in this batch, is now its own PR, #15036.

What it does for users

Each change was measured on its own, against the same engine without it:

Where What gets faster
A fresh engine Every command that starts an engine connects up to 2 s sooner: a fresh dagger check -l --all on dagger/dagger was 1.98 s faster [1.83, 2.14]. Engine start no longer waits for unrelated pending disk writes to flush: 0.42 s sooner after 1 GB of them, 4.6 s after 6 GB. The occasional ~155 s cold build caused by a startup race is gone (#14975).
Image pulls Layers unpack on several goroutines: a golang:1.26-alpine pull is 0.97 s faster, and a fresh listing of dagger/dagger's tests 1.04 s faster.
Services A started service is noticed about 0.05 s after it listens, instead of 0.5–1.3 s later. A large project's fresh test run, which starts many services, was 17.1 s faster.
Cold first builds 0.97 s from Go 1.27 (#14954). 2.6 s from huge pages, on hosts set to always, for execs that opt in (#14981).
Edits 0.46 and 0.27 s from matching include patterns without a regexp (#14980). 0.26–0.35 s from Go 1.27. 0.14–0.20 s from cache hits under the read lock (#14921). 0.16 s from adding dependency edges at once (#14966). 0.06–0.14 s from fewer path walks (#14987). 0.10–0.11 s from the schema digest without JSON (#14989). 0.8 s from huge pages, on hosts set to always.
Unchanged rebuilds 0.42 s (#14980) and 0.06 s (#14989).
Engine CPU and allocations About 3 CPU-s less per cold first build from #14989. Well over 1 GiB less allocated per cold first build across #15007's changes, which is garbage collection saved.
  • How they were measured: building dagger's CLI with dagger/go's per-package Go builds, mostly on AWS c8gd.4xlarge machines (16 Graviton4 vCPUs). Each was measured against its own base, mostly a development branch carrying other pending changes, so the figures show each change's size but don't add up exactly.
  • dagger/go gains a further 0.26–0.32 s per edit from core: keep withDirectory content-keyed when both directories are #14999, and 0.9 CPU-s from the new File.extract filters, once it adopts them.
  • Slowdowns: none measured. On hosts with the usual default huge-page settings, the opt-in changes nothing (within 0.3 s).

What changes in behavior

Nothing changes in what builds produce. Some observable details do:

Commits and testing

Changes first opened as their own PRs

Each of these keeps its full description on its PR, closed with a link here:

Changes first opened here

engine, sdk/go: less work per cached request from Go modules (first opened here)

When a Go module builds a large project one package per exec, as dagger/go does, an edit is mostly cache hits: building dagger's own CLI after a one-line edit walks ~1,400 cached packages before the first compile runs. That walk is bound by the engine's CPU, and every cached package costs a couple of requests. These commits cut work from the requests and setup on that path: in the engine's copier for filtered copies, in loading IDs, and in Go modules' generated clients once they're regenerated.

What changes

  • util/layercopy: stat a source file only when the filter keeps it. A copy from a plain directory ran lstat on every entry before the filter looked at it, though the filter decides from the path and whether the entry is a directory, which the directory listing already gives. Filters like exclude: ["**/*.go"] or include: ["**/go.mod"] drop most of a tree's files. On a copy of dagger's tree, the go.mod include went from 60 to 45 ms and the Go-file exclude from 263 to 250 ms. A kept file that's gone or can't be stat'ed still fails the copy as before; a dropped one no longer can.
  • core: look up a session's installed modules only when a call needs one. Loading an ID (node(id:)) listed every module the session has installed, running a dagql call per module, before checking whether the ID's call graph references any module at all. The list is only used to load referenced modules, and a module's calls to the core API reference none. Building dagger's CLI with dagger/go did this ~5,000 times per edit; the Module._implementationScoped calls in an edit went from 4,979 to 57.
  • sdk/go: keep idle connections to the engine for concurrent requests. The Go SDK's client and a Go module's generated client send every request to one host over a transport with Go's default of 2 idle connections per host. A client with more requests in flight closes the extra connections after each response and dials new ones: one edit of dagger's CLI with dagger/go opened 800–875 connections in 10 s. Both transports now keep up to 100, as many as Go's default transport keeps in all. It's a retention limit, not a pool that's filled up front.
  • cmd/codegen: read a Go module call's name, parent and arguments at once. A Go module's entrypoint asked for the call's parent name, name, parent and argument list in four requests, then each argument's name and value in two more, one after another: 24 requests, ~19 ms, for a function with 10 arguments. It now reads them in one query, through a new method on the core FunctionCall type, DispatchInputs. A method there adds no name to the module's own packages, where an author's identifier or one of the module's generated types could clash with it. Every field it reads exists in v1.0.0-beta.17 and earlier.

Notes for review

  • Generated code in this repository isn't regenerated here. The committed module bindings keep their current dispatch and transport until they're next regenerated; the go-sdk stale-generation check is skipped in dagger.toml, so CI doesn't require it.
  • Older engines: a module regenerated with this generator still dispatches on an older engine. A dagger/go module still declaring v1.0.0-beta.17, regenerated with it, loads, dispatches and runs its setup on a v1.0.0-beta.17 engine exactly as before.
  • Where the numbers come from: a development line of Dagger with and without these changes, not this branch against main. Each change's direct effect is shown above.
  • Wall time: these are each small. A timed comparison of the first three, 4 runs per side on a 16-core arm64 machine building dagger's CLI, gave median differences of −0.15 s on an edit of the CLI's package and −0.07 s on an edit inside dagger. Both are within run-to-run noise: the 95% intervals on the mean difference are −0.25 to +0.05 s and −0.22 to +0.11 s. No regression was detectable in the measured builds.

Testing

  • New tests:
    • TestCopyEntryMissingSourceAfterFilter gains cases for a deferred stat: a missing path and an unstatable one each succeed when the filter drops them and fail when it keeps them.
    • TestModDepsForCallResolvesInstalledOnlyWhenNeeded fails before the core change: a call without module references must not resolve the installed modules, and one that references a module must.
    • TestGeneratedModuleSessionIsLazy now also runs a package of its own against a fake session. It checks that the call's inputs come in one request, with JSON values with quotes and backslashes decoded as sent and with no arguments, and that a second burst of 16 concurrent requests opens no new connection. With the old transport, that burst dials 14 new ones.
  • go build ./... passes, and go test passes for ./util/layercopy and ./cmd/codegen/... with Go 1.26, and for the ModDepsForCall, InstalledPreference and ImplementationScoped tests in ./core and ./core/schema, and sdk/go/engineconn.
  • With Go 1.27, TestParseGoIfaceAcceptsImportedDaggerObject fails on main as on this branch: main's golang.org/x/tools can't read Go 1.27's export data.
  • dagger/go's gobuild, regenerated with this generator, passes its tests and builds a program end to end.
core: File.extract takes include and exclude patterns (first opened here)

File.extract (#14846) unpacks a whole archive. Its main user so far is the Go module's per-package build, which unpacks every Go module zip a build reads: 254 of them on a cold build of dagger's CLI, about 5 CPU-s of engine time. Much of that goes to files no build ever reads, such as a module's tests and its testdata. Filtering the extracted directory afterwards can't save that work, because by then every entry has already been decompressed and written.

This adds two optional arguments to the public File.extract API, include and exclude, so a caller can leave entries out of the extraction itself. Both are part of the call's cache key, and are persisted with the lazy result. There's no version gate, as for File.extract itself, which isn't in a release yet.

Behavior

  • Matching: patterns match each entry's path after stripComponents, with the same semantics as Directory.filter. Each path is matched together with its parent directory's results, so negations (!) behave the same way. An integration test checks File.extract against Directory.filter on the same patterns.
  • Zips: an entry left out is never read or decompressed.
  • Tars: an entry left out is read past, since a tar stream has to be read in order.
  • Left-out directories: a directory left out that holds entries that aren't is still made, with the archive's mode and time for it, as Directory.filter keeps such a directory's metadata. That holds even for a tar that lists the directory after its entries.
  • Hard links: as with tar --exclude, a hard link in a tar whose target was left out fails to extract.
  • Invalid patterns are rejected when the call is made.

Effect

dagger/go's per-package build would leave out each module's *_test.go files and testdata directories. It would unpack a module whole when one of its packages has C or assembly, since such a package can #include any file of its module.

On a cold build of dagger's CLI (c8gd.4xlarge, us-east-1, a fresh engine per run), the engine CPU spent unpacking drops from 4.8–5.0 to 4.0 CPU-s, from session CPU profiles: −0.9 CPU-s, −18% of unpacking. Wall time doesn't change beyond noise: medians of 22.61 and 22.76 s, 4 runs per arm. Unpacking runs alongside the compiles, almost entirely off the critical path. dagger/go takes this up once a release carries the new arguments.

Tests

  • Unit tests: TestExtractZipFilter, TestExtractFilterMatchesWithParents, TestStripTarComponentsFilter and TestExtractFilterRejectsBadPattern.
  • Integration: TestFile/TestExtractFilter, including the parity check with Directory.filter.
  • Generated code: the SDK clients and the GraphQL schema docs are regenerated for the new arguments, with a changelog entry.
engine/snapshots: remove a lease from only the snapshots it owns (first opened here)

Removing an owner lease walked every snapshot's owner set while holding the snapshot manager's lock, so each removal cost time in proportion to the engine's owned snapshots: 0.21 ms among 10,000 and 5.1 ms among 100,000. Engines remove leases in bulk (results released together, a service's lease, transfer pins, stale result leases at startup), so these walks add up to seconds, and they stall other snapshot work for as long as they hold the lock. On one test-base seed they cost 75.6 s over 53 exports.

The snapshot manager now also keeps, for each lease, the snapshots it owns, under the same lock. Adding an owner records it in both maps; removing a lease visits only its own snapshots.

BenchmarkRemoveLeaseAmongOwnedSnapshots, one removal:

Owned snapshots Before After
10,000 0.21 ms 0.85 µs
100,000 5.1 ms 0.99 µs

TestRemoveLeaseOwners checks that a removed lease comes off every snapshot it owned, that other owners and snapshots stay, and that a lease added back is removed cleanly again. It runs in CI's race-enabled test-split/test-packages; the benchmark compiles there but isn't run.

engine: a faster engine start

dial-stdio waits for the engine to listen. A client that starts the engine container dials through dial-stdio as soon as the container runs, before the engine listens. dial-stdio failed at once, and the client's readiness loop slept a second before trying again, twice on a fresh engine. dial-stdio now tries again every 10 ms, up to its existing timeout, while the socket is missing or nobody listens on it, so the first connection is answered as soon as the engine listens. A fresh dagger check -l --all on dagger/dagger was 1.98 s faster [1.83, 2.14], 3 pairs on m8gd.4xlarge. Warm commands are unchanged.

The overlay check no longer syncs the state filesystem. To choose its snapshotter, a starting engine mounted containerd's overlay probe and unmounted it. Unmounting an overlay with an upper directory syncs the whole filesystem under it, so the engine waited for every pending write on its state filesystem before it listened, its own or not: 4.6 s after 6 GB of unrelated writes on an NVMe disk, 0.3–0.4 s after an engine build. The engine already probes overlay with the volatile option, whose unmount doesn't sync. Where that probe succeeds, it now decides overlay support together with the d_type check, and containerd's probe runs only where the kernel doesn't take volatile. A fresh listing was 0.42 s faster after 1 GB of pending writes. With nothing pending there's no measured cost (+0.06 s [−0.19, +0.29], 7 pairs). The probe needs no durable output, and the snapshotter's own settings are unchanged; what changes is that the start no longer flushes other dirty state as a side effect.

Overlay is kept after a local cache reset. A start that finds its local cache invalid moves the worker directory aside and creates the snapshotter again on an empty one. The check above runs its volatile probe once per process, and that probe was what created the snapshotter's root, so the second check found no directory and fell back to the native snapshotter, which copies every layer whole. overlaySupported now creates the directory itself, on every call, as containerd's own check does.

Tests: cmd/dialstdio's tests, including waiting on a stale engine socket; a cache-reset case in core/integration/engine_persistence_test.go, which fails without the fix.

engine/snapshots: extract image layers on several goroutines

Importing an image layer extracted it with containerd's applier, one entry at a time on one goroutine. Each file costs about a dozen system calls, most of them path lookups, so a layer with many files was bound by that goroutine: the Go toolchain layer of golang:1.26-alpine (15,045 files) took about 1.6 s to extract.

The engine now has its own applier for the snapshot manager. It extracts a layer as containerd's file system applier and tar extraction do, entry for entry, with two differences:

  • One goroutine reads the tar and does every step in order, except writing a regular file of at most 1 MiB: it reads such a file into memory and hands it to one of 8 workers, which create it and set its owner, xattrs, mode and times. Before a step that could see or change a file a worker may still be writing (a lookup of that path or one under it, a whiteout, a removal, a hard link, a header for a directory that exists), the reader waits for the workers.
  • The reader remembers each directory's resolved path and which directories exist, and forgets both whenever a symlink or hard link is created or anything is removed.

A goroutine also reads, hashes and counts the uncompressed stream up to 16 MiB ahead of the extraction, so decompression, which runs in its own process behind a 64 KiB pipe, no longer stops whenever extraction is busy.

Mounts it doesn't write into directly (several mounts, a read-only bind mount, a user namespace) go to containerd's applier as before. The helpers containerd's pkg/archive doesn't export are copied from containerd v2.2.5 (Apache License 2.0).

A golang:1.26-alpine pull was 0.97 s faster, and a fresh listing of dagger/dagger's tests 1.04 s faster.

Tests: the same tars are extracted with containerd's archive.Apply and with the new extraction, and the trees compared, including a header after its files, a symlink replacing a remembered directory, hard links, a worker failure, cancellation with files queued, trailing data and a failing stream.

engine/snapshots: check each imported layer against its diffID

Image import reuses a layer it already unpacked when a later image declares the same diffID on the same parent, but it never checked that the layer's content matches the diffID its image declares. A later image could then get another image's files. Each layer's uncompressed digest is now checked against its declared diffID, and the import fails on a mismatch, as containerd's unpacker does.

Test: engine/snapshots/import_test.go rejects a layer whose content doesn't match its diffID.

core: notice a started service as soon as it listens

The port health check dialed with exponential backoff, from 100 ms up to a nominal 10 s between tries (up to 15 s with jitter). A service that started listening between two tries was only noticed at the next one: on average about 1.3 s late after a 4 s start. It now dials about every 100 ms (50–150 ms with jitter), keeping the overall 15-minute limit. A dial into the service's own network namespace is cheap. To keep the span readable, a repeated "port not ready" warning is logged at most every 10 s; a new error is still logged at once.

A large project's fresh test run, which starts many services, was 17.1 s faster (6 pairs).

Test: the prompt health check test in core/integration/services_test.go starts three services that listen after 7, 10 and 13 s and requires each to be noticed within 1 s. It failed 5 of 5 runs without the change and passed 5 of 5 with it.

@sipsma
sipsma requested review from a team as code owners October 30, 2026 23:15
@sipsma
sipsma force-pushed the sipsma/engine-perf-batch branch from 06979d5 to 880ddc2 Compare October 31, 2026 04:07
@sipsma sipsma changed the title engine: a batch of performance changes: cache hits, allocations, path walks and request serving engine: a batch of performance changes: cache hits, allocations, Go 1.27, faster engine start, image import and services Nov 2, 2026
@sipsma
sipsma force-pushed the sipsma/engine-perf-batch branch from 880ddc2 to ee1aaf9 Compare November 2, 2026 20:28
sipsma added a commit that referenced this pull request Nov 2, 2026
sipsma added a commit that referenced this pull request Nov 2, 2026
@sipsma
sipsma force-pushed the sipsma/engine-perf-batch branch from ee1aaf9 to e28f27a Compare November 2, 2026 20:38
sipsma added 24 commits November 2, 2026 22:15
…e pages

The kernel can switch transparent huge pages off for a process, never on,
and a process passes the setting on to the processes it starts. So on a host
set to "always", every exec now starts with them off except where its
program asks for them (PR_THP_DISABLE_EXCEPT_ADVISED, Linux 6.18), as on a
host set to "madvise", unless the exec sets transparentHugePages. The
engine sets the mode on itself while the runtime starts, under a lock, and
puts its own mode back once the runtime has started. Kernels before 6.18
lack the mode; there nothing changes.

Signed-off-by: Erik Sipsma <[email protected]>
A field's schema can mark an argument volatile: its value goes to the
resolver, but not into the call's cache identity, its ID or its telemetry.
Calls that differ only in it are the same call, and share whichever result
was made first. It is for arguments that cannot change the result, such as
a performance hint, and needs a default.

Signed-off-by: Erik Sipsma <[email protected]>
The setting cannot change what an exec produces, so an exec that differs
from a cached one only in it reuses the cached result.

Signed-off-by: Erik Sipsma <[email protected]>
…, and says what the default keeps

Older views keep the schema they had. The documentation said commands get
no huge pages without the setting; they still get them for memory their
own program asks huge pages for, and a host's per-size settings count as
well as its top-level one.

Signed-off-by: Erik Sipsma <[email protected]>
A copy of one content-keyed directory into another now gets a content
digest made from both directories' digests and the copy's arguments, as
a Dockerfile COPY already does. A directory put together from
content-keyed parts, such as two workspace reads, then stays
content-keyed, and what is read from it afterwards, such as a
subdirectory, is keyed by what it holds rather than by every part it was
made from. The digest comes from the inputs' digests, so the copy stays
lazy.

Signed-off-by: Erik Sipsma <[email protected]>
A client that starts the engine container dials through dial-stdio as soon
as the container runs, before the engine listens. dial-stdio then failed at
once, and the client's readiness loop slept a second before trying again,
twice on a fresh engine: its retry right after the sleep fails fast while the
connection is still being re-established. On a fresh engine the CLI
connected about 1.9s after the engine started listening.

dial-stdio now tries again every 10ms, up to its existing timeout, while the
socket is missing or nobody listens on it, so the first connection is
answered as soon as the engine listens.

Signed-off-by: Erik Sipsma <[email protected]>
To choose its snapshotter, a starting engine mounted containerd's overlay
probe and unmounted it. Unmounting an overlay with an upper directory syncs
the whole filesystem under it, so the engine waited for every pending write
on its state filesystem before it listened, its own or not: 4.6s after 6GB
of unrelated writes on an NVMe disk, 0.3-0.4s after an engine build.

The engine already probes overlay with the "volatile" option, whose unmount
doesn't sync. Where that probe succeeds it now decides overlay support
together with the d_type check, and containerd's probe runs only where the
kernel doesn't take "volatile".

Signed-off-by: Erik Sipsma <[email protected]>
A start that finds its local cache state invalid moves the worker
directory aside and creates the snapshotter again on an empty one. The
overlay check without a sync runs its volatile probe once per process,
and that probe was what created the snapshotter's root, so the second
check found no directory, failed its d_type check and fell back to the
native snapshotter, which copies every layer whole. On a large workload
restarted after a reset, that store grew to 92.8GiB; main, after the same
reset, kept 11.8GiB.

The check now creates the directory itself, as containerd's own check
does.

Signed-off-by: Erik Sipsma <[email protected]>
Importing an image layer extracted it with containerd's applier, one
entry at a time on one goroutine. Each file costs about a dozen system
calls, most of them path lookups, so a layer with many files was bound
by that one goroutine: the Go toolchain layer of golang:1.26-alpine
(15,045 files) took about 1.6 s to extract.

The engine now has its own applier for the snapshot manager. It
extracts a layer as containerd's file system applier and tar
extraction do, entry for entry, with two differences:

- One goroutine reads the tar and does every step in order, except
  writing a regular file of at most 1 MiB: it reads such a file into
  memory and hands it to one of 8 workers, which create it and set its
  owner, xattrs, mode and times. Before a step that could see or change
  a file a worker may still be writing (a lookup of that path or one
  under it, a whiteout, a removal, a hard link), the reader waits for
  the workers.
- The reader remembers each directory's resolved path and which
  directories exist, and forgets both whenever a symlink or hard link
  is created or anything is removed.

Mounts it doesn't write into directly (several mounts, a read-only
bind mount, a user namespace) go to containerd's applier as before.
The helpers containerd's pkg/archive doesn't export are copied from
containerd v2.2.5.

The tests extract the same tars with containerd's archive.Apply and
with the new extraction and compare the resulting trees.

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

A file takes some of its directory's metadata when it is created, such
as a default ACL. A directory header that came after files under it
could reach the directory before a worker had created them, and they
would take metadata containerd's extraction doesn't give them. Wait
for the workers before applying a header to a directory that exists.

Workers also stop once the context is done. Tests run the workers
slowed, and cover a header after its files, a symlink replacing a
directory that lookups remembered, hard links, a worker failure and a
cancellation with files queued.

Signed-off-by: Erik Sipsma <[email protected]>
Decompression runs in its own process, behind a pipe that holds 64 KiB.
Extraction read the stream directly, so decompression stopped whenever
extraction was busy, and the two took turns. A goroutine now reads,
hashes and counts the uncompressed stream up to 16 MiB ahead.

Signed-off-by: Erik Sipsma <[email protected]>
Trailing data, a stream that fails, and an extraction that fails while
the read-ahead is still reading, through the applier rather than the
extraction alone. copyBuffered returns explicitly, for the linter.

Signed-off-by: Erik Sipsma <[email protected]>
Image import reuses a layer it already unpacked when a later image
declares the same diffID on the same parent, but it never checked that
the layer's content matches the diffID its image declares. A later
image could then get another image's files. Check each layer's
uncompressed digest against its declared diffID and fail the import on
a mismatch, as containerd's unpacker does.

Signed-off-by: Erik Sipsma <[email protected]>
The port health check dialed with exponential backoff, from 100 ms up
to a nominal 10 s between tries (up to 15 s with jitter). A service
that started listening between two tries was only noticed at the next
one: on average about 1.3 s late after a 4 s start.

Dial about every 100 ms instead (50-150 ms with jitter), keeping the
overall 15 minute limit. A dial into the service's own network
namespace is cheap. To keep the span readable, a repeated "port not
ready" warning is logged at most every 10 s; a new error is still
logged at once.

Signed-off-by: Erik Sipsma <[email protected]>
The old backoff notices one service listening after 10 s within 1 s
about 22% of the time, so the test missed a regression about one run in
five. It notices all three of services listening after 7, 10 and 13 s
within 1 s about 1% of the time. They start together, so the test
waits for the slowest, 13 s, not the sum.

Signed-off-by: Erik Sipsma <[email protected]>
With the client exec cached, a rerun on the same engine returned the
first run's lateness without starting the services again.

Signed-off-by: Erik Sipsma <[email protected]>
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.

2 participants