Skip to content

feat(spec-loop): single-flight lock so a second loop exits 0 as already_running - #1929

Merged
potiuk merged 3 commits into
mainfrom
spec-loop-single-flight-lock
Nov 10, 2026
Merged

potiuk merged 3 commits into
mainfrom
spec-loop-single-flight-lock

Conversation

@justinmclean

Copy link
Copy Markdown
Member

Summary

  • Two spec-loops in one checkout pull the working tree out from under each other (each iteration checks out the base and carves a branch). Started from cron or CI an overlap is routine because a slow iteration outlives the schedule interval.
  • loop.sh now takes a single-flight lock (tools/spec-loop/.lock/, atomic mkdir, gitignored) before its first iteration and releases it on every exit path. A second start prints one already_running: … line and exits 0, so a scheduler records a skipped run rather than a failure, and never launches an agent.
  • Stale locks (dead pid, same host) are taken over; locks from another host are respected. SPEC_LOOP_LOCK=off disables the lock for a run known to be safe to overlap; a shared path serialises several checkouts.

Type of change

  • CI / dev loop (prek, workflows, validators)
  • Documentation (docs/, README.md, CONTRIBUTING.md)
  • Other: tools/spec-loop runner (Bash) and its spec

Test plan

  • bash tools/spec-loop/tests/test_runner_fixtures.sh passes, including two new tests: lock helpers (acquire, contend, release, non-owner release, stale takeover, foreign host) and an end-to-end run of loop.sh against a held lock (exit 0, already_running, agent not launched, holder's lock intact), with a bad argument (exit 1, lock untouched), with SPEC_LOOP_LOCK=off (agent runs), and a normal run (lock released on exit)
  • bash -n on loop.sh, lib.sh and the test script
  • shellcheck reports the same three findings as on main; none introduced
  • prek 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

  • Sandbox — no new host access; the lock lives inside the checkout
  • Write-access discipline — the loop still never pushes or opens a PR

Linked issues

None.

Notes for reviewers (optional)

  • Lock location: 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.
  • Exit 0 on already_running is deliberate and documented in loop.sh, the README, AGENTS.md and the spec; it is what keeps a cron or CI overlap from reading as a failed run.
  • Generative-AI disclosure: authored with Claude Code (Fable 5.1) under maintainer direction; commits carry the Generated-by: trailer.

@github-actions github-actions Bot added family:tools tools/* family:docs Docs, MISSION.md, READMEs family:ci .github workflows, prek, validators substrate:framework-dev Tool substrate: build / validate / eval the framework itself labels Oct 31, 2026

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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_running and 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.

Comment thread tools/spec-loop/lib.sh Resolved
Comment thread tools/spec-loop/loop.sh Resolved
Comment thread tools/spec-loop/lib.sh Resolved
@justinmclean

Copy link
Copy Markdown
Member Author

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 potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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_PID and SPINNER_PID keep their values after both are reaped, so a Ctrl+C between iterations (git checkout, PR-context collection) makes on_stop signal 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.

Comment thread tools/spec-loop/loop.sh Resolved
Comment thread tools/spec-loop/lib.sh Resolved
Comment thread tools/spec-loop/lib.sh Resolved
@potiuk

potiuk commented Nov 1, 2026

Copy link
Copy Markdown
Member

A follow-up to my review above: a tooling bug dropped the suggested fix from each inline comment, so here they are.

  • tools/spec-loop/loop.sh:104 (lock kept for a surviving agent) — before exiting, rewrite the owner atomically (temp file, then mv) to name the agent's pid, or record it in $LOCK_DIR/agent and treat the lock as live while either pid runs. Add a fixture: an agent that ignores TERM, then a second acquire must return 1.
  • tools/spec-loop/lib.sh:181 (empty ps read as "gone") — treat only Z* as gone; when ps fails or prints nothing, fall back to the kill -0 result. Since the agent is the runner's own child, a non-blocking reap is another way to detect the zombie.
  • tools/spec-loop/loop.sh:592 (stale pids in on_stop) — clear both right after the waits: AGENT_PID=""; SPINNER_PID="".
  • tools/spec-loop/tests/test_runner_fixtures.sh:373 (macOS /private path) — local repo; repo="$(cd "$TMPDIR_TEST" && pwd -P)/repo".
  • tools/spec-loop/lib.sh:113 (put-back nests into a fresh lock) — make the put-back fail when the target exists (mv -T on GNU, or a mkdir-guarded put-back), or record the window in the spec's Known gaps.

@potiuk
potiuk force-pushed the spec-loop-single-flight-lock branch from 7d5938c to 2e231ef Compare November 4, 2026 23:39
@potiuk

potiuk commented Nov 4, 2026

Copy link
Copy Markdown
Member

I rebased this onto main and force-pushed, so please pull before pushing again. lib.sh and test_runner_fixtures.sh conflicted with the new update-pathspec code and tests, and I kept both sides. No other changes, and my review comments still stand.

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment thread tools/spec-loop/lib.sh Resolved
Comment thread tools/spec-loop/lib.sh Resolved
claude and others added 3 commits November 10, 2026 01:43
…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
@potiuk
potiuk force-pushed the spec-loop-single-flight-lock branch from 2e231ef to aa69451 Compare November 10, 2026 08:58
@github-actions github-actions Bot added the family:dev Repo dev: .asf.yaml, spec-loop specs, Node manifests, .claude/settings.json label Nov 10, 2026

@potiuk potiuk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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, so ln -s creates 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 than SPEC_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>.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.
  • 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 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 e2e test resolves $TMPDIR with pwd -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.

@potiuk
potiuk merged commit d594f57 into main Nov 10, 2026
9 checks passed
@potiuk
potiuk deleted the spec-loop-single-flight-lock branch November 10, 2026 09:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

family:ci .github workflows, prek, validators family:dev Repo dev: .asf.yaml, spec-loop specs, Node manifests, .claude/settings.json family:docs Docs, MISSION.md, READMEs family:tools tools/* substrate:framework-dev Tool substrate: build / validate / eval the framework itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants