session-runner: two hosts concurrently drain the same ready-for-session ticket — no atomic cross-host claim (a full session wasted per collision) #125

Closed
opened 2026-09-03 17:08:16 +00:00 by matou-build-agent · 2 comments

Symptom

Ticket #123 was drained twice, concurrently, by two different
session-runner hosts:

  • session-runner@elitebook-distributed-server-03 landed 824686b on
    main at 16:51:19 and closed #123 at 16:51:50 (matou-build-agent
    close-report).
  • session-runner@matou-workstation (this session) started its agent
    timeout at ~16:50, independently produced a functionally-equivalent
    commit for the same acceptance criteria, and on git pull --rebase
    discovered the upstream landing — a conflict on the same skeleton section.
    The duplicate was discarded (reset --hard origin/main); nothing double-
    landed. But a full standing session's compute was spent redundantly.

Cause

session-runner.sh picks the first workable ready-for-session ticket and
only THEN claims it with the agent-working label. The per-checkout /
per-slug flocks serialise ticks on one host, but there is no atomic
cross-host claim: two hosts that pick within the same window both see #123
without agent-working, both pick it, and both claim. Classic TOCTOU — the
Forgejo /labels write is not a compare-and-swap, so "skip agent-working"
cannot exclude a peer that has picked-but-not-yet-claimed.

The swarm/triage workers have a claim-comment + agent-working protocol
(claim-lib.sh) with the same fundamental non-atomicity, but the swarm's
/tmp/matou-swarm.lock host-capacity pool bounds how many run at once per
host; the multi-HOST session-runner drainer has no equivalent cross-host
arbiter for the ticket it selects.

Impact

Each collision wastes one full standing session (a headless claude run up to
its timeout, plus the rebase-conflict discard). Harmless to correctness
(the loser discards and never pushes), but pure wasted spend, and it scales
with the number of session-runner hosts draining one repo's queue.

Possible directions (for triage to rule)

  • A best-effort claim-before-work read-back: after PATCHing
    agent-working, re-GET the issue and confirm THIS host's claim marker won
    (a claim comment carrying host=/run=, like the swarm's), else stand
    down — shrinks the window to the round-trip, doesn't close it.
  • A short claim-comment + re-read settle (post claim marker, sleep a
    jittered beat, re-read, lowest-host-id or earliest-timestamp wins) — the
    usual lock-free leader election over a non-atomic store.
  • Accept the race as rare and cheap and just detect + abort early: have
    session-runner re-check agent-working / ticket-state right before the
    expensive agent call and bail if a peer now owns it (turns a full wasted
    session into a cheap early exit).

Found while working #123 (its two-way-door work is already landed at
824686b; this is the coordination follow-up rule 1 asks me to file rather
than chase).

## Symptom Ticket #123 was drained **twice, concurrently**, by two different session-runner hosts: - `session-runner@elitebook-distributed-server-03` landed `824686b` on `main` at **16:51:19** and closed #123 at 16:51:50 (`matou-build-agent` close-report). - `session-runner@matou-workstation` (this session) started its agent `timeout` at ~**16:50**, independently produced a functionally-equivalent commit for the same acceptance criteria, and on `git pull --rebase` discovered the upstream landing — a conflict on the same skeleton section. The duplicate was discarded (`reset --hard origin/main`); nothing double- landed. But a full standing session's compute was spent redundantly. ## Cause `session-runner.sh` picks the first workable `ready-for-session` ticket and only THEN claims it with the `agent-working` label. The per-checkout / per-slug `flock`s serialise ticks **on one host**, but there is no atomic cross-host claim: two hosts that pick within the same window both see #123 without `agent-working`, both pick it, and both claim. Classic TOCTOU — the Forgejo `/labels` write is not a compare-and-swap, so "skip agent-working" cannot exclude a peer that has picked-but-not-yet-claimed. The swarm/triage workers have a claim-comment + `agent-working` protocol (`claim-lib.sh`) with the same fundamental non-atomicity, but the swarm's `/tmp/matou-swarm.lock` host-capacity pool bounds how many run at once per host; the multi-HOST session-runner drainer has no equivalent cross-host arbiter for the *ticket* it selects. ## Impact Each collision wastes one full standing session (a headless claude run up to its `timeout`, plus the rebase-conflict discard). Harmless to correctness (the loser discards and never pushes), but pure wasted spend, and it scales with the number of session-runner hosts draining one repo's queue. ## Possible directions (for triage to rule) - A best-effort **claim-before-work** read-back: after PATCHing `agent-working`, re-GET the issue and confirm THIS host's claim marker won (a claim comment carrying `host=`/`run=`, like the swarm's), else stand down — shrinks the window to the round-trip, doesn't close it. - A short **claim-comment + re-read settle** (post claim marker, sleep a jittered beat, re-read, lowest-host-id or earliest-timestamp wins) — the usual lock-free leader election over a non-atomic store. - Accept the race as rare and cheap and just **detect + abort early**: have session-runner re-check `agent-working` / ticket-state right before the expensive agent call and bail if a peer now owns it (turns a full wasted session into a cheap early exit). Found while working #123 (its two-way-door work is already landed at 824686b; this is the coordination follow-up rule 1 asks me to file rather than chase).
Author
Member

