Skip to content

fix(storage): reclaim the lifecycle gate of a dead holder and stop recovery steps piling up - #3364

Merged
integry merged 3 commits into
mainfrom
fix/storage-gate-orphan-recovery
Oct 29, 2026
Merged

integry merged 3 commits into
mainfrom
fix/storage-gate-orphan-recovery

Conversation

@integry

@integry integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner

Summary

Today the worker was frozen for five hours: 10 jobs sat in active without a single log line, indexing stopped, and goal recovery piled up 93 copies. Cause: the storage lifecycle gate (/tmp/git-processor/.clones-storage-lifecycle/gate, a directory shared by every service container) had been created by the worker 8 minutes before it died of a JS heap OOM. The gate had no owner record or expiry, and use() waits for it forever without logging, so nothing recovered until the directory was removed by hand.

Changes

The gate records its holder and is reclaimed when the holder is gone (packages/core/src/storage/lifecycle.ts)

  • The holder writes owner (container id, pid, process start time, a token) inside the gate right after mkdir.
  • A waiter probes the holder every 5 s with the existing claimOwnerGone check (container restarted or pid gone) and removes an abandoned gate; a gate with no record is abandoned after 10 minutes.
  • Release only removes the gate this call took (token match), so a holder wrongly judged dead cannot remove its successor's gate.
  • A wait is reported every minute with the holder (Still waiting for the storage lifecycle gate after Ns (held by <host> pid <pid>)) unless the caller supplies its own warning, as worktree removal does.

Recovery steps no longer pile up (src/workerTaskStateRecovery.ts)

  • runWithinDeadline abandons a step that exceeds its budget but cannot cancel it. The pass then started the same step again every minute; the heap snapshot of the frozen worker held 93 pending recoverNonterminalGoals runs, and the crashed worker had logged 94 abandoned passes in the two hours before its OOM. A step is now skipped, with a warning, while its previous run is still pending.

Docs: maintenance.md describes the gate, its logs, and the manual unblock for older versions.

Tests

  • packages/core/test/storageLifecycleGate.test.ts (new, real filesystem): holder record and cleanup; a dead holder's gate is reclaimed; a live holder's gate is respected; an ownerless gate is reclaimed only after the grace period; a reclaimed-and-retaken gate is left alone by the original holder; the wait warning names the holder.
  • test/workerTaskStateRecovery.test.ts: a step whose previous run is still pending is skipped and runs again once it finishes.
  • Existing storage suites (storageClaimOwner, instanceStorage, generatedPayloadStorage, fleetDataPlane) pass.

🤖 Generated with Claude Code

…covery steps piling up

The storage lifecycle gate (a directory shared by every service container)
had no owner record or expiry, and every job, indexing scan and release
waited for it forever without logging. When the worker died of a heap OOM
while holding it, the restarted worker picked up 10 jobs that never logged a
line, indexing froze, and goal recovery piled up one copy per minute for
hours until the gate was removed by hand.

The holder now records itself (container, pid, start time) inside the gate.
A waiter probes the holder every 5 s and removes a gate whose holder is
gone; a gate with no record is abandoned after 10 minutes. Release only
removes the gate this call took, so a holder wrongly judged dead cannot
remove its successor's gate. Waits are reported every minute with the
holder, unless the caller supplies its own warning.

The worker's recovery pass abandons a step that exceeds its budget but
cannot cancel it; starting the step again every minute piled up dozens of
copies (93 goal-recovery runs in a heap snapshot) and is the likely cause
of the OOM. A step is now skipped, with a warning, while its previous run
is still pending.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@integry integry added the AI label Oct 28, 2026
@integry

integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

/review fable astra

@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 2 reviews:

View Task Details

@propr-dev

propr-dev Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — fable

Overall Evaluation

The PR addresses a real production freeze with two targeted changes: the storage lifecycle gate now carries an owner record so a waiter can reclaim a gate whose holder is provably gone (reusing the existing claimOwnerGone proof rather than a TTL), waits are logged periodically with the holder, and the worker recovery pass no longer launches a new copy of a step whose previous run is still pending. The design choices are sound and consistent with the existing "no TTL stealing" claim model, the tests use a real filesystem, and CI is fully green at head.

Two correctness problems in the changed code block merge. The reclaim path acts on stale evidence across an awaited docker inspect and can delete a live successor's gate (breaking the mutual exclusion the gate exists to provide), and the new runStep helper starts a step before the budget/abort checks that previously gated it, so a step with no remaining budget is now launched unbounded and outside the lease. Both have localized fixes.

✅ Token-scoped release — releaseGate only removes the gate whose owner.token matches the one this call wrote, and the test "a holder whose gate was reclaimed and retaken leaves the new holder alone" verifies that a displaced holder leaves its successor's gate intact.

✅ Proof-based reclaim, not TTL — Reclaiming an owned gate goes through the existing claimOwnerGone contract (container removed/restarted, or missing PID in the same container), so uncertainty (no Docker, non-container host) keeps the gate, matching the file's stated claim semantics.

