Local preservation snapshot, not a new deployment or simulation acceptance.
154 lines
5.9 KiB
Python
154 lines
5.9 KiB
Python
"""Bounded, run-owned replay of recorded observations through the CMU adapter."""
|
|
|
|
import argparse
|
|
import gzip
|
|
import hashlib
|
|
import http.client
|
|
import json
|
|
import time
|
|
from datetime import UTC, datetime
|
|
from pathlib import Path
|
|
|
|
from model_stack import ModelStack
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--requests", type=Path, required=True)
|
|
parser.add_argument("--requests-sha256", required=True)
|
|
parser.add_argument("--inputs", type=Path, required=True)
|
|
parser.add_argument("--reservation", type=Path, required=True)
|
|
parser.add_argument("--output", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
receipt = json.loads(args.reservation.read_text(encoding="utf-8-sig"))
|
|
if receipt["state"] != "reserved" or not receipt["owner_id"].startswith("airun-"):
|
|
raise ValueError("Core reservation required")
|
|
age = (datetime.now(UTC) - datetime.fromisoformat(receipt["utc"])).total_seconds()
|
|
if not 0 <= age <= 900:
|
|
raise ValueError("Stale reservation")
|
|
if hashlib.sha256(args.requests.read_bytes()).hexdigest() != args.requests_sha256:
|
|
raise ValueError("Replay requests changed")
|
|
args.output.mkdir(parents=True, exist_ok=False)
|
|
active = Path(r"D:\NDC_MISSIONCORE\runtime\simulation\state\active.json")
|
|
if active.exists():
|
|
raise RuntimeError("Operator run active")
|
|
stack, acquired = ModelStack(), []
|
|
|
|
def write(name, value):
|
|
(args.output / name).write_text(json.dumps(value, indent=2), encoding="utf-8")
|
|
|
|
def capture(ids):
|
|
acquired[:] = ids
|
|
write("owned-containers.json", dict(ids=ids))
|
|
|
|
write(
|
|
"acceptance.json",
|
|
dict(
|
|
owner_id=receipt["owner_id"],
|
|
utc=datetime.now(UTC).isoformat(),
|
|
monotonic=time.monotonic(),
|
|
requests_sha256=args.requests_sha256,
|
|
scope="Recorded sensor replay; no new physical trajectory or independent holdout",
|
|
source_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
|
wall_budget_seconds=240,
|
|
),
|
|
)
|
|
try:
|
|
stack.start(cancelled=active.exists, on_acquired=capture, inputs_path=args.inputs)
|
|
start = time.monotonic()
|
|
with (
|
|
gzip.open(args.requests, "rt") as source,
|
|
(args.output / "replies.jsonl").open("w", encoding="utf-8") as output,
|
|
):
|
|
for line in source:
|
|
row = json.loads(line)
|
|
delay = row["offset_seconds"] - (time.monotonic() - start)
|
|
while delay > 0 and time.monotonic() - start <= 240:
|
|
if active.exists():
|
|
raise InterruptedError("Operator run active")
|
|
time.sleep(min(delay, 1))
|
|
delay = row["offset_seconds"] - (time.monotonic() - start)
|
|
if active.exists() or time.monotonic() - start > 240:
|
|
raise TimeoutError("Replay deadline or operator run")
|
|
before = time.monotonic()
|
|
connection = http.client.HTTPConnection("127.0.0.1", 18093, timeout=15)
|
|
try:
|
|
connection.request(
|
|
"POST",
|
|
"/plan",
|
|
body=json.dumps(row["request"]),
|
|
headers={"Content-Type": "application/json"},
|
|
)
|
|
response = connection.getresponse()
|
|
reply = json.loads(response.read())
|
|
if response.status != 200:
|
|
raise RuntimeError(str(reply))
|
|
finally:
|
|
connection.close()
|
|
snapshot = reply.pop("observation_debug", None)
|
|
reply.pop("observed_terrain", None)
|
|
if snapshot is not None:
|
|
write(
|
|
f"frame-{row['frame_id']}.json",
|
|
dict(request=row["request"], reply=reply, snapshot=snapshot),
|
|
)
|
|
output.write(
|
|
json.dumps(
|
|
dict(
|
|
frame_id=row["frame_id"],
|
|
request_wall_offset=before - start,
|
|
scheduling_lag_seconds=before - start - row["offset_seconds"],
|
|
reply=reply,
|
|
)
|
|
)
|
|
+ "\n"
|
|
)
|
|
if snapshot is not None:
|
|
print(
|
|
json.dumps(
|
|
dict(
|
|
frame=row["frame_id"],
|
|
status=reply["status"],
|
|
supported=reply.get("arrival", {}).get("supported_samples"),
|
|
terrain=len(snapshot["terrain"]),
|
|
permitted=len(snapshot["permitted"]),
|
|
)
|
|
),
|
|
flush=True,
|
|
)
|
|
write("completed.json", dict(completed=True, wall_seconds=time.monotonic() - start))
|
|
finally:
|
|
errors = []
|
|
try:
|
|
stack.stop()
|
|
except Exception as exc:
|
|
errors.append(str(exc))
|
|
write(
|
|
"cleanup.json",
|
|
dict(
|
|
owner_id=receipt["owner_id"],
|
|
released=not errors,
|
|
container_ids=acquired,
|
|
native_pid=None,
|
|
errors=errors,
|
|
utc=datetime.now(UTC).isoformat(),
|
|
monotonic=time.monotonic(),
|
|
),
|
|
)
|
|
write(
|
|
"manifest.json",
|
|
{
|
|
"files": {
|
|
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
|
|
for p in args.output.iterdir()
|
|
if p.is_file()
|
|
}
|
|
},
|
|
)
|
|
if errors:
|
|
raise RuntimeError("Replay cleanup failed")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|