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:
|
||||
|
||||
@@ -33,11 +33,12 @@ import sys
|
||||
import typing
|
||||
|
||||
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
|
||||
from loop_claude.waiting import Ask, ask_file, Asking, claim_talk, ClaudeEnded, MAKE_WAY_SECONDS, read_ask, running, send, Typed, waiting
|
||||
from loop_claude.waiting import Ask, ask_file, Asking, claim_talk, ClaudeEnded, drop_ended, MAKE_WAY_SECONDS, read_ask, send, Typed, waiting
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from failure import Failure
|
||||
from loop_claude.hand_over import hand_over
|
||||
from loop_claude.paths import Paths, paths_from
|
||||
from loop_claude.session_lock import running
|
||||
|
||||
USAGE = "usage: loop-inbox"
|
||||
# Milliseconds between refreshes of the list while no key is pressed.
|
||||
@@ -69,6 +70,7 @@ def run(window: curses.window, screen_off: typing.Callable[[], typing.ContextMan
|
||||
window.timeout(REFRESH_MS)
|
||||
screen: Screen = Listing()
|
||||
while True:
|
||||
drop_ended(folder)
|
||||
screen = entered(screen, refreshed(screen, folder), effects)
|
||||
draw(window, screen, effects)
|
||||
try:
|
||||
|
||||
@@ -18,6 +18,7 @@ from loop_claude.hand_over import ClaudeCommand
|
||||
from failure import Failure
|
||||
from loop_inbox import inbox, main
|
||||
from loop_claude.paths import paths_from
|
||||
from loop_claude import session_lock
|
||||
from loop_claude.effects import system_effects
|
||||
from loop_claude import waiting
|
||||
|
||||
@@ -31,10 +32,10 @@ def asked(session, root, question="Which one?", at=100.0, state=ASKING):
|
||||
return Ask(f"ask-{session}", session, root, question, at, state)
|
||||
|
||||
|
||||
def running(test, folder, *sessions):
|
||||
def loops_hold(test, folder, *sessions):
|
||||
"""Holds each session's lock until the test ends, as the loop that lists its ask does."""
|
||||
for session in sessions:
|
||||
test.enterContext(waiting.locked(folder, session))
|
||||
test.enterContext(session_lock.locked(folder, session))
|
||||
|
||||
|
||||
def asks_and_answers(folder):
|
||||
@@ -89,7 +90,7 @@ class Answers(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.folder)
|
||||
running(self, self.folder, "s1", "s2")
|
||||
loops_hold(self, self.folder, "s1", "s2")
|
||||
|
||||
def answer(self, number, text):
|
||||
"""Picks loop number from the list as it waits now and types text to it, as the human does in loop-inbox."""
|
||||
@@ -140,6 +141,11 @@ class Answers(unittest.TestCase):
|
||||
waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask"))
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/log no longer waits for that answer: it was answered elsewhere, or stopped."))
|
||||
|
||||
def test_an_answer_screen_leaves_once_its_loop_ends_though_its_ask_stays_on_disk(self):
|
||||
ask = asked("s3", "/code/bender")
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/bender no longer waits for that answer: it was answered elsewhere, or stopped."))
|
||||
|
||||
def claim(self, ask, loop_does):
|
||||
"""claim_talk's result for ask, and the seconds it waited; loop_does acts as the loop at claim_talk's first wait."""
|
||||
tenths = [0]
|
||||
@@ -184,7 +190,7 @@ class Opens(unittest.TestCase):
|
||||
self.addCleanup(shutil.rmtree, home)
|
||||
self.paths = paths_from(home)
|
||||
self.ask = asked("s1", "/code/log")
|
||||
running(self, self.paths.waiting, "s1")
|
||||
loops_hold(self, self.paths.waiting, "s1")
|
||||
waiting.publish(self.paths.waiting, self.ask)
|
||||
|
||||
def open(self, claude, loop_shows=OpenInInbox(INBOX)):
|
||||
@@ -240,7 +246,7 @@ class Typing(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
paths = paths_from(pathlib.Path(home))
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
running(self, paths.waiting, "s1", "s2")
|
||||
loops_hold(self, paths.waiting, "s1", "s2")
|
||||
for ask in (log, bender):
|
||||
waiting.publish(paths.waiting, ask)
|
||||
def answered_on_terminal():
|
||||
@@ -305,11 +311,11 @@ class Waiting(unittest.TestCase):
|
||||
def test_lists_the_loops_still_running_oldest_first_and_skips_a_file_it_cannot_read(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
late, early, stopped = asked("s1", "/a", at=300, state=OpenInInbox(7)), asked("s2", "/b", at=100), asked("s3", "/c", at=50, state=OpenOnTerminal())
|
||||
running(self, pathlib.Path(folder), "s1", "s2")
|
||||
loops_hold(self, pathlib.Path(folder), "s1", "s2")
|
||||
for ask in (late, early, stopped):
|
||||
waiting.publish(pathlib.Path(folder), ask)
|
||||
pathlib.Path(folder, "s4.json").write_text("{")
|
||||
pathlib.Path(folder, "s5.json").write_text('{"pid": 0}')
|
||||
pathlib.Path(folder, "s5.json").write_text('{"question": "Which one?"}')
|
||||
pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"'))
|
||||
self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late])
|
||||
|
||||
@@ -327,8 +333,19 @@ class Waiting(unittest.TestCase):
|
||||
loop.kill()
|
||||
loop.wait()
|
||||
self.assertEqual(waiting.waiting(folder), [])
|
||||
waiting.drop_ended(folder)
|
||||
self.assertEqual(asks_and_answers(folder), [])
|
||||
|
||||
def test_removes_only_the_asks_and_answers_whose_loop_has_ended(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder = pathlib.Path(temp)
|
||||
loops_hold(self, folder, "s1")
|
||||
for ask in (asked("s1", "/a"), asked("s2", "/b")):
|
||||
waiting.publish(folder, ask)
|
||||
waiting.send(folder, ask, Typed("Use A."))
|
||||
waiting.drop_ended(folder)
|
||||
self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json"])
|
||||
|
||||
def test_a_talk_claim_from_pid_0_or_below_is_no_answer_since_it_would_name_a_process_group(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
ask = asked("s1", "/a")
|
||||
|
||||
Reference in New Issue
Block a user