"""Compaction identity survives response loss and daemon death without replay.""" import json import sqlite3 import time import threading import unittest import urllib.error from inspect_support import Inspection from harness import Albedo, Provider, exclusive, operation_id, text class CompactionReceiptsTest(unittest.TestCase): def test_failed_compaction_retains_selection_and_same_identity(self): provider = Provider(lambda _: text("answer")) self.addCleanup(provider.close) with Albedo(provider) as app: session = app.session() action = operation_id() intent = {"strategy": "rolling"} result = app.compact(session, intent, action_id=action) self.assertEqual(result["state"], "failed") self.assertTrue(result["selection_applied"]) route = f"/sessions/{session}/compactions/{action}" with app.api(route) as response: original = json.load(response) with app.api(route, intent, method="PUT") as response: self.assertEqual(json.load(response), original) with self.assertRaises(urllib.error.HTTPError) as conflict: app.api(route, {"strategy": "coding-lcm"}, method="PUT") self.assertEqual(conflict.exception.code, 409) self.assertEqual(json.load(conflict.exception)["code"], "id_conflict") with app.api(f"/sessions/{session}/configuration") as response: self.assertTrue( json.load(response)["selection"]["extensions"]["rolling"] ) @exclusive def test_compaction_cap_deletion_and_expired_identity(self): provider = Provider(lambda _: text("answer")) self.addCleanup(provider.close) with Albedo(provider) as app: session = app.session() action = operation_id() route = f"/sessions/{session}/compactions/{action}" intent = {"strategy": "rolling"} # Occupy all slots without starting 64 provider calls. with sqlite3.connect(app.home / "albedo.sqlite") as db: db.executemany( """ INSERT INTO operations(id,fingerprint,kind,target,status,http_status,response,created_at) VALUES(?,'fixture','compaction',?,'accepted',202,'{}',?) """, [ (operation_id(), f"fixture-{index}", int(time.time() * 1000)) for index in range(64) ], ) with self.assertRaises(urllib.error.HTTPError) as full: app.api(route, intent, method="PUT") self.assertEqual(json.load(full.exception)["code"], "session_busy") with sqlite3.connect(app.home / "albedo.sqlite") as db: db.execute("DELETE FROM operations WHERE fingerprint='fixture'") result = app.compact(session, intent, action_id=action) with app.api(f"/sessions/{session}/configuration") as response: etag = response.headers["etag"] app.api( f"/sessions/{session}", method="DELETE", headers={"If-Match": etag} ).close() for method in ("GET", "PUT"): with app.api( route, intent if method == "PUT" else None, method=method ) as response: self.assertEqual(json.load(response)["result"], result) expired = operation_id(int(time.time() * 1000) - 8 * 86400000) for method in ("GET", "PUT"): with self.assertRaises(urllib.error.HTTPError) as gone: app.api( f"/sessions/{session}/compactions/{expired}", intent if method == "PUT" else None, method=method, ) self.assertEqual(json.load(gone.exception)["code"], "identity_expired") @exclusive def test_terminal_write_recovers_after_storage_fault(self): provider = Provider(lambda _: text("answer")) self.addCleanup(provider.close) with Albedo(provider) as app: session = app.session() action = operation_id() route = f"/sessions/{session}/compactions/{action}" with sqlite3.connect(app.home / "albedo.sqlite") as db: db.execute(""" CREATE TRIGGER fail_finish BEFORE UPDATE OF terminal_at ON operations WHEN OLD.kind='compaction' AND NEW.terminal_at IS NOT NULL BEGIN SELECT RAISE(FAIL,'terminal receipt unavailable'); END """) app.api(route, {"strategy": "rolling"}, method="PUT").close() # Wait until selection has been applied and the actor has returned # to idle. A same-ID PUT must still return the running receipt. deadline = time.monotonic() + 15 while True: with app.api(f"/sessions/{session}/configuration") as response: if json.load(response)["selection"]["extensions"].get("rolling"): break self.assertLess(time.monotonic(), deadline) time.sleep(0.05) app.idle(session) with app.api(route) as response: self.assertEqual(json.load(response)["state"], "running") with sqlite3.connect(app.home / "albedo.sqlite") as db: db.execute("DROP TRIGGER fail_finish") result = app.compact(session, {"strategy": "rolling"}, action_id=action) self.assertTrue(result["selection_applied"]) self.assertEqual(result["state"], "failed") @exclusive def test_crashed_compaction_is_interrupted_and_never_replayed(self): self.check_interruption(owner_only=False) @exclusive def test_owner_death_releases_admission_without_an_http_read(self): self.check_interruption(owner_only=True) def check_interruption(self, *, owner_only): entered = threading.Event() release = threading.Event() compacting = threading.Event() calls = [] def reply(request): calls.append(request) if compacting.is_set(): entered.set() if not release.wait(30): raise AssertionError("compaction provider was not released") return text("summary") provider = Provider(reply) self.addCleanup(provider.close) self.addCleanup(release.set) with Albedo( provider, prepare=lambda app: app.env.update(ALBEDO_INSPECT="1") ) as app: session = app.session() for prompt in ("older one", "older two", "newest"): app.prompt(session, prompt + " " + "x" * 6000).close() app.idle(session) action = operation_id() route = f"/sessions/{session}/compactions/{action}" intent = {"strategy": "coding-lcm"} compacting.set() # Discard the admission response, then recover by the same identity. app.api(route, intent, method="PUT").close() self.assertTrue(entered.wait(15), "compaction did not reach provider") with app.api(route) as response: running = json.load(response) self.assertEqual(running["state"], "running") with app.api(route, intent, method="PUT") as response: self.assertEqual(json.load(response), running) with self.assertRaises(urllib.error.HTTPError) as busy: app.api( f"/sessions/{session}/compactions/{operation_id()}", intent, method="PUT", ).close() self.assertEqual(busy.exception.code, 409) busy.exception.close() count = len(calls) if owner_only: probe = Inspection(app) probe.evaluate( f"""{{some, {{subject, Pid, _}}}} = Call('albedo@session', live, [<<"{session}">>]), """ "true = Call(erlang, exit, [Pid, kill])" ) deadline = time.monotonic() + 10 with sqlite3.connect(app.home / "albedo.sqlite") as db: while ( db.execute( "SELECT terminal_at FROM operations WHERE id=?", (action,) ).fetchone()[0] is None ): self.assertLess(time.monotonic(), deadline) time.sleep(0.05) else: app.restart(crash=True) release.set() with app.api(route) as response: interrupted = json.load(response) self.assertEqual(interrupted["state"], "interrupted") self.assertIsNone(interrupted["result"]) with app.api(route, intent, method="PUT") as response: self.assertEqual(json.load(response), interrupted) app.idle(session) self.assertEqual(len(calls), count) with app.api(f"/sessions/{session}/history") as response: self.assertTrue(json.load(response)["items"])