This was generated by AI during triage.

Ruled by agent under ADR 0174 — veto anytime

Ruling: category bug, state ready-for-agent. Fix direction ruled below; the swarm may claim it.

Why this is a two-way door. Picking a coordination strategy for the cross-host claim, and shipping it, is fully revertible by a later commit/label change and provable by an existing offline test seam (tests/session-runner-test.sh shims curl and claude hermetically — no network, no docker). It touches none of the one-way-door residues: no personal credentials, no security-posture widening, no member-facing trust accept, no data destruction, no non-routine spend. So it is ruled by this session rather than parked for a human. Veto is asynchronous — relabel anytime.

Why ready-for-agent, not ready-for-session. This edits the root session-runner.sh + its offline test. The ready-for-session set for this repo (docs/agents/triage-labels.md) is the closed enumeration {prompt skeletons, the vendored self-copy under .sandcastle/, .forgejo/}. The root harness lib is none of these — root-lib changes are ordinary factory-core swarm work; the byte-identical copy reaches the running .sandcastle/ only at a human pin-bump (GOTCHAS 4), so no protected-path edit happens inside the sandbox.

What proves it. A new group in tests/session-runner-test.sh that models a two-host collision (a peer's claim already present in the fixture when this host reaches the pre-agent-call arbitration) and asserts the loser stands down before the claude call — i.e. claude.calls stays empty for the losing host, with no fail-<n> counter written (a lost race is not a failed attempt).

Verification of the claim

Confirmed against the code (read-only):

  • The reporter's timeline holds: 824686b landed at 16:51:19 by session-runner@elitebook-distributed-server-03, exactly as described.
  • session-runner.sh claims by a bare additive POST /issues/<n>/labels of agent-working and immediately sets claimed=1 — with no read-back between the queue read that proved the ticket free and the label write, and no re-check before the expensive claude call. POST /labels is additive (no conflict on a duplicate), so two hosts that pick in the same window both "succeed." TOCTOU confirmed.
  • session-runner.sh does not source claim-lib.sh. The swarm workers' claim-lib.sh already implements the exact leader-election the reporter's direction #2 describes: a swarm-claim host=<h> run=<n> claim comment (claim_post) plus claim_won, which re-reads all claim comments and wins only if this host's comment id is the lowest whose run is still live. The mechanism to fix this already exists in the repo; the session-runner just doesn't use it.

Agent Brief

Category: bug
Summary: Give session-runner.sh a cross-host claim arbitration so two hosts draining the same ready-for-session queue don't both spend a full session on one ticket.

Current behavior:
session-runner.sh picks the first workable ready-for-session ticket (filtering out agent-working), then claims it with a single additive POST of the agent-working label, then runs a full headless claude session. There is no arbitration between the queue read and the claim, and no re-check before the agent call. Two hosts picking within the same window both observe the ticket unclaimed, both apply the label, and both run a full session; the loser only discovers the collision after its session, on git pull --rebase (then discards via reset --hard). Correctness is safe (the loser never pushes) but a full standing session's compute is wasted per collision, scaling with the number of draining hosts.

Desired behavior:
When two (or more) hosts pick the same ticket, exactly one proceeds to the expensive claude call; every other host stands down cheaply before that call — releasing its agent-working claim and exiting a quiet tick. A lost race is not a failed attempt: no fail-<n> counter is written, no escalation, no notification noise. The winner runs exactly as today.

Ruled fix direction (reporter's #2 + #3, using the existing seam):
Adopt the claim-comment + read-back leader-election that claim-lib.sh already provides, so the session-runner and the swarm speak one claim language rather than inventing a second protocol:

  • After marking agent-working, post a claim marker (claim_post-style swarm-claim host=<h> run=<n> comment).
  • Immediately before the expensive claude call, re-read and arbitrate (claim_won-style: lowest live claim id wins). If this host did not win, release and stand down (quiet tick).
    This shrinks the race window to a single round-trip and converts a full wasted session into a cheap early exit. Note this does not achieve a distributed compare-and-swap — that is not available over Forgejo labels, and the swarm's own protocol has the same residual non-atomicity; matching the swarm's bound is the target, not perfection.

Key interfaces:

  • claim-lib.sh — claim_post (posts the swarm-claim host= run= comment), claim_won <issue> <my_comment_id> <alive_runs_json> (lowest-live-comment-id arbitration), claim_release. Source and reuse these rather than duplicating them.
  • Known design point to resolve, not gold-plate: claim_won's liveness set comes from claim_alive_runs, which enumerates in-progress swarm run numbers. Session-runner runs are a different population (recorded in swarm.db as sr_run_db_id). Decide how the losing host's arbitration treats a peer session-runner claim whose run is not in the swarm alive-set — e.g. supply an alive-runs set that includes live session-runner runs, or a timestamp/host-id tiebreak that does not depend on the swarm run population. Whatever is chosen, it must make the collision test below deterministic.
  • The pre-agent-call arbitration must sit strictly before the timeout ... claude ... invocation and after the checkout prep is skippable (don't clone/reset if you're about to stand down, if cheap to reorder).

Acceptance criteria:

  • A new group in tests/session-runner-test.sh models a two-host collision: the ticket already carries a peer's swarm-claim marker (lower/winning id) in the fixture when this host reaches arbitration. The test asserts claude.calls is empty for the losing host (it never ran a session).
  • The losing host releases its own agent-working claim on stand-down (a DELETE .../labels/<agent-working-id> appears in curl.log) and writes no fail-<n> counter and no escalation.
  • The winning host (its own claim is lowest/live) proceeds to exactly one claude call, unchanged from today.
  • Existing group 2's invariant still holds: the agent-working claim is POSTed before the session runs.
  • for t in tests/*.sh onboarding/tests/*.sh; do case "$t" in *fakebin*|*fixtures*) continue;; esac; bash "$t" || echo "FAIL: $t"; done is green (CLAUDE.md's offline suite; lib change + its test in the same commit).
  • STATUS.md updated in the same commit (new coordination gate on the session-runner drainer).

Out of scope:

  • A true distributed compare-and-swap / fully closing the TOCTOU — unavailable over Forgejo labels; the swarm's own protocol has the same residual, and matching that bound is the target.
  • Changing the swarm workers' claim-lib.sh protocol or claim-next-task.sh.
  • The <!-- session-host: --> affinity marker (a separate mechanism; it steers, it does not arbitrate).
  • Touching the .sandcastle/ self-copy — the root change reaches it only at a human pin-bump (GOTCHAS 4).
> *This was generated by AI during triage.* ## Ruled by agent under ADR 0174 — veto anytime **Ruling:** category **bug**, state **ready-for-agent**. Fix direction ruled below; the swarm may claim it. **Why this is a two-way door.** Picking a coordination strategy for the cross-host claim, and shipping it, is fully revertible by a later commit/label change and provable by an existing offline test seam (`tests/session-runner-test.sh` shims `curl` and `claude` hermetically — no network, no docker). It touches none of the one-way-door residues: no personal credentials, no security-posture widening, no member-facing trust accept, no data destruction, no non-routine spend. So it is ruled by this session rather than parked for a human. Veto is asynchronous — relabel anytime. **Why `ready-for-agent`, not `ready-for-session`.** This edits the **root** `session-runner.sh` + its offline test. The `ready-for-session` set for this repo (`docs/agents/triage-labels.md`) is the *closed* enumeration {prompt skeletons, the vendored self-copy under `.sandcastle/`, `.forgejo/`}. The root harness lib is none of these — root-lib changes are ordinary factory-core swarm work; the byte-identical copy reaches the running `.sandcastle/` only at a human pin-bump (GOTCHAS 4), so no protected-path edit happens inside the sandbox. **What proves it.** A new group in `tests/session-runner-test.sh` that models a two-host collision (a peer's claim already present in the fixture when this host reaches the pre-agent-call arbitration) and asserts the loser stands down **before** the `claude` call — i.e. `claude.calls` stays empty for the losing host, with no `fail-<n>` counter written (a lost race is not a failed attempt). ## Verification of the claim Confirmed against the code (read-only): - The reporter's timeline holds: `824686b` landed at **16:51:19** by `session-runner@elitebook-distributed-server-03`, exactly as described. - `session-runner.sh` claims by a bare additive `POST /issues/<n>/labels` of `agent-working` and immediately sets `claimed=1` — with **no read-back** between the queue read that proved the ticket free and the label write, and **no re-check** before the expensive `claude` call. `POST /labels` is additive (no conflict on a duplicate), so two hosts that pick in the same window both "succeed." TOCTOU confirmed. - `session-runner.sh` does **not** source `claim-lib.sh`. The swarm workers' `claim-lib.sh` already implements the exact leader-election the reporter's direction #2 describes: a `swarm-claim host=<h> run=<n>` claim comment (`claim_post`) plus `claim_won`, which re-reads all claim comments and wins only if this host's comment id is the lowest whose run is still live. The mechanism to fix this already exists in the repo; the session-runner just doesn't use it. ## Agent Brief **Category:** bug **Summary:** Give `session-runner.sh` a cross-host claim arbitration so two hosts draining the same `ready-for-session` queue don't both spend a full session on one ticket. **Current behavior:** `session-runner.sh` picks the first workable `ready-for-session` ticket (filtering out `agent-working`), then claims it with a single additive `POST` of the `agent-working` label, then runs a full headless `claude` session. There is no arbitration between the queue read and the claim, and no re-check before the agent call. Two hosts picking within the same window both observe the ticket unclaimed, both apply the label, and both run a full session; the loser only discovers the collision after its session, on `git pull --rebase` (then discards via `reset --hard`). Correctness is safe (the loser never pushes) but a full standing session's compute is wasted per collision, scaling with the number of draining hosts. **Desired behavior:** When two (or more) hosts pick the same ticket, exactly one proceeds to the expensive `claude` call; every other host **stands down cheaply before that call** — releasing its `agent-working` claim and exiting a quiet tick. A lost race is **not** a failed attempt: no `fail-<n>` counter is written, no escalation, no notification noise. The winner runs exactly as today. **Ruled fix direction (reporter's #2 + #3, using the existing seam):** Adopt the claim-comment + read-back leader-election that `claim-lib.sh` already provides, so the session-runner and the swarm speak one claim language rather than inventing a second protocol: - After marking `agent-working`, post a claim marker (`claim_post`-style `swarm-claim host=<h> run=<n>` comment). - **Immediately before** the expensive `claude` call, re-read and arbitrate (`claim_won`-style: lowest live claim id wins). If this host did not win, `release` and stand down (quiet tick). This shrinks the race window to a single round-trip and converts a full wasted session into a cheap early exit. Note this does not achieve a distributed compare-and-swap — that is not available over Forgejo labels, and the swarm's own protocol has the same residual non-atomicity; matching the swarm's bound is the target, not perfection. **Key interfaces:** - `claim-lib.sh` — `claim_post` (posts the `swarm-claim host= run=` comment), `claim_won <issue> <my_comment_id> <alive_runs_json>` (lowest-live-comment-id arbitration), `claim_release`. Source and reuse these rather than duplicating them. - **Known design point to resolve, not gold-plate:** `claim_won`'s liveness set comes from `claim_alive_runs`, which enumerates in-progress **swarm** run numbers. Session-runner runs are a different population (recorded in `swarm.db` as `sr_run_db_id`). Decide how the losing host's arbitration treats a peer **session-runner** claim whose run is not in the swarm alive-set — e.g. supply an alive-runs set that includes live session-runner runs, or a timestamp/host-id tiebreak that does not depend on the swarm run population. Whatever is chosen, it must make the collision test below deterministic. - The pre-agent-call arbitration must sit strictly before the `timeout ... claude ...` invocation and after the checkout prep is skippable (don't clone/reset if you're about to stand down, if cheap to reorder). **Acceptance criteria:** - [ ] A new group in `tests/session-runner-test.sh` models a two-host collision: the ticket already carries a peer's `swarm-claim` marker (lower/winning id) in the fixture when this host reaches arbitration. The test asserts `claude.calls` is **empty** for the losing host (it never ran a session). - [ ] The losing host releases its own `agent-working` claim on stand-down (a `DELETE .../labels/<agent-working-id>` appears in `curl.log`) and writes **no** `fail-<n>` counter and no escalation. - [ ] The winning host (its own claim is lowest/live) proceeds to exactly one `claude` call, unchanged from today. - [ ] Existing group 2's invariant still holds: the `agent-working` claim is POSTed before the session runs. - [ ] `for t in tests/*.sh onboarding/tests/*.sh; do case "$t" in *fakebin*|*fixtures*) continue;; esac; bash "$t" || echo "FAIL: $t"; done` is green (CLAUDE.md's offline suite; lib change + its test in the same commit). - [ ] `STATUS.md` updated in the same commit (new coordination gate on the session-runner drainer). **Out of scope:** - A true distributed compare-and-swap / fully closing the TOCTOU — unavailable over Forgejo labels; the swarm's own protocol has the same residual, and matching that bound is the target. - Changing the swarm workers' `claim-lib.sh` protocol or `claim-next-task.sh`. - The `<!-- session-host: -->` affinity marker (a separate mechanism; it steers, it does not arbitrate). - Touching the `.sandcastle/` self-copy — the root change reaches it only at a human pin-bump (GOTCHAS 4).
Author
Member

close-report for #125 — status success

✅ close-report gates passed — every claim verified against main; issue closed.

envelope
{
  "issue": 125,
  "status": "success",
  "commits": [
    "16ef647"
  ],
  "changed_files": [
    "STATUS.md",
    "session-runner.sh",
    "tests/session-runner-test.sh"
  ],
  "tests": [
    {
      "command": "bash tests/session-runner-test.sh",
      "exit_code": 0
    },
    {
      "command": "for t in tests/*.sh onboarding/tests/*.sh; do case \"$t\" in *fakebin*|*fixtures*) continue;; esac; bash \"$t\" || echo FAIL: $t; done",
      "exit_code": 0
    }
  ],
  "criteria": {
    "A new group in tests/session-runner-test.sh models a two-host collision (peer swarm-claim marker with lower/winning id present at arbitration); claude.calls is empty for the losing host": "tests/session-runner-test.sh group 24a — pre-seeds comments-77.json with a peer claim at id 50 and pins .comment-seq so this host's claim gets id 1001; asserts [ -s claude.calls ] fails (no session)",
    "The losing host releases its own agent-working claim on stand-down (DELETE .../labels/<agent-working-id> in curl.log) and writes no fail-<n> counter and no escalation": "group 24a asserts DELETE .../issues/77/labels/103 present, [ -f state/fail-77 ] false, no attempt-77 marker, grep escalat absent, no swarm.db run row; implemented via release_claim on the stand-down path in session-runner.sh",
    "The winning host (its own claim is lowest/live) proceeds to exactly one claude call, unchanged from today": "group 24b — no competing claim; asserts POST .../issues/77/comments (marker posted), 'won the cross-host claim', claude.calls == 1, outcome advanced",
    "Existing group 2's invariant still holds: the agent-working claim is POSTed before the session runs": "group 2 still green (POST .../issues/25/labels asserted before the session); full suite run",
    "The full offline suite is green (lib change + its test in the same commit)": "session-runner-test.sh: 24 groups passed; full loop: only tests/fleet-tui-test.sh fails on a pre-existing environmental gap ('No module named pytest' in fleet-tui/.venv — reproduced on the un-modified tree via git stash; my change touches no fleet-tui file). Its structural checks pass 6/7.",
    "STATUS.md updated in the same commit (new coordination gate on the session-runner drainer)": "STATUS.md header line, Host-state row (#125 entry), and Milestone log entry all in commit 16ef647"
  },
  "summary": "session-runner.sh now runs the swarm's claim-lib leader election between the agent-working claim and the expensive clone/session, so two hosts draining one ready-for-session queue arbitrate lowest-comment-id-wins and the loser stands down cheaply without a wasted session.",
  "blockers": []
}
**close-report** for #125 — status `success` :white_check_mark: **close-report gates passed** — every claim verified against main; issue closed. <details><summary>envelope</summary> ```json { "issue": 125, "status": "success", "commits": [ "16ef647" ], "changed_files": [ "STATUS.md", "session-runner.sh", "tests/session-runner-test.sh" ], "tests": [ { "command": "bash tests/session-runner-test.sh", "exit_code": 0 }, { "command": "for t in tests/*.sh onboarding/tests/*.sh; do case \"$t\" in *fakebin*|*fixtures*) continue;; esac; bash \"$t\" || echo FAIL: $t; done", "exit_code": 0 } ], "criteria": { "A new group in tests/session-runner-test.sh models a two-host collision (peer swarm-claim marker with lower/winning id present at arbitration); claude.calls is empty for the losing host": "tests/session-runner-test.sh group 24a — pre-seeds comments-77.json with a peer claim at id 50 and pins .comment-seq so this host's claim gets id 1001; asserts [ -s claude.calls ] fails (no session)", "The losing host releases its own agent-working claim on stand-down (DELETE .../labels/<agent-working-id> in curl.log) and writes no fail-<n> counter and no escalation": "group 24a asserts DELETE .../issues/77/labels/103 present, [ -f state/fail-77 ] false, no attempt-77 marker, grep escalat absent, no swarm.db run row; implemented via release_claim on the stand-down path in session-runner.sh", "The winning host (its own claim is lowest/live) proceeds to exactly one claude call, unchanged from today": "group 24b — no competing claim; asserts POST .../issues/77/comments (marker posted), 'won the cross-host claim', claude.calls == 1, outcome advanced", "Existing group 2's invariant still holds: the agent-working claim is POSTed before the session runs": "group 2 still green (POST .../issues/25/labels asserted before the session); full suite run", "The full offline suite is green (lib change + its test in the same commit)": "session-runner-test.sh: 24 groups passed; full loop: only tests/fleet-tui-test.sh fails on a pre-existing environmental gap ('No module named pytest' in fleet-tui/.venv — reproduced on the un-modified tree via git stash; my change touches no fleet-tui file). Its structural checks pass 6/7.", "STATUS.md updated in the same commit (new coordination gate on the session-runner drainer)": "STATUS.md header line, Host-state row (#125 entry), and Milestone log entry all in commit 16ef647" }, "summary": "session-runner.sh now runs the swarm's claim-lib leader election between the agent-working claim and the expensive clone/session, so two hosts draining one ready-for-session queue arbitrate lowest-comment-id-wins and the loser stands down cheaply without a wasted session.", "blockers": [] } ``` </details>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Matou/dev-factory#125
No description provided.