List a loop's question in loop-inbox only while the loop holds the session's lock, so a killed loop's question stays gone whatever its pid now names

This commit is contained in:
2026-10-29 18:14:44 +01:00
parent 93d413f5f3
commit 5df105033c
10 changed files with 157 additions and 66 deletions
+73 -17
View File
@@ -1,11 +1,14 @@
"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there.
A waiting loop keeps its ask in <session>.json in Paths.waiting: the question, with an id new for each question.
<session> is the worker's session id, so a loop lists one question at a time. The loop removes the file once the
question is answered or the loop stops. The ask's state says whether the loop waits for an answer, or has claude
open for it, on the loop's own terminal or in loop-inbox. loop-inbox answers by replacing <session>.answer, which
names the ask's id. So an answer meant for an earlier question, or sent as the loop took an answer on its terminal,
never answers a later one.
<session> is the worker's session id, so a loop lists one question at a time. The loop holds <session>.lock with flock
while it lists the ask, and removes the ask once the question is answered or the loop stops. loop-inbox lists an ask
only while its lock is held, and removes one whose lock is free: the kernel frees a lock however its process ends, where
a process id the system may hand out again cannot tell a loop that runs from one that was killed. The lock file stays
once the loop ends: docs/decisions.md → `loop-inbox: …` says why. The ask's state says whether the loop waits for an
answer, or has claude open for it, on the loop's own terminal or in loop-inbox. loop-inbox answers by replacing
<session>.answer, which names the ask's id. So an answer meant for an earlier question, or sent as the loop took an
answer on its terminal, never answers a later one.
/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session:
1. loop-inbox's claim_talk sends ClaudeOpening, with its pid.
@@ -16,6 +19,7 @@ never answers a later one.
"""
import contextlib
import dataclasses
import fcntl
import json
import pathlib
import typing
@@ -61,7 +65,6 @@ class Ask:
question: str
# When the loop asked, in seconds since the epoch.
asked: float
pid: int
state: AskState
@@ -94,6 +97,10 @@ def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.answer"
def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.lock"
def publish(folder: pathlib.Path, ask: Ask) -> Failure | None:
try:
make_private(folder)
@@ -120,25 +127,74 @@ def shown(folder: pathlib.Path, ask: Ask, effects: Effects) -> None:
@contextlib.contextmanager
def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[None]:
"""Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure to take it out only warns: loop-inbox drops the ask once the loop's process ends."""
shown(folder, ask, effects)
"""Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure only warns: the question is still answered on the loop's terminal, and loop-inbox drops the ask once the loop's process ends."""
with locked(folder, ask.session) as unlocked:
if unlocked:
say(f"loop-inbox cannot show this question: {unlocked.reason}", effects)
yield
return
shown(folder, ask, effects)
try:
yield
finally:
if unwithdrawn := withdraw(folder, ask.session):
say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects)
@contextlib.contextmanager
def locked(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None]:
"""Holds the session's lock while the with block runs; a Failure where it cannot. loop-inbox holds it only for as long as it takes to remove an ask, so a loop meets it held only while another loop lists a question for the session."""
try:
yield
finally:
if unwithdrawn := withdraw(folder, ask.session):
say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects)
make_private(folder)
except OSError as failure:
yield Failure(f"cannot make {folder}: {failure.strerror}")
return
path = lock_file(folder, session)
try:
handle = open(path, "a")
except OSError as failure:
yield Failure(f"cannot open {path}: {failure.strerror}")
return
with handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
yield Failure(f"another process holds {path}")
return
except OSError as failure:
yield Failure(f"cannot lock {path}: {failure.strerror}")
return
yield None
def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> list[Ask]:
def waiting(folder: pathlib.Path) -> list[Ask]:
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out."""
try:
paths = sorted(folder.glob("*.json"))
except OSError:
return []
asks = [ask for path in paths if (ask := read_ask(path)) and alive(ask.pid)]
asks = [ask for path in paths if (ask := read_ask(path)) and running(folder, ask.session)]
return sorted(asks, key=lambda ask: ask.asked)
def running(folder: pathlib.Path, session: str) -> bool:
"""Whether the loop that listed the session's ask still holds its lock. Where it doesn't, removes the ask and any answer while holding the lock, so a loop that lists a new ask meanwhile keeps it."""
try:
handle = open(lock_file(folder, session), "a")
except OSError:
return False
with handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True
except OSError:
return False
# A failure to remove leaves the ask out all the same; the next look tries again.
withdraw(folder, session)
return False
def read_ask(path: pathlib.Path) -> Ask | None:
"""The ask in path; None where a field has the wrong type, or names another session than path does."""
try:
@@ -147,8 +203,7 @@ def read_ask(path: pathlib.Path) -> Ask | None:
except (OSError, ValueError, TypeError, KeyError):
return None
texts = all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question))
# A pid of 0 or below would name a process group to alive.
return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) and isinstance(ask.pid, int) and ask.pid > 0 else None
return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) else None
def ask_state(data: object) -> AskState:
@@ -192,7 +247,8 @@ def received(folder: pathlib.Path, ask: Ask) -> Message | None:
match data:
case {"kind": "Typed", "text": str(text)}:
return Typed(text)
case {"kind": "ClaudeOpening", "pid": int(pid)}:
# A pid of 0 or below would name a process group to the loop's alive.
case {"kind": "ClaudeOpening", "pid": int(pid)} if pid > 0:
return ClaudeOpening(pid)
case {"kind": "ClaudeEnded"}:
return ClaudeEnded()