"""A call a crash cut off is answered by the kernel that ran its cell. A turn stopped before its first token, and a turn of more than a hundred tool steps, are checked in process by apps/albedo/test/albedo/session/turn_lifecycle_test.gleam.""" import json import os import unittest from harness import Albedo, Provider, exclusive, fresh_prompt, python, text, wait_until 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, as backgrounded with a wake when it still runs, or as a stand-in when the kernel cannot be heard, with the result journaled once it can.""" # Each "cut N" cell marks started-N, waits for go-N, then runs CELLS[N]. CELLS = { 1: "print('ended while albedo was down')\n" "_ = pathlib.Path('ended-1').write_text('')", 2: "print('ended after the restart')", 3: "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')", } def provider(self): 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.startswith("cut "): n = int(prompt[4:]) gate = ( "" if n == 3 else f"while not pathlib.Path('go-{n}').exists():\n" " await asyncio.sleep(0.02)\n" ) return python( "import asyncio, pathlib\n" f"pathlib.Path('started-{n}').write_text('')\n" + gate + self.CELLS[n] ) return text("after") provider = Provider(reply) self.addCleanup(provider.close) return provider def recovered(self, app, provider, session, n, prepare=None): """The tool results the first turn after a crash sends, the crash cutting off cell `n`. `prepare` runs while no daemon is up.""" app.prompt(session, f"cut {n}").close() wait_until( (app.workspace / f"started-{n}").exists, 30, "the cell never started" ) app.restart(crash=True, prepare=prepare) start = len(provider.requests) app.prompt(session, "after").close() app.idle(session, timeout=60) return tool_results(provider.requests[start:]) # exclusive: crashes the daemon @exclusive def test_a_call_a_crash_cut_off_is_answered_by_the_kernel_that_ran_it(self): provider = self.provider() with Albedo(provider) as app: session = app.session() for index in range(2): app.prompt(session, f"earlier {index}").close() app.idle(session) # The cell ended while the daemon was down: its result, after the # older turns, not the stand-in naming the cell. def end_while_down(app): (app.workspace / "go-1").write_text("") wait_until( (app.workspace / "ended-1").exists, 30, "the cell never ended" ) outputs = self.recovered(app, provider, session, 1, end_while_down) 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, ) # Still running: backgrounded, and it wakes the session at its end. outputs = self.recovered(app, provider, session, 2) recovered = json.loads(outputs[-1].split("\n", 1)[0]) self.assertEqual(recovered["status"], "backgrounded", outputs) (app.workspace / "go-2").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", ) app.idle(session, timeout=60) # The kernel holds its GIL from before the crash until after the # turn, so the restarted daemon never hears it say hello: the # call gets a stand-in, and the journal its result later. os.mkfifo(app.workspace / "release") 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 outputs = self.recovered( app, provider, session, 3, 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" ] if __name__ == "__main__": unittest.main()