Skip to content

overlay: add layer content cache for cross-image layer deduplication - #13308

Open
klueska wants to merge 7 commits into
containerd:mainfrom
klueska:lcc
Open

klueska wants to merge 7 commits into
containerd:mainfrom
klueska:lcc

Conversation

@klueska

@klueska klueska commented Apr 28, 2026 •

Copy link
Copy Markdown

Adds a layer_content_cache option 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 replaces fs/ with a symlink. On a cache hit, Prepare sets LabelSkipApply and 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/unpack are exported from core/snapshots so the snapshotter can use them without an import cycle. The pkg/rootfs.applyLayers path (used by ctr images pull) is also fixed to forward LabelSnapshotDiffID on Prepare and honour LabelSkipApply; 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.go covers the LCC-specific code paths directly, and an end-to-end test package under integration/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-blocking test-overlay-lcc CI job runs the integration suite on every PR.

Open questions

  • fs.DiskUsage follows the fs/ 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 LabelSkipApply is set, the unpacker skips Apply and 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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_cache configuration flag for the overlayfs snapshotter plugin and plumb an enable option into the snapshotter.
  • Export snapshot label constants in core/snapshots and teach the unpacker to honor LabelSkipApply to skip Apply on cache hits.
  • Implement LCC in overlay snapshotter (cache pathing, symlink setup, commit-time promotion, GC) with new unit and integration tests and a new pkg2oci helper.

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.

Comment thread plugins/snapshots/overlay/lcc.go Resolved
Comment thread integration/lcc/cmd/pkg2oci/main.go Resolved
Comment thread integration/lcc/main_test.go Resolved
Comment thread integration/lcc/main_test.go Resolved
Comment thread core/metadata/snapshot_test.go Resolved
Comment thread core/snapshots/snapshotter.go Resolved
Comment thread plugins/snapshots/overlay/lcc.go Resolved
Comment thread plugins/snapshots/overlay/lcc.go Resolved
Copilot AI review requested due to automatic review settings April 28, 2026 10:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Copilot AI review requested due to automatic review settings April 28, 2026 11:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review this pull request because it exceeds the maximum number of lines (20,000). Try reducing the number of changed lines and requesting a review from Copilot again.

// 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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: Why is the separator . instead of /? i.e. not:

Suggested change
LabelSkipApply = "containerd.io/snapshot.skip-apply"
LabelSkipApply = "containerd.io/snapshot/skip-apply"

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@mxpv mxpv left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work! Left a few comments I think are worth calling out.

Comment thread plugins/snapshots/overlay/overlay.go Outdated
cleanup := []string{}
var cleanup []string
if o.lccEnabled {
if cleanup, err = o.getOrphanedLCCPaths(ctx); err != nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this introduces racing?

  1. Cleanup: cleanupDirectories runs under tx, calls getOrphanedLCCPaths, finds cache/sha256.X.0.0.
  2. Cleanup: commits tx (remove is going to happen outside of tx via defer)
  3. Prepare: starts another tx, os.Stat("cache/sha256.X.0.0") still exists, so the symlink gets created
  4. Cleanup: removes os.RemoveAll("cache/sha256.X.0.0") in defer
  5. 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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@klueska klueska Apr 29, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread core/unpack/unpacker.go Resolved
Comment thread plugins/snapshots/overlay/lcc.go Outdated
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 {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@klueska klueska Apr 29, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"`

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 getOrphanedLCCPaths is 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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will think about this and add some documentation around it. Where should this be documented exactly?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot AI review requested due to automatic review settings April 29, 2026 12:03
@klueska
klueska force-pushed the lcc branch 2 times, most recently from 1759e44 to ef5c1d7 Compare May 4, 2026 11:52
Copilot AI review requested due to automatic review settings May 4, 2026 11:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread core/metadata/snapshot.go Resolved
Comment thread plugins/snapshots/overlay/lcc.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread script/setup/install-flox Resolved
Comment thread integration/lcc/main_test.go Resolved
Comment thread plugins/snapshots/overlay/lcc.go Resolved
Comment thread plugins/snapshots/overlay/overlay.go Resolved
Comment thread plugins/snapshots/overlay/overlay.go Resolved
Comment thread plugins/snapshots/overlay/lcc.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread plugins/snapshots/overlay/overlay.go Resolved
Comment thread core/unpack/unpacker.go Resolved
Comment thread plugins/snapshots/overlay/lcc.go Resolved
Comment thread plugins/snapshots/overlay/lcc.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.Walk errors are ignored while recalculating snapCount. If Walk fails, 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
		})

Comment on lines +191 to +198
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)
}
Comment on lines +184 to +187
_ = snapSvc.Walk(env.ctx, func(_ context.Context, _ snapshots.Info) error {
remaining++
return nil
})
Comment on lines +277 to +280
_ = snapSvc.Walk(env.ctx, func(_ context.Context, _ snapshots.Info) error {
bSnapshotCount++
return nil
})
klueska added 7 commits June 4, 2026 08:03
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]>
@kubernetes-prow

Copy link
Copy Markdown

PR needs rebase.

Details

Instructions 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Needs Reviewers

Development

Successfully merging this pull request may close these issues.

Proposal: cross-image layer deduplication for the overlay snapshotter

5 participants