CD / tools /sync_lab_gpx.py
tkadkghdlf's picture
Sync DemoService e2b09b366a64790f3dd1dc93870f72061e3c1aab
e516bd2 verified
Raw History Blame Contribute Delete
26.1 kB
"""Push one consistent Lab approval snapshot to the DemoService route library.
Run on the Lab host: python tools/sync_lab_gpx.py --root /home/jovyan/artifacts/...
The receiver must already be deployed with ROUTE_LIBRARY_TOKEN configured.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
import math
import re
import sqlite3
import time
import uuid
import xml.etree.ElementTree as ET
import urllib.error
import urllib.request
from pathlib import Path
def canonical(value):
return json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
def content_sha(payload):
data = dict(payload)
for key in ("session_id", "generation", "payload_sha256", "gpx_base64", "previous_payload_sha256", "reapprove"):
data.pop(key, None)
return hashlib.sha256(canonical(data).encode()).hexdigest()
def approved_rows(root: Path) -> list[sqlite3.Row]:
database = (root / "inventory.sqlite3").resolve()
connection = sqlite3.connect(f"file:{database.as_posix()}?mode=ro", uri=True)
connection.row_factory = sqlite3.Row
try:
connection.execute("PRAGMA query_only=ON")
connection.execute("BEGIN")
rows = connection.execute("""
SELECT i.id, i.label, i.city_id, i.city_name, i.ai_json,
i.geometry_ok, i.seoul_ok, i.status, a.accepted_at
FROM accepted AS a JOIN items AS i ON i.id = a.item_id
ORDER BY i.id
""").fetchall()
connection.commit()
return rows
finally:
connection.close()
def send(url: str, token: str, method: str, payload: dict | None) -> dict:
request = urllib.request.Request(
url, json.dumps(payload, separators=(",", ":")).encode() if payload is not None else None,
{"Authorization": "Bearer " + token, "Content-Type": "application/json"}, method=method,
)
with urllib.request.urlopen(request, timeout=30) as response:
return json.load(response)
def approved_art_rows(root, source_id=None):
"""Only the Lab SQLite inventory is read; no DemoService database driver."""
with sqlite3.connect((root / "inventory.sqlite3").resolve().as_uri() + "?mode=ro", uri=True) as db:
db.row_factory = sqlite3.Row
db.execute("PRAGMA query_only=ON")
db.execute("BEGIN")
query = """SELECT i.id,i.kind,i.label,i.city_id,i.city_name,i.design_id,i.record_path,
i.ai_json,i.geometry_ok,i.seoul_ok,i.status,a.accepted_at
FROM accepted a JOIN items i ON i.id=a.item_id
WHERE i.label IS a.label AND i.city_id IS a.city_id AND i.design_id IS a.design_id
AND NOT EXISTS (SELECT 1 FROM approval_revocations v WHERE v.item_id=i.id)"""
if source_id is not None:
query += " AND i.id=?"
rows = [dict(r) for r in db.execute(query + " ORDER BY i.id", (source_id,) if source_id is not None else ())]
total = db.execute("SELECT count(*) FROM accepted" + (" WHERE item_id=?" if source_id is not None else ""),
(source_id,) if source_id is not None else ()).fetchone()[0]
if total != len(rows):
raise RuntimeError("Invalid or revoked approval join")
return rows
def verify_source_gpx(raw, expected):
try:
if not 0 < len(raw) <= 128 * 1024 or b"<!DOCTYPE" in raw.upper() or b"<!ENTITY" in raw.upper():
raise ValueError
document = ET.fromstring(raw)
tracks = [n for n in document.iter() if n.tag.rsplit("}", 1)[-1] == "trk"]
segments = [n for n in document.iter() if n.tag.rsplit("}", 1)[-1] == "trkseg"]
if document.tag.rsplit("}", 1)[-1] != "gpx" or len(tracks) != 1 or len(segments) != 1 or segments[0] not in list(tracks[0]):
raise ValueError
points = [(float(n.attrib["lat"]), float(n.attrib["lon"])) for n in segments[0]
if n.tag.rsplit("}", 1)[-1] == "trkpt"]
if not 12 <= len(points) <= 10000 or len(points) != len(expected):
raise ValueError
if (len(set(points)) < 4 or math.dist(points[0], points[-1]) > 1e-5
or not all(math.isfinite(lat) and math.isfinite(lon) and abs(lat) <= 90 and abs(lon) <= 180
and abs(lat - original[1]) <= 5.01e-8 and abs(lon - original[0]) <= 5.01e-8
for (lat, lon), original in zip(points, expected))):
raise ValueError
except (ValueError, TypeError, KeyError, IndexError, ET.ParseError):
raise RuntimeError("GPX does not match approved source GPS") from None
def current_design_review(root, label, template):
item_id = hashlib.sha256(("design:" + label + ":" + template["design_digest"]).encode()).hexdigest()
with sqlite3.connect((root / "inventory.sqlite3").as_uri() + "?mode=ro", uri=True) as db:
db.execute("PRAGMA query_only=ON")
row = db.execute("SELECT status,ai_json FROM items WHERE id=? AND kind='design'", (item_id,)).fetchone()
return (row[0], json.loads(row[1] or "{}")) if row else ("unknown", {})
def art_packets(root, probe_id=None, max_routes=None):
root = root.resolve()
rows = approved_art_rows(root)
if not rows:
raise RuntimeError("Empty approval list; refusing to synchronize")
if probe_id:
rows = [r for r in rows if r["id"] == probe_id]
if len(rows) != 1:
raise RuntimeError("Probe ID is not currently approved")
if max_routes is not None:
if max_routes <= 0:
raise RuntimeError("max_routes must be positive")
rows = rows[:max_routes]
packets, paths = {}, {}
finalized = (root / "completion.json").is_file()
with sqlite3.connect((root / "inventory.sqlite3").as_uri() + "?mode=ro", uri=True) as db:
db.execute("PRAGMA query_only=ON")
db.execute("BEGIN")
for row in rows:
source_id, label = row["id"], row["label"]
if (not re.fullmatch(r"[0-9a-f]{64}", source_id) or label not in {"dog", "heart", "tree", "tshirt", "candle", "pants", "star"}
or row["kind"] != "route" or row["status"] != "ai_pass" or row["geometry_ok"] != 1 or row["seoul_ok"] != 1):
raise RuntimeError("Approval state changed")
record_path = Path(row["record_path"])
record_raw = record_path.read_bytes()
record = json.loads(record_raw)
metadata, route = record["metadata"], record["route"]
design_path = Path(metadata.get("design_file") or ".")
if not design_path.is_file():
design_path = root / "designs" / label / (row["design_id"] + ".json")
design_raw = design_path.read_bytes()
design = json.loads(design_raw)
design_digest = hashlib.sha256(canonical(design).encode()).hexdigest()
if (design_digest != metadata.get("design_digest") or design.get("design_id") != row["design_id"]
or route.get("design_id") != row["design_id"] or str(design.get("version")) != str(route.get("design_version"))):
raise RuntimeError("Source design identity changed")
review = json.loads(row["ai_json"])
if (review.get("status") != "ai_pass" or review.get("expected_label") != label
or review.get("blind") is not True or review.get("qwen_performed") is not True
or not review.get("siglip_support_angles")):
raise RuntimeError("Missing route review evidence")
proof = route.get("verification", {})
if (not all(proof.get(k) is True for k in ("road_only", "graph_connectivity_verified", "access_checked", "directions_checked"))
or type(proof.get("air_length_m")) not in (int, float) or proof["air_length_m"] != 0 or not record.get("assessment", {}).get("success")
or not record.get("assessment", {}).get("route_valid")):
raise RuntimeError("Missing road or geometry evidence")
graph_hash = metadata.get("graph_sha256", "")
if not re.fullmatch(r"[0-9a-f]{64}", graph_hash):
raise RuntimeError("Missing graph digest")
length = route.get("length_m")
if type(length) not in (int, float) or not math.isfinite(length) or length <= 0:
raise RuntimeError("Invalid source road length")
design_item_id = hashlib.sha256(("design:" + label + ":" + design_digest).encode()).hexdigest()
design_review = db.execute("SELECT status,ai_json FROM items WHERE id=? AND kind='design'", (design_item_id,)).fetchone()
design_status = design_review[0] if design_review else "unknown"
design_evidence = json.loads(design_review[1] or "{}") if design_review else {}
gpx_path = root / "gpx" / label / (source_id + ".gpx")
gpx = gpx_path.read_bytes()
verify_source_gpx(gpx, route.get("gps", []))
packet = {"contract_version": 2, "label": label, "region_code": row["city_id"], "region_name": row["city_name"],
"sha256": hashlib.sha256(gpx).hexdigest(), "accepted_at": row["accepted_at"], "review_status": "ai_pass",
"ai_protocol": review["protocol"], "geometry_ok": True, "seoul_ok": True, "collection_finalized": finalized,
"gpx_base64": base64.b64encode(gpx).decode(),
"template": {"design_id": design["design_id"], "source_version": str(design["version"]),
"design_digest": design_digest, "snapshot": design, "design_ai_status": design_status,
"design_ai_evidence": design_evidence},
"route_ai_evidence": review, "road_verification": proof, "graph_sha256": graph_hash,
"distance_m": max(1, int(math.floor(length + .5))), "validator_version": "lab-approved-gpx-import-v1"}
packets[source_id] = packet
paths[source_id] = {str(p): hashlib.sha256(raw).hexdigest() for p, raw in
[(record_path, record_raw), (design_path, design_raw), (gpx_path, gpx)]}
return rows, packets, paths
def _validate_receipt(reply, source_id, packet):
try:
valid_ids = all(uuid.UUID(reply[k]) for k in ("art_template_id", "art_route_candidate_id"))
except (KeyError, ValueError, TypeError, AttributeError):
valid_ids = False
if (not valid_ids or reply.get("status") != "stored" or reply.get("contract_version") != 2
or reply.get("source_id") != source_id or reply.get("sha256") != packet["sha256"]
or reply.get("payload_sha256") != content_sha(packet)
or reply.get("design_ai_status") != packet["template"]["design_ai_status"]
or reply.get("route_validation_status") != "passed"):
raise RuntimeError("Missing or inconsistent art storage receipt")
def sync_v2(root, destination, token, state_path, probe_id=None, max_routes=None,
allow_updates=False, allow_reapproval=False, new_session=False):
root = root.resolve()
rows, packets, paths = art_packets(root, probe_id, max_routes)
manifest = {source_id: content_sha(packet) for source_id, packet in packets.items()}
manifest_hash = hashlib.sha256(canonical(manifest).encode()).hexdigest()
mode = "partial" if probe_id is not None or max_routes is not None else "full"
run_signature = hashlib.sha256(canonical([manifest_hash, mode]).encode()).hexdigest()
state_path.parent.mkdir(parents=True, exist_ok=True)
os.chmod(state_path.parent, 0o700)
endpoint = destination.rstrip("/")
with sqlite3.connect(state_path) as state:
os.chmod(state_path, 0o600)
state.row_factory = sqlite3.Row
state.execute("""CREATE TABLE IF NOT EXISTS http_v2_runs (
client_request_id TEXT PRIMARY KEY, signature TEXT NOT NULL, expected_generation INTEGER NOT NULL,
session_id TEXT, generation INTEGER, completed INTEGER NOT NULL DEFAULT 0)""")
state.execute("""CREATE TABLE IF NOT EXISTS http_v2_sent (
id TEXT PRIMARY KEY, signature TEXT NOT NULL, session_id TEXT NOT NULL,
template_id TEXT NOT NULL, candidate_id TEXT NOT NULL)""")
run = None if new_session else state.execute(
"SELECT * FROM http_v2_runs WHERE signature=? AND completed=0 ORDER BY rowid DESC LIMIT 1", (run_signature,)).fetchone()
if run is None:
remote = send(endpoint + "/sync-state", token, "GET", None)
if remote.get("contract_version") != 2 or type(remote.get("generation")) is not int or remote["generation"] < 0:
raise RuntimeError("Receiver does not support fenced v2 imports")
request_id = str(uuid.uuid4())
state.execute("INSERT INTO http_v2_runs(client_request_id,signature,expected_generation) VALUES (?,?,?)",
(request_id, run_signature, remote["generation"]))
state.commit() # Persist before the request so a lost response can be retried.
run = state.execute("SELECT * FROM http_v2_runs WHERE client_request_id=?", (request_id,)).fetchone()
session = send(endpoint + "/sync-sessions", token, "POST", {"contract_version": 2,
"client_request_id": run["client_request_id"], "expected_generation": run["expected_generation"],
"mode": mode, "manifest": manifest, "manifest_sha256": manifest_hash})
try:
session_id = str(uuid.UUID(session["session_id"]))
except (KeyError, ValueError, TypeError, AttributeError):
raise RuntimeError("Invalid sync session response") from None
if (session.get("contract_version") != 2 or type(session.get("generation")) is not int
or session["generation"] != run["expected_generation"] + 1 or session.get("mode") != mode
or session.get("manifest_sha256") != manifest_hash):
raise RuntimeError("Inconsistent sync session response")
state.execute("UPDATE http_v2_runs SET session_id=?,generation=? WHERE client_request_id=?",
(session_id, session["generation"], run["client_request_id"]))
state.commit()
uploaded = 0
for row in rows:
source_id = row["id"]
if approved_art_rows(root, source_id) != [row] or any(hashlib.sha256(Path(p).read_bytes()).hexdigest() != h
for p, h in paths[source_id].items()):
raise RuntimeError("Approval or source file changed before upload")
template = packets[source_id]["template"]
if current_design_review(root, row["label"], template) != (template["design_ai_status"], template["design_ai_evidence"]):
raise RuntimeError("Design review changed before upload")
packet = {**packets[source_id], "session_id": session_id, "generation": session["generation"],
"payload_sha256": manifest[source_id]}
previous = state.execute("SELECT * FROM http_v2_sent WHERE id=?", (source_id,)).fetchone()
if previous and previous["session_id"] == session_id and previous["signature"] == manifest[source_id]:
continue
if previous and allow_updates:
packet["previous_payload_sha256"] = previous["signature"]
if allow_reapproval:
packet["reapprove"] = True
received = send(endpoint + "/routes/" + source_id, token, "PUT", packet)
_validate_receipt(received, source_id, packet)
state.execute("""INSERT INTO http_v2_sent VALUES (?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET
signature=excluded.signature,session_id=excluded.session_id,
template_id=excluded.template_id,candidate_id=excluded.candidate_id""",
(source_id, manifest[source_id], session_id, received["art_template_id"], received["art_route_candidate_id"]))
state.commit()
uploaded += 1
current_rows, current_packets, _ = art_packets(root, probe_id, max_routes)
if current_rows != rows or {k: content_sha(v) for k, v in current_packets.items()} != manifest:
raise RuntimeError("Approval or metadata changed; snapshot not sent")
if mode == "full":
ids = sorted(manifest)
result = send(endpoint + "/approval-snapshot", token, "POST", {"contract_version": 2,
"session_id": session_id, "generation": session["generation"], "manifest_sha256": manifest_hash,
"ids": ids, "count": len(ids), "ids_sha256": hashlib.sha256("\n".join(ids).encode()).hexdigest(),
"collection_finalized": (root / "completion.json").is_file()})
if (result.get("contract_version") != 2 or result.get("session_id") != session_id
or result.get("generation") != session["generation"] or result.get("active_count") != len(ids)
or type(result.get("deactivated_count")) is not int):
raise RuntimeError("Invalid snapshot storage response")
else:
result = send(endpoint + "/sync-sessions/" + session_id + "/complete?generation=" + str(session["generation"]),
token, "POST", {})
if (result.get("session_id") != session_id or result.get("generation") != session["generation"]
or result.get("session_status") != "completed" or result.get("deactivated_count") != 0):
raise RuntimeError("Invalid partial completion response")
state.execute("UPDATE http_v2_runs SET completed=1 WHERE client_request_id=?", (run["client_request_id"],))
state.commit()
return {"contract_version": 2, "approved": len(rows), "uploaded": uploaded, "snapshot_sent": mode == "full",
"generation": session["generation"], "deactivated_count": result["deactivated_count"]}
def sync(root: Path, destination: str, token: str, state_path: Path,
probe_id: str | None = None) -> dict:
rows = approved_rows(root)
if not rows:
raise RuntimeError("Empty approval list; refusing to synchronize")
if probe_id is not None:
rows = [row for row in rows if row["id"] == probe_id]
if len(rows) != 1:
raise RuntimeError("Probe ID is not in the current approval list")
state_path.parent.mkdir(parents=True, exist_ok=True)
os.chmod(state_path.parent, 0o700)
state = sqlite3.connect(state_path)
try:
state.execute("CREATE TABLE IF NOT EXISTS sent (id TEXT PRIMARY KEY, signature TEXT NOT NULL)")
ids = []
file_hashes = {}
uploaded = 0
for row in rows:
source_id, label = row["id"], row["label"]
if not isinstance(source_id, str) or len(source_id) != 64 or label not in {
"dog", "heart", "tree", "tshirt", "candle", "pants", "star"
}:
raise RuntimeError("Unexpected route ID or label in approval list")
if row["status"] != "ai_pass" or row["geometry_ok"] != 1 or row["seoul_ok"] != 1:
raise RuntimeError(f"Approval state changed for {source_id}")
path = root / "gpx" / label / (source_id + ".gpx")
gpx = path.read_bytes()
sha256 = hashlib.sha256(gpx).hexdigest()
file_hashes[source_id] = sha256
review = json.loads(row["ai_json"] or "{}")
protocol = review.get("protocol")
if not isinstance(protocol, str) or not protocol:
raise RuntimeError(f"Missing review protocol for {source_id}")
metadata = {
"label": label, "region_code": row["city_id"],
"region_name": row["city_name"], "sha256": sha256,
"accepted_at": row["accepted_at"], "review_status": row["status"],
"ai_protocol": protocol, "geometry_ok": True, "seoul_ok": True,
"collection_finalized": (root / "completion.json").is_file(),
}
signature = hashlib.sha256(json.dumps(metadata, sort_keys=True).encode()).hexdigest()
previous = state.execute("SELECT signature FROM sent WHERE id=?", (source_id,)).fetchone()
if probe_id is not None or not previous or previous[0] != signature:
send(destination.rstrip("/") + "/routes/" + source_id, token, "PUT",
{**metadata, "gpx_base64": base64.b64encode(gpx).decode()})
state.execute("INSERT INTO sent VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET signature=excluded.signature",
(source_id, signature))
state.commit()
uploaded += 1
ids.append(source_id)
if probe_id is not None:
return {"probe_id": probe_id, "uploaded": uploaded, "snapshot_sent": False}
# Do not revoke from a partial file set or a changing DB approval list.
if [tuple(row) for row in rows] != [tuple(row) for row in approved_rows(root)]:
raise RuntimeError("Approval list changed during upload; retry from a new snapshot")
if any(hashlib.sha256((root / "gpx" / row["label"] / (row["id"] + ".gpx")).read_bytes()).hexdigest()
!= file_hashes[row["id"]] for row in rows):
raise RuntimeError("GPX files changed during upload; retry from a new snapshot")
digest = hashlib.sha256("\n".join(ids).encode()).hexdigest()
result = send(destination.rstrip("/") + "/approval-snapshot", token, "POST", {
"ids": ids, "count": len(ids), "ids_sha256": digest,
"collection_finalized": (root / "completion.json").is_file(),
})
return {"approved": len(ids), "uploaded": uploaded, **result}
finally:
state.close()
if state_path.exists():
os.chmod(state_path, 0o600)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--url", required=True, help="Full /api/v1/ai/internal/route-library URL")
parser.add_argument("--token-file", type=Path, required=True)
parser.add_argument("--state", type=Path, default=Path.home() / ".local/share/demoservice-sync/state.sqlite3")
parser.add_argument("--interval-seconds", type=int, default=0, help="Repeat after this delay; 0 runs once")
parser.add_argument("--probe-id", help="Send one approved GPX without an approval snapshot")
parser.add_argument("--contract-version", type=int, choices=[1, 2], default=1,
help="Opt in to fenced art imports with 2; existing callers remain on 1")
parser.add_argument("--max-routes", type=int, help="v2 partial import limit; never revokes")
parser.add_argument("--allow-updates", action="store_true", help="v2 compare-and-swap using a previous receipt")
parser.add_argument("--allow-reapproval", action="store_true", help="v2 explicit reapproval with a later accepted_at")
parser.add_argument("--new-session", action="store_true", help="Abandon local pending session and start from current source approvals")
parser.add_argument("--check-only", action="store_true", help="v2 local preparation only; no token read or HTTP")
args = parser.parse_args()
if args.check_only:
rows, packets, _ = art_packets(args.root, args.probe_id, args.max_routes)
print(json.dumps({"approved": len(rows), "templates": len({p['template']['design_digest'] for p in packets.values()}),
"http_requests": 0}, ensure_ascii=False))
return
token = args.token_file.read_text(encoding="utf-8").strip()
if not token:
raise SystemExit("Empty receiver token")
if args.interval_seconds < 0:
parser.error("--interval-seconds must be nonnegative")
if args.probe_id and args.interval_seconds:
parser.error("--probe-id cannot be used with --interval-seconds")
if args.contract_version == 1 and (args.max_routes or args.allow_updates or args.allow_reapproval or args.new_session):
parser.error("v2 options require --contract-version 2")
from urllib.parse import urlsplit
endpoint = urlsplit(args.url)
if endpoint.username or endpoint.password or endpoint.query or endpoint.fragment or not endpoint.hostname:
parser.error("Use an API URL without embedded credentials, query or fragment")
if endpoint.scheme != "https" and not (endpoint.scheme == "http" and endpoint.hostname in {"localhost", "127.0.0.1", "::1"}):
parser.error("Use HTTPS, or loopback HTTP for synthetic tests")
import fcntl
args.state.parent.mkdir(parents=True, exist_ok=True)
with args.state.with_suffix(args.state.suffix + ".lock").open("a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise SystemExit("A sender already owns this state file") from None
while True:
try:
if args.contract_version == 2:
result = sync_v2(args.root, args.url, token, args.state, args.probe_id, args.max_routes,
args.allow_updates, args.allow_reapproval, args.new_session)
else:
result = sync(args.root, args.url, token, args.state, args.probe_id)
print(json.dumps(result, ensure_ascii=False), flush=True)
except Exception as exc:
if not args.interval_seconds:
raise SystemExit(f"Sync failed: {type(exc).__name__}; details suppressed") from None
print(f"Sync retry scheduled after {type(exc).__name__}; details suppressed", flush=True)
if not args.interval_seconds:
break
# Only the first run is explicitly forced; subsequent runs resume normally.
args.new_session = False
time.sleep(args.interval_seconds)
if __name__ == "__main__":
main()