Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ percent-encoding = "2.3.2"
proptest = "1.11.0"
pulldown-cmark = { version = "0.13.3", default-features = false, features = ["html"] }
rand = "0.10.1"
reflink-copy = "0.1.30"
Comment thread
epage marked this conversation as resolved.
Resolved
regex = "1.12.3"
rusqlite = { version = "0.42.0", features = ["bundled"] }
rustc-hash = "2.1.2"
Expand Down Expand Up @@ -206,6 +207,7 @@ os_info.workspace = true
pathdiff.workspace = true
portable-atomic.workspace = true
rand.workspace = true
reflink-copy.workspace = true
regex.workspace = true
rusqlite = { workspace = true, features = ["fallible_uint"] }
rustc-hash.workspace = true
Expand Down
11 changes: 8 additions & 3 deletions crates/cargo-test-support/src/compare.rs

@weihanglo weihanglo Nov 16, 2026 •

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.

Benchmark details (AI generated)

Just FYI, you might want to paste raw markdown table instead of images.

View changes since the review

Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,14 @@ fn add_regex_redactions(subs: &mut snapbox::Redactions) {
.unwrap();
subs.insert("[HASH]", regex!(r"/[a-z0-9\-_]+-(?<redacted>[0-9a-f]{16})"))
.unwrap();
// Match multi-part hashes like `06/b451d0d6f88b1d` used in directory paths
subs.insert("[HASH]", regex!(r"/(?<redacted>[a-f0-9]{2}\/[0-9a-f]{14})"))
.unwrap();
// Match multi-part hashesused in directory paths like:
// - `06/b451d0d6f88b1d`
// - `8a/eb4ec270816bc328e37bebc463004b0f285b2348440f1d8a9f8cec9c74af92`
subs.insert(
"[HASH]",
regex!(r"/(?<redacted>[a-f0-9]{2}\/[0-9a-f]{14,62})"),
)
.unwrap();
// Match file name hashes like `foo-06b451d0d6f88b1d`
subs.insert("[HASH]", regex!(r"[a-z0-9]+-(?<redacted>[a-f0-9]{16})"))
.unwrap();
Expand Down
19 changes: 19 additions & 0 deletions doc/book/src/reference/unstable.md

@ranger-ross ranger-ross Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Summary of open threads

Since this PR has a lot of open threads, its getting a bit difficult to navigate in GitHub.
I've updated the PR description Open Questions section with the unresolved questions as I see them.

I want to call out some of the threads here:

Let me know if I missed any important design decisions.
I'd love to be able to get this PR in the near future. ❤️


(unrelated file, just to make this a comment thread)

View changes since the review

Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ Each new feature described below should explain how to use it.
* [json-target-spec](#json-target-spec) --- Allows the use of `.json` custom target specs.
* [hint-msrv](#hint-msrv) --- Allows Cargo to set `-Zhint-msrv`
* [mem-stats](#mem-stats) --- Reports peak memory usage per build unit in `--timings`.
* [shared-object-storage](#shared-object-storage) --- Deduplicates build artifacts between workspaces
* rustdoc
* [rustdoc-map](#rustdoc-map) --- Provides mappings for documentation to link to external sites like [docs.rs](https://docs.rs/).
* [scrape-examples](#scrape-examples) --- Shows examples within documentation.
Expand Down Expand Up @@ -2029,6 +2030,24 @@ option:
hint-msrv = true
```

## shared-object-storage
* Tracking Issue: [rust-lang/cargo#17453](https://github.com/rust-lang/cargo/issues/17453)

Enables Cargo to automatically deduplicate files across build units and workspaces by hardlink/reflinking
against a shared content addressable object storage located in `~/.cargo/storage`.

You can set this via your global `~/.cargo/config.toml`, and nightly Cargo will

@weihanglo weihanglo Nov 20, 2026 •

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.

Just wonder, should we mention trim-paths so the dedup effect will be better?

View changes since the review

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added the following snippet:

Note that some configuration options can improve or degrade the storage reduction rate.
A notable example of this [`profile.trim-paths`](profiles.md#trim-paths) which helps by reducing the number of absolute paths in compiler outputs making more deduplication possible.

automatically use it, while stable Cargo will silently ignore the unstable
option:

```toml
[unstable]
shared-object-storage = true
```

Note that some configuration options can improve or degrade the storage reduction rate.
A notable example of this [`profile.trim-paths`](profiles.md#trim-paths) which helps by reducing the number of absolute paths in compiler outputs making more deduplication possible.

## builtin-dependencies
* Tracking Issue: [rust-lang/cargo#16960](https://github.com/rust-lang/cargo/issues/16960)
- RFC: [rust-lang/rfcs#3875](https://rust-lang.github.io/rfcs/3875-build-std-explicit-dependencies.html)
Expand Down
12 changes: 11 additions & 1 deletion src/bin/cargo/commands/clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@ pub fn cli() -> Command {
)
.value_name("SIZE")
.value_parser(parse_human_size),
)
.arg(
opt(
"max-shared-storage-age",
"Deletes any shared object data that has not been used \
since the given age (unstable)",
)
.value_name("DURATION")
.value_parser(parse_time_span),
Comment on lines +135 to +142

@epage epage Nov 16, 2026 •

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.

Somewhere where we can track details on this: pure-age based GC will likely not be a good idea.

If something is unused for 6 months, then yes, let's delete it.

Maybe for someone who always does rustup update, 6 weeks can work.

But for people who are doing heavy AI use, we'll likely also need "only keep the latest 30 entries" or something.

View changes since the review

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yeah, the best strategy here is tricky.
I agree that limiting to just size or age like other GC'd things might not be the best policy for shared blob/cache storage.

),

@epage epage Nov 17, 2026 •

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.

(arbitrary location)

Looking at yet another cargo clean reddit thread got me thinking: what is the minimum infrastructure we need in place to support users?

If we stabilized this as-is, users will keep running cargo clean and there will be little to no disk space savings and they will get pretty frustrated.

View changes since the review

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yeah... that is a good point.

one could make a reasonable argument that we should always run shared storage GC on cargo clean as without it, it makes cargo clean much less effective.

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.

cargo clean is already not efficient because of the progress reporting (#10552). I doubt running gc will hurt it too much than the overall benefit.

Perhaps one other alternative is when we have stable cargo clean gc, we do a simple check on SQLite /blob store metadata and suggest running cargo clean gc at the end of cargo clean. LLM Agents and human are good to at reading suggestions.

Though, I would rather always GC when running cargo clean.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Though, I would rather always GC when running cargo clean.

Tbh, I agree with this.
It simplifies the model for us, and the workflow for users.

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.

Ideally, we clean up orphaned files. The question then becomes how to detect orphans.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

the GC algorithm I implemented should detect orphans.
It's doing a mark and sweep alogrithm that starts at the snapshots and marks all reachable blobs.
Then it loops over all blobs that were not marked.

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.

This detects when something is orphaned by snapshots.

What I am talking about is when something is orphaned by a cargo clean removing the only build-dir that references those items in the object store.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hmm yeah good point.
I think it should be theoretically possible. For hardlinks we can use nlink on linux and windows has its own API.
Reflinks are more difficult but I believe its possible to check if there is at least one link.

The questions I have is: What should we do if an object is orphaned by cargo clean but still referenced by the build-index (snapshots)?

I think the answer is to discard the snapshot since the object being orphaned means this snapshot must not be in use anymore.
This way cargo clean will "just work" and delete everything that is unused from both build-dir and the shared object storage.

)
.after_help(color_print::cstr!(
Expand Down Expand Up @@ -200,13 +209,14 @@ fn gc(gctx: &GlobalContext, args: &ArgMatches) -> CliResult {
max_crate_size: size_opt("max-crate-size"),
max_git_size: size_opt("max-git-size"),
max_download_size: size_opt("max-download-size"),
max_shared_storage_age: duration_opt("max-shared-storage-age"),
};
if let Some(age) = duration_opt("max-download-age") {
gc_opts.set_max_download_age(age);
}
// If the user sets any options, then only perform the options requested.
// If no options are set, do the default behavior.
if !gc_opts.is_download_cache_opt_set() {
if !gc_opts.is_download_cache_opt_set() && !gc_opts.is_shared_storage_opt_set() {
gc_opts.update_for_auto_gc(gctx)?;
}

Expand Down
28 changes: 24 additions & 4 deletions src/compiler/build_runner/compilation_files.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! See [`CompilationFiles`].

use crate::compiler::shared_storage::SharedStorage;
use cargo_util::collections::HashMap;
use std::cell::OnceCell;
use std::fmt;
Expand All @@ -9,7 +10,7 @@ use std::sync::Arc;

use cargo_util_schemas::core::CrateType;
use cargo_util_schemas::manifest::TomlTrimPaths;
use tracing::debug;
use tracing::{debug, warn};

use super::{BuildContext, BuildRunner, CompileKind, FileFlavor, Layout};
use crate::compiler::trim_paths;
Expand Down Expand Up @@ -141,6 +142,8 @@ pub struct CompilationFiles<'a, 'gctx> {
metas: HashMap<Unit, Metadata>,
/// For each Unit, a list all files produced.
outputs: HashMap<Unit, OnceCell<Arc<Vec<OutputFile>>>>,
/// The shared object storage
shared_storage: Option<Arc<SharedStorage>>,
}

/// Info about a single file emitted by the compiler.
Expand Down Expand Up @@ -172,7 +175,7 @@ impl<'a, 'gctx: 'a> CompilationFiles<'a, 'gctx> {
build_runner: &BuildRunner<'a, 'gctx>,
host: Layout,
target: HashMap<CompileTarget, Layout>,
) -> CompilationFiles<'a, 'gctx> {
) -> CargoResult<CompilationFiles<'a, 'gctx>> {
let mut metas = HashMap::default();
for unit in &build_runner.bcx.roots {
metadata_of(unit, build_runner, &mut metas);
Expand All @@ -182,15 +185,28 @@ impl<'a, 'gctx: 'a> CompilationFiles<'a, 'gctx> {
.cloned()
.map(|unit| (unit, OnceCell::new()))
.collect();
CompilationFiles {
let shared_storage = build_runner
.bcx
.gctx
.shared_storage_dir()
.and_then(|shared| {
SharedStorage::new(shared, build_runner.bcx.ws.build_dir().as_path_unlocked())
.inspect_err(|err| {
warn!(?err, "Could not initialize object storage, disabling")
})
.ok()
})
.map(Arc::new);
Ok(CompilationFiles {
ws: build_runner.bcx.ws,
host,
target,
export_dir: build_runner.bcx.build_config.export_dir.clone(),
roots: build_runner.bcx.roots.clone(),
metas,
outputs,
}
shared_storage,
})
}

/// Returns the appropriate directory layout for either a plugin or not.
Expand Down Expand Up @@ -669,6 +685,10 @@ impl<'a, 'gctx: 'a> CompilationFiles<'a, 'gctx> {
Ok(Arc::new(ret))
}

pub fn shared_storage(&self) -> Option<Arc<SharedStorage>> {
self.shared_storage.clone()
}

/// Append the SBOM suffix to the file name.
fn append_sbom_suffix(link: &PathBuf) -> PathBuf {
const SBOM_FILE_EXTENSION: &str = ".cargo-sbom.json";
Expand Down
8 changes: 7 additions & 1 deletion src/compiler/build_runner/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! [`BuildRunner`] is the mutable state used during the build process.

use cargo_util::collections::{HashMap, HashSet};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

Expand Down Expand Up @@ -94,6 +95,10 @@ pub struct BuildRunner<'a, 'gctx> {

/// Manages locks for build units when fine grain locking is enabled.
pub lock_manager: Arc<LockManager>,

/// The hashes of the unit outputs (not the individual objects) that were used
/// during the build.
pub object_storage_outputs: BTreeSet<String>,
}

impl<'a, 'gctx> BuildRunner<'a, 'gctx> {
Expand Down Expand Up @@ -135,6 +140,7 @@ impl<'a, 'gctx> BuildRunner<'a, 'gctx> {
failed_scrape_units: Arc::new(Mutex::new(HashSet::default())),
unused_dep_state: UnusedDepState::new(bcx),
lock_manager: Arc::new(LockManager::new()),
object_storage_outputs: BTreeSet::new(),
})
}

Expand Down Expand Up @@ -455,7 +461,7 @@ impl<'a, 'gctx> BuildRunner<'a, 'gctx> {

self.record_units_requiring_metadata();

let files = CompilationFiles::new(self, host_layout, targets);
let files = CompilationFiles::new(self, host_layout, targets)?;
self.files = Some(files);
Ok(())
}
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/job_queue/job_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ impl<'a, 'gctx> JobState<'a, 'gctx> {
self.messages.push(Message::SectionTiming(self.id, section));
}

pub fn add_object_storage_output(&self, hash: String) {
self.messages.push(Message::ObjectStorageOutput(hash));
}

/// Reports the peak resident set size (in bytes) of this unit's process,
/// for the `--timings` report.
pub fn peak_memory(&self, bytes: u64) {
Expand Down
Loading
Loading