"""Cancellation releases execution workers and long tool turns complete.""" from concurrent.futures import ThreadPoolExecutor import json import os import time import unittest from harness import Albedo, Provider, exclusive, fresh_prompt, python, text, wait_until from stream_support import StreamProbe from integration_support import IntegrationScenario class CutOffCallTests(unittest.TestCase): """A call a crash cut off is answered by the kernel that ran its cell: with its result when the cell ended before the next turn, whichever of the kernel's report and the turn reaches the daemon first, or as backgrounded with a wake when it still runs.""" def provider( self, cell, gate="while not pathlib.Path('go').exists():\n await asyncio.sleep(0.02)\n", ): def reply(request): prompt = fresh_prompt(request) if not prompt: return text("done") if prompt.startswith("earlier"): return python(f"print({prompt!r})") if prompt.startswith("check "): # Waits in the kernel for the journal to hold the cell's end. return python( f"while (info := await cells.info({prompt[6:]!r}))['status'] == 'started':\n" " await asyncio.sleep(0.05)\nprint(info['status'])" ) if prompt == "cut": return python( "import asyncio, pathlib\npathlib.Path('started').write_text('')\n" + gate + cell ) return text("after") provider = Provider(reply) self.addCleanup(provider.close) return provider def recovered(self, app, provider, prepare=None, reopened=None): """The tool results the first turn after a crash sends, the crash cutting off a cell that waits for `go` after older turns. `prepare` runs while no daemon is up, `reopened` once the next one is.""" session = app.session() for index in range(2): app.prompt(session, f"earlier {index}").close() app.idle(session) app.prompt(session, "cut").close() wait_until((app.workspace / "started").exists, 30, "the cell never started") app.restart(crash=True, prepare=prepare) if reopened is not None: reopened(app) start = len(provider.requests) app.prompt(session, "after").close() app.idle(session, timeout=60) return session, tool_results(provider.requests[start:]) # exclusive: crashes the daemon @exclusive def test_a_call_a_crash_cut_off_is_answered_by_its_kernel_after_older_turns(self): def end_while_down(app): (app.workspace / "go").write_text("") wait_until((app.workspace / "ended").exists, 30, "the cell never ended") provider = self.provider( "print('ended while albedo was down')\n_ = pathlib.Path('ended').write_text('')" ) with Albedo(provider) as app: _, outputs = self.recovered(app, provider, end_while_down) # Its result, not the stand-in naming the cell. self.assertRegex( outputs[-1], r'^\{"status":"ok","duration":[0-9.]+,"at":"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z"\}\nended while albedo was down\n$', outputs, ) # exclusive: crashes the daemon @exclusive def test_a_cut_off_cell_still_running_is_backgrounded_and_wakes_its_session(self): provider = self.provider("print('ended after the restart')") with Albedo(provider) as app: _, outputs = self.recovered(app, provider) recovered = json.loads(outputs[-1].split("\n", 1)[0]) self.assertEqual(recovered["status"], "backgrounded", outputs) (app.workspace / "go").write_text("") wait_until( lambda: any( "background python cells finished" in str(message.get("content")) and recovered["cell_id"] in str(message.get("content")) for record in provider.requests for message in record["request"]["messages"] ), 30, "the backgrounded cell never woke its session", ) # exclusive: crashes the daemon @exclusive def test_a_kernel_wedged_across_the_restart_leaves_the_stand_in_and_journals_the_result( self, ): provider = self.provider( "import ctypes, os\n" "libc = ctypes.PyDLL(None) # its calls keep the GIL from the link's reader\n" "fd = libc.open(b'release', os.O_RDONLY)\n" "libc.read(fd, ctypes.create_string_buffer(1), 1)\n" "print('ended after the wedge')", gate="", ) writer = [] def wedged(app): # Succeeds once the cell waits in open; it then waits in read, # still holding the GIL, until the test writes. try: writer.append( os.open(app.workspace / "release", os.O_WRONLY | os.O_NONBLOCK) ) except OSError: return False self.addCleanup(os.close, writer[0]) return True with Albedo(provider) as app: os.mkfifo(app.workspace / "release") # The kernel holds its GIL from before the crash until after the # turn, so the restarted daemon never hears it say hello. session, outputs = self.recovered( app, provider, lambda app: wait_until( lambda: wedged(app), 30, "the cell never wedged" ), ) self.assertIn("outcome unknown", outputs[-1], outputs) stand_in = json.loads(outputs[-1]) os.write(writer[0], b"x") start = len(provider.requests) app.prompt(session, f"check {stand_in['cell_id']}").close() app.idle(session, timeout=60) checked = tool_results(provider.requests[start:]) self.assertEqual(checked[-1].split("\n", 1)[1], "ok\n", checked) def tool_results(records): return [ str(message.get("content")) for record in records for message in record["request"]["messages"] if message.get("role") == "tool" ] class ExecutionRecoveryTests(IntegrationScenario): # exclusive: enables the existing native inspection seam @exclusive def test_interrupt_before_first_token_stops_worker_without_killing_it(self): for protocol in ("responses", "chat_completions"): with self.subTest(protocol=protocol): app = self.app_for( protocol, prepare=lambda app: app.env.update(ALBEDO_INSPECT="1") ) session = app.session() start = len(self.provider.requests) with app.prompt(session, "no first token") as response: input_id = json.load(response)["id"] self.wait_for_request(start) captured = self.read(app, f"/sessions/{session}?tail=0") probe = StreamProbe(app) ready = app.workspace / f"monitor-{protocol}" arguments = ( "[" + ",".join( "<<" + json.dumps(value) + ">>" for value in [session, captured["status"]["run_id"], str(ready)] ) + "]" ) with ThreadPoolExecutor(max_workers=1) as pool: exited = pool.submit(probe.call, "worker_exit_json", arguments) deadline = time.monotonic() + 30 while not ready.exists() and time.monotonic() < deadline: time.sleep(0.01) self.assertTrue(ready.exists(), "worker monitor was not installed") app.api( f"/sessions/{session}/interrupt", { "run_id": captured["status"]["run_id"], "through_input_order": captured["input_order"], }, ).close() self.assertEqual(exited.result(timeout=40), {"reason": "normal"}) app.idle(session) receipt = self.read(app, f"/sessions/{session}/inputs/{input_id}") self.assertEqual(receipt["turn"]["state"], "interrupted") # The interrupted session takes a new turn and commits it. self.send(app, session, "continue from branch") self.assertTrue( any( e["kind"] == "assistant" and self.entry_text(e) == "finished" for e in self.history(app, session) ) ) def test_more_than_hundred_tool_turns_complete(self): for protocol in ("responses", "chat_completions"): with self.subTest(protocol=protocol): app = self.app_for(protocol) session = app.session() start = len(self.provider.requests) self.send(app, session, "continue for over 100 turns") self.assertEqual(len(self.records(start)), 106) events = self.history(app, session) self.assertEqual(sum(e["kind"] == "tool_result" for e in events), 105) self.assertTrue( any( e["kind"] == "assistant" and self.entry_text(e) == "finished" for e in events ) )