Skip to content
Merged
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
2 changes: 1 addition & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -2397,7 +2397,7 @@ command's integration tests check its output.

`events` is the load-bearing payload. `summary` is pre-computed from `events` so consumers don't have to walk the array; its action counters count patch-level events, so a GC carrier event (the artifact-level `removed`, or `verified` on a dry run, that `repair` and `remove` emit for a sweep) bumps none of them. The sweep itself is reported once, in `gc`. `error` is set only on top-level failures (e.g. `manifest_not_found`); per-patch failures appear as `events[*]` with `action: "failed"`.

**One GC shape (v5.0).** Every command that sweeps orphan artifacts from `.socket/blobs`, `.socket/diffs` and `.socket/packages` reports the pass as the same `gc` object, `{removedBlobs, removedDiffArchives, removedPackageArchives, bytesFreed, removedRegistryEntries}`: the envelope's `gc` (`repair`, `remove`, `rollback`) and the `gc` of `scan --prune` / `--sync` (which adds its manifest and vendored keys beside them). `removedRegistryEntries` (additive) counts the entries of hosted mode's pnpm registry route that no lockfile uses any more and the run took out of pnpm-workspace.yaml and the pnpm locks (`repair`, `scan --prune` / `--sync`, and `scan --mode hosted --prune`); it is 0 from `remove` and `rollback`, which report the pins they restore as events. Those entries are lines of project files, not artifacts: `bytesFreed` and the carrier event's `count` leave them out, and each is its own `registry_entry_unused` event. On a dry run the counts are what the pass would remove, under the same keys (v5.0, MAJOR: scan's `--dry-run` preview no longer prints `prunableManifestEntries` / `orphanBlobs` / `orphanDiffArchives` / `orphanPackageArchives` / `revertableVendoredEntries` / `vendorOrphanDirs` / `bytesReclaimable`; it prints `prunedManifestEntries`, `removedBlobs`, `removedDiffArchives`, `removedPackageArchives`, `revertedVendoredEntries`, `removedVendorOrphanDirs` and `bytesFreed`, and leaves out only the keys a real pass alone can fill: `keptVendoredEntries`, `failedVendoredEntries`, `skipped`, `warnings`). `summary.bytesFreed` mirrors `gc.bytesFreed` on the envelope commands (0 when no GC ran: `repair --download-only`, `remove --preserve-state`, and every command without a GC pass). `gc` is absent when no sweep ran. v5.0 removes `summary.bytesDownloaded`, which no command ever emitted.
**One GC shape (v5.0).** Every command that sweeps orphan artifacts from `.socket/blobs`, `.socket/diffs` and `.socket/packages` reports the pass as the same `gc` object, `{removedBlobs, removedDiffArchives, removedPackageArchives, bytesFreed, removedRegistryEntries}`: the envelope's `gc` (`repair`, `remove`, `rollback`) and the `gc` of `scan --prune` / `--sync` (which adds its manifest and vendored keys beside them). The three stores sit in the manifest's directory, and only a directory named `.socket` is socket-patch's own (by the last component of the path as given: `--manifest-path manifest.json` run from inside `.socket/` gets the narrower sweep below). Beside a manifest outside one (`--manifest-path state/patches.json`, or a bare file name, whose directory is `--cwd`), `blobs/`, `diffs/` and `packages/` can be the project's own directories (a monorepo's `packages/`), so a sweep there takes blobs alone, and only the ones it can tell from a file of the project's: an unreferenced file in `blobs/` named by 64 hex digits whose bytes hash (git-sha256) to that name. Every other file is left where it is, out of the counts and `bytesFreed`: the project's own files, a blob that no longer hashes to its name, and everything in `diffs/` and `packages/` (no v5 command writes either; a pre-v5 archive left there is removed by hand). `blobs/` is removed only when the sweep took a file out of it and that left it empty. A `blobs` that is a link or a plain file is skipped, with no `cleanup_failed` warning; a link above it (`--cwd` through a symlink) is followed, as the blob writes follow it. `removedRegistryEntries` (additive) counts the entries of hosted mode's pnpm registry route that no lockfile uses any more and the run took out of pnpm-workspace.yaml and the pnpm locks (`repair`, `scan --prune` / `--sync`, and `scan --mode hosted --prune`); it is 0 from `remove` and `rollback`, which report the pins they restore as events. Those entries are lines of project files, not artifacts: `bytesFreed` and the carrier event's `count` leave them out, and each is its own `registry_entry_unused` event. On a dry run the counts are what the pass would remove, under the same keys (v5.0, MAJOR: scan's `--dry-run` preview no longer prints `prunableManifestEntries` / `orphanBlobs` / `orphanDiffArchives` / `orphanPackageArchives` / `revertableVendoredEntries` / `vendorOrphanDirs` / `bytesReclaimable`; it prints `prunedManifestEntries`, `removedBlobs`, `removedDiffArchives`, `removedPackageArchives`, `revertedVendoredEntries`, `removedVendorOrphanDirs` and `bytesFreed`, and leaves out only the keys a real pass alone can fill: `keptVendoredEntries`, `failedVendoredEntries`, `skipped`, `warnings`). `summary.bytesFreed` mirrors `gc.bytesFreed` on the envelope commands (0 when no GC ran: `repair --download-only`, `remove --preserve-state`, and every command without a GC pass). `gc` is absent when no sweep ran. v5.0 removes `summary.bytesDownloaded`, which no command ever emitted.

**GC carrier event (v5.0, MAJOR).** `repair` and `remove` add one artifact-level event (no `purl`) for a sweep that removed something: `removed` (`verified` on a dry run) with `bytes` = bytes freed and `details: {count, checked}` — `count` the artifacts swept (= `gc.removedBlobs + gc.removedDiffArchives + gc.removedPackageArchives`), `checked` the artifacts the sweep examined. It bumps no `summary` counter. `remove`'s carrier no longer carries `details.blobsRemoved` / `details.archivesRemoved` (read `gc`) or `details.rolledBack` (see `remove`'s `rolledBack` events).

Expand Down
146 changes: 146 additions & 0 deletions crates/socket-patch-cli/tests/manifest_path_ledger_root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -540,3 +540,149 @@ fn embedded_vex_allows_the_cwd_projects_own_manifest() {
}
}
}

/// A blob no patch references: socket-patch names a blob for the
/// git-sha256 of its bytes, and this is the name of `b"contents"`.
const ORPHAN_BLOB: &str = "blobs/cc66f07c79fe7e5ed6386b9bf3c254883ac85186f995b3a26fa60f69a6854055";

/// What a project keeps in directories of the same names. The last three
/// only look like artifacts: the bytes do not hash to the 64-digit name (a
/// store keyed by plain sha256), and nothing shows whose a `<uuid>.tar.gz`
/// is, named for the manifest's patch ([`UUID`]) or not.
const USER_FILES: &[&str] = &[
"blobs/logo.png",
"diffs/review.diff",
"packages/README.md",
"packages/tsconfig.base.json",
"packages/web/package.json",
"blobs/ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"diffs/33333333-3333-4333-8333-333333333333.tar.gz",
"packages/22222222-2222-4222-8222-222222222222.tar.gz",
];

/// #2301: a manifest outside `.socket/` makes its own directory the
/// artifact directory: the project root for a bare file name, `state/` for
/// the contract's `state/patches.json`. That directory is the user's, and
/// so are the files they keep in its `blobs/`, `diffs/` and `packages/`
/// (a monorepo's `packages/README.md`). The cleanup every one of these
/// commands ends with takes the unreferenced blob out and leaves the rest.
#[tokio::test]
async fn cleanup_beside_a_manifest_outside_dot_socket_keeps_the_users_files() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// `scan` asks the patch API what is available: nothing.
let api = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v0/orgs/test-org/patches/batch"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"packages": [],
"canAccessPaidPatches": false,
})))
.mount(&api)
.await;
let uri = api.uri();
let online = [
"--api-url",
&uri,
"--api-token",
"fake-token",
"--org",
"test-org",
];

// The patch [`UUID`], of a package that is not installed: `rollback`
// and `remove` drop the record and restore nothing.
let record = format!(
r#"{{"patches":{{"{PURL}":{{"uuid":"{UUID}","exportedAt":"2026-01-01T00:00:00Z",
"files":{{"package/index.js":{{"beforeHash":"{before}","afterHash":"{after}"}}}},
"vulnerabilities":{{}},"description":"d","license":"MIT","tier":"free"}}}}}}"#,
before = "a".repeat(64),
after = "b".repeat(64),
);
let empty = r#"{"patches":{}}"#;
// (name, the manifest, argv).
let commands: [(&str, &str, Vec<&str>); 6] = [
("repair", empty, vec!["repair", "--offline"]),
("rollback", &record, vec!["rollback", "--offline"]),
(
"remove",
&record,
vec!["remove", PURL, "--yes", "--offline"],
),
(
"scan --prune",
empty,
[&["scan", "--prune"][..], &online].concat(),
),
(
"scan --mode agent --prune",
empty,
[&["scan", "--mode", "agent", "--prune"][..], &online].concat(),
),
(
"scan --sync --prune",
empty,
[&["scan", "--sync", "--prune"][..], &online].concat(),
),
];

