Skip to content

Commit ff949a3

Browse files
Report an unreadable vendor ledger instead of "No patch found" in remove and rollback (#2250)
* Start unreadable-ledger-not-found Refs #2249. Assisted-by: Claude Code * Name the unreadable ledger, not "No patch found" A vendored project records its patches only in the vendor ledger. When that file could not be parsed, remove <target> and rollback <target> answered "No patch found matching identifier" for every target the manifest and the hosted pins did not hold. The ledger may hold it, and the lockfiles still install its artifact. report and a bare rollback already named the ledger. A target that selects nothing in the stores that could be read now fails with vendor_state_unreadable in both commands, for an identifier and for a rollback path target, in place of not_found, patch_not_found and path_glob_no_match. The exit code stays 1. remove takes the error it already raised before a vendored revert; the two share one mapping. With every store readable the "not found" codes are unchanged, and so is a target that the manifest or a hosted pin does hold. Fixes #2249. Assisted-by: Claude Code * Refuse an unreadable ledger before any change Review of the previous commit found the same input mishandled in three more places. remove <target> for a manifest record restored the installed files in place and only then failed with vendor_state_unreadable, reporting no event and rolledBack 0. The contract says the refusal comes before any mutation. It now comes before the in-place rollback, so nothing is restored; the ledger no longer reaches that rollback as "nothing vendored". With no manifest, remove and rollback probed for the ledger with a stat and took any error for absence, so a ledger that could not be stat'd (a symlink loop, an unsearchable directory) was "No patches in this project". Only a missing file is absence now, as for the manifest. The error of an unmatched target names that target, so a run given several can tell which one stopped it, and rollback keeps the note that names the project directories below holding it. Refs #2249. Assisted-by: Claude Code * Cover repair's probe; keep the directory hint A second review of the branch. repair probed for the vendor ledger with the same stat as remove and rollback did: with no manifest, a ledger it could not stat was manifest_not_found. Only a missing file is absence there too now, and the run reports the ledger. The contract said a ledger under an unsearchable .socket/vendor/ fails as vendor_state_unreadable. It does not: the apply lock's journal check reads that directory first and fails as lock_io, as it already did with a manifest present. The contract and the comments say that now. rollback <name> keeps its "to target a directory instead" hint when the ledger is what failed. The contract's patched_projects_below row covers an identifier, not a path target, which never carried the note. Refs #2249. Assisted-by: Claude Code * Put rollback's directory hint before the ledger error A review comment on the branch: with the vendor ledger unreadable, rollback <name> appended "(to target a directory instead, use ./x or x/**)" after the ledger's own error, so the hint read as part of the parse error: ... key must be a string at line 4 column 1 (to target a directory instead, use ./x or x/**) The hint now ends the clause about the target, ahead of that error: cannot read .socket/vendor/state.json to look up x, which matches nothing else in the project (to target a directory instead, use ./x or x/**): corrupt ./.socket/vendor/state.json: key must be ... patch_not_found reads as before, and a PURL or UUID target still carries no hint. A test pins where the hint lands. Refs #2249. Assisted-by: Claude Code --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d88450c commit ff949a3

8 files changed

Lines changed: 499 additions & 90 deletions

File tree

‎crates/socket-patch-cli/CLI_CONTRACT.md‎

Lines changed: 7 additions & 7 deletions
Large diffs are not rendered by default.

‎crates/socket-patch-cli/src/commands/remove.rs‎

Lines changed: 79 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,28 @@ async fn track_failed(
334334
}
335335
}
336336

337+
/// Refuse the run with the vendor ledger's load error
338+
/// (`vendor_state_unreadable`, exit 1), before anything is changed.
339+
/// `patches` are the manifest records the target matched, for the event;
340+
/// when it matched nothing anywhere, `unmatched` is the target.
341+
async fn refuse_unreadable_ledger(
342+
args: &RemoveArgs,
343+
err: &std::io::Error,
344+
unmatched: Option<&str>,
345+
patches: &[PatchOutcome],
346+
telemetry: &TelemetryAuth,
347+
) -> i32 {
348+
let error = crate::json_envelope::vendor_ledger_load_error(err, unmatched, "");
349+
track_failed(args, &error.code, &error.message, patches, telemetry).await;
350+
emit_error_envelope(
351+
args.common.json,
352+
args.common.dry_run,
353+
&error.code,
354+
error.message,
355+
);
356+
1
357+
}
358+
337359
/// The `mode: "vendored"` / `"hosted"` tag of a patch event.
338360
fn mode_details(mode: &str) -> serde_json::Value {
339361
serde_json::json!({ "mode": mode })
@@ -533,10 +555,13 @@ pub async fn run(args: RemoveArgs) -> i32 {
533555
// restore retires them from the manifest.
534556
let hosted_pins: Vec<HostedPin> = hosted_inventory.unwindable();
535557
if manifest_missing {
536-
let vendor_ledger_exists = project_state
537-
&& tokio::fs::metadata(args.common.project_root().join(VENDOR_STATE_REL))
538-
.await
539-
.is_ok();
558+
// Only a missing ledger is "no ledger": with one that cannot even
559+
// be stat'd the run goes on, and its first read under
560+
// `.socket/vendor/` (the lock's journal check, else the load
561+
// below) reports the failure.
562+
let ledger = args.common.project_root().join(VENDOR_STATE_REL);
563+
let vendor_ledger_exists =
564+
project_state && !matches!(tokio::fs::try_exists(&ledger).await, Ok(false));
540565
if !vendor_ledger_exists && hosted_pins.is_empty() {
541566
// Contested hosted wiring is still hosted state: name it
542567
// instead of reporting a bare project.
@@ -652,9 +677,9 @@ pub async fn run(args: RemoveArgs) -> i32 {
652677

653678
// The vendor ledger, loaded ONCE under the lock: it scopes the nested
654679
// rollback (vendor-owned purls are not restored in place) and drives
655-
// the vendored leg. An unreadable ledger degrades to "nothing vendored"
656-
// for the rollback and fails closed at the vendored leg — exactly where
657-
// the run is about to mutate vendored state.
680+
// the vendored leg. An unreadable ledger refuses the run before either
681+
// (below), except a removal that only restores hosted pins, which the
682+
// lockfiles record.
658683
let vendor_state_result = if project_state {
659684
load_state(&args.common.project_root()).await
660685
} else {
@@ -722,22 +747,25 @@ pub async fn run(args: RemoveArgs) -> i32 {
722747
if matching.is_empty() {
723748
// Ledger-only entries (vendored mode keeps no manifest record) —
724749
// `remove` is their per-purl exit path (alongside `vendor
725-
// --revert`'s all-at-once). An unreadable ledger falls through to
726-
// `not_found`: nothing is mutated on that path.
727-
if let Ok(state) = vendor_state_result {
728-
let ledger_matches = vendor_entries_matching(&state, None, &target);
729-
if !ledger_matches.is_empty() {
730-
return remove_ledger_only(
731-
&args,
732-
&target,
733-
ledger_matches,
734-
state,
735-
&telemetry,
736-
commit_recovery,
737-
)
738-
.await;
750+
// --revert`'s all-at-once).
751+
let ledger_unread = match vendor_state_result {
752+
Ok(state) => {
753+
let ledger_matches = vendor_entries_matching(&state, None, &target);
754+
if !ledger_matches.is_empty() {
755+
return remove_ledger_only(
756+
&args,
757+
&target,
758+
ledger_matches,
759+
state,
760+
&telemetry,
761+
commit_recovery,
762+
)
763+
.await;
764+
}
765+
None
739766
}
740-
}
767+
Err(e) => Some(e),
768+
};
741769

742770
// Hosted-only patches likewise have no manifest entry — their
743771
// lockfile pins are their only persistence, and `remove` is their
@@ -754,6 +782,14 @@ pub async fn run(args: RemoveArgs) -> i32 {
754782
.await;
755783
}
756784

785+
// The target is in no store that could be read. The ledger could
786+
// not be, and may hold it: that is the ledger's error, not
787+
// `not_found`.
788+
if let Some(e) = ledger_unread {
789+
let unmatched = Some(args.identifier.as_str());
790+
return refuse_unreadable_ledger(&args, &e, unmatched, &[], &telemetry).await;
791+
}
792+
757793
let msg = format!("No patch found matching identifier: {}", args.identifier);
758794
track_failed(&args, "not_found", &msg, &[], &telemetry).await;
759795
if args.common.json {
@@ -768,6 +804,18 @@ pub async fn run(args: RemoveArgs) -> i32 {
768804
return 1;
769805
}
770806

807+
// An unreadable ledger is a hard error before any mutation. The
808+
// in-place rollback below needs it to leave vendor-owned purls alone,
809+
// and the vendored leg cannot know what it would leave wired; restoring
810+
// files first and failing after would report nothing of what changed.
811+
let mut vendor_state = match vendor_state_result {
812+
Ok(state) => state,
813+
Err(e) => {
814+
let failed = matched_patches(OUTCOME_FAILED, "vendor_state_unreadable");
815+
return refuse_unreadable_ledger(&args, &e, None, &failed, &telemetry).await;
816+
}
817+
};
818+
771819
// A record no crawler of this CLI can look for (a newer CLI's
772820
// ecosystem, a key that is not a purl) cannot be rolled back here, and
773821
// the nested rollback would pass over it unseen. Dropping its record
@@ -842,10 +890,7 @@ pub async fn run(args: RemoveArgs) -> i32 {
842890
let (vendored, hosted) = if args.skip_rollback {
843891
(0, 0)
844892
} else {
845-
let vendored = vendor_state_result
846-
.as_ref()
847-
.map(|st| vendor_entries_matching(st, Some(&manifest), &target).len())
848-
.unwrap_or(0);
893+
let vendored = vendor_entries_matching(&vendor_state, Some(&manifest), &target).len();
849894
let hosted = hosted_pins_matching(&hosted_pins, &target, &matched_keys).len();
850895
(vendored, hosted)
851896
};
@@ -867,15 +912,11 @@ pub async fn run(args: RemoveArgs) -> i32 {
867912
// ── nested in-place rollback ────────────────────────────────────────
868913
// Vendor-owned purls are excluded from the in-place restore (the
869914
// vendored leg below reverts them) unless their Cargo shared-cache copy
870-
// still carries an agent-mode patch; an unreadable ledger degrades to
871-
// "nothing vendored" here and fails closed at that leg. Under global
872-
// scope the project's ledger still owns its own NuGet install.
915+
// still carries an agent-mode patch. Under global scope the project's
916+
// ledger still owns its own NuGet install.
873917
// The identifier is the scope, so `--ecosystems` does not narrow it.
874918
let vendored_keys: HashSet<PurlKey> = if project_state {
875-
vendor_state_result
876-
.as_ref()
877-
.map(socket_patch_core::vendor::VendorState::purl_keys)
878-
.unwrap_or_default()
919+
vendor_state.purl_keys()
879920
} else {
880921
crate::commands::vendor_owned_keys(
881922
&GlobalArgs {
@@ -1085,33 +1126,11 @@ pub async fn run(args: RemoveArgs) -> i32 {
10851126
// must not see them dropped from the ledger — its before-blob gate
10861127
// would demand blobs the vendor flow never downloaded) and BEFORE the
10871128
// manifest mutation, so a revert failure aborts with the manifest
1088-
// intact (mirroring the `rollback_failed` contract). A corrupt ledger
1089-
// is a hard error: we are about to mutate and cannot know what we
1090-
// would leave wired. `--skip-rollback` ("don't touch my tree") skips
1091-
// the revert too — the wiring stays until `vendor --revert` / a later
1092-
// `remove` undoes it (a manifest-tracked entry is also reconcile-reverted
1093-
// by the next `vendor` run; detached entries never are).
1094-
let mut vendor_state = match vendor_state_result {
1095-
Ok(s) => s,
1096-
Err(e) => {
1097-
let msg = format!("cannot read .socket/vendor/state.json: {e}");
1098-
track_failed(
1099-
&args,
1100-
"vendor_state_unreadable",
1101-
&msg,
1102-
&matched_patches(OUTCOME_FAILED, "vendor_state_unreadable"),
1103-
&telemetry,
1104-
)
1105-
.await;
1106-
emit_error_envelope(
1107-
args.common.json,
1108-
args.common.dry_run,
1109-
"vendor_state_unreadable",
1110-
msg,
1111-
);
1112-
return 1;
1113-
}
1114-
};
1129+
// intact (mirroring the `rollback_failed` contract). `--skip-rollback`
1130+
// ("don't touch my tree") skips the revert too — the wiring stays until
1131+
// `vendor --revert` / a later `remove` undoes it (a manifest-tracked
1132+
// entry is also reconcile-reverted by the next `vendor` run; detached
1133+
// entries never are).
11151134
let vendored_matches = vendor_entries_matching(&vendor_state, Some(&manifest), &target);
11161135
let mut vendor_leg = RemoveVendorLeg {
11171136
skipped: project_owned,

‎crates/socket-patch-cli/src/commands/repair.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,9 @@ pub async fn run(args: RepairArgs) -> i32 {
102102
.common
103103
.project_root()
104104
.join(socket_patch_core::vendor::VENDOR_STATE_REL);
105-
let mut has_vendor_traces = tokio::fs::metadata(&state_file).await.is_ok();
105+
// Only a missing ledger is "no ledger": one that cannot even be
106+
// stat'd is a trace, and the run's first read of it reports it.
107+
let mut has_vendor_traces = !matches!(tokio::fs::try_exists(&state_file).await, Ok(false));
106108
if !has_vendor_traces {
107109
let refs = crate::commands::vendored_backend::repair::scan_vendor_references(
108110
&args.common.project_root(),

‎crates/socket-patch-cli/src/commands/rollback.rs‎

Lines changed: 40 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1969,10 +1969,14 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 {
19691969
return 1;
19701970
}
19711971
};
1972+
// Only a missing ledger is "no ledger": with one that cannot even be
1973+
// stat'd the run goes on, and its first read under `.socket/vendor/`
1974+
// (the lock's journal check, else the load below) reports the failure.
19721975
let vendor_ledger_exists = project_state
1973-
&& tokio::fs::metadata(ledger_root.join(".socket/vendor/state.json"))
1974-
.await
1975-
.is_ok();
1976+
&& !matches!(
1977+
tokio::fs::try_exists(ledger_root.join(".socket/vendor/state.json")).await,
1978+
Ok(false)
1979+
);
19761980
// The hosted pins the lockfiles wire (read-only discovery; the restore
19771981
// re-reads every file under the lock before it writes).
19781982
let hosted_inventory = if project_state {
@@ -2288,18 +2292,26 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 {
22882292
} else {
22892293
format!(" (to target a directory instead, use ./{id} or {id}/**)")
22902294
};
2291-
let msg = format!("No patch found matching identifier: {id}{hint}");
2292-
track_unstarted(&args, "patch_not_found", &msg, &telemetry).await;
2295+
// In no store that could be read. A ledger that could not be
2296+
// may hold it: its error then, not `patch_not_found`. Either
2297+
// way the hint ends what is said about the target.
2298+
let error = match &vendor_state_result {
2299+
Err(e) => {
2300+
crate::json_envelope::vendor_ledger_load_error(e, Some(&id.to_string()), &hint)
2301+
}
2302+
Ok(_) => EnvelopeError::new(
2303+
"patch_not_found",
2304+
format!("No patch found matching identifier: {id}{hint}"),
2305+
),
2306+
};
2307+
track_unstarted(&args, &error.code, &error.message, &telemetry).await;
22932308
if args.common.json {
2294-
let mut env = error_envelope(
2295-
args.common.dry_run,
2296-
EnvelopeError::new("patch_not_found", msg),
2297-
);
2309+
let mut env = error_envelope(args.common.dry_run, error);
22982310
env.warnings
22992311
.extend(below.unmatched(&args.common).await.warnings());
23002312
println!("{}", env.to_pretty_json());
23012313
} else {
2302-
eprintln!("Error: {msg}");
2314+
eprintln!("Error: {}", crate::ui::sentence_case(&error.message));
23032315
below.unmatched(&args.common).await.print();
23042316
}
23052317
return 1;
@@ -2357,18 +2369,27 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 {
23572369
.enumerate()
23582370
.find(|(idx, _)| !matched_patterns.contains(idx))
23592371
{
2360-
let msg = format!(
2361-
"path pattern matched no patched packages: {} (path targets select \
2362-
installed copies; patches for uninstalled packages are reachable by \
2363-
identifier or an unscoped rollback)",
2364-
unmatched.1
2365-
);
2366-
track_unstarted(&args, "path_glob_no_match", &msg, &telemetry).await;
2372+
// The candidates left out the entries of a ledger that could
2373+
// not be read, and the pattern may select one of them: the
2374+
// ledger's error then, not `path_glob_no_match`.
2375+
let error = match &vendor_state_result {
2376+
Err(e) => crate::json_envelope::vendor_ledger_load_error(e, Some(unmatched.1), ""),
2377+
Ok(_) => EnvelopeError::new(
2378+
"path_glob_no_match",
2379+
format!(
2380+
"path pattern matched no patched packages: {} (path targets select \
2381+
installed copies; patches for uninstalled packages are reachable by \
2382+
identifier or an unscoped rollback)",
2383+
unmatched.1
2384+
),
2385+
),
2386+
};
2387+
track_unstarted(&args, &error.code, &error.message, &telemetry).await;
23672388
emit_rollback_error(
23682389
args.common.json,
23692390
args.common.dry_run,
2370-
"path_glob_no_match",
2371-
&msg,
2391+
&error.code,
2392+
&error.message,
23722393
);
23732394
return 1;
23742395
}

‎crates/socket-patch-cli/src/json_envelope.rs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,34 @@ pub(crate) fn manifest_load_error_code(err: &std::io::Error) -> &'static str {
674674
}
675675
}
676676

677+
/// The top-level error of a `remove` or `rollback` that cannot go on
678+
/// without the vendor ledger, which exists but could not be loaded. One
679+
/// mapping for both commands and both of their reasons:
680+
///
681+
/// - `remove` is about to act on records the ledger may also hold
682+
/// (`unmatched` is `None`);
683+
/// - the run's target selected nothing in the stores that could be read
684+
/// (`unmatched` is that target). That is never "not found", which is a
685+
/// statement about every store: the ledger is a vendored project's only
686+
/// record of its patches, so it may hold the target.
687+
///
688+
/// `hint` is the caller's parenthesis about that target (`rollback`'s "to
689+
/// target a directory instead"), or empty. It stays with the target, ahead
690+
/// of the ledger's own error: after it, the hint reads as part of it.
691+
pub(crate) fn vendor_ledger_load_error(
692+
err: &std::io::Error,
693+
unmatched: Option<&str>,
694+
hint: &str,
695+
) -> EnvelopeError {
696+
let lookup = unmatched.map_or_else(String::new, |target| {
697+
format!(" to look up {target}, which matches nothing else in the project{hint}")
698+
});
699+
EnvelopeError::new(
700+
"vendor_state_unreadable",
701+
format!("cannot read .socket/vendor/state.json{lookup}: {err}"),
702+
)
703+
}
704+
677705
/// The JSON a self-enforced usage error prints under `--json`: a full
678706
/// [`Envelope`] with `status: "error"`.
679707
fn usage_error_json(

0 commit comments

Comments
 (0)