Skip to content

feat(worker): Resume workspaces an interrupted mutation left quarantined - #459

Merged
danny-avila merged 5 commits into
mainfrom
danny-avila/auto-resume
Dec 6, 2026
Merged

danny-avila merged 5 commits into
mainfrom
danny-avila/auto-resume

Conversation

@danny-avila

@danny-avila danny-avila commented Dec 6, 2026 •

Copy link
Copy Markdown
Collaborator

An interrupted workspace mutation leaves a durable marker on the worker, and Code API keeps a matching fence. The interruption is a worker restart or OOM kill while a write or command runs. Every later call on that root or lane is rejected with WORKSPACE_QUARANTINED. To recover, an operator stops the worker, runs clear-workspace-quarantine, and starts it once with --reset-workspace-quarantine. On one production worker, each episode took 10 minutes to more than 4 hours to recover, although the workspace itself stayed usable throughout.

With this change the worker carries out that operator procedure itself, for this one reason class only, and tells the next caller that the change may be partly applied. It builds on #458 (drain on shutdown, OOM preference, now merged), which removes most of these interruptions in the first place.

How it works

run()
  refreshCredential
  findInterrupted           # once per process; registration would otherwise refuse a quarantined root
    each registered root and linked-worktree lane:
      guard.findInterrupted()        # exclusive() queue; qualifies only if every marker qualifies; deletes nothing
  register                  # skips the root check only for roots found above
                            # (CLI environment setup is deferred for those roots for this start)
  resetFound                # before any lease
    resetNativeWorkspace(root, lane, verified)   # the same workspaces/reset call as --reset-workspace-quarantine, 3 attempts
      ok    -> lane interrupted; log "resumed <root>/<lane> after an interrupted <op> (<age> s old)"
      fails -> nothing changed: markers and fence stay; log the exact operator commands
  lease ...
    a call on an interrupted lane
      claimInterruption      # any call whose scope conflicts (the lane, its checkout, a child lane); one at a time
      -> not executed; rejected once with WORKSPACE_INTERRUPTED:
         "<op> was interrupted at <time> when the worker restarted. The workspace may hold partial changes. ..."
      -> Code API accepts it: the lane's found markers are cleared, the next call runs
      -> refused or lost: markers stay, the next call gets the notice
Layer Handling
Durable markers (the workspace marker and detached-command markers) Classified by one new guard method, findInterrupted, which uses the existing exclusive() queue and storage functions and deletes nothing. Its clear() removes exactly the found records (owner-checked, so a marker armed since then stays). That happens only after Code API accepts the notice. The storage format is unchanged.
Code API fence Removed by the existing worker-authenticated workspaces/reset call (resetNativeWorkspace), which still requires an idle worker. Its local check is skipped only for lanes the worker has just classified. Service code, Lua and enqueue are unchanged apart from advertising one settlement code.
In-memory quarantinedWorkspaces Empty in a new process; resetNativeWorkspace deletes the entry, as before.

Reason classes

