Answer principles round 1: 0 🔴, 4 🟡 (0 misread); move the session lock into its own module, split loop-inbox's look from its removal, test every lock branch, file items 253 and 254
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
"""The lock a loop-claude holds on its worker's session while loop-inbox lists its question, which tells loop-inbox the loop still runs.
|
||||
|
||||
The lock is <session>.lock, held with flock. The kernel frees it however the loop ends, killed included, 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.
|
||||
"""
|
||||
import contextlib
|
||||
import fcntl
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from file_writes import make_private
|
||||
|
||||
|
||||
def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.lock"
|
||||
|
||||
|
||||
@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 for a moment where it finds the session's question still listed, so a loop starting after another was killed may meet it held."""
|
||||
try:
|
||||
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 running(folder: pathlib.Path, session: str) -> bool:
|
||||
"""Whether a loop holds the session's lock; False also where the lock cannot be read."""
|
||||
try:
|
||||
with open(lock_file(folder, session)) as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
return False
|
||||
@@ -1,6 +1,7 @@
|
||||
import ast
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import errno
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
@@ -23,7 +24,7 @@ from loop_claude.project import checkout, model_choice, records
|
||||
from chunk_pick import DefaultPlan, LastCut
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT, run_python, say, system_effects
|
||||
from claude_code import entries, reply, session
|
||||
from loop_claude import escalation_mark, hand_over, paths, routing, waiting
|
||||
from loop_claude import escalation_mark, hand_over, paths, routing, session_lock, waiting
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
@@ -1278,6 +1279,35 @@ class Alive(unittest.TestCase):
|
||||
self.assertEqual([system_effects().alive(pid) for pid in (os.getpid(), ended.pid, 1)], [True, False, True])
|
||||
|
||||
|
||||
class SessionLock(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.folder)
|
||||
self.path = session_lock.lock_file(self.folder, "s1")
|
||||
|
||||
def test_a_loop_cannot_take_the_lock_another_holds_and_runs_until_it_lets_it_go(self):
|
||||
self.assertFalse(session_lock.running(self.folder, "s1"))
|
||||
with session_lock.locked(self.folder, "s1") as first:
|
||||
self.assertIsNone(first)
|
||||
with session_lock.locked(self.folder, "s1") as second:
|
||||
self.assertEqual(second, Failure(f"another process holds {self.path}"))
|
||||
self.assertTrue(session_lock.running(self.folder, "s1"))
|
||||
self.assertFalse(session_lock.running(self.folder, "s1"))
|
||||
|
||||
def test_a_lock_that_cannot_be_opened_is_a_failure_and_no_loop_running(self):
|
||||
self.path.mkdir()
|
||||
with session_lock.locked(self.folder, "s1") as unlocked:
|
||||
self.assertEqual(unlocked, Failure(f"cannot open {self.path}: Is a directory"))
|
||||
self.assertFalse(session_lock.running(self.folder, "s1"))
|
||||
|
||||
def test_a_lock_the_kernel_refuses_is_a_failure_and_no_loop_running(self):
|
||||
self.path.touch()
|
||||
with unittest.mock.patch("fcntl.flock", side_effect=OSError(errno.ENOLCK, "No locks available")):
|
||||
with session_lock.locked(self.folder, "s1") as unlocked:
|
||||
self.assertEqual(unlocked, Failure(f"cannot lock {self.path}: No locks available"))
|
||||
self.assertFalse(session_lock.running(self.folder, "s1"))
|
||||
|
||||
|
||||
class ClaudeOnTerminal(unittest.TestCase):
|
||||
def test_leaves_ctrl_c_to_claude_while_it_runs_and_returns_its_exit_code(self):
|
||||
caught = []
|
||||
|
||||
+15
-53
@@ -1,14 +1,12 @@
|
||||
"""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 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.
|
||||
<session> is the worker's session id, so a loop lists one question at a time. The loop holds the session's lock, as
|
||||
session_lock.py describes, 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 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.
|
||||
@@ -19,7 +17,6 @@ answer on its terminal, never answers a later one.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import fcntl
|
||||
import json
|
||||
import pathlib
|
||||
import typing
|
||||
@@ -27,6 +24,7 @@ import typing
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, say
|
||||
from failure import Failure
|
||||
from loop_claude.session_lock import locked, running
|
||||
from file_writes import make_private, replace_json
|
||||
|
||||
# Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way.
|
||||
@@ -97,10 +95,6 @@ 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)
|
||||
@@ -141,32 +135,6 @@ def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[
|
||||
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:
|
||||
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) -> list[Ask]:
|
||||
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out."""
|
||||
try:
|
||||
@@ -177,22 +145,16 @@ def waiting(folder: pathlib.Path) -> list[Ask]:
|
||||
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."""
|
||||
def drop_ended(folder: pathlib.Path) -> None:
|
||||
"""Removes each ask, with any answer, whose session's lock no loop holds: a loop that was killed leaves its ask behind. It removes one while holding the lock, so a loop that lists a new ask meanwhile keeps it. An ask it cannot remove stays on disk, and waiting leaves it out all the same."""
|
||||
try:
|
||||
handle = open(lock_file(folder, session), "a")
|
||||
paths = list(folder.glob("*.json"))
|
||||
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
|
||||
return
|
||||
for path in paths:
|
||||
with locked(folder, path.stem) as unlocked:
|
||||
if not unlocked:
|
||||
withdraw(folder, path.stem)
|
||||
|
||||
|
||||
def read_ask(path: pathlib.Path) -> Ask | None:
|
||||
|
||||
Reference in New Issue
Block a user