| |
| """Export new-DB builds into the export-format files with offset build IDs. |
| |
| The Postgres DB was reset after build 40, so the new DB's build IDs restart at |
| 1. This script exports them with remapped IDs so they don't collide with the |
| existing dataset (builds 1-41 already processed). |
| |
| Usage: |
| uv run --with psycopg2-binary scripts/ticks/00_export_new_db.py 1:42 2:43 |
| uv run --with psycopg2-binary scripts/ticks/00_export_new_db.py 3:44 |
| |
| Each argument is old_db_id:new_dataset_id. Don't export an in-progress build |
| (no ended_at in the DB) — wait for it to finish and the spool to be imported. |
| |
| Safe to re-run: telemetry/position_hf parquets are always overwritten; jsonl |
| files are checked first and skip if the new_id is already present. |
| """ |
| import json |
| import sys |
| from pathlib import Path |
|
|
| import psycopg2 |
| import psycopg2.extras |
| import pyarrow as pa |
| import pyarrow.parquet as pq |
|
|
| sys.path.insert(0, str(Path(__file__).parent.parent)) |
| from _lib import EXPORTS_DIR |
|
|
| DATABASE_URL = "postgres://inova:inova@localhost:5432/inova" |
| BATCH_ROWS = 100_000 |
|
|
|
|
| def get_conn(): |
| return psycopg2.connect(DATABASE_URL, cursor_factory=psycopg2.extras.RealDictCursor) |
|
|
|
|
| def export_telemetry(conn, old_id: int, new_id: int): |
| out = EXPORTS_DIR / "telemetry" / f"{new_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()), |
| ]) |
|
|
| with conn.cursor() as cur: |
| cur.execute( |
| "SELECT COUNT(*) AS n FROM telemetry WHERE build_id = %s", (old_id,) |
| ) |
| total = cur.fetchone()["n"] |
| if total == 0: |
| print(f" [{old_id}→{new_id}] telemetry: 0 rows in DB, skipping") |
| return |
|
|
| cur.execute( |
| "SELECT ts, sensor_id, kind, value FROM telemetry WHERE build_id = %s ORDER BY ts", |
| (old_id,) |
| ) |
| written = 0 |
| with pq.ParquetWriter(out, schema, compression="zstd") as writer: |
| while True: |
| rows = cur.fetchmany(BATCH_ROWS) |
| if not rows: |
| break |
| table = pa.table({ |
| "ts": pa.array([r["ts"] for r in rows], type=pa.timestamp("us", tz="UTC")), |
| "sensor_id": pa.array([r["sensor_id"] for r in rows], type=pa.string()), |
| "kind": pa.array([r["kind"] for r in rows], type=pa.string()), |
| "value": pa.array([float(r["value"]) for r in rows], type=pa.float64()), |
| }, schema=schema) |
| writer.write_table(table) |
| written += len(rows) |
| print(f" [{old_id}→{new_id}] telemetry: {written:,}/{total:,}...", end="\r") |
| print(f" [{old_id}→{new_id}] telemetry: {written:,} rows → {out.name} ") |
|
|
|
|
| def export_position_hf(conn, old_id: int, new_id: int): |
| out = EXPORTS_DIR / "position_hf" / f"{new_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_()), |
| ]) |
|
|
| with conn.cursor() as cur: |
| cur.execute( |
| "SELECT ts, x, y, z1, z2, r, has_homed FROM position_hf WHERE build_id = %s ORDER BY ts", |
| (old_id,) |
| ) |
| rows = cur.fetchall() |
|
|
| if not rows: |
| print(f" [{old_id}→{new_id}] position_hf: 0 rows") |
| return |
|
|
| table = pa.table({ |
| "ts": pa.array([r["ts"] for r in rows], type=pa.timestamp("us", tz="UTC")), |
| "x": pa.array([float(r["x"]) for r in rows], type=pa.float64()), |
| "y": pa.array([float(r["y"]) for r in rows], type=pa.float64()), |
| "z1": pa.array([float(r["z1"]) for r in rows], type=pa.float64()), |
| "z2": pa.array([float(r["z2"]) for r in rows], type=pa.float64()), |
| "r": pa.array([float(r["r"]) for r in rows], type=pa.float64()), |
| "has_homed": pa.array([bool(r["has_homed"]) for r in rows], type=pa.bool_()), |
| }, schema=schema) |
| pq.write_table(table, out, compression="zstd") |
| print(f" [{old_id}→{new_id}] position_hf: {len(rows):,} rows → {out.name}") |
|
|
|
|
| def append_builds_jsonl(conn, old_id: int, new_id: int): |
| 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") == new_id: |
| print(f" [{old_id}→{new_id}] builds.jsonl: id={new_id} already present, skipping") |
| return |
| except Exception: |
| pass |
|
|
| with get_conn() as c, c.cursor() as cur: |
| cur.execute("SELECT * FROM builds WHERE id = %s", (old_id,)) |
| row = cur.fetchone() |
|
|
| if not row: |
| print(f" [{old_id}→{new_id}] builds.jsonl: build {old_id} not in DB, skipping") |
| return |
|
|
| entry = { |
| "id": new_id, |
| "job_name": row["job_name"], |
| "started_at": row["started_at"].isoformat() if row["started_at"] else None, |
| "ended_at": row["ended_at"].isoformat() if row["ended_at"] else None, |
| "phase": row["phase"], |
| "params": row["params"], |
| "notes": (row["notes"] or "") + f" [originally DB id={old_id}, remapped to {new_id}]", |
| } |
| with out.open("a", encoding="utf-8") as f: |
| f.write(json.dumps(entry) + "\n") |
| print(f" [{old_id}→{new_id}] builds.jsonl: appended id={new_id} ({entry['job_name']})") |
|
|
|
|
| def append_frames_jsonl(conn, old_id: int, new_id: int): |
| 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") == new_id: |
| print(f" [{old_id}→{new_id}] frames.jsonl: build_id={new_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 |
|
|
| with conn.cursor() as cur: |
| cur.execute( |
| "SELECT id, ts, kind, path FROM frames WHERE build_id = %s ORDER BY ts", |
| (old_id,) |
| ) |
| rows = cur.fetchall() |
|
|
| if not rows: |
| print(f" [{old_id}→{new_id}] frames.jsonl: 0 frames in DB") |
| return |
|
|
| with out.open("a", encoding="utf-8") as f: |
| for i, r in enumerate(rows): |
| entry = { |
| "id": max_id + i + 1, |
| "build_id": new_id, |
| "ts": r["ts"].isoformat(), |
| "kind": r["kind"], |
| "path": r["path"], |
| } |
| f.write(json.dumps(entry) + "\n") |
| print(f" [{old_id}→{new_id}] frames.jsonl: appended {len(rows):,} rows") |
|
|
|
|
| def append_events_jsonl(conn, old_id: int, new_id: int): |
| """Append build_start event so load_build_to_profile_name() picks up the |
| print profile name for this build.""" |
| 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") == new_id and r.get("kind") == "build_start": |
| print(f" [{old_id}→{new_id}] events.jsonl: build_start already present, skipping") |
| return |
| except Exception: |
| pass |
|
|
| with conn.cursor() as cur: |
| cur.execute( |
| "SELECT * FROM events WHERE build_id = %s AND kind = 'build_start' LIMIT 1", |
| (old_id,) |
| ) |
| row = cur.fetchone() |
|
|
| if not row: |
| print(f" [{old_id}→{new_id}] events.jsonl: no build_start event in DB") |
| return |
|
|
| entry = { |
| "id": -(new_id), |
| "build_id": new_id, |
| "ts": row["ts"].isoformat() if row["ts"] else None, |
| "kind": "build_start", |
| "message": row["message"], |
| "payload": row["payload"], |
| } |
| with out.open("a", encoding="utf-8") as f: |
| f.write(json.dumps(entry) + "\n") |
| print(f" [{old_id}→{new_id}] events.jsonl: appended build_start") |
|
|
|
|
| def main(): |
| if len(sys.argv) < 2: |
| print(__doc__) |
| sys.exit(1) |
|
|
| mappings: list[tuple[int, int]] = [] |
| for arg in sys.argv[1:]: |
| try: |
| old_s, new_s = arg.split(":") |
| mappings.append((int(old_s), int(new_s))) |
| except ValueError: |
| print(f"Bad argument {arg!r} — expected old_id:new_id") |
| sys.exit(1) |
|
|
| conn = get_conn() |
| try: |
| for old_id, new_id in mappings: |
| print(f"\nExporting DB build {old_id} → dataset build {new_id}") |
| export_telemetry(conn, old_id, new_id) |
| export_position_hf(conn, old_id, new_id) |
| append_builds_jsonl(conn, old_id, new_id) |
| append_frames_jsonl(conn, old_id, new_id) |
| append_events_jsonl(conn, old_id, new_id) |
| finally: |
| conn.close() |
|
|
| new_ids = " ".join(str(n) for _, n in mappings) |
| print(f"\nDone. Run: uv run scripts/ticks/01_extract.py {new_ids}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|