Skip to content

Latest commit

 

History

History
432 lines (359 loc) · 22.8 KB

failure-modes.md

File metadata and controls

432 lines (359 loc) · 22.8 KB

Failure modes

Merge conflict

A branch that cannot merge into the integration worktree is marked blocked. Fix it on the owning branch, commit the clean result, and run mergetrain retry <blocked-job-id>. Enqueueing the same active branch again is rejected; retry atomically replaces the old blocked/failed outcome.

git switch <blocked-branch>
git fetch <remote>
git rebase <remote>/<integration-branch>
# resolve conflicts
git add .
git rebase --continue
# Finish the rebase and commit any further fixes; leave the worktree clean.
# Atomically dismiss the old outcome and enqueue a fresh SHA-pinned job:
mergetrain retry <blocked-job-id>

Or let mergetrain fetch and start the rebase with mergetrain retry <blocked-job-id> --rebase. A rebase conflict leaves the worktree ready for manual resolution and does not dismiss the old job. retry only replaces a blocked/failed job (never queued or in-progress work), inherits its task and note, and captures fresh base/head SHAs. It inherits --auto eligibility only while both the approved destination and execution-policy hashes still match and the owning branch is unchanged; a changed destination, processing policy, gate/reuse policy, command timeout, verify hook, or repair branch turns the replacement into a manual job. Only explicitly bounded unattended authorization permits retry JOB --auto, which records fresh current destination/policy approval. Retry alone grants no deployment authority.

Repairing on a separate branch

When the original task branch must stay as handed off, make the repair in a separate clean worktree and name that branch on the existing retry operation:

git worktree add ../repair-<id> -b repair/<id> <original-branch>
# fix and commit in ../repair-<id>, leaving it clean
mergetrain retry <id> --branch repair/<id>

The operation resolves the repair branch's unique worktree, checks it belongs to this repository and is clean, and captures the exact base/head commits. It creates the replacement and cancels the failed outcome in one transaction. An active job on the repair branch or an unresolved ambiguous push is refused; the original task checkout is untouched. In ordered processing the replacement retains queue_order; in batch processing it joins the back as before.

A separate repair branch never inherits automatic approval. A separately authorized repair controller may use retry <id> --branch repair/<id> --auto under its existing bounded task/destination authority. This is an operator operation; ordinary task agents retain enqueue-and-stop. A repair model does not gain queue or push authority merely by writing a repair commit.

Deploy authorization changed

Auto jobs bind approval to a credential-free hash of the fetch URL, the one effective push URL (including remote.<name>.pushurl), integration ref, push refs, and permanent audit-ref policy. Multiple push URLs and relative local push paths are rejected. The daemon checks that identity inside claim, and the runner resolves it again after gates immediately before any recovery marker or push. A mismatch finishes the job blocked with approval_destination_changed and inspect category deploy_authorization_changed. Review the new destination. To create a fresh auto-approved job, dismiss the old blocked job, then enqueue the clean committed branch with --auto only if unattended deployment is approved for that new destination. A retry after an identity change creates a manual replacement.

Auto jobs separately bind the execution policy: effective gates, default command timeout, validation-reuse configuration and authorization, and verify hooks. The daemon compares that identity inside claim, and the runner reloads the control checkout before gates and immediately before the push marker. A blank legacy identity or mismatch becomes blocked with approval_execution_policy_changed, under the same inspect category. Review the current QA/deploy/verify policy. Dismiss the old blocked job before enqueueing a fresh job with newly authorized --auto, or use retry for a manual replacement; do not retrofit a hash onto the old row.

MCP and other preview-driven confirmations use the broader deploy-plan hash. If the train, destination, gate/reuse policy, or verify hooks change, the CLI returns deploy_plan_changed while claiming or blocks before push. Generate a new preview/summary; do not reuse the stale hash.

Gate failure

The processing mode determines whether later submissions can continue:

  • batch (default): if A, B, and C are queued and B fails on its own, mergetrain can land A+C after isolating B and passing checks on that exact combination. B's repaired replacement joins the back on retry.
  • ordered: A lands first. If B fails, C waits. B's repaired replacement keeps its position before C. Explicit cancellation or dismissal can also resolve B's position. Agents can keep developing while later landings wait.

See which mode to choose and agent work examples.

Gate failures are pre-push failures. The deploy ref is not updated. In batch mode, mergetrain isolates the failure so unrelated jobs can still validate/deploy:

  • A one-job train finishes failed. Its failed tree is exactly the base plus that job, so running the gates again could only retry a failed gate. Fix the branch and run mergetrain retry <id>.
  • Multi-job trains are probed by re-assembling and gating subsets until the failure is pinned to either an individually failing job (finished failed) or a semantic conflict — jobs that pass gates alone but fail combined. Conflicting jobs finish blocked with both partners' SHAs in the note and a machine-readable conflict_with field listing the partner job IDs. Surviving jobs are re-run as a fresh train, so nothing ships without a full gate pass over the exact final combination. This classification is independent of unrelated compatible jobs being added to or removed from the batch.

To resolve a semantic conflict, rebase one side onto the other (or onto the integration branch with the other side merged), fix the joint breakage, commit a clean result, and run mergetrain retry <blocked-job-id> for each affected job that should rejoin the queue.

Push failure

A remote can reject a push because of branch protection, a required pull request, denied push permission, or a declined pre-receive hook. mergetrain marks the job blocked with push_status=failed. inspect reports the push_rejected category. This rejection proves that no ref update landed, so mergetrain clears the durable push marker and its pending pin.

Fix the branch protection or push permission. Alternatively, point git.push_refs at a branch you can push and use your forge's review flow. Commit any code fixes in the owning branch and leave its worktree clean. Then replace each blocked job with a queued job:

mergetrain status --json
mergetrain retry <blocked-job-id>

Fixing permission alone does not return the blocked job to the queue. retry replaces it with a job pinned to the current commits. Retry does not authorize validation or deployment. If the destination or execution policy changed, the replacement is manual. See Deploy authorization changed before renewing unattended-deploy approval.

Any other push error after the write-ahead marker is durable — including a transport drop or timeout — has an ambiguous remote outcome. The remote may have accepted the atomic update before the client lost the response, so the job is parked needs_reconcile with push_status=failed and its marker/pin intact; it is never made terminal failed and blindly pushed again. All deploy paths pause until mergetrain reconcile --apply checks the remote and resolves it. The marker also carries a credential-free hash of the endpoint used by the attempt. Reconcile fails closed if the recorded remote name now resolves to a different push endpoint, rather than inspecting the fetch URL or a newly configured pushurl. Markers created before v2.3.1 have no provable endpoint hash and remain parked after migration; reconcile reports the legacy marker without contacting whichever endpoint happens to be configured now. Resolve such an interrupted v2.3.0 deploy before upgrading, or preserve its evidence for explicit operator inspection.

A runner that stops mid-push, whether it was killed or crashed, does not stop the push: managed commands run in their own process group (a Job Object on Windows), so git push keeps running and can still land afterwards. The runner takes a lock before it pushes and hands it to git push, and every process the push starts, a local receive-pack and its hooks included, inherits it. On Windows the push's Job Object is named after the queue and the commit instead, and a small keeper process outside the job holds a handle to it until no process of the push is left, so the name outlives the runner and a git push that dies on its own. Windows keeps these names per logon session, so a runner and a reconcile in different sessions, such as a daemon running as a service, do not see each other's push. While any process of that push is alive, reconcile refuses with lock_held (exit 3) and leaves the job parked, so it never reads the remote before the push has finished changing it. Rerun reconcile once the push has exited.

One gap remains for network remotes: a server that already received the whole push can still apply it after the client has died, even after reconcile has read the remote and requeued the job. That late push never overwrites anything newer, because a ref moves only while it still has the value the push expected. The job's next deploy finds its commits on the remote and records the deployment. If the late push lands while that deploy is under way, the remote refuses the new push. Because the integration branch then moved to a commit that already contains every job of the train, mergetrain requeues the jobs instead of blocking them, and the next train starts from that commit. A refusal on a branch that did not move still blocks the jobs.

When git push exits with a status of its own while the runner is still there, it has already waited for the processes that do the push, so the runner releases the lock for every process that inherited it. A long-lived process that the push started, such as git credential-cache--daemon or a daemon launched by a pre-push hook, then no longer holds it. After a crash, or when the push is stopped, nothing releases the lock early, so such a process keeps it after the push itself has exited. The lock_held error names the lock file under push-locks/ in the state directory. Once no git process of that push is left, stop the process that holds the file (lsof <file> shows it), or delete the file, and rerun reconcile. On Windows only a git push that succeeds releases its job early, because Windows reports a killed process with an ordinary exit status; otherwise stop the process that still runs in the push's job, and the keeper exits with it.

Use mergetrain logs <job-id> --tail 200 for the raw git diagnostics either way.

Validated-gate reuse declined

Reuse is an opt-in optimization, not a deploy prerequisite. If the integration ref, task head, train membership, validation commit/tree, gate policy, environment fingerprint, or age differs, on_mismatch: rerun records a warning event and performs the full reassembly and gate run. on_mismatch: fail blocks before push. A missing or changed task head remains fail-closed even when the general mismatch policy is rerun.

