Repository navigation
feat(spec-loop): single-flight lock so a second loop exits 0 as already_running - #1929
Conversation
potiuk
left a comment
There was a problem hiding this comment.
A single-flight lock is the right guard for scheduled loops, and exiting 0 on already_running is the right call for cron and CI. Two gaps let two loops run over one tree anyway: concurrent takeovers of a stale lock both succeed, and a SIGTERM releases the lock while the backgrounded agent is still working.
At most one loop runs per checkout (tools/spec-loop/lib.sh:111)
At most one loop runs per checkout: a second start while a lock is held prints
already_runningand exits 0, so a scheduler records a skipped run rather than a failure.
rm -rf "$lockdir"
continue
Two starters that find the same stale lock both read the dead pid. A removes the lock, mkdirs it and writes its owner; B then runs rm -rf "$lockdir" on the same path, deleting A's live lock, and acquires too. Both loops run against one working tree. Two cron starts after a crashed run is exactly when this happens.
Reproduced against this lib.sh: interleaving two spec_loop_lock_acquire calls over a lock owned by a dead pid, both return 0, and only B's pid is left in owner.
(#1931 takes over a stale lock the same way in skill-lock, so one fix shape would serve both.)
Suggested fix: Take the stale lock over by mv "$lockdir" "$lockdir.stale.$$": only one contender's rename succeeds. Then check that the moved owner still names the dead pid before deleting it; add the interleaved case to test_runner_fixtures.sh.
Flagged by both the primary and adversarial reviewers.
The lock is released on every exit path (tools/spec-loop/loop.sh:96)
The lock is released on every exit path (normal end,
STOP, error break, Ctrl+C); an exit before acquisition (--help, a bad argument, a missing agent CLI) never releases it.
trap '[ "$LOCK_HELD" = true ] && spec_loop_lock_release "$LOCK_DIR"' EXIT
The agent runs in the background (… &, SPEC_LOOP_AGENT_PID=$! in lib.sh), and the INT/TERM trap just exit 0s. A SIGTERM to the runner, which is what a scheduler timeout or a plain kill <pid> sends, interrupts the wait, fires the EXIT trap and releases the lock, while the agent keeps editing the checkout. The next scheduled start then finds the lock free and runs a second loop over that tree. Releasing the lock on exit is right; releasing it while the work it guards is still running is not.
Suggested fix: In the INT/TERM trap, signal $AGENT_PID (and the spinner), wait for it, and only then exit and release; or leave the lock held when the agent is still alive.
Flagged by both the primary and adversarial reviewers.
Smaller observations
- See inline comments on
tools/spec-loop/lib.sh:114.
This review was drafted by an AI-assisted tool and
confirmed by an Apache Magpie maintainer. After you've
addressed the points above and pushed an update, an Apache Magpie
maintainer — a real person — will take the next look
at the PR. The findings cite the project's review criteria;
if you think one of them is mis-applied, please reply on the
PR and a maintainer will weigh in.More on how Apache Magpie handles maintainer review:
Contributing guide.
c79fc1e to
6a9982e
Compare
|
Thanks Jarek. All three fixed: the stale-lock takeover is an atomic rename with an owner check, INT/TERM stop the agent before the lock is released (and keep it if the agent won't stop), and an owner-less lock goes stale after a one-minute grace period. Fixture tests cover each. |
potiuk
left a comment
There was a problem hiding this comment.
Thanks — the atomic takeover and the owner-less grace period fix two of the three earlier points, but the stop path still lets a second loop start over a live agent: the lock kept for a surviving agent names the runner's pid, which exits right after, and the ps-based liveness check reports a live agent as gone wherever ps is unavailable, including the macOS sandbox the loop is meant to run in.
keep the lock while the agent runs (tools/spec-loop/loop.sh:104)
on INT/TERM the runner signals the agent and waits for it, and keeps the lock if the agent is still running.
Keeping the lock here does not protect the surviving agent. The lock's owner names the runner's own $$ (lib.sh:94), and the runner exits 0 right after, so the next start on this host finds kill -0 failing on that pid (lib.sh:137), judges the lock stale and takes it over — a second loop starts over the tree the agent is still editing, which is the case the earlier thread raised.
Run inside the existing sandbox (tools/spec-loop/lib.sh:181)
No new network/filesystem allowances. Run inside the existing sandbox.
An empty ps output is read as "gone". ps is denied inside the macOS Claude Code sandbox (operation not permitted: ps; the new test_stop_agent_helper fails there) and missing on slim Linux images without procps. There spec_loop_stop_agent returns 0 right after sending TERM, without waiting, and the lock is released while the agent may still be running.
Smaller observations
tools/spec-loop/loop.sh:592—AGENT_PIDandSPINNER_PIDkeep their values after both are reaped, so a Ctrl+C between iterations (git checkout, PR-context collection) makeson_stopsignal pids that may by then belong to unrelated processes.- See inline comments on
tools/spec-loop/tests/test_runner_fixtures.sh:373,tools/spec-loop/lib.sh:113.
This review was drafted by an AI-assisted tool and
confirmed by an Apache Magpie maintainer. After you've
addressed the points above and pushed an update, an Apache Magpie
maintainer — a real person — will take the next look
at the PR. The findings cite the project's review criteria;
if you think one of them is mis-applied, please reply on the
PR and a maintainer will weigh in.More on how Apache Magpie handles maintainer review:
Contributing guide.
|
A follow-up to my review above: a tooling bug dropped the suggested fix from each inline comment, so here they are.
|
7d5938c to
2e231ef
Compare
|
I rebased this onto |
potiuk
left a comment
There was a problem hiding this comment.
A gentle nudge — the round-two points (the kept lock is still taken over as stale, empty ps output still reads as gone, the stale PIDs in on_stop, the macOS path in the test and the put-back window) are still open, and the owner-less-lock thread is fixed so I'm resolving it; a second-read pass by other models added two related lock points, inline below.
GitHub has not yet computed whether this branch merges cleanly with its base.
Takeover can briefly remove a live lock (tools/spec-loop/lib.sh:128)
mv "$lockdir" "$tomb" 2>/dev/null || return 1 # ←
now="$(cat "$tomb/owner" 2>/dev/null)"
The other side of the open put-back thread: if starter A takes over a stale lock and creates a fresh one after starter B read the old owner, B's unconditional mv moves A's live lock into B's tombstone. Until B notices and puts it back, the lock path is free, so a third starter C can mkdir it; B then sees the path exists, skips the put-back and rm -rfs the tombstone, deleting A's lock while A and C both run. Avoid moving a lock you have not proven stale: e.g. take over by renaming only a lock whose owner content you compare first under a separate takeover mutex (mkdir "$lockdir.takeover"), or have each owner re-check that its owner file is still in place before every iteration.
Flagged by codex (adversarial review); cross-checked.
Smaller observations
- See inline comments on
tools/spec-loop/lib.sh:213.
This review was drafted by an AI-assisted tool and
confirmed by an Apache Magpie maintainer. The findings
below are observations, not blockers; an Apache Magpie
maintainer — a real person — will take the next look at the
PR. If you think a finding is mis-applied, please reply on
the PR and a maintainer will weigh in.More on how Apache Magpie handles maintainer review:
Contributing guide.
…dy_running Two loops in one checkout fight over the working tree: each iteration checks out the base and the agent carves a branch, so the second run pulls files out from under the first. Started from cron or CI an overlap is routine, since a slow iteration outlives the schedule interval. - loop.sh takes a lock (tools/spec-loop/.lock/, atomic mkdir, gitignored) after argument and agent validation and before the first iteration, and releases it on every exit path. A second start prints one `already_running: …` line naming the holder and exits 0, so a scheduler records a skipped run rather than a failure, and never launches an agent or touches the holder's lock. - A lock whose owning pid is dead on this host is stale and is taken over; a lock from another host is respected. An exit before acquisition (--help, bad argument, missing CLI) never removes someone else's lock. - SPEC_LOOP_LOCK relocates the lock (to serialise several checkouts) or, set to `off`, disables it for a run known to be safe to overlap. - lib.sh carries the deterministic helpers; the fixture script covers acquire/contend/release/stale/foreign-host and an end-to-end run of loop.sh against a held lock, with the lock off, and a clean release. - README, AGENTS.md, the spec-loop-runner spec and the spec-driven development page document the behaviour. Generated-by: Claude Code (Fable 5.1)
…gent runs Review fixes for the single-flight lock: - Two starters that found the same stale lock could both acquire it: A removed the lock and re-created it, then B's rm -rf deleted A's live lock. A takeover now renames the stale lock to a unique tombstone (only one rename succeeds) and deletes it only if it still holds the owner judged stale; otherwise the live lock is put back. - SIGTERM fired the EXIT trap and released the lock while the backgrounded agent kept editing the tree. INT/TERM now stop the agent first and keep the lock if it will not exit. - A runner killed between mkdir and the owner write left a lock nobody could clear. An owner-less lock older than SPEC_LOOP_LOCK_GRACE_MIN minutes (default 1) is now stale. Fixture tests cover the interleaved takeover, the owner-less lock and stopping the agent. Generated-by: Claude Code (Opus 5.5)
… and stuck agents Addresses the open review points on the lock: - The lock is a symbolic link whose target is the owner line, so `ln -s` creates the lock and its owner in one atomic step. There is no longer an owner-less window, so the grace period (and the double acquire it allowed) is gone. - A background heartbeat refreshes the link's mtime. A lock is stale when its pid is gone on this host, or when its heartbeat is older than SPEC_LOOP_LOCK_STALE_MIN (default 10) on any host, so a crashed container or a reused pid no longer makes every later start exit 0. A pid of another user (EPERM) counts as alive. - Takeovers are serialised by a `<lock>.takeover` link: the taker re-reads the owner and removes the lock only if it still names the stale owner. No rename-and-put-back, so no nested lock and no live lock removed. - When the agent will not stop on Ctrl+C / TERM, the lock is handed to the agent's pid and the heartbeat keeps it fresh, so the next start is refused until the agent exits. - Empty `ps` output no longer reads as "gone". - A stopped run exits 130 / 143 instead of 0. - AGENT_PID / SPINNER_PID are cleared after the waits. - The end-to-end test resolves $TMPDIR with `pwd -P` (macOS /private). - New fixtures for each case, including a TERM end-to-end run against an agent that ignores TERM. Docs and spec updated; the remaining limits (only the agent pid is signalled, a suspended live holder) are listed under Known gaps. Generated-by: Claude Opus 5
2e231ef to
aa69451
Compare
potiuk
left a comment
There was a problem hiding this comment.
Thanks Justin. To get this in, I rebased it on main and pushed one maintainer commit (aa69451) on top that addresses the open review points on the lock:
- Atomic owner (
lib.sh): the lock is now a symbolic link whose target is the owner line, soln -screates the lock and its owner in one step. The owner-less window and its grace period are gone, which also closes the double acquire on that path. - Heartbeat (
lib.sh,loop.sh): a background heartbeat refreshes the lock; a lock is stale when its pid is gone on this host, or when its heartbeat is older thanSPEC_LOOP_LOCK_STALE_MIN(default 10) on any host. A crashed container or a reused pid no longer makes every later start exit 0, and a pid owned by another user (EPERM) counts as alive. - Takeover (
lib.sh): serialised by a<lock>.takeoverlink; the taker re-reads the owner and removes the lock only if it still names the stale owner. No rename-and-put-back, so no nested lock and no live lock removed. - Stuck agent (
loop.sh): when the agent will not stop, the lock is handed to the agent's pid and kept fresh until it exits, so the next start is refused meanwhile. - Smaller points: empty
psoutput no longer reads as "gone"; a stopped run exits 130 / 143 instead of 0;AGENT_PID/SPINNER_PIDare cleared after the waits; the e2e test resolves$TMPDIRwithpwd -P. - Tests and docs: fixtures for each case, including a TERM end-to-end run against an agent that ignores TERM; README, spec and docs updated. Signalling only the agent's own pid (wrappers must
exec) and a suspended live holder are recorded under Known gaps.
Please shout if any of this does not match what you intended.
This review was drafted by an AI-assisted tool and
confirmed by an Apache Magpie maintainer. The maintainer
approving this PR has read the findings and signed off. If
something feels off, please reply on the PR and a maintainer
will follow up.More on how Apache Magpie handles maintainer review:
Contributing guide.
Summary
loop.shnow takes a single-flight lock (tools/spec-loop/.lock/, atomicmkdir, gitignored) before its first iteration and releases it on every exit path. A second start prints onealready_running: …line and exits 0, so a scheduler records a skipped run rather than a failure, and never launches an agent.SPEC_LOOP_LOCK=offdisables the lock for a run known to be safe to overlap; a shared path serialises several checkouts.Type of change
prek, workflows, validators)docs/,README.md,CONTRIBUTING.md)tools/spec-looprunner (Bash) and its specTest plan
bash tools/spec-loop/tests/test_runner_fixtures.shpasses, including two new tests: lock helpers (acquire, contend, release, non-owner release, stale takeover, foreign host) and an end-to-end run ofloop.shagainst a held lock (exit 0,already_running, agent not launched, holder's lock intact), with a bad argument (exit 1, lock untouched), withSPEC_LOOP_LOCK=off(agent runs), and a normal run (lock released on exit)bash -nonloop.sh,lib.shand the test scriptshellcheckreports the same three findings as onmain; none introducedprek run --files <changed files>passes (spec-validate,check-doc-sync, markdownlint, typos, lychee)prek run --all-files(not run in full in the authoring sandbox)RFC-AI-0004 compliance
Linked issues
None.
Notes for reviewers (optional)
tools/spec-loop/.lock/rather than.git/, so the runner never writes into git's own directory; it is gitignored and survives the base checkout because it is untracked.already_runningis deliberate and documented inloop.sh, the README,AGENTS.mdand the spec; it is what keeps a cron or CI overlap from reading as a failed run.Generated-by:trailer.