Skip to content

engine: reclaim released snapshot data and count retained parent layers - #14470

Merged
sipsma merged 15 commits into
dagger:mainfrom
sipsma:cache-gc-released-snapshots
Oct 5, 2026
Merged

sipsma merged 15 commits into
dagger:mainfrom
sipsma:cache-gc-released-snapshots

Conversation

@sipsma

@sipsma sipsma commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

A comment on #7711 reports an engine filling a 1 TiB disk in about 11 hours. The GC logged no reclaim target every pass, with usedBytes around 14 GB while the worker directory held 570 GB.

Two engine bugs explain how disk usage can grow far beyond what the GC sees:

  • Released snapshot data was only deleted after a prune removed an entry. Removing a snapshot's last lease only marks containerd's metadata DB dirty. The engine ran GarbageCollect only after a dagql prune removed at least one entry. Leases are released all the time outside any prune: session teardown, failed execs, stopped services. An engine whose policies never removed anything therefore kept that data forever, and none of it was counted. The commenter's policies all had a 72h keepDuration, which is exactly that case.
  • Cache usage counted only each result's top snapshot. A result's owner lease retains its whole parent chain, but its usage was its own overlay diff plus blob. The lower layers of a pulled image, and layers left under a result whose own entry is gone, were retained but counted nowhere. The space limits compare against this total.

Changes

Collecting released data

  • snapshotGarbage tracks deletions through containerd's RegisterMutationCallback. Every GC pass, and every explicit localCache.prune, collects whatever is pending, whatever the policies decided.
  • The first pass after startup always collects, because containerd's deletion count doesn't survive a restart.
  • Collection also runs with gc.enabled=false. Disabling GC stops the engine from choosing entries to drop, but this data is no longer referenced by anything.
  • Operation leases no longer expire. An operation's lazy lease scope protects the snapshots it is producing, and it was created with a one-hour expiry. containerd stops treating an expired lease as a root, so collection could delete data a long-running exec or service was still using; more frequent collection made that much more likely. Operation leases are now labeled, carry no expiry, and are released at startup, the same way transfer leases already are.

Counting parent layers

  • A result's usage identities are now its snapshots plus their ancestors, resolved through a new SnapshotManager.SnapshotParent outside the graph lock. Ancestors are sized by snapshot ID.
  • Shared layers were already deduplicated by identity. Each layer counts once, against the lowest result ID listing it, and the prune simulation credits a layer only once every result listing it is collected. In practice:
    • from shows the whole image;
    • an exec stacked on others shows, and is credited with reclaiming, only its own layer while the results below it are alive;
    • layers left behind by collected results are charged to the result still retaining them.
  • A row whose chain has an unresolved link, either because a lookup failed or because the row appeared after sampling, defers the pass like other incomplete membership. Otherwise the simulation could credit layers the row still retains. Failed lookups are retried on the next pass.

Keeping the extra accounting cheap

  • Resolved parents and sorted chains carry between usage passes. Only the ones the latest pass visited are kept, so memory stays bounded by live snapshots. Chains handed to later passes are never written again.
  • Prune measured usage for every policy, taking the graph lock twice each time. It now measures once per pass, and measures again before a later policy plans removals or after a policy removes entries.

Docs. The engine.json reference gets a garbage collection section. It covers:

  • the space settings, described as targets;
  • how keepDuration behaves under disk pressure;
  • ending a custom policy list with a catch-all policy that has space limits;
  • how engine.toml settings, including gckeepstorage, relate to engine.json.

internal-docs/cache_pruning.md is updated as well.

Limitations

  • A merge snapshot's recorded usage leaves out files hardlinked from other merge inputs, and those inputs are not in its parent chain. Once the inputs' results are collected, that data stays with the merge uncharged. This predates the change and is documented in the internal doc.
  • Counting ancestors makes the locked usage bookkeeping proportional to the total chain length, not the number of results. On a synthetic cache of 20,000 persisted results (400 exec chains 50 deep on 20 ten-layer images), each locked prune-state section takes about 140 ms, against about 80 ms before. Because a pass now measures once instead of per policy, a default three-policy pass that removes nothing takes the lock twice instead of six times, and takes about 470 ms against about 750 ms before. Aggregating per layer instead of per result would bring each section back down, but that would be a larger rework.
  • Unchanged: keepDuration still keeps recently used entries out of their policy under disk pressure, as before. The new docs describe that.