Post-push verify failure

Verify hooks run after push. The remote ref is already updated, so jobs remain deployed with push_status=succeeded and verify_status=failed instead of being rewritten as a pre-push failure. Run JSON returns result=warning and ok=true, human output names both outcomes, the final completion event remains a warning, and status and hub status keep the job in Attention. A later deployment does not dismiss the failure. Run the exact status.next_action.command to recheck it; one verify --job invocation runs the recorded policy once and resolves every member of that deployment. If the policy is missing or has changed, mergetrain refuses to infer success and requires explicit review through verify --job <id> --ack succeeded|failed. Legacy rows without a provable deployment/policy identity can be acknowledged but are not automatically grouped or re-run.

Queue database contention

SQLite allows one writer at a time. If another process holds the write lock past busy_timeout (5s), a queue write raises error.code: queue_busy, retryable: true — never failed. failed means the branch is at fault, fix it and enqueue a fresh commit, and contention says nothing about the branch.

The runner then writes nothing, with one exception: if it pushed and saw the refs land, it still finalizes deployed (with the contention recorded as a warning), because that is the one thing it knows for certain.

Everything else is left exactly as the last durable write left it, which is indistinguishable from a crash at the same instant — deliberately, because that is a state the recovery machinery already understands. What the row looks like depends only on how far the deploy got before the contention:

Contention hit Row is left reconcile --apply / the next claim resolves it to
before the write-ahead marker in_progress, no marker, remote untouched queued
after the marker, push outcome unknown in_progress with its marker and pin ref needs_reconcile, then the remote decides
after the refs landed finalized deployed with a warning nothing to do

The split is made by persistence.leases.recover_orphans from durable evidence (is there a marker?), never from what the failing run believed — an in-memory push status can belong to a different frame, or describe a marker write that never committed.

Two consequences worth knowing:

  • queue_busy does not mean "nothing was pushed". It means "a queue write did not happen". The refs may well be on the remote; read status --json and, if the row carries a marker, run reconcile.

  • A row left in_progress with no runner lock is a stranded claim. status reports next_action.code: reconcile_stranded_claim; mergetrain reconcile --apply clears it. mergetrain reconcile without --apply changes nothing: its stranded[] entries say what --apply will do with each claim (queued, needs_reconcile, or canceled), and a claim whose push may have landed is also checked against the remote in jobs[].

    Recovering it dissolves any validated-train identity it carried, on purpose: a requeued row asserting a validation it no longer holds would collateral-block unrelated auto deploys. A later deploy validates the current queued set and presents a new exact plan, so the dissolved identity cannot silently inherit approval. The requeue also records the dissolution and prior train in the job note.

Reconcile conflict

Reconcile parks a job blocked instead of deciding when the remote cannot settle its push: the audit ref proves the push landed but a payload ref was rewritten afterwards, only some push refs carry the commit, the audit ref points somewhere unexpected, or the commit cannot be resolved locally. The job keeps its marker and pin ref, inspect reports the reconcile_conflict category, and status recommends mergetrain reconcile, which checks such jobs against the remote again and settles them with --apply once the remote does. A cancel requested before the job was parked still counts: if the push turns out not to have landed, reconcile records canceled rather than requeueing the job. When the conflict's recorded endpoint has changed or cannot be reached, reconcile reports it still blocked with the reason it could not check it, and goes on to settle every needs_reconcile job.

Because its push may have landed, such a job is not an ordinary blocked job. dismiss, retry, and cancel refuse it, and dismiss --all skips it and lists it under skipped: dismissing would record that the push never landed, and a retried redeploy could put back content an administrator removed. After inspecting the remote, an operator with recovery authority can pass --force to dismiss or retry.

Stale lock

The runner lock records an owner, unique token, and lease expiry. Claimed jobs store the same token. Managed subprocesses renew the lease periodically, and at their next poll after the machine wakes from sleep. A refresh or state update with a stale token fails immediately.

Reclaim rules when another runner tries to acquire:

  • Dead owner PID — reclaimed immediately.
  • Valid (non-expired) lease — never stolen, whether the owner PID looks alive or unknown. This is the concurrency guarantee. unlock --force also refuses it with exit 4, even if the heartbeat setting changed since the runner started. A forced unlock of a live or unknown owner must wait for lease expiry; a provably dead owner is still cleared immediately.
  • Expired lease, no in-progress jobs — reclaimed, even if the owner PID still looks alive. A healthy runner would have refreshed its lease, so an expired lease means the owner is dead, hung, or a recycled PID. This prevents a reused PID from holding an abandoned lock open forever.
  • Expired lease with in-progress jobs — not auto-reclaimed; left for operator investigation. status recommends unlock_wedged_runner, and unlock --force clears the lock only after watching the lease for one queue.heartbeat_interval_seconds plus 5 s without a renewal. It refuses with exit 4 when the owner renews it, as a runner that slept past its lease does once it wakes. Renewal during the remote check also refuses with exit 4 and leaves the lock and jobs unchanged.

