File size: 9,936 Bytes
7615f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python3
"""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()