Validation

  • go test ./dagql/ ./engine/snapshots/ ./engine/server/ ./core/ ./core/schema/ -skip 'TestNativeWorkspaceMerge|TestGitNativeCommit': passes. The skipped git-native tests need a newer git than the 2.43 on the machine used.
  • go test -race ./dagql/ -run 'TestCacheUsage|TestCachePrune': passes.
  • New tests cover each behavior: collection without a prune, with GC disabled, and on explicit prune; non-expiring operation leases and their release at restart; chain counting and reclaim credit; deferral on incomplete chains; chain reuse, including a concurrent read; and measuring once per pass. Each fails with its change disabled. The collection and lease tests run against a real containerd metadata DB.
  • A dev engine built from this branch ran on a 6 GB loop-mounted disk with the commenter's policies (keepDuration 72h and 48h):
    • python:3.12-slim is counted at 188 MB, matching its disk usage. Before, it was counted as 17 KB.
    • Execs of 300, 200 and 100 MB stacked on alpine each show only their own layer. The 800 MB total matches the disk.
    • A failing exec and a stopped service raised the snapshot directory from 717 to 1,480 MiB. It was back to 717 MiB within 30 s, while no prune removed an entry.
    • After an engine restart, the cache was intact and new work ran normally.
  • Not run locally: the integration suites and the docs site build.

sipsma added 15 commits October 3, 2026 23:12
Removing the last lease on a snapshot only marks containerd's metadata DB
dirty; the data stays on disk until GarbageCollect runs. The engine ran that
collection only after a prune removed at least one entry. Leases are released
all the time without a prune (session teardown, failed execs, stopped
services), so an engine whose policies never removed an entry kept that data
forever, and none of it was counted in the cache's usage.

Track deletions with containerd's mutation callback and collect any pending
garbage at the end of every GC pass, whatever the policies decided. GC passes
already run after sessions end (at most once a minute) and under disk
pressure. The first pass after startup always collects, because containerd's
deletion count does not survive a restart.

Signed-off-by: Erik Sipsma <[email protected]>
A result's cache usage was the size of its own top snapshot: its overlay
diff plus its blob. Its owner lease retains the whole parent chain, though,
so the lower layers of a pulled image, and the layers under a result whose
own entry was gone, stayed on disk without being counted anywhere. A pulled
python:3.12-slim used 163MB on disk and was counted as 17KB. The space limits
compare against this total, so they could not see much of what filled the
disk.

Make each result's usage identities its snapshots plus their ancestors.
Shared layers are already deduplicated by identity: each layer counts once,
against the earliest result listing it, and the prune simulation credits a
layer only once every result listing it is collected. So an image's `from`
result shows the whole image, an exec stacked on others still shows and
reclaims only its own layer while the results below it are alive, and
layers left behind by collected results are charged to the result still
retaining them.

Parents are looked up through a new SnapshotParent method, outside the graph
lock. A snapshot's parent never changes, so each usage pass reuses the links
the previous pass resolved and keeps only the ones it visited, which bounds
the carried map by the live snapshots.

Signed-off-by: Erik Sipsma <[email protected]>
The engine.json reference had no garbage collection section. Describe the
space settings and their defaults, how a policy's keepDuration interacts with
free space, why a custom policy list should end with a catch-all policy, and
how engine.toml settings relate to engine.json.

Signed-off-by: Erik Sipsma <[email protected]>
Disabling GC stops the engine from choosing cache entries to drop. Data that
nothing references anymore is not such a choice, so it is still collected.
Document that, and test it so the behavior stays deliberate.

Signed-off-by: Erik Sipsma <[email protected]>
An operation's lazy lease scope protects the snapshots the operation is still
producing, such as an exec's output or a service's root filesystem. It was
created with a one-hour expiry, and containerd stops treating an expired lease
as a root. Any garbage collection after the deadline could delete snapshots a
long-running exec or service was still using. Collection now runs on every GC
pass, which made that far more likely.

Create operation leases without an expiry. The scope deletes the lease when
its operation ends, and the engine releases leases an earlier process left
behind at startup, as it already does for transfer leases.

Signed-off-by: Erik Sipsma <[email protected]>
An explicit prune ran the prune stages but only collected garbage when they
removed an entry, so data released outside any prune stayed on disk. Collect
pending garbage there too, as a GC pass does.

Signed-off-by: Erik Sipsma <[email protected]>
A row whose parent chain was only partly resolved listed fewer ancestors than
it retains. The prune simulation then credited those layers as reclaimed once
their other holders were collected, though the row still kept them on disk.
That happened for rows that appeared after sampling, whose parents are only
looked up outside the graph lock, and when a parent lookup failed.

Track whether each row's chains are complete, and defer the pass like any
other incomplete membership when one is not. A failed lookup is not
remembered, so the next pass retries it. Also document that merge snapshots
do not charge data hardlinked from other merge inputs.