Inspect with:

mergetrain status --diagnose --json
mergetrain inspect <job-id> --json
mergetrain events --job <job-id> --after <last-event-id> --follow --jsonl

A scoped event follower emits stream_end.reason=lost_lease and exits 1 if an in_progress job no longer matches a live runner lease. This distinguishes an abandoned run from a merely quiet long-running gate.

Orphan in_progress

If the runner lock is gone and in_progress jobs remain, the next lock claim re-queues them with this note:

re-queued by mergetrain (previous runner gone)

If an orphan already had cancel_requested_at, recovery finalizes it as canceled instead of re-queueing it.

Cancellation while running

Cancellation is cooperative until atomic push begins. cancel records a request for the whole active claim; the runner heartbeat terminates the process group and records canceled. The write-ahead marker is recorded only while no request exists, so a request that arrives at any point before it, including during the deploy audit-ref lookup, stops the deploy with nothing pushed. Once the durable marker exists, cancellation no longer overrides remote truth: the runner continues to renew ownership without interrupting the irreversible remote update. If the push outcome is ambiguous, the job remains needs_reconcile with the cancellation request preserved; reconcile records deployed when every ref landed or canceled when none did. Calling cancel directly on a needs_reconcile job is refused until that remote check is applied. Canceling a validated train that a deploy claims at the same moment turns into a cancellation request for that running deploy, and canceling one that has already finished is refused; it is never reported as canceled while the train deploys.

Command timeout

Git operations, gates, and verify hooks are bounded by queue.command_timeout_seconds. A timeout terminates the process group and is reported as a command failure; pre-push timeouts leave deploy refs unchanged. On POSIX the group gets SIGTERM, and any process still in it five seconds later gets SIGKILL, even when the command's own process has already exited.

Temporary worktrees

Dry-run cleanup:

mergetrain gc --json

Apply cleanup:

mergetrain gc --apply --json

Delete terminal local branches as well:

mergetrain gc --apply --delete-branches --json

A terminal job's branch is deleted only while it still points at the head that job recorded, and only when that head has landed: it is merged into the integration ref, or into the commit the job pushed. The delete is a compare-and-delete, so a commit that arrives in the meantime makes it fail rather than disappear. A branch with later commits, a canceled branch that never landed, and a branch that a worktree still uses are kept; each branch_candidates[] entry carries eligible and the reason it was kept. A worktree uses a branch when it has it checked out, is rebasing or bisecting it, or is registered with it while its directory is missing, the same cases for which git branch -d refuses.

Worktree cleanup removes only directories under state.worktree_root that carry the project's temporary-worktree name and that nothing else owns. A worktree locked with git worktree lock, a worktree of another repository (two clones can share an absolute worktree_root), a nested repository, and the worktree of a verify or deploy preview whose process is still running are listed as protected, with the reason, and left in place.

Why a persisted marker, instead of reconstructing from Git?

A question worth answering once, properly (it came up in the launch thread — see issue #38's origin): after a crash, why does recovery need the SQLite marker at all, when the Git objects and refs are all still there?

Because Git alone cannot distinguish "never pushed" from "pushed, then died before hearing back." The local objects, the assembled commit, even the pin ref look identical in both worlds; the only difference is on the remote. So the runner persists two things before the push — the lease (a SQLite lock row with token, heartbeat, TTL, and PID liveness) and a fsynced pending_deploy_sha marker plus a refs/mergetrain/pending/<id> pin — and recovery then reads the marker as what we intended and asks the remote for what actually happened. A train is marked deployed only when the push ref really carries its SHA; a landed train is never pushed twice; and when the remote is unreachable, reconcile refuses to guess and exits with its own code instead. A successful deploy or an unambiguous policy rejection clears both the DB marker and pending pin; an ambiguous outcome and a reconcile conflict retain them as recovery evidence. Each successful atomic push also retains refs/mergetrain/deploys/<sha> remotely. If every payload ref later loses that SHA but the audit ref remains, reconcile knows the deploy landed before the rewrite and blocks instead of replaying it. Deployments made before this audit ref existed retain the legacy ambiguity and are classified from payload ancestry alone.