| |
| """One-off recovery: build 41 from NVMe spool into export-format files. |
| |
| Build 41 ran 2026-07-09 21:09 → 2026-07-10 00:55 UTC (~3h45m) but the |
| Postgres DB was wiped before the spool importer could process it. This script |
| reads the raw spool files directly and produces the same export-format files |
| that `export.py` would have written, with build_id=41 throughout. |
| |
| Outputs (written into the recorder repo's data/exports/): |
| telemetry/41.parquet — (ts, sensor_id, kind, value) |
| position_hf/41.parquet — (ts, x, y, z1, z2, r, has_homed) |
| frames.jsonl — appended rows with build_id=41 |
| builds.jsonl — appended row with id=41 |
| events.jsonl — appended build_start row with build_id=41 |
| |
| Safe to re-run: telemetry and position_hf parquets are overwritten; jsonl |
| files are checked first and a second run skips appending if id=41 is already |
| present. |
| """ |
| import json |
| import sys |
| from pathlib import Path |
| from datetime import datetime, timezone |
|
|
| import pyarrow as pa |
| import pyarrow.parquet as pq |
|
|
|
|
| def parse_ts(s: str) -> datetime: |
| """Parse ISO 8601 string (with tz offset or Z) to a UTC-aware datetime.""" |
| return datetime.fromisoformat(s.replace("Z", "+00:00")) |
|
|
| sys.path.insert(0, str(Path(__file__).parent.parent)) |
| from _lib import EXPORTS_DIR, AGENTIC_ROOT |
|
|
| SPOOL_DIR = Path("/home/ppak/.agentic-sls/spool/41") |
| BUILD_ID = 41 |
| JOB_NAME = "Unknown 2026_07_09" |
|
|
|
|
| def expand_snapshot(snap: dict) -> list[dict]: |
| """Mirror telemetry.ts:expand() — one JSON spool line → list of rows.""" |
| ts = snap["respondedAt"] |
| s = snap["data"] |
| rows: list[dict] = [] |
|
|
| for k in ("x", "y", "z1", "z2", "r"): |
| rows.append({"ts": ts, "sensor_id": "positions", "kind": f"position.{k}", |
| "value": float(s["position"][k])}) |
|
|
| rows.append({"ts": ts, "sensor_id": "lights", "kind": "lights.enabled", |
| "value": 1.0 if s["lights"]["isEnabled"] else 0.0}) |
| rows.append({"ts": ts, "sensor_id": "lights", "kind": "lights.count", |
| "value": float(s["lights"]["lightCount"])}) |
|
|
| for e in s["power"]["entries"]: |
| rows.append({"ts": ts, "sensor_id": e["id"], "kind": "power", |
| "value": float(e["power"])}) |
| pm = s["power"]["powerman"] |
| rows.append({"ts": ts, "sensor_id": "powerman", "kind": "power.current", |
| "value": float(pm["currentPower"])}) |
| rows.append({"ts": ts, "sensor_id": "powerman", "kind": "power.required", |
| "value": float(pm["requiredPower"])}) |
| rows.append({"ts": ts, "sensor_id": "powerman", "kind": "power.max", |
| "value": float(pm["maxPower"])}) |
|
|
| for e in s["temperature"]["entries"]: |
| rows.append({"ts": ts, "sensor_id": e["id"], "kind": "temp.current", |
| "value": float(e["currentTemperature"])}) |
| rows.append({"ts": ts, "sensor_id": e["id"], "kind": "temp.average", |
| "value": float(e["averageTemperature"])}) |
| tgt = e.get("targetTemperature") |
| if tgt is not None: |
| rows.append({"ts": ts, "sensor_id": e["id"], "kind": "temp.target", |
| "value": float(tgt)}) |
|
|
| return rows |
|
|
|
|
| def build_telemetry_parquet() -> tuple[str, str]: |
| """Expand spool telemetry → data/exports/telemetry/41.parquet. |
| Returns (first_ts_str, last_ts_str) for builds.jsonl.""" |
| path = SPOOL_DIR / "telemetry.ndjson" |
| out = EXPORTS_DIR / "telemetry" / f"{BUILD_ID}.parquet" |
| out.parent.mkdir(parents=True, exist_ok=True) |
|
|
| schema = pa.schema([ |
| pa.field("ts", pa.timestamp("us", tz="UTC")), |
| pa.field("sensor_id", pa.string()), |
| pa.field("kind", pa.string()), |
| pa.field("value", pa.float64()), |
| ]) |
|
|
| BATCH = 50_000 |
| first_ts = last_ts = None |
| bad = 0 |
| total = 0 |
|
|
| with pq.ParquetWriter(out, schema, compression="zstd") as writer: |
| buf: list[dict] = [] |
|
|
| def flush(): |
| nonlocal total |
| if not buf: |
| return |
| ts_arr = pa.array([parse_ts(r["ts"]) for r in buf], type=pa.timestamp("us", tz="UTC")) |
| table = pa.table({ |
| "ts": ts_arr, |
| "sensor_id": pa.array([r["sensor_id"] for r in buf], type=pa.string()), |
| "kind": pa.array([r["kind"] for r in buf], type=pa.string()), |
| "value": pa.array([r["value"] for r in buf], type=pa.float64()), |
| }, schema=schema) |
| writer.write_table(table) |
| total += len(buf) |
| buf.clear() |
|
|
| with path.open(encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| snap = json.loads(line) |
| except json.JSONDecodeError: |
| bad += 1 |
| continue |
| ts = snap.get("respondedAt") |
| if first_ts is None: |
| first_ts = ts |
| last_ts = ts |
| try: |
| rows = expand_snapshot(snap) |
| except Exception: |
| bad += 1 |
| continue |
| buf.extend(rows) |
| if len(buf) >= BATCH: |
| flush() |
| flush() |
|
|
| print(f" telemetry: {total:,} rows, {bad} bad lines → {out.name}") |
| return first_ts, last_ts |
|
|
|
|
| def build_position_parquet(): |
| path = SPOOL_DIR / "position.ndjson" |
| out = EXPORTS_DIR / "position_hf" / f"{BUILD_ID}.parquet" |
| out.parent.mkdir(parents=True, exist_ok=True) |
|
|
| schema = pa.schema([ |
| pa.field("ts", pa.timestamp("us", tz="UTC")), |
| pa.field("x", pa.float64()), |
| pa.field("y", pa.float64()), |
| pa.field("z1", pa.float64()), |
| pa.field("z2", pa.float64()), |
| pa.field("r", pa.float64()), |
| pa.field("has_homed", pa.bool_()), |
| ]) |
|
|
| rows: list[dict] = [] |
| bad = 0 |
| with path.open(encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| rec = json.loads(line) |
| d = rec["data"] |
| rows.append({ |
| "ts": rec["respondedAt"], |
| "x": float(d["x"]), |
| "y": float(d["y"]), |
| "z1": float(d["z1"]), |
| "z2": float(d["z2"]), |
| "r": float(d["r"]), |
| "has_homed": bool(d["hasHomed"]), |
| }) |
| except Exception: |
| bad += 1 |
|
|
| if rows: |
| table = pa.table({ |
| "ts": pa.array([parse_ts(r["ts"]) for r in rows], type=pa.timestamp("us", tz="UTC")), |
| "x": pa.array([r["x"] for r in rows], type=pa.float64()), |
| "y": pa.array([r["y"] for r in rows], type=pa.float64()), |
| "z1": pa.array([r["z1"] for r in rows], type=pa.float64()), |
| "z2": pa.array([r["z2"] for r in rows], type=pa.float64()), |
| "r": pa.array([r["r"] for r in rows], type=pa.float64()), |
| "has_homed": pa.array([r["has_homed"] for r in rows], type=pa.bool_()), |
| }, schema=schema) |
| pq.write_table(table, out, compression="zstd") |
| print(f" position_hf: {len(rows):,} rows, {bad} bad lines → {out.name}") |
|
|
|
|
| def append_frames_jsonl(): |
| path = SPOOL_DIR / "frames.ndjson" |
| out = EXPORTS_DIR / "frames.jsonl" |
|
|
| |
| if out.exists(): |
| with out.open(encoding="utf-8") as f: |
| for line in f: |
| try: |
| r = json.loads(line) |
| if r.get("build_id") == BUILD_ID: |
| print(f" frames.jsonl: build {BUILD_ID} already present, skipping") |
| return |
| except Exception: |
| pass |
|
|
| |
| max_id = 0 |
| if out.exists(): |
| with out.open(encoding="utf-8") as f: |
| for line in f: |
| try: |
| r = json.loads(line) |
| max_id = max(max_id, int(r.get("id", 0))) |
| except Exception: |
| pass |
|
|
| rows: list[dict] = [] |
| bad = 0 |
| with path.open(encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| rec = json.loads(line) |
| rows.append({ |
| "id": max_id + len(rows) + 1, |
| "build_id": BUILD_ID, |
| "ts": rec["respondedAt"], |
| "kind": rec["kind"], |
| "path": rec["path"], |
| }) |
| except Exception: |
| bad += 1 |
|
|
| with out.open("a", encoding="utf-8") as f: |
| for r in rows: |
| f.write(json.dumps(r) + "\n") |
| print(f" frames.jsonl: appended {len(rows):,} rows, {bad} bad lines") |
|
|
|
|
| def append_builds_jsonl(started_at: str, ended_at: str): |
| out = EXPORTS_DIR / "builds.jsonl" |
|
|
| if out.exists(): |
| with out.open(encoding="utf-8") as f: |
| for line in f: |
| try: |
| r = json.loads(line) |
| if r.get("id") == BUILD_ID: |
| print(f" builds.jsonl: build {BUILD_ID} already present, skipping") |
| return |
| except Exception: |
| pass |
|
|
| row = { |
| "id": BUILD_ID, |
| "job_name": JOB_NAME, |
| "started_at": started_at, |
| "ended_at": ended_at, |
| "phase": "recovered", |
| "params": {"notes": "recovered from NVMe spool after DB reset"}, |
| "notes": "spool-only recovery; job_name is a placeholder", |
| } |
| with out.open("a", encoding="utf-8") as f: |
| f.write(json.dumps(row) + "\n") |
| print(f" builds.jsonl: appended build {BUILD_ID}") |
|
|
|
|
| def append_events_jsonl(started_at: str): |
| """Add a build_start event so load_build_to_profile_name() can find |
| this build. Profile name is unknown; leave null.""" |
| out = EXPORTS_DIR / "events.jsonl" |
|
|
| if out.exists(): |
| with out.open(encoding="utf-8") as f: |
| for line in f: |
| try: |
| r = json.loads(line) |
| if r.get("build_id") == BUILD_ID and r.get("kind") == "build_start": |
| print(f" events.jsonl: build_start for {BUILD_ID} already present, skipping") |
| return |
| except Exception: |
| pass |
|
|
| row = { |
| "id": -41, |
| "build_id": BUILD_ID, |
| "ts": started_at, |
| "kind": "build_start", |
| "message": JOB_NAME, |
| "payload": {"printProfileName": None, "notes": "recovered from spool"}, |
| } |
| with out.open("a", encoding="utf-8") as f: |
| f.write(json.dumps(row) + "\n") |
| print(f" events.jsonl: appended build_start for build {BUILD_ID}") |
|
|
|
|
| def main(): |
| if not SPOOL_DIR.exists(): |
| print(f"Spool dir not found: {SPOOL_DIR}") |
| sys.exit(1) |
|
|
| print(f"Recovering build {BUILD_ID} from spool: {SPOOL_DIR}") |
| started_at, ended_at = build_telemetry_parquet() |
| build_position_parquet() |
| append_frames_jsonl() |
| append_builds_jsonl(started_at, ended_at) |
| append_events_jsonl(started_at) |
| print("Done. Run: uv run scripts/ticks/01_extract.py 41") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|