Signed-off-by: Erik Sipsma <[email protected]>
reservedSpace is a floor for pruning to maxUsedSpace, not the size that
pruning reaches; maxUsedSpace is. keepDuration does not keep an entry whose
cache TTL has expired.

Signed-off-by: Erik Sipsma <[email protected]>
Pruning removes whole cache entries until it reaches its target, so a pass can
go past maxUsedSpace or below reservedSpace, and pruning for minFreeSpace does
not consider reservedSpace. Describe the settings as targets rather than hard
limits.

Signed-off-by: Erik Sipsma <[email protected]>
Each usage pass rebuilt every row's expanded identities from the parent links:
walking its chain, allocating a new slice, and sorting it, although a
snapshot's chain never changes. On a synthetic cache of 20,000 results with
chains about 35 deep, that was the largest single cost of a pass.

Cache each snapshot's sorted chain alongside its parent, carried between
passes and bounded by the live snapshots like the parents. Rows on the same
snapshot share the slice. Decide whether a payload can size an identity by
checking its own identities, instead of building a map of ancestors per row.

Signed-off-by: Erik Sipsma <[email protected]>
Prune measured result sizes and rebuilt the prune state for every policy,
although a policy only changes the cache by removing entries. Each measurement
takes the graph lock twice, so a default three-policy pass that removed
nothing held it six times.

Measure once per pass, and again only after a policy removes entries or a
measurement was deferred. On a synthetic cache of 20,000 results with chains
about 35 deep, a three-policy pass that removes nothing now takes about
450-510ms and takes the lock twice. Before parent chains were counted it took
about 750ms with six lock holds.

Signed-off-by: Erik Sipsma <[email protected]>
A usage pass hands its resolved chains to later passes as soon as sampling
ends, and those passes read them without a lock. A row first seen during
finalization then cached its newly assembled chain into the handed-off map,
racing with those readers; the race detector flags it.

Mark the chains published at handoff, and have finalization assemble chains
without caching them. Such rows are rare, so not caching them costs nothing.

Signed-off-by: Erik Sipsma <[email protected]>
Reusing a pass's measurement across policies also reused its view of which
results retain which layers. A result published between policies could then
still be retaining layers that a later policy counted as reclaimed when it
pruned their other holder.

Reuse the measurement only to decide a policy has nothing to do, and measure
again before planning removals. A pass that prunes nothing still measures
once. Add a test hook that runs before each policy, so the test can publish a
result between policies.

Signed-off-by: Erik Sipsma <[email protected]>
@sipsma
sipsma force-pushed the cache-gc-released-snapshots branch from 4876beb to 18d8526 Compare October 3, 2026 23:16
@sipsma
sipsma merged commit 17ccfb8 into dagger:main Oct 5, 2026
90 checks passed
sipsma added a commit that referenced this pull request Oct 5, 2026
When an exec fails and opens a terminal on its output, the terminal shows each
writable mount's failed output. It did so by writing through the input mount's
accessors, but since #14043 execInputMounts shares those with the exec's parent
container, which is a cached result. The cached container then pointed at the
failed output snapshots, which only the failed operation holds.

That silently gave the next exec from the cached container the failed run's
files instead of its inputs. Since #14470 collects released snapshots on every
GC pass, the output is usually gone by then, and the exec fails with
"parent snapshot ... does not exist", as in
TestModule/TestDaggerTerminal/on_failure.

Install the failed output on the terminal's own cloned mount with a new
accessor, and leave the input mounts alone.

Signed-off-by: Erik Sipsma <[email protected]>
neongreen added a commit to neongreen/dagger that referenced this pull request Oct 20, 2026
Port of upstream 42edb39 (dagger#14470) onto v0.21.7.

An operation's lazy lease scope protects the snapshots the operation is
still producing, such as an exec's root filesystem. v0.21.7 creates it
with a one-hour expiry, and containerd stops treating an expired lease as
a GC root, so any collection after the first hour deletes snapshots a
long-running exec is still using.

Create operation leases without an expiry and label them
dagger.io/operation=true. The scope deletes the lease when its operation
ends. At startup the engine deletes leases carrying exactly that label,
right after creating the lease manager and before the snapshot manager,
the dagql cache or any session use it; a failure stops engine start.
Unlabelled and pre-patch operation leases are untouched; the latter still
expire on their own.

The upstream test depends on engine/snapshots/testutil, which v0.21.7
lacks, so the tests here use a real containerd metadata store, the native
snapshotter and containerd's own garbage collector.

Co-Authored-By: Claude Opus 5.5 <[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