Skip to content

fix(install): replay an abandoned deploy journal on the next install (#4863) - #4982

Merged
Daniel Meppiel (danielmeppiel) merged 21 commits into
mainfrom
fix-4863-journal-replay
Nov 23, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 21 commits into
mainfrom
fix-4863-journal-replay

Conversation

@danielmeppiel

@danielmeppiel Daniel Meppiel (danielmeppiel) commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Description

If apm install is killed after deploying and before a gate refusal restores the deployed paths, the next install deletes the abandoned deploy journal (reap_abandoned_journals). The deployed files then stay on disk with no lockfile row claiming them.

This PR makes the next install, under the lifecycle lock and before anything else, replay that journal: every journaled path goes back to its prior state. The journal is trusted no further than the deployment ledger. A path that cannot be restored, a malformed journal, a path escaping its deploy root, or copy bytes the ledger does not vouch for each keep the journal, name the path and stop the install, without applying anything.

How it works. A deploy journal bound to a deploy root writes each unit (base, relative path, kind, copy name, content hash) to journal.jsonl in its store as it records it. InstallTransaction, once it holds the lifecycle lock and before it changes anything, calls deploy_snapshot.replay_abandoned_journals for its deploy root. That function owns the format and the replay. Each unit is checked before anything is applied:

  • the path stays inside its base;
  • the copy re-hashes to the journal's hash;
  • under the deploy root, the hash matches the deployment ledger (DeploymentLedgerCodec hashes from the current apm.lock.yaml). An absent unit is removed only when the ledger claims nothing at that path.

If any unit fails, the journal is kept (retained-*), each path is named, the install exits 1, and nothing is applied. If a proven journal hits a restore error, the other paths are restored, the journal is kept and the path is named, as an in-process restore does. Each restored file is written to a staging path and re-hashed before it replaces the target. apm install replays once at the start of every entry (dependency pipeline, local bundle, --mcp) before it writes, except on --dry-run; the shared owner is transaction.replay_abandoned_deploys. Journals for other deploy roots are left for that root's next install. A journal is only replayed while holding the lifecycle lock, by the next install.

Receipts have journal-only integrity. Deployment receipts are APM metadata the deployment ledger does not record, so a receipt is restored only when its journal copy re-hashes to the journal's recorded hash. That rule is QL-accepted, with these binding conditions:

  • APM-home units are confined to deployment-receipts/, both as written (no .., no absolute or drive paths) and as resolved (no symlinked component leaves it);
  • only file and absent kinds are allowed, and the target must be a regular file, never a link;
  • copies are read with no-follow, as regular files only.

Sealing (QL R4). Each write is bracketed in the journal:

  • before it: a pending event carrying the expected content hash where the writer knows it (the unit line itself opens the first write);
  • after it: a post-write seal, a fingerprint of what APM wrote, covering content, mode and directory entries.

Replay restores a unit only while every path in it holds one of: nothing, its prior (journaled) state, its last post-write seal, or, for a write that began and was never sealed, its expected hash. Anything else, such as a file a user edited after the kill or a mode they changed, is kept and named in a Kept <path>: ... warning through remediation.kept_note, and the store is retained so the pre-install copies survive. Gate-time seals were removed.

Every production writer now passes the hash of the bytes it is about to write:

  • text writers in their encoding; the hook settings JSON and the .gitignore append now write their full text through write_seam.write_text, the latter with newline="" so its line endings are kept;
  • write_json_config via json_config_text, the same render the writer uses;
  • the MCP adapter config writes, which hand journal_config_write (now in adapters/client/config_journal.py) the rendered text;
  • copies and renames, with the source's hash, dir or absent;
  • removals (absent), mkdir (dir), and the new write_seam.chmod (the file's current hash; the mode is sealed after it, so a skill executable or Kiro hook made private by APM is not mistaken for a user edit).

write_seam.open_for_write has no production callers left. It remains the seam's only streaming writer (used by tests), and the only one that may restore an unsealed write unconditionally.

A directory unit also checks its own mode, and trusts a child directory without its own evidence only when APM wrote something below it.

Guard. install-deployment-deploy-write-seam now also requires every seam writer to report its finished write (record_after_write). Only a closed list of functions outside the seam may record a path themselves (BaseIntegrator.write_text_if_changed, journal_config_write and its 5 MCP adapter callers, and skill-path migration's 2 deletions), and each must report its finished write. Mutation cases: seam-writer-skips-seal, direct-recorder-skips-seal, unlisted-direct-recorder.

Workspace. A journal names its deploy root and its metadata workspace (lockfile directory). User scope and a project at HOME share a deploy root, but each replays only its own journals, against its own ledger and commit identity. apm lock (lock-only) and any dry run (--dry-run or a direct dry_run pipeline call) never replay.

Fast apply. The diff-apply fast path reports post-write seals through the same seam. It declines (full pipeline) while an abandoned journal exists, so replay always runs first. A store with no manifest (an in-memory fast-apply journal, or one from an older APM) has nothing to replay and is reclaimed.

A committed journal is settled, not replayed. Just before the lockfile is written, the transaction records the staged lockfile's content identity (before_lockfile_commit, a new hook in the lockfile write authority). Just before the journal is discarded it records the identity of the lockfile on disk again, which covers a no-op commit and formatting differences. If the process dies after the write and before the journal is gone, the next install finds the lockfile on disk matching a mark and deletes the journal without rolling back; a mismatch never settles.

Fail-closed cases. Each of these keeps the journal and reports it, applying nothing:

  • an unreadable lockfile (a missing one claims nothing);
  • a non-canonical path (./x, ., x//y, a backslash);
  • a path crossing a symlink inside the deploy root;
  • malformed ancestors, or an ancestor that is not an ancestor of its path;
  • a directory whose ledger subtree differs from its journaled files;
  • a symlinked receipts directory or component.

When a changed (user) file is kept, the store is retained, so its pre-install copies stay available.

Known limit (ruling on the shared-config thread, tracked in #5009): shared hook settings, sidecars and MCP configuration the ledger does not claim keep the journal and are reported, never restored; recovery is manual until an owner-backed baseline exists.

Known limit: the manifest is not fsynced per line. A SIGKILL keeps it; after power loss, a torn manifest is kept and reported as malformed.

Red-first cells (tests/integration/test_abandoned_deploy_journal_replay_lifecycle.py). The kill is deterministic: tests/integration/_deploy_kill/sitecustomize.py exits the engine process with os._exit where the in-process restore would run.

  1. Killed before each gate refusal (content scan, require_hashes, unmanaged_files deny), then apm install: every journaled path is restored, the journal is gone and apm audit --ci is clean. On main the killed install's extra-agent.md stays on disk, unrecorded.
  2. A journaled path that cannot be restored: the journal is kept and the path is named.
  3. A malformed journal: kept and reported, not applied.
  4. A journal path escaping the deploy root: kept and reported, not applied, and the file outside is untouched.
  5. Copy bytes that re-hash to the journal's hash but not to the ledger's: kept and reported, not restored.
  6. A file a user wrote after the kill at a path the killed install created: kept, with a named warning, and the install converges (red on the previous head: the file was deleted).
  7. Owner cells (tests/unit/install/test_deploy_snapshot.py):
    • a receipt whose copy does not match its hash is not restored;
    • a receipt path leaving deployment-receipts/ is refused: .., a symlinked directory, a symlinked receipt, another APM-home file, another journal store, an absolute path or a drive path. The non-receipt APM-home case was red before R1;
    • a deploy-root path that is absolute, a drive path, a UNC path or escapes with .. is refused;
    • a restored file keeps its mode;
    • shared config the ledger does not claim keeps the journal;
    • a fresh-home receipts directory the killed install created is removed;
    • an unsealed changed path, an unreadable ledger, an incomplete directory subtree, malformed units (./, ., //, bad ancestors, bad copy) and a symlinked receipts directory each keep the journal.
  8. A kill after the lockfile commit: the journal is settled, the committed deployment stays and audit --ci is clean.
  9. A kill mid-deploy after N writes, before any gate seal: all N journaled paths are auto-restored and the next install and audit --ci are clean (red on b018312).
  10. A tampered root-unit copy is kept and reported, not restored.
  11. A repair killed at the journal discard keeps the repaired file and settles the journal (red on b018312).
  12. apm install --mcp replays a killed install before it writes (red on b018312).
  13. Owner cells: a mode changed after the kill is kept; a path through a symlink alias inside the root is refused; backslash and unrelated-ancestor units are malformed.
  14. A kill after 2 sealed writes, then a user edit to write Why do we need a GitHub token? #1: Why do we need a GitHub token? #1 is kept and named, and the other journaled paths are restored (red on 58ad0f1).
  15. A write killed after it landed but before its post-write seal: restored (its bytes match the expected hash) and the next install is clean (red on 58ad0f1).
  16. A JSON config written through the seam, killed before its seal, then edited by the user: kept (red on dfeea6b). Owner cells: a directory mode changed after the kill keeps the directory; a malformed expected keeps and reports the journal.
  17. Owner cells, all red on 0a829e0:
  • hook settings edited after a kill before their seal: kept;
  • another workspace's journal at the same root: left alone;
  • a lock-only or dry-run transaction: never replays;
  • a malformed seal shape: kept and reported;
  • an unreadable copy: kept and reported;
  • a chmod through the seam: sealed, so APM's executable is removed.

The post-deploy require_hashes refusal is injected at its real call site (check_before_lockfile). Install always records a hash for git rows and exempts local rows, so that refusal cannot be produced from inputs alone.

Issue and approved scope

Issue: Fixes #4863

Human scope-approval comment: #4863 (apm-scope:v1 approval by Daniel Meppiel (@danielmeppiel))

Does this PR complete the issue, or what remains? It completes it. QL W3b ACCEPT and H8 sign-off are pending.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Maintenance / refactor

Docs: reference/cli/install.md (Failed or interrupted installs) now describes the replay.

Testing

  • Tested locally

  • All existing tests pass

  • Added tests for new functionality (if applicable)

  • APM_BINARY_PATH="$(uv run which apm)" uv run --extra dev pytest tests/integration/test_abandoned_deploy_journal_replay_lifecycle.py -n 4 -q: 7 failed on main (red-first); all 17 cells pass with the fix.

  • Neighbours (tests/unit/install, the install commit-order, lockfile commit-point, workspace-lock, transaction and install-policy-fields lifecycle modules plus the replay module): 3545 passed. test_unix_install_ownership.py fails identically on main in this environment (installer-script environment, unrelated).

  • tests/integration/test_architecture_owner_rule_mutations.py -k "commit or journal or deploy": 354 passed. tests/quality/test_lifecycle_bug_ledger.py: passed (new row bugs/4863.json).

  • ruff 0.15.12 check and format --check on the changed files, check_test_assertions.py, lint_architecture_boundaries.py --root ., tests.quality.taxonomy --changed and tests.lifecycle.generator --check: all clean.

Changelog

  • One fragment per section, changelog.d/<pr>.<section>.md, holding
    one line: user-visible effect first, 25 words or fewer, ending with
    (#PR); breaking changes only under upgrade notes; no Highlights; no
    new lines under ## [Unreleased]. See changelog.d/README.md and
    .github/instructions/changelog.instructions.md.
  • N/A -- internal-only change (CI, tests, refactor).

Spec conformance (OpenAPM v0.1)

  • Spec edit
  • Manifest edit
  • Test edit
  • CONFORMANCE.{md,json} regenerated
  • N/A -- this PR does not change OpenAPM-observable behaviour.

apm-spec-waiver: deploy-journal crash replay is APM transaction hardening; no OpenAPM v0.1 requirement governs deploy-target crash recovery (req-lk-023 covers package staging only)

…4863)

An install killed between deploy and a gate refusal's restore (content
scan, require_hashes, unmanaged_files deny) must have its journal replayed
by the next install. A journal that cannot be restored, is malformed,
escapes its deploy root or carries bytes the ledger does not vouch for is
kept and reported, never applied. These cells fail on main.

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
@danielmeppiel Daniel Meppiel (danielmeppiel) added this to the 0.38.x milestone Nov 23, 2026
Copilot AI balanced review requested due to automatic review settings November 23, 2026 10:52
Co-authored-by: copilot-swe-agent[bot] <[email protected]>

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.

🟡 Changes recommended

The fault hook shadows the isolation environment’s sitecustomize.py, disabling the network guard for killed engine runs unless the existing guard is executed before importing APM.

1 open issue
What changed in this PR

Adds red-first lifecycle coverage for #4863, defining how apm install should recover abandoned deployment journals. This snapshot establishes the regression tests; the production fix is still pending.

Changes:

  • Tests recovery after three post-deploy gate refusals, including restored files, journal cleanup, and clean audit results.
  • Tests rejection and preservation of malformed, unrestorable, escaping, or tampered journals.
  • Adds deterministic process-kill hooks and a changelog fragment describing the intended fix.
File Description
tests/​integration/​test_abandoned_deploy_journal_replay_lifecycle.py Defines successful recovery and fail-closed recovery scenarios.
tests/​integration/​_deploy_kill/​sitecustomize.py Injects process termination before rollback and a post-deploy hash refusal.
changelog.d/​4982.fixed.md Describes the intended journal-replay behavior.

Review effort: Balanced

…4863)

A deploy journal bound to a deploy root now writes each unit to a
journal.jsonl manifest in its store as it records it. The next install,
under the lifecycle lock and before it changes anything, replays an
abandoned journal for its deploy root instead of deleting it. Every unit
must stay inside its base directory, its copy must re-hash to the
journal's hash and, under the deploy root, to the deployment ledger's
hash for the path; otherwise the journal is kept and reported and nothing
is applied. A path that cannot be restored keeps the journal, names the
path and stops the install, as a failed in-process restore does.
apm-spec-waiver: deploy-journal crash replay is APM transaction hardening; no OpenAPM v0.1 requirement governs deploy-target crash recovery (req-lk-023 covers package staging only)

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
…journal

Replay restores a file with its mode bits, as the in-process restore
does, rejects a Windows drive or rooted path instead of any colon, and
reports a manifest nested too deeply as malformed.

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
…le (#4863)

A receipt restores only when its journal copy re-hashes as recorded, and
a receipt path that leaves the receipts directory (.., a symlinked
directory, a symlinked receipt, another APM-home file) is refused.

Co-authored-by: copilot-swe-agent[bot] <[email protected]>

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.

Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/transaction.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
…ll (#4863)

APM-home journal units are deployment receipts only: confined to the
receipts directory as written and as resolved, file or absent kinds,
regular-file targets, copies read without following links. Receipts have
journal-only integrity.

The pipeline seals what each journaled path holds before each post-deploy
gate. Replay removes or replaces a path only while it holds its sealed
state; anything else, such as a file a user wrote after the kill, is kept
and named in a warning.

Co-authored-by: copilot-swe-agent[bot] <[email protected]>

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.

🟡 Changes recommended

Unresolved critical recovery flaws can delete user-modified or unrelated files and permit destructive replay without verifiable ledger evidence.

10 open issues
2 previously missed issues

In code that hasn't changed since last review

High severity Recovery fingerprint misses structural and byte-level edits

src/​apm_cli/​install/​deploy_snapshot.py:294

The recovery fingerprint ignores CRLF-only and mode-only file edits, empty subdirectories, and nested symlink targets. Those user changes can still match the seal after a kill, so replay deletes or replaces the changed file or tree. Persist a separate byte-exact, mode-aware structural fingerprint for copies and current/prior/sealed states, including directory entries and link targets; keep normalized hashes for ledger provenance.

Medium severity Committed installs fail recovery if journal settlement is interrupted

src/​apm_cli/​install/​deploy_snapshot.py:440

A kill after the lockfile is published but before _settle_deploy_journal leaves a journal for an already-committed install (lockfile_write_authority.py:475-485). The current ledger then rejects the journal's old hashes or previously absent paths, so the next install exits 1 despite disk and lockfile agreeing. Bind the journal to durable commit evidence and settle committed attempts instead of replaying them.

2 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
- Route the kept-file warning through remediation.kept_note.
- Refuse non-canonical journal paths, malformed ancestors and units, a
  directory whose ledger subtree differs from its copy, and a symlinked
  receipts directory or component.
- An unreadable lockfile keeps the journal; a missing one claims nothing.
- A unit changed after a kill that came before any seal keeps the journal;
  a sealed one holding other data is kept with its store retained.
- Record ancestors strictly inside their base, so a fresh-home receipts
  directory replays.
- Seal and mark the staged lockfile just before it is written, so a kill
  after the commit settles the journal instead of rolling it back.
- The kill hook runs the isolated environment's network guard first.

Co-authored-by: copilot-swe-agent[bot] <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/transaction.py Resolved
…nstall entry (#4863)

A unit is sealed when its manifest line, and any hash-checked copy, reach
the store before its first write, so a kill mid-deploy restores every
journaled path. Gate-time seals now fingerprint content, modes and
directory entries and can only keep a path, never force one. Journal
paths may not cross a symlink inside the deploy root, use a backslash,
or name an ancestor that is not one. The commit mark uses the lockfile's
content identity, and is written again just before the journal is
discarded. apm install replays before its local-bundle and --mcp entries
write, through one shared owner.

Co-authored-by: copilot-swe-agent[bot] <[email protected]>

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.

Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 23, 2026
Resolved: replay now seals units at record time and records modes; the
shared config check compares against the journal copy's full state.

Co-authored-by: Copilot App <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
…edits (#4863)

Every write through the deploy write seam now brackets itself in the
journal: a pending event with the expected content hash before the write
(where the writer knows it) and a post-write seal after it. Replay
restores a path only while it holds nothing, its prior state, the sealed
bytes, or the expected bytes of a write that never sealed; anything else
is kept and named. Gate-time seals are removed.

The deploy-write-seam guard now requires every seam writer, and a closed
list of direct recorders, to report the finished write.

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 23, 2026
…ecovery

Co-authored-by: Copilot App <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
…in-memory journals

A direct dry_run pipeline call no longer replays an abandoned journal.
Main's journaled_apply now reports post-write seals through the seam and
never reaps; diff_apply declines its fast path while an abandoned journal
exists, and replay reclaims stores that carry no manifest.

apm-spec-waiver: deploy-journal crash replay is APM transaction hardening; no OpenAPM v0.1 requirement governs deploy-target crash recovery (req-lk-023 covers package staging only)

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>

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.

🟡 Changes recommended

Crash recovery can silently delete or overwrite line-ending-only user edits because recovery fingerprints normalize line endings instead of preserving byte-exact file contents.

3 open issues
1 resolved since last review

Review effort: Balanced

Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
Comment thread src/apm_cli/install/deploy_snapshot.py 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.

🔵 Needs a closer look

Recovery can silently delete user-edited files because filesystem seals ignore line-ending changes, while deeply nested journal headers can repeatedly abort installation without the retain-and-report diagnostic.

3 open issues

Review effort: Balanced

Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 23, 2026
…config-recovery

Co-authored-by: Copilot App <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
…the last seal

Prior states, seals and expected write hashes are byte-exact, so a
line-ending-only edit after a kill is kept; ledger and copy-integrity
hashes stay normalized. Each seam writer's expected hash models the bytes
it leaves (newline translation, LF normalization). A pending event keeps
the last seal, so a kill before a repeated write restores APM's bytes. A
deeply nested journal header is kept and named instead of aborting replay.

apm-spec-waiver: deploy-journal crash replay is APM transaction hardening; no OpenAPM v0.1 requirement governs deploy-target crash recovery (req-lk-023 covers package staging only)

Co-authored-by: copilot-swe-agent[bot] <[email protected]>

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.

🔵 Needs a closer look

Human assessment is needed because an update dry-run can trigger recovery that modifies deployed files and consumes an abandoned journal before the preview callback runs.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

Co-authored-by: copilot-swe-agent[bot] <[email protected]>

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.

🟡 Changes recommended

Unresolved replay-safety issues can delete a permission-modified native-adapter config directory after a crash or leave committed files missing after interrupted directory removal or migration.

2 open issues

Review effort: Balanced

Comment thread src/apm_cli/install/deploy_snapshot.py Resolved
@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit a9282cb into main Nov 23, 2026
100 of 101 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the fix-4863-journal-replay branch November 23, 2026 17:48
Gregory (gdelpu) pushed a commit to gdelpu/apm that referenced this pull request Nov 23, 2026
On 2026-11-23 the job took 252 s at p50, 296 s at p90 and 299 s at most
across 30 green runs, against a 300 s timeout, and about 9 runs were
cancelled at the cap (microsoft#4975, microsoft#4964, microsoft#5001, microsoft#4982). The cap moves to 10
minutes as headroom only: the scaling assertion, selection and the job's
non-required status are unchanged. The ratchet topology pin follows.

Co-authored-by: Copilot App <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Replay an abandoned deploy journal on the next install

2 participants