"""Transient transport loss and a lost release receipt never strand the coordinator.""" import http.client from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[1] @pytest.fixture def preparer(monkeypatch): monkeypatch.syspath_prepend(str(ROOT / "simulation/ai-polygon")) import infrastructure_preparer monkeypatch.setattr(infrastructure_preparer.time, "sleep", lambda seconds: None) return infrastructure_preparer @pytest.mark.parametrize( "error", [ConnectionAbortedError, http.client.RemoteDisconnected, TimeoutError] ) def test_indefinite_transport_loss_is_not_calculation_failure(preparer, error): calls = [] class Client: def request(self, endpoint, body): calls.append((endpoint, body)) raise error() phase = dict(phase="survey", completed=1, total=90) for _ in range(100): assert preparer.report_progress(Client(), "/job", phase) is None assert calls == [("/job", dict(action="progress", **phase))] * 100 @pytest.mark.parametrize("status", [400, 401, 403, 409]) def test_confirmed_rejection_still_stops_calculation(preparer, status): from core_client import CoreRequestRejected calls = [] class Client: def request(self, *args): calls.append(args) raise CoreRequestRejected(status, "cancelled or invalid owner") with pytest.raises(CoreRequestRejected): preparer.report_progress(Client(), "/job", dict(phase="survey", completed=1, total=90)) assert len(calls) == 1 @pytest.mark.parametrize("status", [500, 502, 503, 504]) def test_temporary_gateway_outage_keeps_calculation(preparer, status): from core_client import CoreRequestRejected class Client: def request(self, *args): raise CoreRequestRejected(status, "upstream unavailable") assert ( preparer.report_progress(Client(), "/job", dict(phase="survey", completed=1, total=90)) is None ) def test_core_restart_recovers_registration_without_reclaim(preparer): from core_client import CoreRequestRejected from infrastructure_transport import EXPIRED_SESSION calls = [] class Client: instance = "same-owner" def request(self, endpoint, body): calls.append((endpoint, body)) if len(calls) == 1: raise CoreRequestRejected(409, EXPIRED_SESSION) return {"ok": True} phase = dict(phase="survey", completed=8, total=90) hello = dict(instance_id="same-owner", immutable_provider="same-provider") assert preparer.report_progress(Client(), "/job", phase, hello=hello) == {"ok": True} assert calls == [ ("/job", dict(action="progress", **phase)), ("/worker/register", hello), ("/job", dict(action="progress", **phase)), ] @pytest.mark.parametrize("failure", ["transport", "cleanup"]) def test_failed_receipt_keeps_marker_until_reconnect_and_cleanup( preparer, monkeypatch, tmp_path, failure ): events = [] class Client: instance = "worker" online = False def request(self, path, body=None, **kwargs): action = body.get("action") if body else "source" events.append(action) if action in ("fail", "release") and not self.online: raise ConnectionAbortedError() return {} client = Client() profile = dict(job_root=str(tmp_path / "jobs"), minimum_free_gib=0, maximum_seconds=60) read = preparer.read_json monkeypatch.setattr( preparer, "read_json", lambda p: profile if str(p).endswith("worker-profile.json") else read(p), ) monkeypatch.setattr(preparer, "provider_identity", lambda: "d" * 64) def source(*args, **kwargs): raise ValueError("Invalid source") def cleanup(marker): events.append("cleanup") if failure == "cleanup" and not client.online: raise RuntimeError("Docker unavailable; cannot prove release") monkeypatch.setattr(preparer, "prepare_native", source) monkeypatch.setattr(preparer, "cleanup", cleanup) row = dict( key="a" * 64, identity=dict(provider_sha256="d" * 64), world=dict(world_id="example") ) marker = tmp_path / "active.json" # The coordinator must regain control even when fail AND release fail. preparer.prepare_infrastructure(client, row, tmp_path / "state", marker) assert marker.exists() assert not list(tmp_path.rglob("urban-map.json")) if failure == "cleanup": assert "release" not in events client.online = True preparer.reconcile(client, marker) assert events[-2:] == ["cleanup", "release"] assert not marker.exists() # Idempotent retry after acknowledgement cannot release a different job. count = len(events) preparer.reconcile(client, marker) assert len(events) == count def outbox(preparer, monkeypatch, tmp_path): profile = dict(job_root=str(tmp_path), maximum_seconds=60) read = preparer.read_json monkeypatch.setattr( preparer, "read_json", lambda p: profile if str(p).endswith("worker-profile.json") else read(p), ) key = "a" * 64 output = tmp_path / key output.mkdir() preparer.write_json(output / "urban-map.json", {"features": [], "verified": "fixture"}) marker = tmp_path / "active.json" preparer.write_json( marker, dict( key=key, owner="worker", containers=[], completion=dict(sha256=preparer.checksum(output / "urban-map.json")), ), ) return marker, output @pytest.mark.parametrize("lost_ack", [False, True]) def test_result_outbox_survives_outage_and_lost_ack(preparer, monkeypatch, tmp_path, lost_ack): marker, output = outbox(preparer, monkeypatch, tmp_path) events, maps = [], [] class Client: instance = "worker" online = False def request(self, path, body): events.append(body["action"]) if body["action"] == "complete": if self.online or lost_ack: if maps: assert maps[0] == body["map"] else: maps.append(body["map"]) if not self.online: raise ConnectionResetError() return {"ok": True} client = Client() for _ in range(4): with pytest.raises(ConnectionResetError): preparer.reconcile(client, marker) assert marker.exists() and preparer.read_json(marker)["completion"] assert "release" not in events client.online = True preparer.reconcile(client, marker) assert events[-2:] == ["complete", "release"] and len(maps) == 1 assert not marker.exists() and (output / "urban-map.json").exists() def test_cancel_while_result_offline_rejects_publication_then_releases( preparer, monkeypatch, tmp_path ): from core_client import CoreRequestRejected marker, output = outbox(preparer, monkeypatch, tmp_path) events = [] class Client: def request(self, path, body): events.append(body["action"]) if body["action"] == "complete": raise CoreRequestRejected(409, "Analysis cancellation requested") return {} preparer.reconcile(Client(), marker) assert events == ["complete", "release"] and not marker.exists() assert (output / "publication-rejection.json").exists() def test_pending_result_tamper_keeps_queue_barrier(preparer, monkeypatch, tmp_path): marker, output = outbox(preparer, monkeypatch, tmp_path) (output / "urban-map.json").write_text("{}") with pytest.raises(ValueError, match="result changed"): preparer.reconcile(object(), marker) assert marker.exists() def test_source_read_retries_transport_only(preparer): calls = [] class Client: def request(self, path, **kwargs): calls.append(path) if len(calls) < 5: raise ConnectionResetError() return {"source": "verified"} assert preparer.source_package(Client(), "/source", lambda: None, float("inf")) == { "source": "verified" } assert len(calls) == 5