Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AUTONOMY.md
Original file line number Diff line number Diff line change
Expand Up @@ -592,8 +592,9 @@ Watcher latency (M3.7c, the human's plan decisions of 2026-11-19):
failing workspace the watcher cannot map, or a report it cannot read,
blocks every library, chain and workspace repo. A run list that has
failed on every read for 30 minutes (from the first failure; any good
read resets it) holds those repos' PRs instead: a wait, not a refusal,
as `workspace sweep unknown: run list unreadable since <time>`. No
read resets it, and so does a new shift, or a gap of over 2 hours since
the previous read) holds those repos' PRs instead: a wait, not a
refusal, as `workspace sweep unknown: run list unreadable since <time>`. No
session starts and no slot is taken; the next good read releases them,
and the shift does not close early meanwhile. A close-out already
running on a blocked repo finds a `.sweep-red` marker (red or unknown)
Expand Down
4 changes: 3 additions & 1 deletion agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,9 @@ red: <url>`, right after the S7 check. An unmapped workspace or an
unreadable report blocks every library, chain and workspace repo. A run
list failing for 30 minutes from the streak's first failure holds those
PRs in `counters["sweep_waits"]` instead (a wait, re-judged each tick, no
refusal), and `early_close_ready` keeps the shift open. A running close-out on a
refusal), and `early_close_ready` keeps the shift open. A failed read whose
previous read was another shift's (`read_shift`), or over 2 hours old
(`SWEEP_STREAK_GAP_S`), starts a fresh streak. A running close-out on a
blocked repo gets `leases/<task>.sweep-red` and refuses before it merges;
a marker the current block does not cover is removed.
A later green run clears the block, as does `/clear-sweep`. The latest
Expand Down
12 changes: 12 additions & 0 deletions agents/conductors/batch/_digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,8 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False,
state += f" — worktree: {co['cleanup']}"
elif url in (counters.get("merge_waits") or {}):
state = wait_state(url, counters) # merge order (M3.6j, #683)
elif url in (counters.get("sweep_waits") or {}):
state = sweep_wait_state(url, counters) # unknown sweep (M3.7e, #694)
elif co.get("state") == "refused":
state = f"awaiting /prm — close-out refused: {co.get('why', '?')}"
elif co.get("state") == "running":
Expand Down Expand Up @@ -309,6 +311,15 @@ def _order_word(url: str, counters: dict) -> str:
return "open"


def sweep_wait_state(url: str, counters: dict) -> str:
"""A PR held while the sweep's run list is unreadable (M3.7e, #694): since
when the sweep is unknown, from the wait's `why`."""
wait = (counters.get("sweep_waits") or {}).get(url) or {}
_, sep, since = str(wait.get("why") or "").partition(" since ")
since = (since if sep else "") or wait.get("since") or "?"
return f"waiting: workspace sweep unknown since {since}"


def wait_state(url: str, counters: dict) -> str:
"""A PR waiting in merge order: behind which PRs, what they are doing, and
which one to merge first (M3.6j, PyAutoBrain#683)."""
Expand Down Expand Up @@ -615,6 +626,7 @@ def label(task: str, pick: dict | None, url: str = "") -> str:
("close-out running", "Still running — close-out checking it"),
(UPDATING, "Still running — close-out updating the branch from main"),
("waits behind", "Waiting — merges after an earlier PR (your /prm first)"),
("waiting: workspace sweep unknown", "Waiting — workspace sweep unknown"),
(UPDATED, "Branch updated from main — CI re-running"),
(CURRENT, "Branch up to date — awaiting its merge close-out"),
(STILL_OUT, "Still running at review time"),
Expand Down
4 changes: 2 additions & 2 deletions agents/conductors/batch/_orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3396,7 +3396,7 @@ def _sweep_tick(slot: Path, counters: dict, now: _dt.datetime) -> None:
return
home = slot.parent
try:
state = _sweep.observe(home, cfg, now)
state = _sweep.observe(home, cfg, now, slot.name)
hmap = _sweep.heart_map() # local reads of the Heart checkout
everything = _flow_keys(hmap)
blk = _sweep.block(home, cfg, hmap, _repo_key, state, now, everything)
Expand All @@ -3419,7 +3419,7 @@ def _sweep_read(slot: Path, counters: dict, now: _dt.datetime) -> None:
if not cfg:
return
try:
_sweep.observe(slot.parent, cfg, now)
_sweep.observe(slot.parent, cfg, now, slot.name)
except Exception as e: # noqa: BLE001
counters["sweep"] = {**(counters.get("sweep") or {}),
"error": f"{type(e).__name__}: {e}"[:200]}
Expand Down
28 changes: 21 additions & 7 deletions agents/conductors/batch/_sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@
#: (measured from the streak's first failure) holds every PR a merge could
#: break: a wait, not a refusal (review round 2).
UNKNOWN_AFTER_S = 1800
#: A failed read starts a fresh streak when the previous read attempt (good
#: or failed) was made by another shift (`read_shift`, none recorded counts
#: as another), or is older than this backstop: far above any tick, even one
#: whose gh calls all hang to their timeouts; it covers a laptop asleep
#: mid-shift (#694, review round 1).
SWEEP_STREAK_GAP_S = 7200
UNKNOWN_WHY = "workspace sweep unknown: run list unreadable since {since}"
SWEEP_DIR = "sweep"
STATE_FILE = "state.json"
Expand Down Expand Up @@ -344,16 +350,22 @@ def is_red(run: dict | None) -> bool:
return bool(run) and run.get("status") == "completed" and run.get("conclusion") in RED


def observe(home: Path, cfg: dict, now: _dt.datetime) -> dict:
"""The tick's one read of the sweep (once a tick: `read_at`). Returns the
state; a failed list keeps the last known runs, with the error noted."""
def observe(home: Path, cfg: dict, now: _dt.datetime, shift: str = "") -> dict:
"""The tick's one read of the sweep (once a tick: `read_at`, by `shift`,
the slot's name). Returns the state; a failed list keeps the last known
runs, with the error noted."""
state = load_state(home)
if not cfg or state.get("read_at") == _iso(now):
return state
state["read_at"] = _iso(now)
prev = _parse(state.get("read_at") or "")
prev_shift = state.get("read_shift") or ""
state.update(read_at=_iso(now), read_shift=shift)
runs, why = list_runs(cfg)
if runs is None:
state.update(ok=False, error=why, fail_since=state.get("fail_since") or _iso(now))
gap = prev is None or not prev_shift or prev_shift != shift \
or (now - prev).total_seconds() > SWEEP_STREAK_GAP_S
since = "" if gap else state.get("fail_since") or ""
state.update(ok=False, error=why, fail_since=since or _iso(now))
_write(sweep_dir(home) / STATE_FILE, state)
return state
state.update(ok=True, error="", runs=runs, ok_at=_iso(now), fail_since="")
Expand Down Expand Up @@ -397,8 +409,10 @@ def red_run(home: Path, state: dict | None = None) -> dict | None:

def unknown_since(state: dict, now: _dt.datetime) -> str | None:
"""The first failure of the current failing streak (`fail_since`, reset
by any successful read) when it is UNKNOWN_AFTER_S old or more; else
None. One failure after a long gap is no unknown state."""
by any successful read, a change of shift and a gap over
SWEEP_STREAK_GAP_S since the previous read) when it is UNKNOWN_AFTER_S
old or more; else None. One failure after a long gap is no unknown
state."""
since = state.get("fail_since") or ""
at = _parse(since) if since else None
if at is None or (now - at).total_seconds() < UNKNOWN_AFTER_S:
Expand Down
116 changes: 116 additions & 0 deletions tests/test_shift_end_sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,20 @@ def __init__(self):
self.closeouts = []


class LateLibs(TwoLibs):
"""TwoLibs whose workers report only when the test calls `finish`: a
shift can tick on, a few minutes apart, before its PRs open."""

def spawn(self, task, prompt_path, lease_dir):
Path(lease_dir).mkdir(parents=True, exist_ok=True)
self.lease_dir = Path(lease_dir)
return {"pid": 0, "session_id": None, "worktree": None}

def finish(self):
for task, text in self.done.items():
(self.lease_dir / f"{task}.done").write_text(text)


def _red(sweep, project="autofit", rid=200, fit="d"):
sweep.runs = [_run(rid, "failure", minutes=-60), _run(100)]
sweep.artifacts = {
Expand Down Expand Up @@ -801,3 +815,105 @@ def test_r1_8_a_clear_before_the_artifacts_are_read_still_files_the_draft(tmp_pa
_ltick(mind, brief, home, sp, minutes)
assert [o["path"].rsplit("/", 1)[1] for o in _draft_ops(slot)] == \
["workspace_sweep_red_200.md"]


# --- follow-ups (PyAutoBrain#694) ---------------------------------------------------

def _fail_every(mind, brief, home, sp, minutes):
"""Ticks a few minutes apart (one run of ticks); a LateLibs shift's PRs
open on the last."""
for m in minutes[:-1]:
_ltick(mind, brief, home, sp, m)
if isinstance(sp, LateLibs):
sp.finish()
_ltick(mind, brief, home, sp, minutes[-1])


def _seed(home, **state):
sd = orch._sweep.sweep_dir(home)
sd.mkdir(parents=True)
(sd / orch._sweep.STATE_FILE).write_text(json.dumps(
{"ok": False, "error": "HTTP 502", **state}))
return sd / orch._sweep.STATE_FILE


@pytest.mark.parametrize("prev_shift", ["2026-11-04-earlier-shift", None])
def test_694_a_failed_read_in_a_new_shift_starts_a_fresh_streak(tmp_path, sweep, prev_shift):
"""The previous shift's last read failed (a streak an hour old, its last
read 5 minutes ago); the next shift's first read fails too: a fresh
streak, so no PR is held as unknown. State with no shift recorded is
treated the same."""
seed = {"read_at": orch._iso(_at(-5)), "fail_since": orch._iso(_at(-60))}
if prev_shift:
seed["read_shift"] = prev_shift
path = _seed(tmp_path / "home", **seed)
sweep.runs = None
mind, brief, home, sp = _libs_shift(tmp_path)
_ltick(mind, brief, home, sp, 0)
_ltick(mind, brief, home, sp, 1)
c = orch.read_counters(orch.slot_dir(brief, home))
assert not c["sweep"].get("block")
assert c["sweep_waits"] == {}
assert sorted(pr for _, pr in sp.closeouts) == sorted([FIT8, GA7])
state = json.loads(path.read_text())
assert state["fail_since"] == "2026-11-04T09:00:00Z"
assert state["read_shift"] == orch.slot_dir(brief, home).name


def test_694_slow_ticks_in_one_shift_still_hold_prs_after_30_minutes(tmp_path, sweep):
"""An outage where each gh call hangs to its timeout: ticks 12 minutes
apart, every read failing. The streak runs on, so PRs are held."""
sweep.runs = None
mind, brief, home, _ = _libs_shift(tmp_path)
sp = LateLibs()
_fail_every(mind, brief, home, sp, [0, 12, 24, 36])
c = orch.read_counters(orch.slot_dir(brief, home))
assert c["sweep"]["block"]["why"] == UNKNOWN.format("2026-11-04T09:00:00Z")
assert set(c["sweep_waits"]) == {FIT8, GA7} and sp.closeouts == []


def test_694_a_gap_over_two_hours_in_one_shift_restarts_the_streak(tmp_path, sweep):
"""The laptop asleep mid-shift: failing reads 0-20, then failing reads
from 141 (a 121-minute gap): the streak counts from 141."""
sweep.runs = None
mind, brief, home, sp = _libs_shift(tmp_path)
slot = orch.slot_dir(brief, home)
_fail_every(mind, brief, home, sp, list(range(0, 21, 5)))
_ltick(mind, brief, home, sp, 141)
assert not orch.read_counters(slot)["sweep"].get("block")
state = json.loads((orch._sweep.sweep_dir(home) / orch._sweep.STATE_FILE).read_text())
assert state["fail_since"] == "2026-11-04T11:21:00Z"


def test_694_30_minutes_of_continuous_failures_still_hold_prs(tmp_path, sweep):
sweep.runs = None
mind, brief, home, _ = _libs_shift(tmp_path)
sp = LateLibs()
_fail_every(mind, brief, home, sp, list(range(0, 31, 5)))
c = orch.read_counters(orch.slot_dir(brief, home))
assert set(c["sweep_waits"]) == {FIT8, GA7}
assert sp.closeouts == []


def test_694_the_digest_row_of_a_pr_held_by_an_unknown_sweep_says_so(tmp_path, sweep):
sweep.runs = None
mind, brief, home, _ = _libs_shift(tmp_path)
sp = LateLibs()
_fail_every(mind, brief, home, sp, list(range(0, 31, 5)))
slot = orch.slot_dir(brief, home)
c = orch.read_counters(slot)
row = "waiting: workspace sweep unknown since 2026-11-04T09:00:00Z"
for task, pr in (("named", FIT8), ("picked", GA7)):
assert _digest.task_state(task, c, t._health)[0] == f"{pr} — {row}"
d = _digest.build(_brief.parse(brief.read_text())["brief"], slot, c, health=t._health)
assert d.count("- **Waiting — workspace sweep unknown** — ") == 2
assert d.count(f" · {row}") == 2
why = UNKNOWN.format("2026-11-04T09:00:00Z")
assert f"- {why} — blocked:" in d and "PRs waiting: autofit#8, autogalaxy#7" in d


def test_694_the_digest_row_falls_back_to_the_waits_own_since():
counters = {"sweep_waits": {FIT8: {"task": "named", "why": "unreadable",
"since": "2026-11-04T09:31:00Z"}}}
assert _digest.sweep_wait_state(FIT8, counters) == \
"waiting: workspace sweep unknown since 2026-11-04T09:31:00Z"
Loading