"""Durable outbox/inbox boundaries, including crash and acknowledgement replay.""" import copy import importlib.util import json from pathlib import Path import pytest from test_semantic_edits import change, make_setup from k1link.simulation.ai_polygon.semantic_edits import SemanticEdits, digest spec = importlib.util.spec_from_file_location( "dataset_store", Path(__file__).parents[1] / "simulation/semantic-learning/dataset_store.py" ) ds = importlib.util.module_from_spec(spec) spec.loader.exec_module(ds) def fixture(tmp_path): world, model, maps, edits, sha = make_setup(tmp_path / "core") world["world_id"] = "aiworld-fixture" body = change(sha) body["origin"] = "agent-proposal" saved = edits.save(world, body) envelope = dict( world=world, source={"world_sha256": world["sha256"]}, annotation=edits.export(world, saved["revision"]), ) return world, edits, maps, saved, envelope def test_outbox_commit_and_receipt_replay(tmp_path): world, edits, maps, saved, env = fixture(tmp_path) edits = SemanticEdits(edits.root.parents[1], maps) assert edits.pending([world])[0]["revision"] == saved["revision"] assert saved["edited"]["features"][0]["properties"]["annotation_origin"] == "agent-proposal" worker = ds.Store(tmp_path / "worker", reserve=0) key = worker.accept(env) worker.db.close() # Received data survives process loss before HTTP ack. worker = ds.Store(tmp_path / "worker", reserve=0) assert worker.accept(env) == key assert worker.db.execute("SELECT count(*) FROM jobs").fetchone()[0] == 1 receipt = json.loads(worker.db.execute("SELECT receipt FROM jobs").fetchone()[0]) assert edits.receipt(world, key, receipt) == receipt assert edits.receipt(world, key, receipt) == receipt assert edits.pending([world]) == [] assert edits.get(world)["learning"]["state"] == "received" newer = {**receipt, "state": "building"} edits.receipt(world, key, newer) assert edits.receipt(world, key, receipt) == newer altered = {**receipt, "package_sha256": "0" * 64} with pytest.raises(ValueError): edits.receipt(world, key, altered) assert edits.export(world, key) == env["annotation"] def test_inbox_conflict_capacity_and_orphan_replay(tmp_path): _, _, _, saved, env = fixture(tmp_path) worker = ds.Store(tmp_path / "worker", reserve=0) key = saved["revision"] ds.write(worker.root / "inbox" / (key + ".json"), env) # crash before SQL commit worker.accept(env) changed = copy.deepcopy(env) changed["annotation"]["package"]["review"]["state"] = "fake-approved" with pytest.raises(ValueError): worker.accept(changed) changed["annotation"]["sha256"] = digest(changed["annotation"]["package"]) with pytest.raises(ValueError): worker.accept(changed) full = ds.Store(tmp_path / "full", reserve=0, quota=1) with pytest.raises(RuntimeError): full.accept(env) assert full.db.execute("SELECT count(*) FROM jobs").fetchone()[0] == 0 def draft(root): root.mkdir() ds.write(root / "labels.json", {"review": "unreviewed"}) ds.write( root / "sample.json", {"members": ["labels.json"], "training_eligible": False, "complete_regions": []}, ) files = {p.name: {"sha256": ds.checksum(p), "bytes": p.stat().st_size} for p in root.iterdir()} ds.write( root / "dataset.json", { "schema_version": ds.SCHEMA, "training_eligible": False, "files": files, "samples": ["sample.json"], }, ) def test_atomic_publication_restart_portability_and_corruption(tmp_path): _, _, _, _, env = fixture(tmp_path) worker = ds.Store(tmp_path / "worker", reserve=0) key = worker.accept(env) assert worker.next() == key staging = worker.root / "work" / "draft" draft(staging) expected = ds.verify(staging) # Crash after atomic publication but before state commit. staging.rename(worker.root / "datasets" / key) worker.db.close() worker = ds.Store(worker.root, reserve=0) assert worker.next() is None receipt = json.loads(worker.db.execute("SELECT receipt FROM jobs").fetchone()[0]) assert receipt["dataset_sha256"] == expected["sha256"] import shutil elsewhere = tmp_path / "unrelated-root" shutil.copytree(worker.root / "datasets" / key, elsewhere) assert ds.verify(elsewhere) == expected (elsewhere / "labels.json").write_text("{}") with pytest.raises(ValueError): ds.verify(elsewhere) def test_retry_bound_and_next_job_not_starved(tmp_path): _, _, _, _, env = fixture(tmp_path) worker = ds.Store(tmp_path / "worker", reserve=0) key = worker.accept(env) for _ in range(3): assert worker.next() == key assert worker.next() is None assert worker.db.execute("SELECT state FROM jobs").fetchone()[0] == "failed" assert not ds.confined(worker.root, "labels.json").exists() for bad in ("../outside", "/absolute", "C:/data", "a\\b"): with pytest.raises(ValueError): ds.confined(worker.root, bad) def test_failed_job_does_not_block_next_and_published_corruption_is_preserved(tmp_path): _, _, _, _, first = fixture(tmp_path / "first") _, _, _, _, second = fixture(tmp_path / "second") worker = ds.Store(tmp_path / "worker", reserve=0) a, b = worker.accept(first), worker.accept(second) assert worker.next() == a target = worker.root / "datasets" / a draft(target) (target / "labels.json").write_text("corrupted") assert worker.next() is None assert worker.db.execute("SELECT state FROM jobs WHERE id=?", (a,)).fetchone()[0] == "failed" assert (target / "labels.json").read_text() == "corrupted" assert worker.next() == b def test_complete_collection_receipt_keeps_identity_and_terminal_invariants(tmp_path): world, edits, _, saved, env = fixture(tmp_path) receipt = dict( state="draft-ready", package_sha256=env["annotation"]["sha256"], dataset_sha256="c" * 64, sample_count=213, ) for count in [-1, 0, True, 213.0, 1025]: with pytest.raises(ValueError): edits.receipt(world, saved["revision"], {**receipt, "sample_count": count}) with pytest.raises(ValueError): edits.receipt(world, saved["revision"], {**receipt, "package_sha256": "d" * 64}) with pytest.raises(ValueError): edits.receipt(world, saved["revision"], {**receipt, "dataset_sha256": None}) assert edits.receipt(world, saved["revision"], receipt) == receipt assert edits.receipt(world, saved["revision"], receipt) == receipt assert edits.get(world)["learning"]["state"] == "draft-ready" with pytest.raises(RuntimeError): edits.receipt(world, saved["revision"], {**receipt, "sample_count": 212}) def test_research_and_dataset_budgets_are_separate_and_bounded(tmp_path): worker = ds.Store(tmp_path / "worker", quota=65536, reserve=0, research_quota=1024) (worker.root / "experiments").mkdir() (worker.root / "experiments/history.bin").write_bytes(b"x" * 1024) worker.capacity(0) (worker.root / "experiments/history.bin").write_bytes(b"x" * 1025) with pytest.raises(RuntimeError, match="research storage"): worker.capacity(0) (worker.root / "experiments/history.bin").unlink() (worker.root / "unknown-new-directory").mkdir() (worker.root / "unknown-new-directory/data.bin").write_bytes(b"x" * 65536) with pytest.raises(RuntimeError, match="learning storage"): worker.capacity(0) worker.db.close()