let mut failures = Vec::new();
for (manifest, artifact_dir) in [("socket-patches.json", ""), ("state/patches.json", "state")] {
for (name, manifest_json, argv) in &commands {
let tmp = tempfile::tempdir().expect("tempdir");
let root = tmp.path();
// One installed package: a scan that crawls nothing skips its GC.
let installed = root.join("node_modules/left-pad");
std::fs::create_dir_all(&installed).unwrap();
std::fs::write(
root.join("package.json"),
r#"{"name":"app","version":"0.0.0"}"#,
)
.unwrap();
std::fs::write(
installed.join("package.json"),
r#"{"name":"left-pad","version":"1.3.0"}"#,
)
.unwrap();
let stores = root.join(artifact_dir);
for file in USER_FILES.iter().chain([&ORPHAN_BLOB]) {
let file = stores.join(file);
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(file, b"contents").unwrap();
}
std::fs::write(root.join(manifest), manifest_json).unwrap();

let out = hermetic::binary_command()
.args(argv)
.args(["--manifest-path", manifest])
.current_dir(root)
.output()
.expect("run socket-patch");
let run = format!("{name} --manifest-path {manifest}");
if out.status.code() != Some(0) {
failures.push(format!(
"{run}: exit {:?}\n{}{}",
out.status.code(),
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
));
}
let deleted: Vec<&str> = USER_FILES
.iter()
.copied()
.filter(|file| {
std::fs::read(stores.join(file)).ok().as_deref() != Some(&b"contents"[..])
})
.collect();
if !deleted.is_empty() {
failures.push(format!("{run}: deleted the user's {deleted:?}"));
}
// The cleanup did run: the unreferenced blob is gone.
if stores.join(ORPHAN_BLOB).exists() {
failures.push(format!("{run}: kept the unreferenced {ORPHAN_BLOB}"));
}
}
}
assert!(failures.is_empty(), "\n{}", failures.join("\n"));
}
55 changes: 48 additions & 7 deletions crates/socket-patch-core/src/api/blob_fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,20 +80,30 @@ pub async fn get_corrupt_blobs(manifest: &PatchManifest, blobs_path: &Path) -> H
if !meta.is_file() {
continue;
}
let intact = match tokio::fs::File::open(&blob_path).await {
Ok(file) => compute_git_sha256_from_reader(meta.len(), file)
.await
.is_ok_and(|actual| blob_hash_matches(&hash, &actual)),
Err(_) => false,
};
if !intact {
if !blob_file_is_intact(&blob_path, &hash).await {
corrupt.insert(hash);
}
}

corrupt
}

/// Whether the file at `path` holds the blob `hash` names: a regular file
/// whose bytes hash to that git-sha256. An unreadable file does not.
///
/// The sweep asks this of files in a directory the user owns, so the open
/// is the FIFO-safe one: a pipe swapped in after the caller's `lstat`
/// fails fast instead of blocking the run, and the size is read off the
/// handle that is hashed.
pub(crate) async fn blob_file_is_intact(path: &Path, hash: &str) -> bool {
match crate::utils::fs::open_regular_file(path).await {
Ok((file, metadata)) => compute_git_sha256_from_reader(metadata.len(), file)
.await
.is_ok_and(|actual| blob_hash_matches(hash, &actual)),
Err(_) => false,
}
}

/// Download all missing `afterHash` blobs referenced in the manifest.
/// `on_progress` is called before each download with
/// `(hash, 1-based index, total)`.
Expand Down Expand Up @@ -561,6 +571,37 @@ mod tests {
use crate::manifest::schema::{PatchFileInfo, PatchManifest, PatchRecord};
use std::collections::HashMap;

/// The sweep hashes files in a directory the user owns. A pipe where a
/// blob was a moment ago must read as "not this blob" at once: a plain
/// open(2) of a FIFO waits for a writer that never comes.
#[cfg(unix)]
#[tokio::test]
async fn blob_file_is_intact_does_not_block_on_a_fifo() {
use std::os::unix::ffi::OsStrExt;
let dir = tempfile::tempdir().unwrap();
let hash = compute_git_sha256_from_bytes(b"contents");
let blob = dir.path().join(&hash);
std::fs::write(&blob, b"contents").unwrap();
assert!(blob_file_is_intact(&blob, &hash).await);
assert!(!blob_file_is_intact(&blob, &"0".repeat(64)).await);

let fifo = dir.path().join("fifo");
let c_path = std::ffi::CString::new(fifo.as_os_str().as_bytes()).unwrap();
assert_eq!(unsafe { libc::mkfifo(c_path.as_ptr(), 0o644) }, 0);
let deadline = std::time::Duration::from_secs(5);
let verdict = tokio::time::timeout(deadline, blob_file_is_intact(&fifo, &hash)).await;
if verdict.is_err() {
// Release the reader wedged in open(2) so the test binary can
// exit, then fail.
use std::os::unix::fs::OpenOptionsExt;
let _ = std::fs::OpenOptions::new()
.write(true)
.custom_flags(libc::O_NONBLOCK)
.open(&fifo);
}
assert_eq!(verdict.ok(), Some(false), "a FIFO must fail fast");
}

fn make_manifest_with_hashes(after_hashes: &[&str]) -> PatchManifest {
let mut files = HashMap::new();
for (i, ah) in after_hashes.iter().enumerate() {
Expand Down
Loading
Loading