Spaces:
Runtime error
Runtime error
Download api/ai-service/tests/test_route_library_postgres.py from tkadkghdlf/CD: direct link, hf CLI and curl.
- Browser
- Download file 38.6 kB
-
https://huggingface.co/spaces/tkadkghdlf/CD/resolve/main/api/ai-service/tests/test_route_library_postgres.py
- Command line
-
hf download hf://spaces/tkadkghdlf/CD/api/ai-service/tests/test_route_library_postgres.py
-
curl -L -o test_route_library_postgres.py https://huggingface.co/spaces/tkadkghdlf/CD/resolve/main/api/ai-service/tests/test_route_library_postgres.py
38.6 kB
| """Synthetic-only integration tests. Never fall back to an application DB URL.""" | |
| from concurrent.futures import ThreadPoolExecutor | |
| import base64 | |
| import hashlib | |
| import importlib.util | |
| import json | |
| import math | |
| import os | |
| from pathlib import Path | |
| import sqlite3 | |
| import subprocess | |
| import sys | |
| import urllib.error | |
| from urllib.parse import urlsplit | |
| import uuid | |
| import pytest | |
| SERVICE = Path(__file__).resolve().parents[1] | |
| ROOT = SERVICE.parents[1] | |
| sys.path.insert(0, str(SERVICE)) | |
| from app.api.v1.endpoints import route_library as api | |
| from app.services import route_library_store as store | |
| from app.services.art_route_ingest import SOURCE, IngestError, content_sha, sha | |
| def load_file(name, path): | |
| spec = importlib.util.spec_from_file_location(name, path) | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| return module | |
| def database(): | |
| dsn = os.environ.get("TEST_ROUTE_LIBRARY_DATABASE_URL") | |
| if not dsn: | |
| pytest.skip("Set the dedicated isolated PostgreSQL test URL") | |
| import psycopg | |
| from psycopg.conninfo import conninfo_to_dict | |
| from sqlalchemy import create_engine | |
| from sqlalchemy.engine import make_url | |
| from alembic.migration import MigrationContext | |
| from alembic.operations import Operations | |
| info = conninfo_to_dict(dsn) | |
| assert info.get("dbname", "").startswith("route_library_test"), "Refusing a non-test database" | |
| assert info.get("host", "") in {"localhost", "127.0.0.1", "::1"} or info.get("host", "").startswith("/"), "Refusing a remote database" | |
| url = make_url(dsn).set(drivername="postgresql+psycopg") | |
| engine = create_engine(url) | |
| migration_dir = ROOT / "api/auth-service/alembic/versions" | |
| original = load_file("art_original_migration", migration_dir / "0013_create_art_routing_tables.py") | |
| migration = load_file("art_link_migration", migration_dir / "0014_link_lab_art_routes.py") | |
| with engine.begin() as conn: | |
| conn.exec_driver_sql("DROP TABLE IF EXISTS lab_route_sync_sessions,lab_route_sync_state,art_route_candidates,art_templates,lab_route_library CASCADE") | |
| with Operations.context(MigrationContext.configure(conn)): | |
| original.upgrade() | |
| migration.upgrade() | |
| yield dsn, engine, migration | |
| engine.dispose() | |
| def client(database, monkeypatch): | |
| import psycopg | |
| from fastapi import FastAPI | |
| from fastapi.testclient import TestClient | |
| dsn, _, _ = database | |
| with psycopg.connect(dsn) as conn: | |
| conn.execute("TRUNCATE lab_route_sync_sessions,lab_route_sync_state,art_route_candidates,art_templates,lab_route_library CASCADE") | |
| key = "synthetic-" + uuid.uuid4().hex | |
| monkeypatch.setenv("ROUTE_LIBRARY_DATABASE_URL", dsn) | |
| monkeypatch.setenv("ART_ROUTE_CATALOG_DATABASE_URL", dsn) | |
| monkeypatch.delenv("ART_ROUTE_CATALOG_JSON", raising=False) | |
| monkeypatch.setenv("ROUTE_LIBRARY_TOKEN", key) | |
| monkeypatch.setattr(api.settings, "ai_workspace_dir", str(ROOT / "router/ai")) | |
| api._invalidate_cache() | |
| app = FastAPI() | |
| app.include_router(api.router, prefix="/api/v1") | |
| with TestClient(app) as instance: | |
| instance.headers["Authorization"] = "Bearer " + key | |
| yield instance | |
| BASE = "/api/v1/ai/internal/route-library" | |
| def route_id(name): | |
| return hashlib.sha256(name.encode()).hexdigest() | |
| def test_authenticated_storage_verification_hides_original_coordinates(client, database): | |
| source_id, packet, _ = fixture_packet('storage-proof') | |
| session, _ = begin(client, {source_id: packet}, mode='partial') | |
| receipt = put(client, source_id, packet, session).json() | |
| response = client.get(BASE + '/routes/' + source_id + '/storage') | |
| assert response.status_code == 200 | |
| proof = response.json() | |
| assert proof['verified'] and proof['coordinates_match_gpx'] and all(proof['tables'].values()) | |
| assert proof['art_template_id'] == receipt['art_template_id'] | |
| assert proof['art_route_candidate_id'] == receipt['art_route_candidate_id'] | |
| assert proof['design_ai_status'] == 'ai_reject' | |
| assert 'coordinates' not in proof and 'gpx' not in proof and 'outline' not in proof | |
| assert client.get(BASE + '/routes/' + source_id + '/storage', headers={'Authorization': 'Bearer wrong'}).status_code == 401 | |
| def legacy_put(client, name): | |
| source_id, packet, _ = fixture_packet(name) | |
| legacy = {key: packet[key] for key in api.RouteImport.model_fields if key in packet} | |
| legacy['contract_version'] = 1 | |
| assert client.put(BASE + '/routes/' + source_id, json=legacy).status_code == 200 | |
| return source_id | |
| def test_private_inventory_lists_actual_links_without_geometry(client, database): | |
| legacy_id = legacy_put(client, 'legacy-inventory') | |
| source_id, packet, _ = fixture_packet('inventory-v2') | |
| session, _ = begin(client, {source_id: packet}) | |
| receipt = put(client, source_id, packet, session).json() | |
| response = client.get(BASE + '/inventory') | |
| assert response.status_code == 200 | |
| value = response.json() | |
| rows = {r['source_id']: r for r in value['rows']} | |
| assert value['count'] == len(rows) == 2 | |
| assert rows[source_id]['projection_complete'] is True | |
| assert rows[source_id]['art_template_id'] == receipt['art_template_id'] | |
| assert rows[source_id]['art_route_candidate_id'] == receipt['art_route_candidate_id'] | |
| assert rows[legacy_id]['projection_complete'] is False and rows[legacy_id]['library_active'] | |
| assert rows[legacy_id]['art_route_candidate_id'] is None | |
| assert all(not ({'coordinates', 'gpx', 'outline', 'snapshot'} & set(r)) for r in rows.values()) | |
| assert client.get(BASE + '/inventory', headers={'Authorization': 'Bearer wrong'}).status_code == 401 | |
| def test_snapshot_expectations_reject_unapproved_changes_atomically(client, database, failure): | |
| legacy_id = legacy_put(client, 'retired-legacy') | |
| source_id, packet, _ = fixture_packet('approved-new') | |
| session, _ = begin(client, {source_id: packet}) | |
| assert put(client, source_id, packet, session).status_code == 200 | |
| state = client.get(BASE + '/sync-state').json() | |
| payload = {'contract_version': 2, 'session_id': session['session_id'], 'generation': session['generation'], | |
| 'manifest_sha256': session['manifest_sha256'], 'ids': [source_id], 'count': 1, | |
| 'ids_sha256': hashlib.sha256(source_id.encode()).hexdigest(), | |
| 'expected_catalog_revision': state['catalog_revision'], 'expected_deactivation_ids': [legacy_id]} | |
| if failure == 'ids': payload['expected_deactivation_ids'] = [] | |
| if failure == 'revision': payload['expected_catalog_revision'] += 1 | |
| if failure == 'incomplete': payload.pop('expected_catalog_revision') | |
| if failure == 'duplicates': payload['expected_deactivation_ids'] = [legacy_id, legacy_id] | |
| response = client.post(BASE + '/approval-snapshot', json=payload) | |
| assert response.status_code in {409, 422} | |
| assert all(row['active'] for row in query(database, 'SELECT active FROM lab_route_library')) | |
| assert client.get(BASE + '/sync-sessions/' + session['session_id']).json()['session_status'] == 'open' | |
| payload.update(expected_catalog_revision=state['catalog_revision'], expected_deactivation_ids=[legacy_id]) | |
| response = client.post(BASE + '/approval-snapshot', json=payload) | |
| assert response.status_code == 200 and response.json()['deactivated_count'] == 1 | |
| def test_full_session_reuses_confirmed_storage_without_reupload(client, database): | |
| old_id, old_packet, _ = fixture_packet('already-confirmed') | |
| first, _ = begin(client, {old_id: old_packet}, mode='partial') | |
| old_receipt = put(client, old_id, old_packet, first).json() | |
| assert client.post(BASE + '/sync-sessions/' + first['session_id'] + '/complete', | |
| params={'generation': first['generation']}, json={}).status_code == 200 | |
| before = query(database, 'SELECT updated_at FROM lab_route_library WHERE source_id=%s', (old_id,))[0] | |
| new_id, new_packet, _ = fixture_packet('pending') | |
| session, _ = begin(client, {old_id: old_packet, new_id: new_packet}) | |
| assert put(client, new_id, new_packet, session).status_code == 200 | |
| assert finish(client, session, {old_id: old_packet, new_id: new_packet}).status_code == 200 | |
| assert query(database, 'SELECT updated_at FROM lab_route_library WHERE source_id=%s', (old_id,))[0] == before | |
| rows = {r['source_id']: r for r in client.get(BASE + '/inventory').json()['rows']} | |
| assert rows[old_id]['art_route_candidate_id'] == old_receipt['art_route_candidate_id'] | |
| assert len(rows) == 2 and all(r['projection_complete'] for r in rows.values()) | |
| def test_deployment_status_requires_live_revision_and_server_preflight(client, database, tmp_path, monkeypatch): | |
| report = tmp_path / 'report.json' | |
| provenance = tmp_path / 'source.json' | |
| monkeypatch.setattr(api, 'DEPLOYMENT_REPORT_PATH', report) | |
| monkeypatch.setattr(api, 'DEPLOYMENT_SOURCE_PATH', provenance) | |
| assert client.get(BASE + '/deployment-status').status_code == 503 | |
| report.write_text(json.dumps({'ready': True, 'same_database': True, 'catalog_uses_database': True, 'existing_rows_preserved': True})) | |
| provenance.write_text(json.dumps({'github_sha': 'a' * 40})) | |
| with database[1].begin() as connection: | |
| connection.exec_driver_sql('CREATE TABLE IF NOT EXISTS alembic_version(version_num varchar(128) PRIMARY KEY)') | |
| connection.exec_driver_sql('DELETE FROM alembic_version') | |
| connection.exec_driver_sql("INSERT INTO alembic_version VALUES ('0014_link_lab_art_routes')") | |
| response = client.get(BASE + '/deployment-status') | |
| assert response.status_code == 200 and response.json()['ready'] | |
| assert response.json()['same_database'] and all(response.json()['tables'].values()) | |
| def fixture_packet(name="one", design_status="ai_reject", design_variant=0): | |
| points = [[37.5 + .003 * math.sin(i * math.tau / 40), 127.0 + .003 * math.cos(i * math.tau / 40)] for i in range(40)] | |
| points.append(points[0]) | |
| raw = ('<gpx><trk><trkseg>' + ''.join(f'<trkpt lat="{a}" lon="{b}"/>' for a, b in points) + '</trkseg></trk></gpx>').encode() | |
| evidence = {"protocol": "synthetic-v1", "status": "ai_pass", "expected_label": "dog", "blind": True, | |
| "qwen_performed": True, "siglip_support_angles": [0], "siglip_views": [{"top_label": "dog"}], | |
| "qwen": [{"valid": True, "object": "dog", "clarity": 3}]} | |
| snapshot = {"design_id": "synthetic_dog", "version": "1", "name": "Synthetic dog", | |
| "outline": {"coordinate_system": "cartesian_y_up"}, | |
| "points": [[0, 0], [1, 0], [1, 1], [.5 + design_variant * .01, 1.2], [0, 1]]} | |
| packet = {"contract_version": 2, "label": "dog", "region_code": "synthetic", "region_name": "Synthetic", | |
| "sha256": hashlib.sha256(raw).hexdigest(), "accepted_at": "2026-11-09T00:00:00+00:00", "review_status": "ai_pass", | |
| "ai_protocol": "synthetic-v1", "geometry_ok": True, "seoul_ok": True, "collection_finalized": False, | |
| "gpx_base64": base64.b64encode(raw).decode(), | |
| "template": {"design_id": snapshot["design_id"], "source_version": "1", "design_digest": sha(snapshot), | |
| "snapshot": snapshot, "design_ai_status": design_status, | |
| "design_ai_evidence": evidence if design_status == "ai_pass" else {"status": design_status}}, | |
| "route_ai_evidence": evidence, "road_verification": {"road_only": True, "graph_connectivity_verified": True, | |
| "access_checked": True, "directions_checked": True, "air_length_m": 0, "field_access_verified": False}, | |
| "graph_sha256": "b" * 64, "distance_m": 2000, "validator_version": "synthetic-v1"} | |
| return route_id(name), packet, points | |
| def begin(client, packets, mode="full", request_id=None): | |
| current = client.get(BASE + "/sync-state").json() | |
| manifest = {source_id: content_sha(packet) for source_id, packet in packets.items()} | |
| body = {"client_request_id": request_id or str(uuid.uuid4()), "expected_generation": current["generation"], | |
| "mode": mode, "manifest": manifest, "manifest_sha256": sha(manifest)} | |
| response = client.post(BASE + "/sync-sessions", json=body) | |
| assert response.status_code == 200, "Session start failed" | |
| return response.json(), body | |
| def put(client, source_id, packet, session, **actions): | |
| body = {**packet, "session_id": session["session_id"], "generation": session["generation"], | |
| "payload_sha256": content_sha(packet), **actions} | |
| return client.put(BASE + "/routes/" + source_id, json=body) | |
| def finish(client, session, packets): | |
| ids = sorted(packets) | |
| return client.post(BASE + "/approval-snapshot", json={"contract_version": 2, "session_id": session["session_id"], | |
| "generation": session["generation"], "manifest_sha256": session["manifest_sha256"], "ids": ids, "count": len(ids), | |
| "ids_sha256": hashlib.sha256("\n".join(ids).encode()).hexdigest(), "collection_finalized": False}) | |
| def query(database, sql, parameters=()): | |
| import psycopg | |
| from psycopg.rows import dict_row | |
| with psycopg.connect(database[0], row_factory=dict_row) as conn: | |
| return conn.execute(sql, parameters).fetchall() | |
| def test_atomic_ids_gpx_and_independent_design_review(client, database): | |
| source_id, packet, points = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| response = put(client, source_id, packet, session) | |
| assert response.status_code == 200 | |
| receipt = response.json() | |
| assert receipt["design_ai_status"] == "ai_reject" | |
| assert receipt["route_validation_status"] == "passed" | |
| template = query(database, "SELECT * FROM art_templates")[0] | |
| candidate = query(database, "SELECT * FROM art_route_candidates")[0] | |
| library = query(database, "SELECT * FROM lab_route_library")[0] | |
| assert str(template["id"]) == receipt["art_template_id"] | |
| assert str(candidate["id"]) == receipt["art_route_candidate_id"] | |
| assert candidate["template_id"] == template["id"] | |
| assert candidate["coordinates"] == points | |
| assert candidate["coordinate_crs"] == "EPSG:4326" and candidate["coordinate_order"] == "latlon" | |
| assert candidate["coordinates"] != library["outline"] | |
| assert template["design_ai_status"] == "ai_reject" and candidate["route_ai_status"] == "ai_pass" | |
| assert finish(client, session, {source_id: packet}).status_code == 200 | |
| def test_retransmission_is_a_real_noop_and_receipts_survive_completion(client, database): | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| first = put(client, source_id, packet, session).json() | |
| before = query(database, "SELECT updated_at FROM lab_route_library")[0] | |
| second = put(client, source_id, packet, session).json() | |
| assert second["result"] == "unchanged" | |
| assert first["art_template_id"] == second["art_template_id"] | |
| assert first["art_route_candidate_id"] == second["art_route_candidate_id"] | |
| assert query(database, "SELECT updated_at FROM lab_route_library")[0] == before | |
| assert finish(client, session, {source_id: packet}).status_code == 200 | |
| assert put(client, source_id, packet, session).json()["result"] == "unchanged" | |
| assert finish(client, session, {source_id: packet}).json()["deactivated_count"] == 0 | |
| def test_concurrent_same_route_has_one_identity(client, database): | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| with ThreadPoolExecutor(max_workers=2) as pool: | |
| responses = list(pool.map(lambda _: put(client, source_id, packet, session), range(2))) | |
| assert [r.status_code for r in responses] == [200, 200] | |
| assert len({r.json()["art_route_candidate_id"] for r in responses}) == 1 | |
| for table in ["art_templates", "lab_route_library", "art_route_candidates"]: | |
| assert query(database, "SELECT count(*) AS n FROM " + table)[0]["n"] == 1 | |
| def test_failures_rollback_all_three_tables(client, database, monkeypatch, function): | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| original = getattr(store, function) | |
| def fail(*args, **kwargs): | |
| original(*args, **kwargs) | |
| raise IngestError("synthetic_failure", 503) | |
| monkeypatch.setattr(store, function, fail) | |
| assert put(client, source_id, packet, session).status_code == 503 | |
| for table in ["art_templates", "lab_route_library", "art_route_candidates"]: | |
| assert query(database, "SELECT count(*) AS n FROM " + table)[0]["n"] == 0 | |
| assert query(database, "SELECT catalog_revision FROM lab_route_sync_state")[0]["catalog_revision"] == 0 | |
| def test_changed_route_requires_compare_and_swap(client, database): | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| first = put(client, source_id, packet, session).json() | |
| changed = {**packet, "distance_m": packet["distance_m"] + 1} | |
| newer, _ = begin(client, {source_id: changed}) | |
| assert put(client, source_id, changed, newer).status_code == 409 | |
| assert query(database, "SELECT distance_m FROM art_route_candidates")[0]["distance_m"] == packet["distance_m"] | |
| response = put(client, source_id, changed, newer, previous_payload_sha256=content_sha(packet)) | |
| assert response.status_code == 200 | |
| assert response.json()["art_route_candidate_id"] == first["art_route_candidate_id"] | |
| assert response.json()["result"] == "updated" | |
| def test_same_source_design_version_different_digest_is_not_overwritten(client, database): | |
| a, one, _ = fixture_packet("one") | |
| b, two, _ = fixture_packet("two", design_variant=1) | |
| session, _ = begin(client, {a: one, b: two}) | |
| assert put(client, a, one, session).status_code == put(client, b, two, session).status_code == 200 | |
| templates = query(database, "SELECT id,version,source_design_version FROM art_templates") | |
| assert len(templates) == 2 and len({t["version"] for t in templates}) == 2 | |
| assert all(t["source_design_version"] == "1" for t in templates) | |
| def test_revocation_fences_old_requests_and_requires_explicit_new_approval(client, database): | |
| a, one, _ = fixture_packet("one") | |
| b, two, _ = fixture_packet("two") | |
| session, _ = begin(client, {a: one, b: two}) | |
| assert put(client, a, one, session).status_code == put(client, b, two, session).status_code == 200 | |
| assert finish(client, session, {a: one, b: two}).status_code == 200 | |
| newer, _ = begin(client, {a: one}) | |
| assert finish(client, newer, {a: one}).json()["deactivated_count"] == 1 | |
| assert not query(database, "SELECT active FROM lab_route_library WHERE source_id=%s", (b,))[0]["active"] | |
| assert not query(database, "SELECT active FROM art_route_candidates WHERE source_id=%s", (b,))[0]["active"] | |
| assert query(database, "SELECT count(*) AS n FROM art_templates")[0]["n"] == 1 | |
| assert put(client, b, two, session).status_code == 409 | |
| retry, _ = begin(client, {b: two}, "partial") | |
| assert put(client, b, two, retry).status_code == 409 | |
| assert put(client, b, two, retry, reapprove=True).status_code == 409 | |
| reapproved = {**two, "accepted_at": "2026-11-10T00:00:00+00:00"} | |
| latest, _ = begin(client, {b: reapproved}, "partial") | |
| assert put(client, b, reapproved, latest, reapprove=True, previous_payload_sha256=content_sha(two)).status_code == 200 | |
| def test_incomplete_and_partial_snapshots_cannot_revoke(client, database): | |
| a, one, _ = fixture_packet("one") | |
| b, two, _ = fixture_packet("two") | |
| session, _ = begin(client, {a: one, b: two}) | |
| assert put(client, a, one, session).status_code == 200 | |
| assert finish(client, session, {a: one, b: two}).status_code == 409 | |
| partial, _ = begin(client, {b: two}, "partial") | |
| assert put(client, b, two, partial).status_code == 200 | |
| assert finish(client, partial, {b: two}).status_code == 409 | |
| complete = client.post(BASE + "/sync-sessions/" + partial["session_id"] + "/complete", params={"generation": partial["generation"]}) | |
| assert complete.status_code == 200 and complete.json()["deactivated_count"] == 0 | |
| assert query(database, "SELECT count(*) AS n FROM lab_route_library WHERE active")[0]["n"] == 2 | |
| def test_session_begin_is_idempotent_and_cannot_replay_after_new_generation(client): | |
| source_id, packet, _ = fixture_packet() | |
| session, body = begin(client, {source_id: packet}) | |
| assert client.post(BASE + "/sync-sessions", json=body).json() == session | |
| newer, _ = begin(client, {source_id: packet}) | |
| assert newer["generation"] == session["generation"] + 1 | |
| assert client.post(BASE + "/sync-sessions", json=body).status_code == 409 | |
| assert put(client, source_id, packet, session).status_code == 409 | |
| def test_legacy_request_compatibility_and_v2_write_fence(client, database): | |
| source_id, packet, _ = fixture_packet() | |
| keys = {"label", "region_code", "region_name", "sha256", "accepted_at", "review_status", "ai_protocol", "geometry_ok", "seoul_ok", "collection_finalized", "gpx_base64"} | |
| legacy = {k: v for k, v in packet.items() if k in keys} | |
| assert client.put(BASE + "/routes/" + source_id, json=legacy).status_code == 200 | |
| assert query(database, "SELECT count(*) AS n FROM art_templates")[0]["n"] == 0 | |
| session, _ = begin(client, {source_id: packet}) | |
| assert put(client, source_id, packet, session).status_code == 200 | |
| assert client.put(BASE + "/routes/" + source_id, json=legacy).status_code == 200 | |
| assert client.put(BASE + "/routes/" + source_id, json={**legacy, "region_name": "changed"}).status_code == 409 | |
| assert client.post(BASE + "/approval-snapshot", json={"ids": [], "count": 0, "ids_sha256": hashlib.sha256(b"").hexdigest()}).status_code == 409 | |
| def test_v2_rejects_client_coordinates_and_redacts_validation_values(client): | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| response = put(client, source_id, {**packet, "coordinates": "private-input-marker"}, session) | |
| assert response.status_code == 422 | |
| assert "private-input-marker" not in response.text | |
| assert packet["gpx_base64"] not in response.text | |
| def test_catalog_and_live_outline_cache_drop_revoked_routes(client, database, monkeypatch): | |
| from app.services.art_route_catalog import load_art_route_catalog | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| assert put(client, source_id, packet, session).status_code == 200 | |
| monkeypatch.setenv("ART_ROUTE_COORDINATE_ORDER", "lonlat") | |
| assert "dog" in load_art_route_catalog() # v2 order is per-row, independent of legacy config. | |
| assert "dog" in api.active_outlines() | |
| empty, _ = begin(client, {}) | |
| assert finish(client, empty, {}).status_code == 200 | |
| assert load_art_route_catalog() == {} and api.active_outlines() == {} | |
| def test_database_outage_never_replays_live_outline_cache(client, monkeypatch): | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| assert put(client, source_id, packet, session).status_code == 200 | |
| assert api.active_outlines() | |
| monkeypatch.delenv("ROUTE_LIBRARY_DATABASE_URL") | |
| assert api.active_outlines() == {} | |
| def make_lab(tmp_path, name="sender"): | |
| source_id, packet, points = fixture_packet(name) | |
| root = tmp_path / "lab" | |
| (root / "gpx/dog").mkdir(parents=True) | |
| (root / "designs/dog").mkdir(parents=True) | |
| design_path = root / "designs/dog/synthetic_dog.json" | |
| design_path.write_text(json.dumps(packet["template"]["snapshot"])) | |
| gpx_path = root / "gpx/dog" / (source_id + ".gpx") | |
| gpx_path.write_bytes(base64.b64decode(packet["gpx_base64"])) | |
| record_path = root / "synthetic_record.json" | |
| record_path.write_text(json.dumps({"metadata": {"design_file": str(design_path), "design_digest": packet["template"]["design_digest"], | |
| "graph_sha256": packet["graph_sha256"]}, "assessment": {"success": True, "route_valid": True}, | |
| "route": {"design_id": "synthetic_dog", "design_version": "1", "length_m": 2000, | |
| "verification": packet["road_verification"], "gps": [[b, a] for a, b in points]}})) | |
| with sqlite3.connect(root / "inventory.sqlite3") as db: | |
| db.executescript("""CREATE TABLE items(id TEXT PRIMARY KEY,kind TEXT,label TEXT,city_id TEXT,city_name TEXT, | |
| design_id TEXT,record_path TEXT,ai_json TEXT,geometry_ok INT,seoul_ok INT,status TEXT); | |
| CREATE TABLE accepted(item_id TEXT PRIMARY KEY,label TEXT,city_id TEXT,design_id TEXT,accepted_at TEXT); | |
| CREATE TABLE approval_revocations(item_id TEXT PRIMARY KEY);""") | |
| db.execute("INSERT INTO items VALUES (?,?,?,?,?,?,?,?,?,?,?)", (source_id, "route", "dog", "synthetic", "Synthetic", | |
| "synthetic_dog", str(record_path), json.dumps(packet["route_ai_evidence"]), 1, 1, "ai_pass")) | |
| design_item_id = hashlib.sha256(("design:dog:" + packet["template"]["design_digest"]).encode()).hexdigest() | |
| db.execute("INSERT INTO items(id,kind,status,ai_json) VALUES (?,?,?,?)", (design_item_id, "design", "ai_reject", json.dumps({"status": "ai_reject"}))) | |
| db.execute("INSERT INTO accepted VALUES (?,?,?,?,?)", (source_id, "dog", "synthetic", "synthetic_dog", packet["accepted_at"])) | |
| return root, source_id | |
| def test_http_sender_resumes_a_lost_success_without_duplicate_rows(client, database, tmp_path, monkeypatch): | |
| sender = load_file("art_http_sender", ROOT / "tools/sync_lab_gpx.py") | |
| root, source_id = make_lab(tmp_path) | |
| lost, sessions, puts = [], [], [] | |
| def http(url, token, method, payload): | |
| parsed = urlsplit(url) | |
| response = client.request(method, parsed.path + ("?" + parsed.query if parsed.query else ""), json=payload) | |
| assert response.status_code == 200, "Synthetic HTTP request failed" | |
| if parsed.path.endswith("/sync-sessions"): | |
| sessions.append(response.json()["session_id"]) | |
| if method == "PUT": | |
| puts.append(response.json()["art_route_candidate_id"]) | |
| if not lost: | |
| lost.append(True) | |
| raise urllib.error.URLError("synthetic response loss") | |
| return response.json() | |
| monkeypatch.setattr(sender, "send", http) | |
| state = tmp_path / "sender/state.sqlite3" | |
| with pytest.raises(urllib.error.URLError): | |
| sender.sync_v2(root, "https://example.test" + BASE, "synthetic", state, probe_id=source_id) | |
| result = sender.sync_v2(root, "https://example.test" + BASE, "synthetic", state, probe_id=source_id) | |
| assert result["snapshot_sent"] is False and result["deactivated_count"] == 0 | |
| assert len(set(sessions)) == len(set(puts)) == 1 | |
| assert query(database, "SELECT count(*) AS n FROM art_route_candidates")[0]["n"] == 1 | |
| with sqlite3.connect(state) as db: | |
| saved = db.execute("SELECT template_id,candidate_id FROM http_v2_sent").fetchone() | |
| assert saved and saved[1] == puts[0] | |
| def test_sender_does_not_mark_legacy_success_as_art_storage(client, tmp_path, monkeypatch): | |
| sender = load_file("art_http_sender_bad_ack", ROOT / "tools/sync_lab_gpx.py") | |
| root, source_id = make_lab(tmp_path) | |
| def http(url, token, method, payload): | |
| response = client.request(method, urlsplit(url).path, json=payload) | |
| assert response.status_code == 200 | |
| result = response.json() | |
| if method == "PUT": | |
| result.pop("art_template_id") | |
| return result | |
| monkeypatch.setattr(sender, "send", http) | |
| state = tmp_path / "sender/state.sqlite3" | |
| with pytest.raises(RuntimeError, match="receipt"): | |
| sender.sync_v2(root, "https://example.test" + BASE, "synthetic", state, probe_id=source_id) | |
| with sqlite3.connect(state) as db: | |
| assert db.execute("SELECT count(*) FROM http_v2_sent").fetchone()[0] == 0 | |
| def test_migration_preserves_legacy_rows_and_downgrade_keeps_library(client, database): | |
| from alembic.migration import MigrationContext | |
| from alembic.operations import Operations | |
| _, engine, migration = database | |
| with engine.begin() as conn: | |
| with Operations.context(MigrationContext.configure(conn)): | |
| migration.downgrade() | |
| old_id = str(uuid.uuid4()) | |
| conn.exec_driver_sql("INSERT INTO art_templates(id,template_key,name,version,svg) VALUES (%s,'legacy','legacy',1,'<svg/>')", (old_id,)) | |
| conn.exec_driver_sql("""INSERT INTO lab_route_library(source,source_id,label,region_code,region_name,gpx_sha256, | |
| accepted_at,ai_protocol,gpx,outline) VALUES ('legacy','legacy','dog','legacy','legacy','legacy',now(),'legacy',%s,'[]')""", (b"synthetic-evidence",)) | |
| with Operations.context(MigrationContext.configure(conn)): | |
| migration.upgrade() | |
| assert conn.exec_driver_sql("SELECT design_ai_status FROM art_templates WHERE id=%s", (old_id,)).scalar() == "unknown" | |
| assert conn.exec_driver_sql("SELECT gpx FROM lab_route_library WHERE source='legacy'").scalar() == b"synthetic-evidence" | |
| def test_snapshot_failure_rolls_back_both_deactivations(client, database, monkeypatch): | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| assert put(client, source_id, packet, session).status_code == 200 | |
| empty, _ = begin(client, {}) | |
| original = store._deactivate | |
| def fail(*args): | |
| original(*args) | |
| raise IngestError("synthetic_snapshot_failure", 503) | |
| monkeypatch.setattr(store, "_deactivate", fail) | |
| assert finish(client, empty, {}).status_code == 503 | |
| assert query(database, "SELECT active FROM lab_route_library")[0]["active"] | |
| assert query(database, "SELECT active FROM art_route_candidates")[0]["active"] | |
| def test_cannot_claim_approved_design_without_its_own_review(client): | |
| source_id, packet, _ = fixture_packet(design_status="ai_pass") | |
| packet["template"]["design_ai_evidence"] = {"status": "ai_pass"} | |
| session, _ = begin(client, {source_id: packet}) | |
| assert put(client, source_id, packet, session).status_code == 422 | |
| def test_sender_rejects_gpx_that_does_not_match_source_gps(tmp_path): | |
| sender = load_file("art_sender_source_gpx", ROOT / "tools/sync_lab_gpx.py") | |
| root, _ = make_lab(tmp_path) | |
| record_path = root / "synthetic_record.json" | |
| record = json.loads(record_path.read_text()) | |
| record["route"]["gps"][0][0] += .1 | |
| record_path.write_text(json.dumps(record)) | |
| with pytest.raises(RuntimeError, match="approved source GPS"): | |
| sender.art_packets(root) | |
| def test_sender_source_change_prevents_snapshot(client, tmp_path, monkeypatch): | |
| sender = load_file("art_sender_source_change", ROOT / "tools/sync_lab_gpx.py") | |
| root, _ = make_lab(tmp_path) | |
| snapshot_calls = [] | |
| def http(url, token, method, payload): | |
| path = urlsplit(url).path | |
| if path.endswith("approval-snapshot"): | |
| snapshot_calls.append(True) | |
| response = client.request(method, path, json=payload) | |
| assert response.status_code == 200 | |
| if method == "PUT": | |
| with sqlite3.connect(root / "inventory.sqlite3") as db: | |
| db.execute("UPDATE items SET status='geometry_rejected' WHERE kind='route'") | |
| return response.json() | |
| monkeypatch.setattr(sender, "send", http) | |
| with pytest.raises(RuntimeError): | |
| sender.sync_v2(root, "https://example.test" + BASE, "synthetic", tmp_path / "state/db.sqlite3") | |
| assert not snapshot_calls | |
| def test_full_alembic_history_with_synthetic_legacy_prerequisites(database): | |
| """The repository's old history assumes these two base domain tables exist.""" | |
| import psycopg | |
| from psycopg import sql | |
| from sqlalchemy.engine import make_url | |
| database_name = "route_library_test_history_" + uuid.uuid4().hex[:8] | |
| test_url = make_url(database[0]).set(database=database_name) | |
| with psycopg.connect(database[0], autocommit=True) as admin: | |
| admin.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(database_name))) | |
| try: | |
| with psycopg.connect(test_url.render_as_string(hide_password=False)) as conn: | |
| conn.execute("CREATE TABLE run_sessions(id bigint PRIMARY KEY)") | |
| conn.execute("CREATE TABLE routes(id bigint PRIMARY KEY)") | |
| environment = {**os.environ, "DATABASE_URL": test_url.set(drivername="postgresql+psycopg").render_as_string(hide_password=False)} | |
| auth = ROOT / "api/auth-service" | |
| def migrate(*arguments): | |
| result = subprocess.run([sys.executable, "-m", "alembic", *arguments], cwd=auth, | |
| env=environment, capture_output=True, text=True) | |
| assert result.returncode == 0, "Isolated full-history migration failed" | |
| migrate("upgrade", "head") | |
| with psycopg.connect(test_url.render_as_string(hide_password=False)) as conn: | |
| assert conn.execute("SELECT version_num FROM alembic_version").fetchone()[0] == "0014_link_lab_art_routes" | |
| conn.execute("ALTER TABLE alembic_version ALTER COLUMN version_num TYPE varchar(32)") | |
| migrate("upgrade", "head") # Widen an existing version table without replacing its revision. | |
| migrate("downgrade", "0013_create_art_routing_tables") | |
| migrate("upgrade", "head") | |
| with psycopg.connect(test_url.render_as_string(hide_password=False)) as conn: | |
| assert conn.execute("SELECT character_maximum_length FROM information_schema.columns WHERE table_name='alembic_version' AND column_name='version_num'").fetchone()[0] == 128 | |
| finally: | |
| with psycopg.connect(database[0], autocommit=True) as admin: | |
| admin.execute(sql.SQL("DROP DATABASE {} WITH (FORCE)").format(sql.Identifier(database_name))) | |
| def test_commit_time_failure_never_returns_storage_ids(client, database): | |
| import psycopg | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| with psycopg.connect(database[0]) as conn: | |
| conn.execute("""CREATE FUNCTION synthetic_fail_art_commit() RETURNS trigger LANGUAGE plpgsql AS $$ | |
| BEGIN RAISE EXCEPTION 'synthetic_deferred_failure'; END; $$""") | |
| conn.execute("""CREATE CONSTRAINT TRIGGER synthetic_art_commit AFTER INSERT ON art_route_candidates | |
| DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION synthetic_fail_art_commit()""") | |
| try: | |
| response = put(client, source_id, packet, session) | |
| assert response.status_code == 503 and "art_template_id" not in response.json() | |
| for table in ["art_templates", "lab_route_library", "art_route_candidates"]: | |
| assert query(database, "SELECT count(*) AS n FROM " + table)[0]["n"] == 0 | |
| finally: | |
| with psycopg.connect(database[0]) as conn: | |
| conn.execute("DROP TRIGGER synthetic_art_commit ON art_route_candidates") | |
| conn.execute("DROP FUNCTION synthetic_fail_art_commit()") | |
| def test_generation_finishes_from_its_snapshot_while_catalog_changes(client, monkeypatch): | |
| from app.api.v1.endpoints import route_generation | |
| from types import SimpleNamespace | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| assert put(client, source_id, packet, session).status_code == 200 | |
| def compute(_): | |
| empty, _ = begin(client, {}) | |
| assert finish(client, empty, {}).status_code == 200 | |
| return {"routes": []} | |
| monkeypatch.setattr(route_generation, "_generate_routes", compute) | |
| monkeypatch.setattr(route_generation, "_load_pipeline_module", lambda _: SimpleNamespace()) | |
| result = route_generation.generate_routes( | |
| route_generation.RouteGenerateRequest(source="current", latitude=37, longitude=127) | |
| ) | |
| assert result["routes"] == [] | |
| def test_snapshot_cannot_confirm_a_failed_candidate(client, database): | |
| import psycopg | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| assert put(client, source_id, packet, session).status_code == 200 | |
| with psycopg.connect(database[0]) as conn: | |
| conn.execute("UPDATE art_route_candidates SET validation_status='failed'") | |
| assert finish(client, session, {source_id: packet}).status_code == 409 | |
| assert put(client, source_id, packet, session).status_code == 409 | |
| def test_nonfinite_snapshot_values_are_a_redacted_client_error(client): | |
| source_id, packet, _ = fixture_packet() | |
| session, _ = begin(client, {source_id: packet}) | |
| body = {**packet, "session_id": session["session_id"], "generation": session["generation"], "payload_sha256": content_sha(packet)} | |
| body["template"]["snapshot"]["points"][0][0] = float("nan") | |
| response = client.put(BASE + "/routes/" + source_id, content=json.dumps(body), headers={"Content-Type": "application/json"}) | |
| assert response.status_code == 422 and response.json()["detail"] == "invalid_json_value" | |
| def test_sender_full_http_sync_rechecks_receipts_without_business_updates(client, database, tmp_path, monkeypatch): | |
| sender = load_file("art_sender_complete_http", ROOT / "tools/sync_lab_gpx.py") | |
| root, _ = make_lab(tmp_path) | |
| def http(url, token, method, payload): | |
| response = client.request(method, urlsplit(url).path, json=payload) | |
| assert response.status_code == 200, "Synthetic full sync failed" | |
| return response.json() | |
| monkeypatch.setattr(sender, "send", http) | |
| state = tmp_path / "sender/state.sqlite3" | |
| first = sender.sync_v2(root, "https://example.test" + BASE, "synthetic", state) | |
| timestamp = query(database, "SELECT updated_at FROM art_route_candidates")[0] | |
| second = sender.sync_v2(root, "https://example.test" + BASE, "synthetic", state) | |
| assert first["snapshot_sent"] and second["snapshot_sent"] | |
| assert second["generation"] == first["generation"] + 1 | |
| assert query(database, "SELECT updated_at FROM art_route_candidates")[0] == timestamp | |
| assert query(database, "SELECT count(*) AS n FROM art_route_candidates")[0]["n"] == 1 | |
| def test_sender_check_only_never_reads_auth_file_or_calls_http(tmp_path, monkeypatch, capsys): | |
| sender = load_file("art_sender_check_only", ROOT / "tools/sync_lab_gpx.py") | |
| root, _ = make_lab(tmp_path) | |
| def forbidden(*args, **kwargs): | |
| raise AssertionError("check-only attempted HTTP") | |
| monkeypatch.setattr(sender, "send", forbidden) | |
| monkeypatch.setattr(sys, "argv", ["sync_lab_gpx.py", "--root", str(root), "--url", "https://example.test", | |
| "--token-file", str(tmp_path / "auth-file-does-not-exist"), "--contract-version", "2", "--check-only"]) | |
| sender.main() | |
| assert json.loads(capsys.readouterr().out)["http_requests"] == 0 | |