File size: 11,720 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/env python3
"""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"

    # Idempotency: skip if already appended.
    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

    # Determine the highest existing frame id so we can assign new ones.
    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()