✅ In-flight guard is settle-safe — pending.then(forget, forget) attaches handlers to the abandoned promise, so a late rejection of an abandoned step cannot become an unhandled rejection, and the map entry is cleared only if it still refers to the same promise.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F1: 🔴 Reclaim can remove a live successor's gate, breaking mutual exclusion

  • Required behavior: The gate must remain a mutual-exclusion primitive, and a reclaim must remove only the gate incarnation it judged abandoned (the PR's own stated invariant that a process "cannot remove its successor's gate").

  • Evidence: packages/core/src/storage/lifecycle.ts:127-145, reclaimAbandonedGate

    Static trace:

    1. Holder A's container has restarted (the incident scenario); its gate still exists with A's owner record. Several waiters (worker jobs in use(), the daemon's cleanup()/sweep(), queue producers via protectStorageQueue) are polling; each runs reclaimAbandonedGate immediately on its first EEXIST (nextOrphanCheck = 0) and every 5 s after.
    2. Waiter B and waiter C both call gateRecord(gate) and read A's record, then both await claimOwnerGone(record.owner, …). For an owned gate this awaits docker inspect (execFile, up to the 10 s timeout) — tens to hundreds of milliseconds on a loaded host.
    3. B's probe resolves first: B unlinks owner, rmdir(gate), logs the reclaim, continues, mkdir(gate) succeeds, writes its own record (token tB), and enters run().
    4. C's probe then resolves true for A. C executes fs.unlink(path.join(gate, 'owner')) — this is now B's record — then fs.rmdir(gate), which succeeds because the gate contains only the owner file. C logs "Removed an abandoned storage lifecycle gate: its holder (A …) is gone", continues, takes the gate and runs.
    5. B and C now execute their exclusive bodies concurrently. If B is the daemon's cleanup() (deletion in progress, cooperative cancellation only) and C is a worker admission in use(), the job proceeds against a clone/worktree root that cleanup is still deleting — the exact race the gate barrier exists to prevent. B's releaseGate later reads token tC ≠ tB and logs the misleading "the holder was probably judged dead", although B was never probed.

    The token check in releaseGate does not cover this path: reclaimAbandonedGate never re-verifies that the record it is about to delete is still the one it judged abandoned, and nothing makes removal atomic per gate incarnation. The same stale-evidence window exists when an operator removes the gate by hand (the documented manual unblock) while a waiter's probe is in flight. None of the new tests run two reclaimers against one dead gate. Assumption I could not verify: actual docker inspect latency in the deployed containers; the window scales with it.

    Proposed regression: plant a dead-owner gate, construct a probe whose containerStartedAt for one StorageLifecycle instance resolves only after a second instance has reclaimed and retaken the gate, and assert the second instance's record survives and the first instance does not enter run() while the second is inside it.

  • Minimum fix: In reclaimAbandonedGate, after claimOwnerGone resolves true, re-read the record and abort the reclaim unless it is byte-identical (same token/owner) to the record that was probed; then remove the gate atomically per incarnation by fs.rename(gate, <unique tombstone path under this.root>) (treat ENOENT as "someone else reclaimed it") and delete the tombstone, instead of unlinking owner inside the live gate path. Keep the ownerless path on the same rename-then-remove step.

F2: 🔴 runStep starts a step before the budget and abort checks that previously gated it

  • Required behavior: A recovery step must not be started when the pass has no remaining budget (or is aborted); the PR's objective is to stop unbudgeted stray step copies, and the base behavior never launched a step past the deadline.

  • Evidence: src/workerTaskStateRecovery.ts:246-256, runStep (const pending = operation(); precedes runWithinDeadline)

    Static trace:

    1. A pass with a large backlog: reconcileStaleTaskStates is given timeBudgetMs = deadline - now - leaseReleaseBudgetMs and uses it fully (the paged cursor/backlog design in this file expects that), so on return deadline - leaseReleaseBudgetMs - Date.now() ≤ 0.
    2. execute calls runStep('Task replacement recovery', () => replacement.resumePending(), deadline - leaseReleaseBudgetMs, signal).
    3. runStep unconditionally invokes operation() — resumePending() is now running — and records it in stepsInFlight, then calls runWithinDeadline(name, () => pending, …), whose first lines throw RecoveryOperationTimeoutError because remainingMs <= 0 (and signal?.throwIfAborted() likewise only runs after the step was started).
    4. The pass logs "Failed to reconcile stale persisted task states", releases the Redis lease in finally, and returns false. resumePending() keeps running with no deadline, no abort wiring, and no lease; another worker can acquire the lease and run the same step concurrently. The next pass on this worker logs "Skipping a recovery step whose previous run has not finished" for a step the base code would never have started.

    Before this diff, runWithinDeadline performed the remainingMs <= 0 and throwIfAborted checks before calling the thunk, so a budget-exhausted step was never launched. The new in-flight map bounds this to one copy per worker but does not prevent the launch. Existing tests only cover a step that starts with budget and overruns.

    Proposed regression: with timeBudgetMs small and a reconcileStaleTaskStates mock that sleeps past the budget, assert recoverGoals/replacement.resumePending mock call counts remain 0 after the pass fails.

  • Minimum fix: Start and register the step inside the runWithinDeadline thunk (e.g. runWithinDeadline(name, () => { const pending = operation(); stepsInFlight.set(name, pending); pending.then(forget, forget); return pending; }, deadline, signal)), or perform the deadline - Date.now() <= 0 and signal.throwIfAborted() checks in runStep before operation() is called.

Suggestions

These are optional follow-ups and are not sent to /fix.

S1: 🟢 Defer the first orphan probe to avoid a docker inspect per contention

nextOrphanCheck = 0 means every EEXIST — including the routine millisecond-scale contention between job admission, release(), and protectStorageQueue adds — immediately reads the owner file and runs claimOwnerGone, which spawns docker inspect (10 s timeout) for any owned gate. That adds process-spawn latency to every contended wait and a steady stream of Docker CLI invocations under normal load. Initialising nextOrphanCheck to Date.now() + GATE_ORPHAN_CHECK_MS (or skipping the probe while the record's takenAt is younger than the probe interval) keeps the reclaim behavior for genuinely stuck gates without taxing the common path. Optional because it is a performance characteristic, not a correctness defect.

S2: 🟢 Document that non-container hosts cannot reclaim an owned gate

dockerContainerStartedAt returns undefined for hostnames that are not 12-hex container IDs, and claimOwnerGone keeps the claim under uncertainty, so on native/dev installs a crashed holder's gate (which now has an owner record, so the 10-minute ownerless grace never applies) is still never reclaimed. The new periodic warning makes this visible, which is an improvement, but maintenance.md reads as if reclaim is universal; a sentence scoping automatic reclaim to Docker-hosted services (with the manual unblock for the rest) would avoid misleading operators. Pre-existing contract, so not a blocker.

S3: 🟢 Docs overstate what the gate covers

maintenance.md says every job "runs under a host-wide lock" held by the gate. In use() the gate is held only for admission and the use-clock touch; the job itself holds a reader claim while the gate is free. Stating this precisely would help operators interpret the holder named in wait warnings (the holder is usually a brief admission or a cleanup, not a running job).

S4: 🟢 if (result) suppresses the info line for void-returning steps

The four step results are now logged only when truthy. For steps that return objects this is fine, but replacement.resumePending()'s return type is not visible in the supplied context; if it resolves undefined, "Resumed interrupted task replacement decisions" is silently dropped on every pass. Distinguishing the skipped case with a sentinel (or result !== null) preserves the previous logging contract regardless of return type.

S5: 🟢 Make the new recovery test deterministic

The test relies on a 100 ms sleep versus a 60 ms budget, plus a setImmediate for forget to run. It passes in CI, but under contention (shared shard hosts) the startup pass could still be inside lease acquisition at 100 ms, which would make runOnce coalesce into it. Awaiting the "Failed to reconcile…" log call (or a resolver captured inside recoverGoals) before asserting would remove the timing dependence.

S6: 🟢 Ownerless grace is a TTL during mixed-version deploys

A gate created by an older release has no record, and is reclaimed once the directory is 10 minutes old even if that old process is alive and still inside cleanup(). This is the one place the file's "elapsed time never does" comment no longer holds. It is a deliberate, bounded compromise for the upgrade window (API cleanup has a 60 s deadline), but worth a note in the class comment and in the docs' upgrade section so the trade-off is explicit.

Score

The change is well-motivated and mostly well-built, but the reclaim path can remove a live holder's gate across the awaited liveness probe, and the new step helper launches steps the base code would have refused to start; both need fixing before merge.

Score: 5/10


🤖 Review Details

  • Model: Claude Fable 5.1
  • Time: 5m 54s
  • Tokens: 77,413 (58,140 in / 19,273 out)
  • Cost: $1.69

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F1 F2 S1 S2 S3 S4 S5 S6

🤖 Review by ProPR

@propr-dev

propr-dev Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — astra

Overall Evaluation

The PR addresses abandoned storage gates and accumulating recovery promises, but needs changes before merge: concurrent reclamation can break mutual exclusion, and recovery steps now start before their deadline is checked.

✅ Pending-step tracking — Unfinished recovery promises remain tracked after timeout, and both fulfillment and rejection remove them from the map.

✅ Operational visibility — Default admission/release waits now report the holder periodically while preserving caller-supplied warnings.

✅ Focused coverage — Tests cover dead and live holders, ownerless grace periods, and pending-step suppression. All reported current-head checks passed or were skipped.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F3: 🔴 Concurrent reclaimers can delete a successor’s gate

  • Required behavior: Gate recovery must preserve exclusive access and must not remove a gate belonging to a live successor.

  • Evidence: packages/core/src/storage/lifecycle.ts, reclaimAbandonedGate and releaseGate.

    1. A dead holder leaves its gate behind. Two waiting processes, A and B, read the same owner record.
    2. Both await claimOwnerGone(record.owner, this.ownerProbe). A’s probe completes first; B’s Docker inspection remains pending.
    3. A removes the abandoned gate, acquires a new gate, writes its own owner record, and enters its exclusive callback.
    4. B’s inspection completes and correctly reports that the old holder is dead. B unconditionally unlinks the current gate/owner and removes the current gate directory, which now belong to A.
    5. B acquires the gate and enters its callback while A’s callback is still running. Storage operations intended to be exclusive now overlap.

    The competing waiters are not serialized during reclamation; the shared gate is precisely what they are trying to recover. No identity check connects the deletion to the record inspected before the awaited probe. releaseGate checks a token only when the callback finishes, so it cannot prevent this overlap. Its own separate read/check/delete sequence also does not provide atomic ownership protection. The existing takeover test replaces the gate before release begins and does not exercise concurrent reclamation.

    static trace: Verified against the supplied acquisition loop, asynchronous owner probe, reclamation mutations, and release path; no commands or tests were run.

  • Minimum fix: Coordinate reclamation and gate mutation so deletion remains tied to the inspected gate generation. Serialize reclaimers and revalidate ownership under that coordination, with acquisition/release respecting the same protocol wherever necessary. A token reread followed by an unguarded deletion leaves another race window. Add a regression that pauses B’s probe until A has acquired the replacement gate and verifies B cannot enter until A releases it.

F4: 🔴 Recovery starts work after its budget expires

  • Required behavior: Recovery must check its deadline and cancellation state before starting a new step; a rejected step must not begin uncancellable background work.

  • Evidence: src/workerTaskStateRecovery.ts, runStep.

    1. A pass acquires the Redis lease and runs reconcileStaleTaskStates with the remaining reconciliation budget.
    2. Reconciliation returns at or after deadline - leaseReleaseBudgetMs. This path remains reachable because runUntilAborted does not impose a deadline on that promise, and completing at the budget boundary does not reserve time for another step.
    3. runStep invokes operation() immediately—for example, recoverGoals begins queue/database recovery—before calling runWithinDeadline.
    4. runWithinDeadline sees the expired deadline and rejects immediately. The pass releases its Redis lease, while the newly started operation continues and can perform recovery effects.

    Before this change, runWithinDeadline checked the deadline before invoking the operation. Tracking the promise prevents another invocation in this runner but neither cancels that work nor retains the distributed lease. Another worker can acquire the released lease while this unnecessarily started recovery continues. The supplied native-goal callback performs database selection and sequential goal recovery, so invocation is consequential.

    static trace: Verified against runStep, the deadline guards, the reconciliation call, lease-release finally, and the supplied native-goal callback. No execution was performed.

  • Minimum fix: Create and register the pending promise inside the operation callback passed to runWithinDeadline, preserving its guards before invocation. Add a regression asserting that an exhausted reconciliation budget does not invoke a subsequent recovery callback.

Suggestions

These are optional follow-ups and are not sent to /fix.

S7: 🟢 Cover rejected pending steps

The new recovery test exercises fulfillment after timeout. A companion test where that pending promise rejects would confirm that rejection is handled and the step becomes eligible again. The implementation already attaches both settlement handlers, so this is optional coverage.

Score

The change is focused and has passing checks, but the reclamation race compromises the storage barrier, and the recovery wrapper regresses deadline enforcement. Both require correction before merge.

Score: 5/10


🤖 Review Details

  • Model: GPT-6 Astra
  • Time: 1m 20s
  • Tokens: 46,573 (44,946 in / 1,627 out)
  • Cost: $0.42

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F3 F4 S7

🤖 Review by ProPR

@integry

integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

/fix all

@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ Applied the requested follow-up changes in commit 08c4b30

Addressed 2 AI review comments (IDs: 6480290776, 6480317548)

Addressed findings F1, F2, F3, F4 · suggestions S1, S2, S3, S4, S5, S6, S7

Summary of Changes

All selected records are applied and verified. No visual previews: nothing here is user-visible UI.

F1 / F3, gate reclaim atomicity (packages/core/src/storage/lifecycle.ts)

  • The holder's record is now named by its own token, owner-<token>, instead of a fixed owner file. A reclaim unlinks the record under the name it probed, so the kernel's unlink is the compare-and-remove: a successor's record has a different name and survives. The waiter whose unlink fails with ENOENT lost the race and keeps waiting.
  • Only the winner removes the then-recordless directory. Nothing else can act on it in that window: mkdir sees it, its fresh mtime is far from the ownerless grace, and there is no record left to unlink.
  • Release uses the same conditional unlink. A holder wrongly judged dead finds its own record gone and leaves the successor's gate alone.
  • I did not use the rename-to-tombstone approach F1 proposed. A rename moves whatever is at the gate path, so a reread followed by a rename still has the window F3 points out. Unlink by token-specific name has no such window.
  • Acquisition retries if its record write hits ENOENT, which closes the only remaining microsecond hazard where an ownerless-grace sweep removes a freshly created empty gate. The ownerless path also removes stale leftover entries only by the names it saw.
  • Regression: two StorageLifecycle instances wait on a dead holder's gate, one with a probe that answers only after the other has reclaimed and entered its callback. The late waiter does not enter, the holder's record survives, and exactly one reclaim is logged. The test fails on an unguarded-unlink variant with the mutual-exclusion break and passes on the fix.

F2 / F4, step start after budget (src/workerTaskStateRecovery.ts)

  • runStep now starts and registers the step inside the thunk handed to runWithinDeadline, so the deadline and abort checks run before the step is invoked. Regression: reconciliation consumes the whole budget and neither resumePending nor recoverGoals is invoked, the lease is released, and the next pass runs both. This fails on the branch's previous runStep.

Suggestions

  • S1: the first holder probe waits a full interval. A new orphanCheckMs option lets tests shorten it. A test asserts no probe is spawned during a wait shorter than the interval.
  • S2, S3, S6: maintenance.md now scopes automatic reclaim to Docker-hosted services with the manual unblock for native installs, describes precisely when the gate is held, and documents the ownerless grace as a bounded TTL during mixed-version upgrades, with a matching note in the upgrade steps. The class comment states the same exception.
  • S4: step results are logged unless the step was skipped (!== null), restoring the previous logging contract for any return type.
  • S5: the pending-step test awaits the "Failed to reconcile" log call instead of a fixed sleep.
  • S7: a companion test rejects the pending step late and asserts the step becomes eligible again with no unhandled rejection.

Verification

  • Gate suite 8 passed, recovery suite 11 passed, related storage suites 123 passed.
  • Core tsc --noEmit and root tsc clean; eslint zero warnings on the changed source files.

Independent observations, not acted on: the ownerless-grace rmdir can in a microsecond window remove a just-created empty gate whose holder has not yet written its record. The holder now retries, so mutual exclusion holds, but this is inherent to directory-as-lock without a holder record. No code depends on the old fixed owner file name elsewhere in the repo.


🤖 Implementation Details

  • Model: Claude Fable 5.1 (medium)
  • Requested By: @integry
  • Time: 13m 45s
  • Tokens: 1,797,502 (1,763,019 in / 34,483 out)
  • Cost: $3.36
  • Subscription usage: Session +3%, Weekly +1%, Fable +1%

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 6480394746✓

…eviews: nothing here is user-visible UI.

All selected records are applied and verified. No visual previews: nothing here is user-visible UI.

**F1 / F3, gate reclaim atomicity** (`packages/core/src/storage/lifecycle.ts`)
- The holder's record is now named by its own token, `owner-<token>`, instead of a fixed `owner` file. A reclaim unlinks the record under the name it probed, so the kernel's unlink is the compare-and-remove: a successor's record has a different name and survives. The waiter whose unlink fails with `ENOENT` lost the race and keeps waiting.
- Only the winner removes the then-recordless directory. Nothing else can act on it in that window: `mkdir` sees it, its fresh mtime is far from the ownerless grace, and there is no record left to unlink.
- Release uses the same conditional unlink. A holder wrongly judged dead finds its own record gone and leaves the successor's gate alone.
- I did not use the rename-to-tombstone approach F1 proposed. A rename moves whatever is at the gate path, so a reread followed by a rename still has the window F3 points out. Unlink by token-specific name has no such window.
- Acquisition retries if its record write hits `ENOENT`, which closes the only remaining microsecond hazard where an ownerless-grace sweep removes a freshly created empty gate. The ownerless path also removes stale leftover entries only by the names it saw.
- Regression: two `StorageLifecycle` instances wait on a dead holder's gate, one with a probe that answers only after the other has reclaimed and entered its callback. The late waiter does not enter, the holder's record survives, and exactly one reclaim is logged. The test fails on an unguarded-unlink variant with the mutual-exclusion break and passes on the fix.

**F2 / F4, step start after budget** (`src/workerTaskStateRecovery.ts`)
- `runStep` now starts and registers the step inside the thunk handed to `runWithinDeadline`, so the deadline and abort checks run before the step is invoked. Regression: reconciliation consumes the whole budget and neither `resumePending` nor `recoverGoals` is invoked, the lease is released, and the next pass runs both. This fails on the branch's previous `runStep`.

**Suggestions**
- S1: the first holder probe waits a full interval. A new `orphanCheckMs` option lets tests shorten it. A test asserts no probe is spawned during a wait shorter than the interval.
- S2, S3, S6: `maintenance.md` now scopes automatic reclaim to Docker-hosted services with the manual unblock for native installs, describes precisely when the gate is held, and documents the ownerless grace as a bounded TTL during mixed-version upgrades, with a matching note in the upgrade steps. The class comment states the same exception.
- S4: step results are logged unless the step was skipped (`!== null`), restoring the previous logging contract for any return type.
- S5: the pending-step test awaits the "Failed to reconcile" log call instead of a fixed sleep.
- S7: a companion test rejects the pending step late and asserts the step becomes eligible again with no unhandled rejection.

**Verification**
- Gate suite 8 passed, recovery suite 11 passed, related storage suites 123 passed.
- Core `tsc --noEmit` and root `tsc` clean; eslint zero warnings on the changed source files.

**Independent observations, not acted on:** the ownerless-grace `rmdir` can in a microsecond window remove a just-created empty gate whose holder has not yet written its record. The holder now retries, so mutual exclusion holds, but this is inherent to directory-as-lock without a holder record. No code depends on the old fixed `owner` file name elsewhere in the repo.

PR: #3364
Comment by: @integry (ID: 6480394746)
Model: Claude Fable 5.1
@integry

integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

/review astra

@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — astra

Overall Evaluation

The PR addresses abandoned storage gates and duplicate recovery work with focused changes and useful regression coverage. It needs changes before merge: concurrent ownerless-gate reclamation can allow two callers into the exclusive section.

✅ Recovery deduplication — Pending steps remain tracked after a timeout, and both fulfillment and rejection restore eligibility.

✅ Token-specific reclamation — A delayed probe cannot unlink a successor’s differently named owner record; the added test covers this case.

✅ Operational visibility — Default wait warnings identify the holder, and deployment documentation explains mixed-version behavior.

The supplied current-head checks report 21 passed, none failed, and none pending. This review used static analysis only, as requested.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F5: 🔴 Ownerless reclamation can break exclusivity

  • Required behavior: Storage lifecycle operations must remain mutually exclusive during reclamation and takeover; successful holder publication must belong to the directory that caller acquired.

  • Evidence: packages/core/src/storage/lifecycle.ts, reclaimAbandonedGate, recordHolder, and exclusive.

    1. Two waiting callers, A and B, inspect the same empty gate older than the ten-minute grace period. Both complete the awaited fs.stat(gate) and qualify it for reclamation.
    2. A pauses before its fs.rmdir(gate). B removes the old directory, loops through exclusive, and successfully creates a new gate. B pauses before recordHolder opens its owner file.
    3. A’s already-authorized fs.rmdir(gate) removes B’s new, still-empty directory. The removal uses only the pathname; it does not verify which directory A previously inspected.
    4. A loops, creates another gate, publishes owner-A, and enters its critical section.
    5. B resumes fs.writeFile(gate/owner-B, ..., { flag: 'wx' }). It succeeds inside A’s directory because owner-B is a distinct filename. B also enters its critical section while A is running.

    The observable result is simultaneous execution of callbacks promised exclusive access, allowing storage cleanup, admission, or registry mutations to overlap. Release can additionally fail with ENOTEMPTY while the other owner record remains.

    These interruption points are ordinary asynchronous filesystem operations between competing waiters. The fresh directory mtime does not protect against A’s previously completed age check. The ENOENT retry only handles an absent directory; it does not detect a replacement. Unique filenames protect against stale unlink operations but permit both writes in step 5. Existing tests exercise delayed probes against recorded owners, not concurrent reclamation of an ownerless gate.

    static trace: verified against the supplied acquisition, ownerless-reclamation, and release paths. proposed regression: deterministically pause two reclaimers after their age checks and one acquirer between directory creation and owner publication, then assert that their callbacks never overlap.

  • Minimum fix: Couple holder publication to the specific directory acquired, so replacement during acquisition forces a retry without entering the callback. Coordinate ownerless reclamation with that acquisition protocol; a pathname existence check or another age check alone does not close this window. Add the deterministic interleaving regression described above.

Suggestions

These are optional follow-ups and are not sent to /fix.

S8: 🟢 Bound test log polling

The new logged() helper polls indefinitely if its expected message never arrives. A bounded timeout with a diagnostic rejection would make regressions fail clearly instead of hanging the test process. This is optional test-maintenance work.

Score

The recovery guard, documentation, and passing checks are strong, but the remaining takeover race violates the central storage-exclusion guarantee and requires correction before merge.

Score: 6/10


🤖 Review Details

  • Model: GPT-6 Astra
  • Time: 1m 3s
  • Tokens: 53,117 (51,795 in / 1,322 out)
  • Cost: $0.47

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F5 S8

🤖 Review by ProPR

@integry

integry commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

/fix

@propr-dev

propr-dev Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ Applied the requested follow-up changes in commit f6ac268

Addressed 1 AI review comment (IDs: 6482551878)

Addressed finding F5

Summary of Changes

F5 is applied. Nothing here is user-visible UI, so no preview files were created.

The defect. Holder publication was a plain write into whatever directory sat at the gate path, and an ownerless reclaim removed that path after an age check that could be stale. Two reclaimers plus one acquirer paused between creating the directory and writing its record could therefore end with two records in one gate and two callbacks running at once.

The correction in packages/core/src/storage/lifecycle.ts:

  • A holder now prepares its gate under a token-unique name with its record already inside, then renames that directory onto the gate path. The record can only ever land in the directory its writer prepared, so the "created but not yet published" moment no longer exists at the gate path.
  • The rename is the only way in. It fails while any directory exists at the path and, per rename(2), atomically replaces only an empty one. Outside a reclaim the acquirer still creates the gate plainly first, so an empty gate from an older version or a release in progress is waited on rather than replaced before the grace period, as before.
  • Reclamation no longer removes the directory by pathname. It empties the gate (record unlinked under its token name, or ownerless leftovers after the grace period) and then renames the reclaimer's own prepared gate onto it. A stale, age-authorized takeover can only succeed against a directory that is still empty, never against a holder that has published a record. A replacement during acquisition yields ENOTEMPTY, which forces a retry without entering the callback.
  • Release treats ENOTEMPTY as a successor having taken the briefly empty directory. The prepared directory is removed if acquisition fails.

Sibling check. The other rmdir and wx sites in packages/core/src/storage (database export lease, registry, generated payloads, cache removal) each act on token-unique names or on paths only their own call creates, so none share the pathname-replacement assumption. The claim-owner tests that create and remove the gate by hand still pass.

Regressions in packages/core/test/storageLifecycleGate.test.ts, both driven by holding the lifecycle's own stat and mkdir calls rather than by timing:

  • Two reclaimers of an ownerless gate, one stalled after its age check, the other paused between creating the gate directory and publishing. Critical sections must not overlap and each holder must release its own gate.
  • A stale reclaim against a fresh acquirer paused between creation and publication.

Both fail on the previous implementation with the release ENOTEMPTY the finding predicts, and pass ten of ten runs on the new one. The full storage suite set passes (133 tests), as do core typecheck and lint.

Docs. The maintenance page now describes the prepare-and-rename protocol and the leftover gate-<token> directory a crash can leave.

Independent observation, not changed. The admission test in storageClaimOwner.test.ts measures free disk space twice and expects it not to grow in between. It failed once while lint ran concurrently and passed five of five alone, so it is environmental.


🤖 Implementation Details

  • Model: Claude Fable 5.1 (medium)
  • Requested By: @integry
  • Time: 21m 2s
  • Tokens: 2,556,502 (2,517,259 in / 39,243 out)
  • Cost: $3.76
  • Subscription usage: Session +2%, Weekly +1%, Fable +1%

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 6482695676✓

…ew files were created.

F5 is applied. Nothing here is user-visible UI, so no preview files were created.

**The defect.** Holder publication was a plain write into whatever directory sat at the gate path, and an ownerless reclaim removed that path after an age check that could be stale. Two reclaimers plus one acquirer paused between creating the directory and writing its record could therefore end with two records in one gate and two callbacks running at once.

**The correction** in `packages/core/src/storage/lifecycle.ts`:

- A holder now prepares its gate under a token-unique name with its record already inside, then renames that directory onto the gate path. The record can only ever land in the directory its writer prepared, so the "created but not yet published" moment no longer exists at the gate path.
- The rename is the only way in. It fails while any directory exists at the path and, per rename(2), atomically replaces only an empty one. Outside a reclaim the acquirer still creates the gate plainly first, so an empty gate from an older version or a release in progress is waited on rather than replaced before the grace period, as before.
- Reclamation no longer removes the directory by pathname. It empties the gate (record unlinked under its token name, or ownerless leftovers after the grace period) and then renames the reclaimer's own prepared gate onto it. A stale, age-authorized takeover can only succeed against a directory that is still empty, never against a holder that has published a record. A replacement during acquisition yields ENOTEMPTY, which forces a retry without entering the callback.
- Release treats ENOTEMPTY as a successor having taken the briefly empty directory. The prepared directory is removed if acquisition fails.

**Sibling check.** The other `rmdir` and `wx` sites in `packages/core/src/storage` (database export lease, registry, generated payloads, cache removal) each act on token-unique names or on paths only their own call creates, so none share the pathname-replacement assumption. The claim-owner tests that create and remove the gate by hand still pass.

**Regressions** in `packages/core/test/storageLifecycleGate.test.ts`, both driven by holding the lifecycle's own stat and mkdir calls rather than by timing:

- Two reclaimers of an ownerless gate, one stalled after its age check, the other paused between creating the gate directory and publishing. Critical sections must not overlap and each holder must release its own gate.
- A stale reclaim against a fresh acquirer paused between creation and publication.

Both fail on the previous implementation with the release ENOTEMPTY the finding predicts, and pass ten of ten runs on the new one. The full storage suite set passes (133 tests), as do core typecheck and lint.

**Docs.** The maintenance page now describes the prepare-and-rename protocol and the leftover `gate-<token>` directory a crash can leave.

**Independent observation, not changed.** The admission test in `storageClaimOwner.test.ts` measures free disk space twice and expects it not to grow in between. It failed once while lint ran concurrently and passed five of five alone, so it is environmental.

PR: #3364
Comment by: @integry (ID: 6482695676)
Model: Claude Fable 5.1
@integry

integry commented Oct 29, 2026

Copy link
Copy Markdown
Owner Author

/review

@propr-dev

propr-dev Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

✅ AI Code Review Complete requested by @integry

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

🔍 AI Code Review — claude:claude-opus-5-5

Overall Evaluation

This PR fixes the two failure modes behind the five-hour worker freeze.

  1. Storage lifecycle gate (packages/core/src/storage/lifecycle.ts). The gate now records its holder, and a waiter reclaims it once that holder is provably gone. A gate with no holder record is reclaimed after a bounded grace period. Every wait is now logged.
  2. Recovery runner (src/workerTaskStateRecovery.ts). The runner no longer starts a new copy of a step whose previous run is still pending.

I traced the gate protocol across these interleavings:

  • normal acquire;
  • release;
  • release racing a reclaim;
  • two reclaimers of a dead-holder gate;
  • two reclaimers of an ownerless gate;
  • a stale ownerless reclaim racing a fresh acquirer's empty mkdir;
  • a reclaim racing a gate that disappeared.

The design closes each of these windows:

  • Acquisition always goes through rename(prepared, gate), which replaces only an empty directory.
  • A probed record is removed by its token-specific name, so only one reclaimer's unlink can succeed.
  • The record is written before the directory is published.
  • The unlink in a reclaim updates the gate's mtime, so a second reclaimer cannot take the emptied directory as an aged ownerless gate.

Release is fenced by token, and a successor's rename onto a briefly empty gate is tolerated (ENOTEMPTY is ignored). The recovery-step guard registers the in-flight promise only after runWithinDeadline has checked the deadline and the abort signal. It handles late rejections through pending.then(forget, forget). All current-head checks pass.

The PR is ready to merge. I found no verified blockers.

✅ Publish-by-rename removes the record/directory window — prepareGate builds gate-<token> with its owner-<token> record already inside, and takeGate publishes it with rename. A stale takeover therefore cannot consume a directory where a holder has already published its record. A plain mkdir placeholder that is replaced makes its creator fail with ENOTEMPTY and wait, which is the correct outcome.

✅ Token-named compare-and-remove — reclaimAbandonedGate and releaseGate both unlink the exact record they inspected or own. A late probe (docker inspect on a loaded host) or a holder that was wrongly judged dead cannot remove a successor's gate. The real-filesystem tests in storageLifecycleGate.test.ts exercise this with injected stalls on stat and mkdir.

✅ Recovery steps cannot pile up and are not launched out of budget — runStep keys in-flight work by step name and starts it inside the guarded thunk. Three tests cover the behaviour: a pending step that resolves, one that rejects late, and a pass that has exhausted its budget.

Merge blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S9: 🟢 Sweep leftover gate-<token> directories

Every exclusive() call creates gate-<token> in the lifecycle root before it starts waiting. A process killed while waiting leaves that directory behind; during the incident this would have been every blocked admission across a restart. Today nothing removes these directories, and the docs only mention removing them by hand. A waiter could already sweep gate-* siblings whose owner-* record names a holder that claimOwnerGone proves dead, using the same probe. This is optional because the leftovers are inert: nothing enumerates them as gates.

S10: 🟢 Bound docker inspect fan-out while a long holder runs

While a daemon cleanup or sweep holds the gate for its whole operation, each waiter calls claimOwnerGone every 5 s. These waiters include job admissions, reader-claim releases and queue producers via protectStorageQueue, and on a container host each call spawns docker inspect with a 10 s timeout. Some ways to reduce this:

  • cache one probe result per holder token for the probe interval within the process;
  • back off the interval while the same live holder persists.

S11: 🟢 Default wait warning also covers time inside the gate

withWaitWarning wraps the whole exclusive(...) call. That includes admit(), which can itself probe several reader claims through docker inspect. A slow admission therefore logs Still waiting for the storage lifecycle gate ... (held by <own host> pid <own pid>) even though this process already holds the gate. To make the message accurate, either stop the interval once the gate is taken, or detect that the holder is the current owner.

S12: 🟢 Abandoned steps still run outside the lease

A step that runStep has abandoned keeps running after the pass releases the Redis lease. Another worker that then acquires the lease can start the same step concurrently, because stepsInFlight is per-process. This is pre-existing and the PR does not worsen it, but the new skip warning could note it. Alternatively, the lease could be kept, or renewed, while a tracked step is still pending.

S13: 🟢 Tight timing in the new recovery tests

The new workerTaskStateRecovery tests use timeBudgetMs: 60, which leaves the steps about 54 ms after leaseReleaseBudgetMs. They also rely on a single setImmediate after resolving the stuck step. Both pass in CI, but on a loaded shard the startup pass could time out in reconciliation instead of in the goal step. Polling until stepsInFlight has drained, through an observable side effect, would make them more robust, consistent with this repository's contention-sensitive test history.

Score

The gate protocol holds up under every interleaving I traced, both incident causes are addressed with focused real-filesystem and unit tests, and all checks are green; the remaining items are optional hardening.

Score: 8/10


🤖 Review Details

  • Model: Claude Opus 5.5
  • Time: 1m 15s
  • Tokens: 80,864 (74,008 in / 6,856 out)
  • Cost: $0.51

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S9 S10 S11 S12 S13

🤖 Review by ProPR

@integry
integry merged commit 4476e5b into main Oct 29, 2026
42 checks passed
propr-dev Bot pushed a commit that referenced this pull request Oct 29, 2026
…) into the branch and added both fixes to the 0.9.0 release notes. One catch: this is not a real merge commit, because `git merge` can't run in this workspace. Git's metadata folder is read-only here, so it failed trying to write `ORIG_HEAD`. Instead I made the working tree match what the merge would produce:

I brought `main` (`2727fe3ad`, which includes #3364 and #3366) into the branch and added both fixes to the 0.9.0 release notes. One catch: this is not a real merge commit, because `git merge` can't run in this workspace. Git's metadata folder is read-only here, so it failed trying to write `ORIG_HEAD`. Instead I made the working tree match what the merge would produce:

- **Files only `main` changed** (8 of them, from the two PRs) were copied over from `origin/main` unchanged.
- **`src/jobs/processGoalJob.ts`** was changed on both sides, so I combined it with a three-way merge. There were no conflicts, and the only difference from `main` is this branch's earlier agent-failure-reason change.

When ProPR commits this, the commit will have one parent rather than two, so GitHub may still show the branch as behind `main`. The contents will merge cleanly either way. If you need a true merge commit, use ProPR's merge-from-main flow.

**Release notes:**
- **`CHANGELOG.md`**: no existing bullet covered goal recovery, and **Worker restarts** under 0.9.0 **Fixed** already covers worker recovery and storage claims. So I added both fixes to that bullet rather than starting new ones.
- **`docs/release-0.9.0-audit.md`**: I added a "Later merges" note to the end of the 2026-10-29 section. It lists #3364 and #3366 and says the release scope now runs through `2727fe3ad`.

Nothing else changed. There's nothing visual here, so I made no previews.

**Checks:**
- `EXPECTED_VERSION=0.9.0 RELEASE_TAG=v0.9.0 RELEASE_CANDIDATE=true npm run release:verify`: passed ("Release metadata is consistent for v0.9.0").
- `node --test test/releaseValidation.test.mjs`: all 15 tests passed.
- `git diff --check` is clean, and eslint with zero warnings allowed passes on the merged `processGoalJob.ts`.
- `test/processGoalJob.test.ts` (18), `test/goalContinuation.test.ts` (46) and `test/workerTaskStateRecovery.test.ts` (11) all pass when run one file at a time. Running all three in a single `tsx --test` command gave 46 failures. I put that down to the files clashing with each other rather than the merge, since every file passes alone, but I didn't confirm it.

I didn't merge, tag, publish or deploy anything.

PR: #3368
Comment by: @integry (ID: 6484905795)
Model: Claude Opus 5.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants