A newer agent patch whose apply fails still replaces the recorded one: rollback refuses the package, and after a prune every scan and apply exits 1

Abierto
#2,299 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
48/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
rust
Área
backend, cli

Línea de trabajo

Start with download_and_apply_patches_into in crates/socket-patch-cli/src/commands/agent_download.rs and the corresponding save/apply sequence in get.rs; the issue also identifies crates/socket-patch-cli/tests/in_process_agent_patch_replace.rs and two failing tests. Read the replacement handling and existing rollback behavior, then run the named integration tests. Done means a failed replacement leaves enough recorded state for rollback to restore the prior patched file, while the tests capture the maintainer's chosen strict replacement behavior.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

agent:triaged arch-audit bug priority:p1

[agent] Found by the architecture refactor routine (ledger discussion #2244, lead L42), on main at cfc870f.

Problem

An agent-mode scan or get that finds a newer patch for a package the project already patches writes the new record into the manifest first and applies the new patch second. When the apply cannot finish, the record stays replaced. The installed files still hold the old patch's bytes, and the record that described them is gone.

Four ways to get there without the user having edited anything:

  • the new patch's blob cannot be downloaded (one 5xx, where the patch view did not carry the file contents);
  • --strict / SOCKET_STRICT, which refuses a file that holds the old patch's output;
  • .socket/blobs/ does not hold the old patch's blob (not committed, or deleted);
  • get <uuid> --save-only, which replaces the record and applies nothing. No command fails until the apply.

After that the only proof that the installed bytes are a Socket patch's output is the old patch's blob in .socket/blobs/, which no record references any more. The next cleanup deletes it: the --prune of the same failing run, repair, or a rollback that itself fails. From then on apply refuses the file on every run, and rollback and remove refuse the package.

Who it hurts

  • A CI job or a bot that runs scan --mode agent --prune over dependencies that are already patched (a cached node_modules, a developer's tree). One failed download, and every later scan and apply there exits 1 until someone reinstalls the package or runs apply --force. scan, apply and apply --check name neither.
  • Anyone who follows the advice the commands print after the failed run. apply --check says "Run socket-patch apply", which fails. repair says "Repair complete." and deletes the blob the recovery needed.
  • Someone who wants the patch off. rollback says the file "was edited, or is another build's; nothing here can restore it". The file holds exactly what the earlier Socket patch wrote, and its original is available.
  • vex withholds the statement for a vulnerability the installed bytes still fix. Before the scan it was attested.

Evidence on main

The binary is built from cfc870f. The project is an npm tree with six patched packages and a stand-in patch API (both scripts are in the routine's ledger entry of 2026-11-26 22:56Z; this run's entry adds the failure rules). [email protected] is patched and recorded with patch aaaaaaaa-…-0001, and apply --check passes. The API then serves a newer patch for the same release, aaaaaaaa-…-0011, which changes the same file, package/index.js.

One failed blob download under scan --prune. The patch view carries no file contents, so the apply downloads the blob; that request answers 500 once. The transcripts leave out the lines about the other five packages.

$ socket-patch scan --mode agent --prune
1 package has a newer patch available.
  [update] pkg:npm/[email protected] (replacing aaaaaaaa)
Failed to download 1 blob:
  - 3a86bf7e98ed...: Failed to fetch blob 3a86bf7e…: status 500: injected
Error: Some patch artifacts could not be downloaded; cannot apply patches.
Error: Some patches could not be applied.
GC: pruned 0 manifest entries and removed 1 orphan file (42 B).              (exit 1)

The manifest now records …-0011. node_modules/lodash/index.js still holds the output of …-0001. The file the GC removed is the after-blob of …-0001. The API is healthy for every command below.

$ socket-patch scan --mode agent --prune
Downloaded 1 blob
Error: Failed to patch pkg:npm/[email protected]: Cannot apply patch: package/index.js - File hash does not match expected value
Applied 0 of 6 patches: 5 already patched, 1 failed.
Error: Some patches could not be applied.                                    (exit 1)

$ socket-patch apply
Downloaded 1 blob
Error: Failed to patch pkg:npm/[email protected]: Cannot apply patch: package/index.js - File hash does not match expected value
Summary: 0 of 6 targeted patches applied, 5 already patched, 1 failed, 0 not found on disk   (exit 1)

$ socket-patch apply --check
Error: Patches are OUT OF SYNC:
  pkg:npm/[email protected]: an installed copy matches neither the original nor the patched bytes
Run `socket-patch apply` to regenerate them.                                 (exit 1)

$ socket-patch rollback lodash
Failed to roll back:
  pkg:npm/[email protected]: Cannot roll back: package/index.js - File holds neither the patched nor the original content. Cannot safely roll back.
A file that holds neither content was edited, or is another build's; nothing here can restore it:
  Reinstall the package to get the published files back, then roll back again.
  Or drop the record and leave the files as they are: `socket-patch remove <purl> --skip-rollback`.
Error: Some patches could not be rolled back.                                (exit 1)

$ socket-patch vex --output -
Warning: omitting pkg:npm/[email protected] from VEX: a patched file matches neither the original nor the patched content (hash_mismatch)
Emitted 5 VEX statements                                                     (exit 0)

--strict, with no failure injected. The view carries the file contents.

$ socket-patch scan --mode agent --strict
1 package has a newer patch available.
  [update] pkg:npm/[email protected] (replacing aaaaaaaa)
Error: Failed to patch pkg:npm/[email protected]: Cannot apply patch: package/index.js - File hash does not match expected value
Applied 0 of 6 patches: 5 already patched, 1 failed.
Error: Some patches could not be applied.                                    (exit 1)

$ socket-patch rollback lodash
Failed to roll back:
  pkg:npm/[email protected]: Cannot roll back: package/index.js - File holds neither the patched nor the original content. Cannot safely roll back.
…
Freed 42 B of unused blobs and archives                                      (exit 1)

The manifest records …-0011 after the scan, and the failed rollback frees the after-blob of …-0001.

What each sequence leaves. Each starts from the in-sync project and ends with the API healthy.

Sequence Manifest record Installed file Last command
scan (no failure) new new patch exit 0; rollback lodash restores the original
scan (blob 500), scan new new patch exit 0: a plain retry recovers while the old blob is still stored
scan --prune (blob 500), scan --prune new old patch exit 1, and on every later run
scan (blob 500), repair, apply new old patch repair exit 0, apply exit 1
get <new uuid> (blob 500), repair, apply new old patch apply exit 1
scan --strict, apply --strict, repair, apply new old patch apply exit 1
scan --strict, apply new new patch exit 0
get <new uuid> --save-only, repair, apply new old patch get and repair exit 0 ("Removed 1 unused blob", "Repair complete."), apply exit 1, then rollback lodash exit 1
get <new uuid> --save-only, apply new new patch exit 0
scan with .socket/blobs/ emptied first new old patch exit 1; rollback refuses the package
scan, the newer patch's view answers 500 old old patch exit 1; apply --check passes, rollback works
scan, the newer patch drops a file and the old one cannot be rolled back old old patch exit 1, replaced_patch_not_restored; apply --check passes

The last two rows are the outcome the contract describes for a replacement that cannot go through.

Two tests that fail on main. Added to crates/socket-patch-cli/tests/in_process_agent_patch_replace.rs, beside the suite's strict_replacement_applies_the_new_patch_to_the_shared_file. Patch B and patch C both change index.js alone, so replacing B with C drops no file.

const UUID_C: &str = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
const INDEX_C: &[u8] = b"module.exports = 'index patch C';\n";
const PATCH_C: &[PatchFile] = &[(INDEX, INDEX_ORIGINAL, INDEX_C)];

async fn project_with_patch_b(root: &Path, server: &MockServer) {
    install(root);
    serve(server, UUID_B, PATCH_B).await;
    assert_eq!(agent_scan(root, server).await, 0, "patch B must apply");
    assert_eq!(read(root, INDEX), INDEX_B);
    assert_eq!(recorded_uuid(root), UUID_B);
}

// `strict_scan` is `agent_scan` with `common.strict = true`.

#[tokio::test]
#[serial]
async fn strict_replacement_that_drops_no_file_applies_the_new_patch() {
    let server = MockServer::start().await;
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    project_with_patch_b(root, &server).await;

    serve(&server, UUID_C, PATCH_C).await;
    let code = strict_scan(root, &server).await;

    assert_eq!(
        (code, recorded_uuid(root).as_str(), String::from_utf8_lossy(&read(root, INDEX)).trim_end()),
        (0, UUID_C, String::from_utf8_lossy(INDEX_C).trim_end()),
        "a strict replacement applies the new patch"
    );
}

#[tokio::test]
#[serial]
async fn replacement_whose_apply_fails_leaves_a_project_rollback_can_restore() {
    let server = MockServer::start().await;
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    project_with_patch_b(root, &server).await;

    serve(&server, UUID_C, PATCH_C).await;
    assert_eq!(strict_scan(root, &server).await, 1, "the strict apply refuses the file");
    assert_eq!(read(root, INDEX), INDEX_B, "the file still holds patch B");

    assert_eq!(
        (rollback_all(root, &server).await, String::from_utf8_lossy(&read(root, INDEX)).trim_end()),
        (0, String::from_utf8_lossy(INDEX_ORIGINAL).trim_end()),
        "rollback restores the file a Socket patch wrote (recorded: {})",
        recorded_uuid(root)
    );
}
$ cargo test -p socket-patch-cli --test in_process_agent_patch_replace -- drops_no_file apply_fails strict_replacement
test replacement_whose_apply_fails_leaves_a_project_rollback_can_restore ... FAILED
test strict_replacement_applies_the_new_patch_to_the_shared_file ... ok
test strict_replacement_that_drops_no_file_applies_the_new_patch ... FAILED

assertion `left == right` failed: rollback restores the file a Socket patch wrote (recorded: cccccccc-cccc-4ccc-8ccc-cccccccccccc)
  left: (1, "module.exports = 'index patch B';")
 right: (0, "module.exports = 'index original';")

assertion `left == right` failed: a strict replacement applies the new patch
  left: (1, "cccccccc-cccc-4ccc-8ccc-cccccccccccc", "module.exports = 'index patch B';")
 right: (0, "cccccccc-cccc-4ccc-8ccc-cccccccccccc", "module.exports = 'index patch C';")

test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 13 filtered out

The first test states the minimum: after a replacement that failed, rollback still restores the file. The second states the outcome the suite already expects of a strict replacement; the planned fix leaves that choice to a maintainer (below), so the PR keeps whichever of the two it settles on.

Cause

download_and_apply_patches_into (crates/socket-patch-cli/src/commands/agent_download.rs) inserts the new record (line 2423), writes the manifest (line 2431) and then runs the nested apply (line 2504). get <uuid> has its own copy of that order in get.rs: save_patch_record inserts the record (line 2262) and save_and_apply_patch runs the nested apply (line 2384). #1835 is open for that second copy. Nothing puts the old record back when the apply fails for an updated patch.

The apply's default policy, MismatchPolicy::SocketContent (core patch/apply.rs, line 55), overwrites a file that matches neither hash only when the file's hash names a stored blob, and Strict never does. So the replacement depends on the old patch's after-blob from the moment the manifest stops referencing it.

#2119 (for #2096) fixed this class for the files a newer patch drops. The old patch is rolled back first, and its commit message gives the rule: "When such a file cannot be restored, refuse the replacement: keep the old record, drop the new patch's blobs, and fail the patch". The same message leaves the other half as it was: "Files both patches list are left to the nested apply, so a replacement that drops no file behaves as before."

What settles the expected behavior

  • CLI_CONTRACT.md, "Events per mode": "When a copy the recorded patch is on cannot be rolled back (…), the replacement is refused: the patch is failed / replaced_patch_not_restored, the recorded patch stays recorded and applied, the new patch is not applied, and the run exits 1." For this branch the same paragraph says only "A new patch that lists every file of the recorded one needs no rollback; the apply moves each file to it", and nothing about a run where the apply cannot.
  • The global arguments section documents that a pruned blob makes earlier output read as drift: "Only a stored blob proves this: when it is gone (pruned by gc / scan --prune, or .socket/blobs/ is not shared with the checkout), the earlier output reads as unknown drift and apply --force is the explicit way to replace it." That covers a blob the user pruned. Here the failed run is what left the blob unreferenced, and under --prune the same run deleted it.
  • The same paragraph, on --save-only: "This runs with --save-only too, which then leaves the package original and recorded, like a --save-only of a new patch." A save-only replacement that drops no file leaves the package on the old patch and recorded as the new one.
  • The suite #2119 added expects a strict replacement to succeed, and tests it only for a newer patch that drops a file.

Planned fix

Make a replacement one step: the manifest names the new patch only when the installed copies no longer hold the old one's bytes.

  1. Fetch the newer patch's blobs before the record is replaced, so a failed download is a download_failed that leaves the old record, as a failed view already does.
  2. Roll the recorded patch back before every replacement, not only when the newer patch drops a file. That is the order #2119 chose: "roll back the old patch, record the new one, apply it". A rollback that cannot be done keeps the old record (replaced_patch_not_restored), as today. No replacement then depends on a blob the manifest no longer references, --save-only leaves the package original and recorded in both branches, and a --strict replacement goes through in both.
  3. One implementation for scan and get <uuid> (#1835).

A smaller alternative keeps "needs no rollback" for a patch that drops no file and puts the old record back when its apply fails. It leaves --save-only and --strict as they are. A maintainer's preference between the two is welcome; the first is what a PR would bring.


Generated by Claude Code

Lenguaje dominante
Rust
Estrellas
9
Forks
2
Merge medio
1 d 8 h
PR fusionados (30 d)
313

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de SocketDev/socket-patch

Todos los issues de SocketDev/socket-patch

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.