Marker At startup
Workspace mutation <op> is pending settlement, where <op> is write_file, edit_file, execute_command or import_file, owned by an earlier incarnation Resumed: fence reset, one notice, then cleared
The same reason for create_worktree or remove_worktree Kept: an interrupted lifecycle change can leave Git metadata and a retired or partial lane that need inspection, and the lane may no longer be listed
The same reason, owned by this incarnation Kept (still in flight, or this run's own quarantine)
Programmatic execution pending settlement Kept
Failed environment setup (Environment preparation did not settle, Dependency restoration did not settle) Kept
Stateful runtime-session quarantine, worker-wide WORKER_QUARANTINED Kept (these are not lane markers)
Any unrecognised reason or workspace, or any kept marker on the same lane as a qualifying one Kept, together with every marker on that lane

These two cases are not covered and stay operator-only, unchanged: a single-slot worker with exactly one root, whose guard is the legacy workspaceMutationQuarantine, and per-conversation worktree instances.

Edge cases

  • Fail closed. Markers stay on disk until Code API has accepted the notice, so every early exit leaves the lane exactly as quarantined as today: a failed reset, a refused notice, a crash or OOM kill between reset and notice, or a graceful stop. The next start classifies the lane again, resets the fence again (idempotent) and sends the notice again. When the reset keeps failing, the CLI logs the commands to run, clear-workspace-quarantine --worker-dir … --workspace-id … and a single start with --reset-workspace-quarantine … (plus --reset-workspace-worktree … for a lane). No new persistence is needed, because the existing marker is the durable record of the pending notice.
  • One notice per lane, on any conflicting scope. The notice goes to the first call whose scope conflicts with the resumed one: the lane itself, its checkout, or a lane of a resumed checkout. Otherwise a checkout call would meet the lane's retained marker and quarantine the checkout. A detached command does not hold its worktree, so it can run beside an ordinary call; the first call claims the notice, and the others wait for that settlement, then run if it was accepted or claim the notice themselves if it was not. Delivery is at least once: a crash between acceptance and the marker clear repeats it on the next start.
  • A command that kills the worker every time it runs. It is never replayed. After the restart, the lane's next call receives the notice and does not run, so every further crash needs a new, explicit call made after that notice. Classification runs once per process, a crash loop during startup only repeats the idempotent reset, and systemd's start limit still applies. With fix(worker): Drain leased work on shutdown and let OOM kill commands first #458, an OOM kill takes the command rather than the worker.
  • Environment setup. A root with setup is classified before setup runs. If only an interrupted mutation quarantines it, setup is skipped for that start (logged as setup deferred), because running it would mutate a half-applied workspace; the next start runs setup normally. Any other marker still fails setup as before.
  • Markers that go stale while the worker keeps running (after a rejected or lost settle). These are not resumed. The live incarnation owns them, also holds the in-memory fence, and may still be delivering the quarantine receipt. The next restart resumes them under the same rule.
  • Mixed versions. Code API advertises WORKSPACE_INTERRUPTED in supportedWorkspaceToolErrorCodes. Against an older Code API the worker sends the existing fallback, EXECUTION_ABORTED. An older worker never sends the new code. Roll out Code API before workers.

Size

172 product lines (worker, guard, CLI log line, protocol code and one service line); tests are separate.

Tests

  • workspace-guards on real marker files:
    • An earlier incarnation's workspace and detached markers are found and kept until clear().
    • This run's own markers are not found.
    • clear() never removes a marker armed after the lane was found.
    • Nothing is found when a setup, programmatic, lifecycle or non-mutation marker is on the same lane.
  • worker-receipts on real marker files:
    • The fence is reset before the first lease.
    • The marker is still on disk when the notice is sent.
    • The notice is sent exactly once, then the next call runs and settles fulfilled, against both a current and an older Code API.
    • A refused notice is sent again on the next call.
    • When the fence cannot be reset, the marker stays untouched after three attempts.
    • When registration fails, the marker stays in place.
  • worker-detached:
    • On a resumed lane, a detached command and an ordinary call get exactly one notice between them; the other runs. This test fails without the per-lane claim.
    • A checkout call on a resumed lane takes its notice, the next checkout call runs, and nothing is quarantined. This test fails when the claim matches only the exact key.
  • service:
    • Registration advertises the code.
    • A WORKSPACE_INTERRUPTED settlement is answered with 422 and its code.
    • The bridge and workspace-tools router suites pass (104 tests).
  • npx tsc --noEmit in packages/code is clean. On Linux, worker (61), worker-slots (13), worker-detached (9), worker-receipts (16), workspace-guards (12), environment (11), environment-preparation (10) and native-process-child (5) pass.

@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review (head 163035b): stacked on #458; review only the auto-resume commits. Focus on fail-closed restore of released markers and one-time notice delivery.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 6, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-06T15:09:56.536436Z acfd01a Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 163035bd27

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/code/src/workspace-guards.ts Outdated
Comment on lines +99 to +101
for (const { file, record } of markers)
await clearWorkspaceMutationQuarantine(file, record.ownerId);
return markers.map(({ file, record, operation }) => ({

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve rollback records before removing any markers

If a marker's unlink succeeds but its directory fsync fails, or clearing a later marker fails, this method throws before returning any restore closures. BridgeWorker.releaseInterrupted() catches that error without adding the lane to this.released, so neither resetReleased() nor the final restoreReleased() handles the markers already removed. With a single marker, the local guard is now clear even though no fence reset or interruption notice was arranged. Retain rollback information before the first removal and restore removed markers on the error path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8eebe3c by removing the window instead of adding rollback: startup no longer deletes any marker. findInterrupted only classifies, and its clear() removes exactly the found records once Code API has accepted the interruption notice. A failed unlink or fsync at that point leaves a marker behind, which keeps the lane quarantined (fail closed). Tests: workspace-guards find/clear cases; worker-receipts asserts the marker is still on disk when the notice is sent.

Comment thread packages/code/src/worker.ts Outdated
Comment on lines +1698 to +1700
if (worktree != null && this.interrupted.has(worktree))
await this.deliverInterruption(adjusted, worktree);
else await this.executeOwned(adjusted, signal);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize interruption notice delivery per workspace lane

On a multi-slot worker, a detached command and another assignment for the same recovered workspace can reach this check concurrently: detached commands use assignment-specific active keys and deliberately do not hold the workspace. Both therefore see the interruption entry while the first settlement is awaiting acknowledgement, and both reject their calls with WORKSPACE_INTERRUPTED. This rejects additional user calls rather than delivering the notice once. Serialize notice delivery by workspace key, making later assignments wait and recheck whether the first settlement was accepted before deciding to reject or execute.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8eebe3c. claimInterruption lets one call per lane answer the notice; others on the same lane, including a detached command that does not hold the worktree, wait for that settlement, then run if it was accepted or claim the notice if it was not. The wait comes before the assignment's remaining budget is computed, so the waiting call's deadline accounts for it. Test: worker-detached 'a detached command and an ordinary call on a resumed lane get the interruption notice once' (fails without the claim).

Comment thread packages/code/src/worker.ts Outdated
Comment on lines +1036 to +1037
pending.shift();
if (reset) this.interrupted.set(workspaceIsolationKey(lane.workspaceId, undefined, lane.worktree), lane);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Persist pending interruption notices across worker restarts

If the worker stops after a successful fence reset but before any caller receives the notice, the notice is lost: this removes the lane from released and records it only in the in-memory interrupted map, while its durable markers have already been deleted. Even a graceful shutdown invokes restoreReleased() with nothing left to restore. The next process consequently finds neither markers nor a server fence and executes the next call without warning about the partial mutation. Persist the pending notice across process lifetimes and remove that durable state only after Code API accepts its settlement.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8eebe3c without new persistence: the existing markers are the durable record. They now stay on disk until Code API accepts the notice, so a crash or stop after the fence reset leaves the lane quarantined; the next start classifies it again, repeats the idempotent reset and sends the notice. The root registration check skips only roots the worker has just classified.

@danny-avila
danny-avila force-pushed the danny-avila/auto-resume branch from 163035b to 8eebe3c Compare December 6, 2026 14:42
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review (pass 2, head 8eebe3c): stacked on #458, so review only the auto-resume commits. Markers now stay until the notice is accepted, the reset skips the local check only for lanes just classified, and the notice is claimed per lane. Check every exit path for a lane left without either a marker or a delivered notice.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8eebe3cbd7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1290 to +1292
await this.findInterrupted();
await this.register(signal);
await this.resetFound(signal);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle interrupted roots before the CLI's setup availability check

For a multi-slot worker whose environment defines setup, an interrupted root never reaches this recovery path. Before constructing or running BridgeWorker, cli.ts unconditionally calls guard.assertAvailable() on that environment's root marker (lines 1525–1535), which rejects the qualifying pending-mutation marker and exits startup—even when setup would otherwise reuse an existing receipt. Consequently these workers still require manual quarantine recovery after an interrupted mutation. Integrate classification with the earlier setup phase so eligible roots can reach reset and notice delivery without running setup against their quarantined contents.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b4cc34d. The CLI setup loop now classifies the root with the same findInterrupted before assertAvailable. For a root that only an interrupted mutation quarantines, it skips setup for that start and logs environment <id> setup deferred after an interrupted <op>, so setup never runs over the half-applied change; the worker then resets the fence and delivers the notice, and the next start runs setup normally. Any other marker still fails setup exactly as before. No CLI-level test exists for the setup loop; the classification it calls is covered by workspace-guards, and environment and environment-preparation suites pass.

@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review (pass 3, head b4cc34d): environment setup is now deferred for roots only an interrupted mutation quarantines. Check the startup order (setup, classification, registration, reset) for any root that can skip both setup and quarantine.

@danny-avila
danny-avila deleted the branch danny-avila/worker-drain December 6, 2026 14:53
@danny-avila danny-avila closed this Dec 6, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Provided git ref b4cc34da86381d081414f472ad0ea753e743f4e3 does not exist
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danny-avila danny-avila reopened this Dec 6, 2026
@danny-avila
danny-avila changed the base branch from danny-avila/worker-drain to main December 6, 2026 14:53
At startup the worker releases a root or linked-worktree lane whose only markers are mutations an earlier incarnation left pending settlement, resets its Code API fence through the existing workspace reset, and answers its next call once with WORKSPACE_INTERRUPTED instead of running it. Any other marker keeps the lane quarantined; a fence that cannot be reset gets its markers back.
…cepted

Startup classifies a lane without removing its markers, resets the Code API fence with the local check already done, and clears exactly the found records once Code API accepts the notice. A crash or failed reset therefore leaves the lane quarantined as before. One call at a time answers a lane notice, so a detached command and an ordinary call cannot both receive it.
…n left quarantined

Setup used to refuse the root before the worker could resume it. It now skips setup for that start, so setup never runs over a half-applied change; the worker resets the fence and delivers the notice, and the next start runs setup again.
@danny-avila
danny-avila force-pushed the danny-avila/auto-resume branch from b4cc34d to 744b999 Compare December 6, 2026 14:54
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review (pass 4, head 744b999): rebased onto main after #458 merged; the diff is now only the auto-resume change. Includes the deferred environment setup from b4cc34d.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 744b999c06

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +997 to +1000
const lanes = root.workspaceScopes?.includes('git_linked_worktree') === true
? ((await this.options.linkedWorktreeNames?.(root.id).catch(() => [])) ?? [])
: [];
for (const worktree of [undefined, ...lanes]) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Discover interrupted lanes whose worktree directory was removed

If the worker stops during remove_worktree after WorktreeLifecycle.remove() renames the lane to .retired-* (worktree-lifecycle.ts:170), the pending mutation marker survives outside the checkout, but the original lane no longer appears in linkedWorktreeNames(), which reads .worktrees and filters valid lane names (cli.ts:1674–1681). This startup scan therefore never classifies or resets that interrupted lane. Its persistent server fence continues blocking both that lane and checkout-level calls, leaving this explicitly supported mutation dependent on manual recovery. Discover pending lanes independently of surviving worktree directories, or otherwise retain their names for recovery.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in acfd01a by scope rather than discovery: interrupted create_worktree and remove_worktree are no longer resumed and stay quarantined until an operator reset, as today. Their own failure path already asks for inspection (inspect its Git registration and retirement directory before reset), and an interrupted create or remove can leave Git metadata and a retired or partial lane, which is not safe to hand back with a notice. Discovering lanes from marker files is not possible either, because marker names are hashed root paths. No production worker advertises lifecycle operations today. Test: workspace-guards keeps markers for both lifecycle operations.

});
this.activeAssignmentIds.add(assignment.assignmentId);
}
const noticed = worktree == null ? undefined : await this.claimInterruption(worktree);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle interruption notices across conflicting workspace scopes

When an existing linked-worktree lane is resumed and the first subsequent call targets its checkout root, this exact-key claim misses the lane's pending notice. The reset has removed the server-side lane fence, so the root call can reach executeOwned(), but assertLaneFamilyAvailable() rejects it because the lane's durable marker is deliberately retained until notice acceptance. executeAndSettle() then quarantines the root and runConcurrent() sends its quarantine receipt. That new root fence prevents subsequent lane calls from reaching the pending notice, while checkout calls also remain fenced, making automatic recovery require manual intervention. Handle pending notices for conflicting parent/child scopes before running their availability checks rather than treating the retained recovery marker as a new quarantine.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in acfd01a. claimInterruption now matches any resumed scope that conflicts with the call (workspaceIsolationKeysConflict: the same lane, its checkout, or a lane of a resumed checkout), before executeOwned and its availability checks. A checkout call on a resumed lane therefore takes the notice instead of meeting the retained marker and quarantining the checkout. Test: worker-detached 'a checkout call on a resumed lane takes its notice instead of quarantining the checkout' (fails when the claim matches only the exact key).

…scope, and keep lifecycle interruptions operator-only

A call on the checkout of a resumed lane, or on a lane of a resumed checkout, now takes that notice instead of meeting the retained marker and quarantining the parent. Interrupted create_worktree and remove_worktree stay quarantined: they can leave Git metadata and a retired or partial lane that need inspection, and their lane may no longer be listed.
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review (final pass, head acfd01a): final review before merge. After three actionable rounds I rechecked by invariant: for every scope found at startup, either its marker and Code API fence both remain (quarantined as today: failed reset, refused notice, crash, stop, or a lifecycle or unknown marker), or the fence is reset and the first conflicting call (lane, checkout, child lane, or detached) receives the notice once before the markers are cleared. Please look for any path that violates it, including registration, CLI environment setup and the lane-family checks.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: acfd01af3f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danny-avila
danny-avila merged commit c2f659c into main Dec 6, 2026
31 checks passed
@danny-avila
danny-avila deleted the danny-avila/auto-resume branch December 6, 2026 15:14
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.

1 participant