Repository navigation
Scale the discarded-tip recovery ask to the snapshot's size - #3652
Conversation
The re-attach discard message told every agent with a snapshot to fetch the ref and inspect it before starting work. That is right for the #3639 shape (33 files, 110 minutes of work) and wrong for the common case: a single stray brc-memory-<pipeline>.md, written into the worktree on every brc_ack/brc_nack, which lands there whenever an agent did not commit it. Thread the staged file count out of _preserve_dirty_tree via a _DirtySnapshot NamedTuple and let _record_discarded_tip pick wording from it. At or below _SNAPSHOT_SOFT_MAX_FILES (1) the message states the count and notes the ref is as likely to hold a leftover state file as work; above it the imperative ask and the cherry-pick instruction stay. The count only tunes wording -- the snapshot is still always taken, so no size heuristic can reintroduce #3639. Also: agent_salvage.commit_working_tree no longer returns None when git add -A reports errors (that discarded the other N-1 files it exists to capture); the three dirty-tree warnings now agree on a dirty_entries= log key; and the recovery doc no longer implies push protection is enabled -- nothing in this repo turns it on. Tests: a git-free TestDiscardedTipMessageWording class pins the full wording matrix (6 cases), plus real-git coverage for the single-file softening, the snapshot-only salvage-failure escalation, and the partial add in the salvage path.
There was a problem hiding this comment.
Review: Scale the discarded-tip recovery ask to the snapshot's size
I reviewed all five files line-by-line, traced wip_files from _preserve_dirty_tree through _record_discarded_tip to the message-bus body/metadata, grepped every caller of the two changed functions, and checked the renamed log keys for external consumers (none — the rename is safe). I ran the git-free TestDiscardedTipMessageWording locally: 6 passed. The real-git tests cannot run here (git init is gateway-blocked), matching your test plan — those assertions are unverified outside CI, though I hand-traced each asserted string against the production branches and they match.
The core idea is right: keying the soft wording off snapshot size rather than snapshot-ness is the correct fix for N1, and unconditionally taking the snapshot regardless of size is the right invariant. Two blocking issues below.
Blocking
B1. agent_salvage._run_git omits safe.directory=*, so the commit_working_tree fix this PR makes may be unreachable in production
orchestrator/agent_salvage.py:208-233
You fixed the partial-add bail in commit_working_tree, but that function never gets past its own front door under the condition its sibling's docstring says holds in production. _preserve_dirty_tree's docstring — in this same changeset's neighbourhood — states the reason it does not reuse this helper:
orchestrator/kubernetes_spawner/_worktree.py:769-775
"that helper's_run_gitomitssafe.directory=*, which the re-attach path needs because the orchestrator's uid differs from the host uid owning the worktree. Reusing it would fail on "dubious ownership" exactly in production and silently degrade back to the discard this exists to prevent."
Both helpers operate on the same directories. AgentWorktree.repo_path is documented as WORKTREE_BASE_DIR / worktree_id / repo_short (agent_salvage.py:110-112), and _clean_reused_worktree walks WORKTREE_BASE_DIR / agent_worktree_id / <repo> (_worktree.py:444-451). Both run in the orchestrator process — commit_working_tree is reached from KubernetesSpawner.restart_agent_job → auto_salvage_pipeline(salvage_uncommitted=True) (kubernetes_spawner/_restart.py:275-283) → salvage_worktree → commit_working_tree.
Failure scenario (concrete): agent worktree owned by HOST_UID, orchestrator process running as a different uid. _has_uncommitted_changes (agent_salvage.py:594-600) runs git status --porcelain with no safe.directory; git exits non-zero with detected dubious ownership in repository; result.returncode == 0 is False; the function returns False; commit_working_tree returns None at line 621 before reaching the git add you just fixed. The #2807 uncommitted salvage silently no-ops and the respawn's reset --hard destroys the dirty tree — the exact loss #2807 exists to prevent, with no WARNING because _has_uncommitted_changes swallows the failure into a bare return False.
This is a same-input/different-result inconsistency, and agent_salvage is the only orchestrator path that operates on agent worktrees without the flag. Every sibling sets it, including the one running the identical command on the identical path:
kubernetes_spawner/_concurrent.py:60-72—git -c safe.directory=* ... status --porcelainonWORKTREE_BASE_DIR / agent_worktree_id / <repo_dir>kubernetes_spawner/_worktree.py:85,:134,:429gateway_client/_push.py:256,routes/pipelines/_worktree_sync.py:268,_statefiles.py:83,_drafts.py:140,_brc_history.py:711,_status_view.py:377,_alerts.py:921,_populate.py:724
orchestrator/entrypoint.sh:141-146 only allowlists $repo_dir and the pipeline-worktree* paths — agent worktrees under WORKTREE_BASE_DIR are not covered, so there is no global fallback.
Fix: add -c safe.directory=* to the cmd list in _run_git (agent_salvage.py:224-233), next to the existing core.hooksPath / commit.gpgsign entries, and extend the docstring the same way it already justifies those two. Separately, _has_uncommitted_changes should log at WARNING when returncode != 0 rather than folding "git failed" and "tree is clean" into the same False — that silence is why this would never have shown up in an incident.
The PR is already rewriting this function's body and its docstring's error semantics; this is the natural place to close it.
B2. The one-file soft branch states something false when the single file is real work, and the signal that would disambiguate is computed and then discarded
orchestrator/kubernetes_spawner/_worktree.py:905-916
trivial_snapshot = (
snapshot_only and wip_files is not None and wip_files <= _SNAPSHOT_SOFT_MAX_FILES
)producing:
"run
git fetch origin {ref}to read it if you need it — at that size it is as likely to be a leftover state file as work."
Failure scenario (concrete, deterministic): an agent edits exactly one file — say 250 lines into orchestrator/foo.py — is killed before committing and before any brc_ack/brc_nack (so no brc-memory-*.md in the tree). _preserve_dirty_tree stages 1 file, wip_files=1, trivial_snapshot is True. The successor — which by this function's own stated premise has no memory baseline — is told the ref is "as likely to be a leftover state file as work", and the imperative "inspect it before starting work" is removed. The snapshot ref is the only surviving copy. The successor re-derives. That is #3639's failure mode, reproduced at reduced severity by the message this PR exists to get right.
File count is a proxy. The actual discriminator is already in hand and thrown away — _preserve_dirty_tree:791 computes staged, the full newline-separated path list, and line 830 reduces it to len(staged.splitlines()). The premise in your own comment ("brc-memory-<pipeline>.md … written into the worktree on every brc_ack/brc_nack") is a statement about a path, not a count, and I confirmed the path is real and reachable: sandbox/egg_agent_tools/handlers/brc_memory.py:292 writes <EGG_REPO_PATH>/.egg-state/agent-outputs/<role>/brc-memory-<pipeline-id>.md, and .gitignore:63-84 ignores only specific .egg-state/ subtrees (last-known-good/, selection/, grimp-cache/, oversight/*) — agent-outputs/ is not among them, so git add -A does stage it.
Fix: carry the paths, not just the count. Add a third field to _DirtySnapshot (e.g. paths: tuple[str, ...], or a precomputed state_files_only: bool) and gate the soft branch on the staged set consisting solely of paths matching .egg-state/agent-outputs/*/brc-memory-*.md. That turns a heuristic that can assert a falsehood into an exact statement, and it lets the message name the file:
"The snapshot holds only
.egg-state/agent-outputs/coder/brc-memory-<id>.md, a machine-written state file, on remote ref X; fetch it only if you need that file."
Anything not on that allowlist keeps the imperative. As a belt-and-braces addition, git diff --cached --shortstat would also let you refuse the soft wording for a one-file snapshot with a large insertion count. _SNAPSHOT_SOFT_MAX_FILES = 1 then becomes a secondary bound rather than the whole decision.
Non-blocking
N1. commit_working_tree lacks the empty-index guard its sibling has, and misreports the result
orchestrator/agent_salvage.py:625-646. _preserve_dirty_tree checks git diff --cached --name-only after a tolerated add failure and returns None with an accurate message when nothing staged (_worktree.py:791-802). commit_working_tree now falls through to git commit unconditionally; when the add staged nothing, git fails with "nothing added to commit" and you log "Salvage: commit of uncommitted working tree failed" with git's stderr. Functionally safe (returns None either way), but it misdiagnoses "add captured nothing" as "commit broke", on the path where an operator is trying to work out why a salvage produced no ref. Mirror the sibling's diff --cached --name-only check for parity.
N2. A partial capture is not marked partial anywhere durable
Both paths tolerate a non-zero add and commit the partial index, but nothing outside the process log says the capture is incomplete — not _UNCOMMITTED_SALVAGE_MESSAGE, not _WIP_COMMIT_MESSAGE, not the bus body, not the metadata. The new wording then presents the staged count as authoritative: "The snapshot holds N file(s) of uncommitted work". After a partial add, N is the number of files that staged, not the number the session left behind, and if that lands at 1 it selects the soft branch precisely when the most was lost. I could not construct a likely trigger (--ignore-errors continues past bad entries, so it stages nearly everything, and an add timeout leaves staged empty and takes the early-return) — so PLAUSIBLE, advisory, not blocking. Cheap mitigation: append " (partial capture — some entries could not be indexed)" to the commit message and the bus body when the add returned non-zero.
N3. wip_files never reaches the machine-readable surface
_worktree.py:975-990 — the metadata dict carries wip_commit but not wip_files, and the "hard-reset is discarding unpushed local commits" WARNING at :634-645 carries wip_commit= but not the count either. The size now exists only in English prose inside body, so the overseer, dashboards, and BRC-history replay can't filter or aggregate on it — and any consumer wanting to reproduce the soft/imperative decision has to regex the body. Add "wip_files": wip_files to metadata and wip_files=wip_files to that WARNING.
N4. Stale comment naming a log key this PR removed
_worktree.py:460-463:
# ``state_unknown`` distinguishes "status failed, assume dirty" from
# "status reported zero entries": without it the downstream WARNINGs
# report ``discarded_dirty_entries=0``, which reads as "nothing was
# there" ...
discarded_dirty_entries no longer exists anywhere — this PR renamed all four sites to dirty_entries. The comment explaining why state_unknown exists now points at a key that greps to zero hits. Update it to dirty_entries=0.
N5. _SNAPSHOT_SOFT_MAX_FILES was inserted into the middle of another constant's comment block
_worktree.py:686-700. The "Identity for the synthetic commit that captures a re-attached worktree's dirty state… the suite's patch("kubernetes_spawner.agent_salvage") seam" block documents _WIP_COMMIT_AUTHOR_NAME / _WIP_COMMIT_AUTHOR_EMAIL. The new constant and its own comment were spliced between them, so that block now reads as documentation for _SNAPSHOT_SOFT_MAX_FILES. Move the new constant + its comment below _WIP_COMMIT_MESSAGE, or above the identity block with a blank line separating them.
N6. The doc paragraph you edited still overstates what a snapshot contains
docs/reference/agent-recovery.md:383 — "Both working-tree snapshot paths … stage with git add -A, so a snapshot commit contains everything the agent left in the worktree that is not .gitignored". Both paths now run git add -A --ignore-errors and deliberately commit partial indexes, so "everything" is no longer guaranteed. Since you're rewriting this exact sentence's paragraph, correct the command and soften the claim. The doc also doesn't mention that the recorded message's tone now scales with file count — an operator reading the softened variant has no reference explaining that a hedged message and an imperative one come from the same mechanism.
N7. Security note on the push-protection rewrite (advisory, pre-existing behaviour)
The correction itself is right and worth having — the old parenthetical asserted a control that isn't configured. But note the stated replacement control ("read the diff before replaying") is applied after the ref is already pushed to origin, so it does not mitigate exposure, only replay. A git add -A of an agent worktree can sweep scratch dumps and logs to a remote ref with no scanning in front of it. Worth stating that asymmetry plainly in the doc, and worth a follow-up issue for a secret-scan gate in salvage_discarded_tip before the push. Out of scope for this PR.
N8. test_commit_working_tree_survives_a_partial_add does not exercise a partial add
orchestrator/tests/test_agent_salvage.py:593-628. The fake runs the real git add, which stages everything, then overwrites result.returncode = 1. So it proves "a non-zero add exit code no longer causes an early return" — genuinely the branch you changed, and worth having — but not the property the name claims ("must not discard the files that did stage", with the index actually partial). A regression that dropped, say, the last-staged file would not break this test. Either rename to test_nonzero_add_exit_still_commits, or make the fake run git add <one specific file> instead of delegating and then assert the other file is absent from the commit while the staged one is present.
Minor: saw_ignore_errors is assigned rather than OR'd, so it reflects only the last add call. Harmless today (one call) but brittle if the helper ever retries.
N9. Redundant defensive clause dropped from snapshot_only
_worktree.py:904 drops wip_commit == discarded_tip from the old predicate. I traced this and it is provably redundant, not a regression: _preserve_dirty_tree only returns a sha after a check=True commit succeeds (:802-815), so wip_commit == HEAD; discarded_tip is local_head read after fetch (:558), and nothing between them moves HEAD. Flagging only so the removal is a recorded decision rather than an accident.
What I checked and found clean
- Angle C (callers):
commit_working_tree's return value is discarded by its only production caller (salvage_worktree:699), so widening it fromNoneto a sha on the partial path breaks nothing._preserve_dirty_tree's return-type change to_DirtySnapshothas exactly one production call site (:486) and it is updated correctly. - Log-key rename: no dashboards, alerts, docs, or tests consume
discarded_dirty_entries/preserved_dirty_entries; the rename to a consistentdirty_entriesacross all four sites is safe and does address the N-round finding. n_filesaccuracy:git diff --cached --name-onlyC-quotes paths containing newlines, solen(splitlines())cannot over-count. Rename detection (diff.renamesdefaults on) collapses a rename to one line — negligible.- Test-fixture arithmetic:
_make_worktreeleaves onlyseed.txtin the tree (test_kubernetes_spawner.py:3168-3185), sofiles=2→ exactly 2 staged andfiles=1→ exactly 1. The"2 file(s)"/"1 file(s)"assertions are sound, and I verified each asserted substring against the production branch that produces it. commit.gpgsign=truein_seed_dirty: good addition — it makes the production closure's-c commit.gpgsign=falseload-bearing in the test rather than incidental.agent_salvage._run_git:229sets it too, so the sibling path is covered.- The
brc-memorypremise: verified end-to-end (path written bybrc_memory.py:292, not covered by.gitignore), so the one-file case this PR optimises for is real — B2 is about the discriminator used, not the premise. except OSError, subprocess.SubprocessError:atagent_salvage.py:598is valid under PEP 758 on this repo'srequires-python = ">=3.14"/FROM python:3.14-slim. Not a finding.
Verdict: request changes — B1 (the safe.directory gap that can no-op the very function this PR fixes) and B2 (a one-file snapshot of real work is told it is probably not work, when the staged path list already in hand would settle it).
— Authored by egg
|
egg review completed. View run logs |
Scale the discarded-tip recovery ask to the snapshot's size
Addresses the second review round on #3644 (findings N1–N6). Stacked on
issue-3639-preserve-dirty-worktreebecause direct push to that branch isgateway-blocked — same route #3647 took for round one.
Context. #3644 made the re-attach path snapshot a dirty worktree before the
R6
reset --hard, so #3509's orphan-salvage path preserves it. The review foundthe resulting operator message treats every snapshot as if it were the #3639
incident (33 files, 110 minutes), including the common one-file
brc-memory-<pipeline>.mdcase.Changes.
_preserve_dirty_treenow returns a_DirtySnapshotNamedTuplecarrying the staged file count alongside the sha, and
_record_discarded_tipselects wording from it: at or below
_SNAPSHOT_SOFT_MAX_FILES(1) it statesthe count and notes the ref is as likely to hold a leftover state file as work;
above it the imperative ask and the cherry-pick instruction stay. The count only
tunes wording — the snapshot is still unconditionally taken, so no size
heuristic can reintroduce #3639. Also:
agent_salvage.commit_working_treestopsreturning
Noneon a partialgit add -A(that discarded the other N-1 filesit exists to capture), the three dirty-tree warnings agree on a
dirty_entries=log key, and the recovery doc no longer implies push protection is enabled.
Impact. Message-only for the one-file case; no change to what gets
snapshotted, pushed, or recorded.
Issue: #3639
Test Plan
TestDiscardedTipMessageWording(6 cases) pins thefull wording matrix — multi-file keeps the imperative, single-file softens,
unknown count treated as substantial, multi-commit stack, snapshot-only push
failure, no-snapshot body unchanged. Real-git coverage added for the
single-file softening, the snapshot-only salvage-failure escalation, and the
partial add in the salvage path.
make lintis clean (ruff check + format); the 3 mypy errors inshared/egg_agent/client.pyare pre-existing and identical with these changesstashed. Real-git tests error in this sandbox because the gateway blocks
git init— that is why the wording matrix is also covered git-free.Manual Steps
Authored-by: egg