"""catches global-store read serialization under real concurrent daemon work.""" import json from pathlib import Path import threading import unittest import urllib.error from harness import ( Albedo, Provider, ROOT, exclusive, exclusive_class, python, text, wait_until, ) from inspect_support import Inspection from storage_sync_support import StorageSync @exclusive_class class StorageConcurrencyTest(unittest.TestCase): def setUp(self): self.provider = Provider(lambda _: text("committed while storage is reading")) self.addCleanup(self.provider.close) def test_reads_and_prompt_commit_continue_while_snapshot_is_held(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" with Albedo(self.provider, prepare=prepare) as app: probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) session = app.session() ready = app.home / "snapshot-ready" try: probe.call("hold_snapshot", f"[<<{json.dumps(str(ready))}>>]") wait_until(ready.exists, 10, "snapshot gate never opened") with app.api("/sessions?scope=all") as response: self.assertEqual(response.status, 200) self.assertTrue(json.load(response)["items"]) with app.api(f"/sessions/{session}/history") as response: self.assertEqual(response.status, 200) app.prompt(session, "commit while a reader snapshot is held").close() app.idle(session) self.assertTrue( any( part.get("text") == "committed while storage is reading" for part in app.history(session)["items"][-1]["content"] ) ) finally: probe.call("release") wait_until( lambda: not ready.exists(), 10, "snapshot gate did not close" ) def test_reads_do_not_wait_on_an_uncommitted_writer_transaction(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" with Albedo(self.provider, prepare=prepare) as app: probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) session = app.session() ready = app.home / "writer-ready" try: probe.call("hold_writer", f"[<<{json.dumps(str(ready))}>>]") wait_until(ready.exists, 10, "writer gate never opened") with app.api("/sessions?scope=all") as response: self.assertEqual(response.status, 200) items = json.load(response)["items"] self.assertTrue(items) self.assertNotIn( "uncommitted storage gate", json.dumps(items), ) with app.api(f"/sessions/{session}/history") as response: self.assertEqual(response.status, 200) finally: probe.call("release") wait_until(lambda: not ready.exists(), 10, "writer gate did not close") def test_session_answers_while_its_admission_waits_for_the_writer(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" with Albedo(self.provider, prepare=prepare) as app: probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) session = app.session() ready = app.home / "writer-ready" admitted = [] def admit(): with app.prompt(session, "admitted behind a slow commit") as response: admitted.append(response.status) prompt = threading.Thread(target=admit) try: probe.call("hold_writer", f"[<<{json.dumps(str(ready))}>>]") wait_until(ready.exists, 10, "writer gate never opened") prompt.start() self.assertEqual( probe.call("queued", '[<<"admit_pending">>, 1]'), "queued" ) # A slow commit delays the receipt, not the session: on a slow # disk a session waiting here refused everything for 15 s. with app.api(f"/sessions/{session}?view=status") as response: self.assertEqual(response.status, 200) self.assertTrue(prompt.is_alive()) finally: probe.call("release") wait_until(lambda: not ready.exists(), 10, "writer gate did not close") prompt.join(30) self.assertEqual(admitted, [202]) app.idle(session) self.assertTrue( any( part.get("text") == "committed while storage is reading" for part in app.history(session)["items"][-1]["content"] ) ) def test_creations_commit_together_behind_a_slow_commit(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" with Albedo(self.provider, prepare=prepare) as app: probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) app.session() ready = app.home / "writer-ready" created = [] spawns = [ threading.Thread(target=lambda: created.append(app.session())) for _ in range(2) ] try: probe.call("hold_writer", f"[<<{json.dumps(str(ready))}>>]") wait_until(ready.exists, 10, "writer gate never opened") for spawn in spawns: spawn.start() # The registry decides each creation and leaves its commit to # the caller: one slow commit holds neither the registry nor # the creations behind it, which then share one commit. self.assertEqual( probe.call("queued", '[<<"create_identified">>, 2]'), "queued" ) finally: probe.call("release") wait_until(lambda: not ready.exists(), 10, "writer gate did not close") for spawn in spawns: spawn.join(30) self.assertEqual(len(created), 2) for session in created: with app.api(f"/sessions/{session}?view=status") as response: self.assertEqual(response.status, 200) def test_settings_and_event_validation_do_not_wait_on_writer_maintenance(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" with Albedo(self.provider, prepare=prepare) as app: probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) app.session() route = "/settings?group=ui" with app.api(route) as response: tools = json.load(response)["tools"] etag = response.headers["ETag"] ready = app.home / "writer-ready" try: probe.call("hold_writer_tick", f"[<<{json.dumps(str(ready))}>>]") # The registry used to wait on the tick's prune write, and a # successful settings save queried SQLite for a fake session. with app.api( route, {"tools": not tools}, method="PATCH", headers={"If-Match": etag}, ) as response: self.assertEqual( json.load(response)["resource"]["value"]["tools"], not tools ) with self.assertRaises(urllib.error.HTTPError) as refused: app.api("/events") self.assertEqual(refused.exception.code, 400) finally: probe.call("release") wait_until(lambda: not ready.exists(), 10, "writer gate did not close") def test_saving_settings_does_not_need_a_sqlite_reader(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" with Albedo(self.provider, prepare=prepare) as app: probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) route = "/settings?group=ui" with app.api(route) as response: tools = json.load(response)["tools"] etag = response.headers["ETag"] ready = app.home / "readers-ready" try: probe.call("hold_readers", f"[<<{json.dumps(str(ready))}>>]") with app.api( route, {"tools": not tools}, method="PATCH", headers={"If-Match": etag}, ) as response: self.assertEqual( json.load(response)["resource"]["value"]["tools"], not tools ) finally: probe.call("release") wait_until(lambda: not ready.exists(), 10, "readers gate did not close") # exclusive: boots with a storage sync probe loaded @exclusive def test_checkpoint_sync_does_not_hold_the_committing_writer(self): gates = [] def prepare(app): gates.append(StorageSync(app)) with Albedo(self.provider, prepare=prepare) as app: gate = gates[0] probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) session = app.session() committed = app.home / "tiny-write-committed" try: gate.arm("main") probe.call("fill_wal") probe.call("tiny_write", f"[<<{json.dumps(str(committed))}>>]") gate.wait_entered() # This is a real SQLite database sync, not an actor sleep. On # the old writer the one-row INSERT owns this checkpoint. wait_until( committed.exists, 3, "a one-row commit is waiting for the checkpoint's database sync", ) for route in ( f"/sessions/{session}?tail=0", f"/sessions/{session}?view=status", "/sessions?scope=roots", ): with app.api(route) as response: self.assertEqual(response.status, 200) app.prompt(session, "commit while the disk sync is stalled").close() app.idle(session) finally: gate.release() def test_checkpoint_reuses_wal_after_a_reader_releases(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" with Albedo(self.provider, prepare=prepare) as app: probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) app.session() wal = Path(probe.call("wal_path")) def header_salt(): with wal.open("rb") as handle: return handle.read(24)[16:24] ready = app.home / "snapshot-ready" try: probe.call("hold_snapshot", f"[<<{json.dumps(str(ready))}>>]") probe.call("fill_wal") probe.call("grow_wal") before_pulse = wal.stat().st_size probe.call("pulse") pinned_size = wal.stat().st_size pulse_bytes = pinned_size - before_pulse salt = header_salt() finally: probe.call("release") wait_until( lambda: not ready.exists(), 10, "snapshot gate did not close" ) def recycled(): probe.call("pulse") return header_salt() != salt wait_until(recycled, 10, "the released snapshot still pins WAL frames") sizes = [pinned_size] for _ in range(3): salt = header_salt() probe.call("grow_wal") sizes.append(wal.stat().st_size) wait_until(recycled, 10, "periodic checkpoints did not recycle the WAL") self.assertLess(max(sizes), pinned_size + 5_000_000, sizes) print( f"WAL bytes: pinned={pinned_size}, one pulse={pulse_bytes}, " f"reused={sizes[1:]}" ) def test_kernel_capture_survives_a_stalled_host_call_write(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" code = """ from pathlib import Path Path("host-call-armed").touch() while not Path("start-host-call").exists(): await asyncio.sleep(0.01) await work.list() Path("host-call-completed").write_text("done") """ calls = iter([python(code), text("background task armed")]) provider = Provider(lambda _: next(calls)) self.addCleanup(provider.close) with Albedo(provider, prepare=prepare) as app: probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) session = app.session() app.prompt(session, "arm a background host call").close() wait_until( (app.workspace / "host-call-armed").exists, 10, "the kernel never reached the host-call barrier", ) with app.api(f"/sessions/{session}?tail=0") as response: before = json.load(response) kernel = before["kernel"]["instance_id"] ready = app.home / "writer-ready" try: probe.call("hold_writer", f"[<<{json.dumps(str(ready))}>>]") (app.workspace / "start-host-call").touch() self.assertEqual( probe.call("kernel_waiting", f"[<<{json.dumps(kernel)}>>]"), "waiting", ) self.assertEqual( probe.call("idle_report", f"[<<{json.dumps(session)}>>]"), "reported", ) # The owner is durably claiming a host call, not answering its # mailbox. Reads still have its last complete kernel facts. for route in ( f"/sessions/{session}?tail=0", f"/sessions/{session}?view=status", "/sessions?scope=roots", ): with app.api(route) as response: self.assertEqual(response.status, 200) observed = json.load(response) if "kernel" in observed: self.assertEqual(observed["kernel"], before["kernel"]) finally: probe.call("release") wait_until(lambda: not ready.exists(), 10, "writer gate did not close") wait_until( (app.workspace / "host-call-completed").exists, 10, "the durable host call never resumed", ) def test_large_scans_do_not_fill_four_default_sqlite_caches(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" with Albedo(self.provider, prepare=prepare) as app: probe = Inspection( app, ROOT / "test/e2e/albedo_storage_concurrency_probe.erl" ) measured = probe.call_json("reader_cache_growth") self.assertLess(measured["growth"], 1024 * 1024, measured)