File size: 6,688 Bytes
ba16cc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Back THE NOTEBOOK up to the Hub. It is the recovery artifact, not the box.

WHY THE NOTEBOOK IS THE RIGHT UNIT TO BACK UP
    It carries the queue policy (`queue_policy`), the job list, and the bytes of every program
    (`agent_benchmark_payload`, zlib + sha256). Everything else on /home/marimo is either
    regenerable from it or was already published (facts.duckdb, adapters, traces). /home/marimo is
    an OVERLAY and has been lost twice (RESUME 14); the notebook is the one file that survived both
    relaunches. So: back up the notebook, and back up nothing else by hand.

WHAT IT DOES, IN ORDER
    1. snapshot /marimo/notebook.py -> notebook_snapshot/notebook.py (sha256, size, cell count);
    2. VERIFY the snapshot before trusting it: compile it, then decode its payload cell and check
       every program against the hash the notebook records. A backup whose payload does not decode
       is worthless, and that is better discovered here than during a relaunch;
    3. push to dragonlimited/dragon-state as state/notebook.py + state/notebook_snapshot.json when a
       token is present, then RE-DOWNLOAD it and compare sha256 - a round trip, not a hope;
    4. with no token: write notebook_backup_pending.json carrying the exact command and the hash to
       expect, and exit 0. The push is a one-liner for whoever holds a token.

IDEMPOTENT: if the Hub copy already has the same sha256, it says so and pushes nothing.
"""
import base64, hashlib, json, os, re, subprocess, sys, time, zlib
import pathlib
from pathlib import Path

W = Path("/home/marimo/dragon_fsds")
SRC = Path("/marimo/notebook.py")
SNAP = W / "notebook_snapshot"
SNAP.mkdir(exist_ok=True)
REPO = "dragonlimited/dragon-state"
def _token():
    """The key, from the environment OR the project's own key file.

    Both paths matter: a cell launched from the notebook does not inherit the shell that ran the
    training, and the file is the convention this project already uses (box_autopilot_plan reads it).
    Without this, a notebook-driven push silently reported "no token" while a token existed.
    """
    t = os.environ.get("HF_TOKEN_BOOT") or os.environ.get("HF_TOKEN") or ""
    if not t:
        p = pathlib.Path("/home/marimo/.hf_token_boot")
        if p.exists():
            t = p.read_text().strip()
    return t


TOKEN = _token()
LOG = W / "backup_notebook.log"

def log(*a):
    line = time.strftime("%H:%M:%S") + " " + " ".join(str(x) for x in a)
    print(line, flush=True)
    with open(LOG, "a") as fh: fh.write(line + "\n")

def sha(b): return hashlib.sha256(b).hexdigest()

def remote_sha(path="state/notebook.py"):
    """The Hub copy is readable without a token; the comparison is what makes this idempotent."""
    import urllib.request
    try:
        req = urllib.request.Request(f"https://huggingface.co/{REPO}/resolve/main/{path}",
                                     headers={"Authorization": f"Bearer {TOKEN}"} if TOKEN else {})
        return sha(urllib.request.urlopen(req, timeout=60).read())
    except Exception as e:
        return f"unreadable:{type(e).__name__}"

# ---- 1. snapshot ------------------------------------------------------------
raw = SRC.read_bytes()
digest = sha(raw)
(SNAP / "notebook.py").write_bytes(raw)
cells = raw.decode("utf-8", "replace").count("@app.cell")
log(f"snapshot: {len(raw):,} bytes, {cells} cells, sha256 {digest[:16]}...")

# ---- 2. verify the snapshot: compile it and decode the payload it carries ----
report = {"at": time.strftime("%Y-%m-%d %H:%M:%S"), "bytes": len(raw), "cells": cells,
          "sha256": digest, "source": str(SRC)}
try:
    compile(raw, "notebook.py", "exec")
    report["compiles"] = True
except SyntaxError as e:
    report["compiles"] = False
    report["compile_error"] = f"{e.__class__.__name__}: {e}"
log(f"compiles: {report['compiles']}")

text = raw.decode("utf-8", "replace")
triples = re.findall(
    r"'([\w.\-]+\.(?:py|json))': \(\s*'([0-9a-f]{64})',\s*\n"
    r"((?:\s*'[A-Za-z0-9+/=]*'\s*\n)+)\s*\)", text)
programs, bad = {}, []
for name, want, blob in triples:
    b64 = "".join(re.findall(r"'([A-Za-z0-9+/=]*)'", blob))
    try:
        data = zlib.decompress(base64.b64decode(b64))
    except Exception as e:
        bad.append((name, f"undecodable: {type(e).__name__}")); continue
    got = sha(data)
    programs[name] = {"bytes": len(data), "sha256": got, "matches_notebook_record": got == want}
    if got != want:
        bad.append((name, "hash mismatch"))
report["programs_carried"] = programs
report["payload_ok"] = not bad and bool(programs)
report["payload_problems"] = bad
log(f"payload: {len(programs)} programs carried, all hashes match: {report['payload_ok']}")
if bad:
    log(f"  PROBLEMS: {bad}")

# ---- 3./4. push, or say exactly what the push would be ----------------------
have = remote_sha()
report["remote_sha256"] = have
report["remote_matches"] = (have == digest)
if not TOKEN:
    report["status"] = "PENDING - no token on this box; push is one command"
    report["push_command"] = (f"HF_TOKEN_BOOT=<rotated-token> python -u backup_notebook.py")
    log("no token: nothing was pushed")
elif have == digest:
    report["status"] = "already backed up (Hub copy has the same sha256)"
    log(report["status"])
else:
    dest = f"state/notebook.py"
    r = subprocess.run(f'hf upload {REPO} "{SNAP / "notebook.py"}" "{dest}" --repo-type model',
                       shell=True, capture_output=True, text=True,
                       env={**os.environ, "HF_TOKEN": TOKEN})
    log(f"upload rc={r.returncode} {(r.stdout + r.stderr).strip()[:200]}")
    report["pushed"] = r.returncode == 0
    subprocess.run(f'hf upload {REPO} "{W / "notebook_snapshot.json"}" "state/notebook_snapshot.json" '
                   f'--repo-type model', shell=True, capture_output=True, text=True,
                   env={**os.environ, "HF_TOKEN": TOKEN})
    back = remote_sha()
    report["round_trip_sha256"] = back
    report["round_trip_ok"] = (back == digest)
    if not report["pushed"]:
        report["status"] = f"PUSH FAILED (rc={r.returncode}) - nothing was uploaded"
    else:
        report["status"] = ("pushed and verified by re-download" if report["round_trip_ok"]
                            else "pushed, but the round trip did not verify")
    log(report["status"])

(W / "notebook_snapshot.json").write_text(json.dumps(report, indent=2))
(W / "notebook_backup_pending.json").write_text(json.dumps(
    {k: report[k] for k in ("at", "status", "sha256", "bytes", "cells", "payload_ok",
                            "programs_carried", "push_command", "remote_matches")
     if k in report}, indent=2))
log(f"status: {report['status']}")
sys.exit(0)