Repository navigation
Conversation
There was a problem hiding this comment.
Pull request overview
Adds an optional “Layer Content Cache” (LCC) mode to the overlayfs snapshotter to deduplicate extracted layer filesystem content across images by extracting into a shared <root>/cache/… directory and symlinking snapshot fs/ to cached content. This is wired through snapshot labels so the unpacker can skip extraction on cache hits, and includes unit + integration coverage.
Changes:
- Add
layer_content_cacheconfiguration flag for the overlayfs snapshotter plugin and plumb an enable option into the snapshotter. - Export snapshot label constants in
core/snapshotsand teach the unpacker to honorLabelSkipApplyto skipApplyon cache hits. - Implement LCC in overlay snapshotter (cache pathing, symlink setup, commit-time promotion, GC) with new unit and integration tests and a new
pkg2ocihelper.
Reviewed changes
Copilot reviewed 18 out of 18 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| plugins/snapshots/overlay/plugin/plugin.go | Adds layer_content_cache config option and enables LCC via snapshotter opt. |
| plugins/snapshots/overlay/overlay_test.go | Runs existing overlay snapshotter tests with LCC enabled. |
| plugins/snapshots/overlay/overlay.go | Wires LCC into snapshot creation/commit and cleanup paths; creates cache/ dir when enabled. |
| plugins/snapshots/overlay/lcc.go | Implements LCC: cache keying by diffID+uid/gid, skip-apply signaling, commit promotion, and orphan GC discovery. |
| plugins/snapshots/overlay/lcc_test.go | Unit tests for cache miss/hit behavior, concurrent extraction handling, GC, and ownership isolation. |
| core/unpack/unpacker.go | Uses exported snapshot label constants; stats snapshot post-Prepare and skips Apply on LabelSkipApply. |
| core/snapshots/snapshotter.go | Exports snapshot label constants (diffID, parent chain, skip-apply) and updates FilterInheritedLabels. |
| core/metadata/snapshot_test.go | Updates tests to use exported snapshot label constants/prefix. |
| core/metadata/snapshot.go | Updates metadata snapshotter logic to reference exported snapshot label constants. |
| integration/lcc/main_test.go | Adds LCC integration test harness that boots containerd and inspects cache/snapshots. |
| integration/lcc/snapshotter_test.go | End-to-end LCC tests validating cache population, lifecycle, and pruning/GC behavior. |
| integration/lcc/flox_test.go | End-to-end Flox-based integration workflows exercising LCC with real envs (optional GPU path). |
| integration/lcc/cmd/pkg2oci/main.go | Adds pkg2oci tool to build OCI layout tarballs from package blobs/Flox envs for tests. |
| integration/lcc/cmd/pkg2oci/flox.go | Flox integration for pkg2oci: layer generation, deterministic packing, activation layer. |
| integration/lcc/Makefile | Adds a convenience make test target for LCC integration tests. |
| integration/client/snapshot_linux_test.go | Runs snapshotter client tests with LCC enabled via daemon config. |
| contrib/Dockerfile.test | Adds lcc-integration Docker build stage for running LCC integration tests. |
| Makefile | Adds lcc-integration target to run the new integration suite. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // LabelSkipApply instructs the unpacker to skip calling Apply for this | ||
| // active snapshot. Set by the snapshotter when the layer content is already | ||
| // present (e.g. via CAS deduplication) and extraction is unnecessary. | ||
| LabelSkipApply = "containerd.io/snapshot.skip-apply" |
There was a problem hiding this comment.
Question: Why is the separator . instead of /? i.e. not:
| LabelSkipApply = "containerd.io/snapshot.skip-apply" | |
| LabelSkipApply = "containerd.io/snapshot/skip-apply" |
There was a problem hiding this comment.
The . makes it unexported (i.e. internal only) whereas the \ makes it exported (i.e. a user could add this as an annotation on the layer to trigger this behaviour, which we don't want).
mxpv
left a comment
There was a problem hiding this comment.
Great work! Left a few comments I think are worth calling out.
| cleanup := []string{} | ||
| var cleanup []string | ||
| if o.lccEnabled { | ||
| if cleanup, err = o.getOrphanedLCCPaths(ctx); err != nil { |
There was a problem hiding this comment.
I think this introduces racing?
- Cleanup:
cleanupDirectoriesruns under tx, callsgetOrphanedLCCPaths, findscache/sha256.X.0.0. - Cleanup: commits tx (remove is going to happen outside of tx via
defer) - Prepare: starts another tx,
os.Stat("cache/sha256.X.0.0")still exists, so the symlink gets created - Cleanup: removes
os.RemoveAll("cache/sha256.X.0.0")in defer - Committed snapshot's symlink to a path that no longer exists. mount/Apply attempts later will fail with ENOENT
I'd rename dirs scheduled for deletion as part of transaction.
There was a problem hiding this comment.
Yes. I agree, this sounds like a race to me. Are you suggesting I mv the folder to a temporary location (inside the tx), and then mark the folder for deletion as the new temporary path. Yes, I think that will resolve the race.
There was a problem hiding this comment.
Updated to rename to a folder at the same path with a .<id>.orphaned suffix. That way if anything goes wrong, the next GC cycle can pick these up and reap them then.
| if !errors.Is(err, syscall.ENOTEMPTY) && !errors.Is(err, syscall.EEXIST) { | ||
| return fmt.Errorf("failed to promote layer content to cache %s: %w", lccContentPath, err) | ||
| } | ||
| if err := os.RemoveAll(upperFSPath); err != nil { |
There was a problem hiding this comment.
This might be expensive to call inside of a tx when container image is large?
Tx will be blocking every other Prepare/Commit/Remove on the snapshotter.
There was a problem hiding this comment.
Makes sense. Let me think how to combine this with changes to be made to support #13308 (comment) such that a similar convention can be used for where to move these "orphaned" directories so they don't get lost and eventually get cleaned up no matter what.
There was a problem hiding this comment.
Updated. PTAL.
I opted to rename the folders to have a <id>.orphaned suffix similar to what I did for #13308 (comment), without and explicit removal immediately after exiting the transaction. Races on extracting the same content from two different snapshots should be very rare, so its not worth the added complexity. Instead, any such orphaned directories will now simply be cleaned up on the next GC cycle.
|
|
||
| // LayerContentCache enables layer content caching and deduplication. | ||
| // When true, identical layers are shared across all images on this node. | ||
| LayerContentCache bool `toml:"layer_content_cache"` |
There was a problem hiding this comment.
It worth documenting the downgrade path. E.g. Once layer_content_cache = true populates the cache, what happens if I disable this?
- Existing committed snapshots have symlinks into cache/. They still resolve, so reads work.
- But
getOrphanedLCCPathsis never called and cache directories accumulate forever, consuming disk. - If someone wipes /cache to reclaim space, every existing snapshot becomes dangling.
Worth mentioning that in order to disable this safely, we should remove all snapshots first at least or beaware that its not safe to delete cache even though lcc disabled.
There was a problem hiding this comment.
I will think about this and add some documentation around it. Where should this be documented exactly?
There was a problem hiding this comment.
oh, ok, I realized that we don't have the doc for overlay in ./docs/snapshotters/.
Can update the field above directly about caveats, I can follow up with broader doc after.
There was a problem hiding this comment.
One thought -- does it make sense to not gate the Cleanup() path for this feature?
Meaning, even if the feature gate get disabled, cleanups will still continue to work for cached directories (at least on the current / future versions of containerd where this feature is merged).
True downgrades to an older containerd would require more surgery to get them removed.
I have ungated the cleanup for now, pending feedback.
1759e44 to
ef5c1d7
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 22 out of 22 changed files in this pull request and generated 2 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
adc0ea5 to
64e6d63
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 22 out of 22 changed files in this pull request and generated 6 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 22 out of 22 changed files in this pull request and generated 4 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 22 out of 22 changed files in this pull request and generated 3 comments.
Comments suppressed due to low confidence (1)
integration/lcc/snapshotter_test.go:306
- Inside the prune/poll loop,
snapSvc.Walkerrors are ignored while recalculatingsnapCount. IfWalkfails, the loop may break early or time out with a confusing message. Handle the error explicitly so failures surface with the real cause.
for attempt := range pruneMaxAttempts {
time.Sleep(pruneInterval)
blobCount = countCachedBlobs(t, cacheDir)
snapCount = 0
_ = snapSvc.Walk(env.ctx, func(_ context.Context, _ snapshots.Info) error {
snapCount++
return nil
})
| info := snapshots.Info{Labels: map[string]string{ | ||
| snapshots.LabelSnapshotDiffID: tc.diffID, | ||
| labelSnapshotUID: "0", | ||
| labelSnapshotGID: "0", | ||
| }} | ||
| if _, err := sn.lcc.contentPath(info); err == nil { | ||
| t.Errorf("expected error for diffID %q, got nil", tc.diffID) | ||
| } |
| _ = snapSvc.Walk(env.ctx, func(_ context.Context, _ snapshots.Info) error { | ||
| remaining++ | ||
| return nil | ||
| }) |
| _ = snapSvc.Walk(env.ctx, func(_ context.Context, _ snapshots.Info) error { | ||
| bSnapshotCount++ | ||
| return nil | ||
| }) |
Label strings used by the unpacker, metadata snapshotter, and client
were duplicated as unexported constants across packages. Consolidate
them as exported constants in core/snapshots:
InheritedLabelsPrefix ("containerd.io/snapshot/")
LabelSnapshotRef ("containerd.io/snapshot.ref")
LabelSnapshotDiffID ("containerd.io/snapshot/diff-id")
LabelSnapshotParentChainID ("containerd.io/snapshot/parent-chain-id")
Update core/unpack and core/metadata to reference the exported names
and drop their local definitions.
Signed-off-by: Kevin Klues <[email protected]>
Adds a new layer_content_cache boolean option to the overlayfs snapshotter. When enabled, snapshots that share a layer diffID share a single extracted copy on disk rather than each storing their own. The motivation is package-manager-style images (e.g. Nix/Flox) where many images are composed from the same discrete packages as individual OCI layers. Such layers may appear at different positions across different image stacks, producing different chain IDs and thus different snapshots even though the content is identical. The content store already deduplicates downloads by digest; this extends that guarantee to extracted content. The implementation relies on the fact that overlayfs resolves lowerdir paths through symlinks. Extracted layer content is stored in a shared cache at <root>/cache/<algo>.<hex>.<uid>.<gid>/ and each snapshot's fs/ becomes a symlink into that cache. On a cache hit, Prepare sets LabelSkipApply so the unpacker skips extraction entirely. Concurrent first-time extractors of the same layer race via os.Rename; losers discard their copy and symlink to the winner. Cache entries are garbage-collected in Cleanup when no live snapshot references them. The uid/gid component of the cache path ensures ID-mapped mounts get separate entries with correct ownership. Chain IDs, snapshot keys, and all other snapshotter semantics are unchanged. Signed-off-by: Kevin Klues <[email protected]>
The core/unpack unpacker has always set LabelSnapshotDiffID on the Prepare call so that snapshotters can act on the per-layer content identity (e.g. the overlay layer content cache). The older pkg/rootfs.applyLayers path — used by client.(*image).Unpack, i.e. `ctr images pull --local` — was missing this label, so snapshotters never saw a diff ID and LCC was silently bypassed. Similarly, applyLayers never checked LabelSkipApply after Prepare, so on a cache hit the snapshotter would have set up an fs/ symlink but Apply would then extract on top of the cache directory, corrupting it. Fix both gaps to match the behaviour of core/unpack/unpacker.go: - build prepareOpts with LabelSnapshotDiffID before the Prepare loop - after a successful Prepare, stat the key and skip Apply (and the diff digest check) when LabelSkipApply == "true" Signed-off-by: Kevin Klues <[email protected]>
Extends the TestOverlay option matrix with WithLayerContentCache and WithLayerContentCache/AsynchronousRemove variants so that the full containerd snapshotter contract suite (testsuite.SnapshotterSuite) and all overlay-specific sub-tests are re-run with WithLayerContentCache enabled, both alone and combined with AsynchronousRemove. Also adds WithLayerContentCache/WithRemapIDs to ensure idmapped-mount paths are covered. Adds integration/client/snapshot_linux_test.go with TestSnapshotterClientWithLCC, which runs the full snapshotter contract suite against an LCC-enabled overlay snapshotter via the containerd gRPC API, following the same pattern as daemon_config_linux_test.go. Signed-off-by: Kevin Klues <[email protected]>
Tests cover all code paths in lcc.go: - lccContentPath layout and error cases for malformed diffIDs - cache miss: fs/ is a real directory, LabelSkipApply not set, content promoted to cache on commit, fs/ replaced with symlink - cache hit: LabelSkipApply set, fs/ created as symlink on Prepare - cache hit commit: symlink preserved through CommitActive - concurrent extraction: race-loser discards content and symlinks to the winner's cache entry (ENOTEMPTY/EEXIST on rename) - GC: orphaned entries removed by Cleanup, live entries preserved, last-reference removal collects the entry on the next Cleanup - shared entry: cache dir survives until the last referencing snapshot is removed - ownership isolation: same diffID with different uid/gid yields separate cache paths - no-op transparency: snapshots without LabelSnapshotDiffID leave the cache dir empty and use a real fs/ directory throughout Signed-off-by: Kevin Klues <[email protected]>
…ache Adds end-to-end integration tests for the overlay snapshotter's layer content cache feature under integration/lcc/. Tests cover cache hit/miss behavior, cross-image deduplication, and GC/prune correctness. Adds an lcc-integration stage to contrib/Dockerfile.test so the test suite can be built and run with a single docker build --target. Adds a top-level make lcc-integration target following the same pattern as the existing integration and cri-integration targets. Adds a non-blocking lcc-integration CI job that runs the integration tests. The job is not listed in the results needs array so it does not block merge. Signed-off-by: Kevin Klues <[email protected]>
…pport OverlayFS rejects lower_dir sequences containing duplicate paths. An image whose layer chain repeats the same diff-ID (e.g. [A, B, A]) would map both occurrences to the same cache directory, producing duplicate lower-dir entries. Add a sequence number — the count of times the same diff-ID already appears in the snapshot's parent chain (0-based) — appended to the cache directory name: <root>/cache/<algo>.<hex>.<uid>.<gid>.<seq>/ The sequence is derived by diffIDSeqInChain, an in-memory walk of lccState.snapInfo. snapInfo is a flat map of every committed snapshot's parent and diff-ID, populated eagerly at NewSnapshotter time by walking all committed snapshots once. This keeps sequence computation O(chain depth) with no bolt reads on the Prepare hot path. The seq is also persisted as the containerd.io/snapshot.diffID.seq label so that lccContentPath can reconstruct the cache directory path from labels alone, without a chain walk. This ensures Cleanup correctly identifies referenced cache dirs even when LCC is disabled but legacy LCC snapshots still exist. Signed-off-by: Kevin Klues <[email protected]>
|
PR needs rebase. DetailsInstructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. |
Adds a
layer_content_cacheoption to the overlayfs snapshotter that deduplicates extracted layer content across images at the snapshotter level.overlayfs follows symlinks when resolving lowerdir paths, so a snapshot's
fs/directory does not need to privately own its content. This PR extracts each layer once into a shared cache at<root>/cache/<algo>.<hex>.<uid>.<gid>/and replacesfs/with a symlink. On a cache hit,PreparesetsLabelSkipApplyand the unpacker skips extraction.Concurrent first-time extractors race via
os.Rename; losers symlink to the winner. Cache entries are garbage-collected when the last referencing snapshot is removed. Cleanup runs unconditionally even when the feature is disabled, so cache directories left over from a previously-enabled configuration are cleaned up. Chain IDs, snapshot keys, and all other snapshotter semantics are unchanged.Two label constants previously package-private in
core/unpackare exported fromcore/snapshotsso the snapshotter can use them without an import cycle. Thepkg/rootfs.applyLayerspath (used byctr images pull) is also fixed to forwardLabelSnapshotDiffIDonPrepareand honourLabelSkipApply; without this, LCC would be silently bypassed on that path and a cache hit would corrupt the cache directory by extracting on top of it.The existing overlay unit and snapshotter contract tests are re-run with LCC enabled to confirm transparency. A new
lcc_test.gocovers the LCC-specific code paths directly, and an end-to-end test package underintegration/lcc/exercises the full stack — image import, container execution, cross-image deduplication, and GC — including a test against a real flox environment to validate behaviour with Nix store path layers. A non-blockingtest-overlay-lccCI job runs the integration suite on every PR.Open questions
fs.DiskUsagefollows thefs/symlink to the shared cache directory, so every snapshot sharing a layer reports the full layer size. Should shared cache entries be excluded from per-snapshot usage accounting?When
LabelSkipApplyis set, the unpacker skipsApplyand therefore skips digest verification. Correctness relies on the content having been verified at first-commit time. Is that guarantee sufficient, or should a re-verification step be added?Closes #13307