chronist 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. chronist/__init__.py +20 -0
  2. chronist/blobs.py +83 -0
  3. chronist/cli.py +373 -0
  4. chronist/client/__init__.py +4 -0
  5. chronist/client/code.py +619 -0
  6. chronist/client/files.py +214 -0
  7. chronist/client/prune.py +173 -0
  8. chronist/client/run.py +484 -0
  9. chronist/client/rundir.py +213 -0
  10. chronist/client/sync.py +97 -0
  11. chronist/client/uploader.py +336 -0
  12. chronist/codec.py +40 -0
  13. chronist/hist.py +399 -0
  14. chronist/meta.py +719 -0
  15. chronist/query.py +444 -0
  16. chronist/readback.py +680 -0
  17. chronist/server/__init__.py +8 -0
  18. chronist/server/app.py +748 -0
  19. chronist/server/core.py +731 -0
  20. chronist/server/tokens.py +129 -0
  21. chronist/store/__init__.py +18 -0
  22. chronist/store/base.py +178 -0
  23. chronist/store/cache.py +109 -0
  24. chronist/store/chunked.py +679 -0
  25. chronist/store/hist_store.py +219 -0
  26. chronist/store/sqlite_rows.py +305 -0
  27. chronist/ui/static/api.js +99 -0
  28. chronist/ui/static/app.css +307 -0
  29. chronist/ui/static/app.js +277 -0
  30. chronist/ui/static/code.js +187 -0
  31. chronist/ui/static/drawer.js +93 -0
  32. chronist/ui/static/files.js +64 -0
  33. chronist/ui/static/histplot.js +320 -0
  34. chronist/ui/static/index.html +15 -0
  35. chronist/ui/static/plot.js +408 -0
  36. chronist/ui/static/query.js +100 -0
  37. chronist/ui/static/share.js +83 -0
  38. chronist/ui/static/table.js +131 -0
  39. chronist/ui/static/util.js +165 -0
  40. chronist/ui/static/vendor/LICENSE.htm +202 -0
  41. chronist/ui/static/vendor/LICENSE.uplot +21 -0
  42. chronist/ui/static/vendor/hljs/LICENSE +29 -0
  43. chronist/ui/static/vendor/hljs/bash.min.js +21 -0
  44. chronist/ui/static/vendor/hljs/c.min.js +41 -0
  45. chronist/ui/static/vendor/hljs/cmake.min.js +7 -0
  46. chronist/ui/static/vendor/hljs/core.min.js +306 -0
  47. chronist/ui/static/vendor/hljs/cpp.min.js +46 -0
  48. chronist/ui/static/vendor/hljs/diff.min.js +9 -0
  49. chronist/ui/static/vendor/hljs/dockerfile.min.js +8 -0
  50. chronist/ui/static/vendor/hljs/ini.min.js +16 -0
  51. chronist/ui/static/vendor/hljs/javascript.min.js +81 -0
  52. chronist/ui/static/vendor/hljs/json.min.js +8 -0
  53. chronist/ui/static/vendor/hljs/makefile.min.js +14 -0
  54. chronist/ui/static/vendor/hljs/markdown.min.js +32 -0
  55. chronist/ui/static/vendor/hljs/plaintext.min.js +3 -0
  56. chronist/ui/static/vendor/hljs/python.min.js +42 -0
  57. chronist/ui/static/vendor/hljs/rust.min.js +27 -0
  58. chronist/ui/static/vendor/hljs/shell.min.js +5 -0
  59. chronist/ui/static/vendor/hljs/xml.min.js +29 -0
  60. chronist/ui/static/vendor/hljs/yaml.min.js +28 -0
  61. chronist/ui/static/vendor/htm-preact.module.js +1 -0
  62. chronist/ui/static/vendor/uPlot.esm.js +6140 -0
  63. chronist/ui/static/vendor/uPlot.min.css +1 -0
  64. chronist/ui/static/widgets.js +77 -0
  65. chronist-0.1.0.dist-info/METADATA +393 -0
  66. chronist-0.1.0.dist-info/RECORD +73 -0
  67. chronist-0.1.0.dist-info/WHEEL +5 -0
  68. chronist-0.1.0.dist-info/entry_points.txt +2 -0
  69. chronist-0.1.0.dist-info/licenses/LICENSE +28 -0
  70. chronist-0.1.0.dist-info/licenses/chronist/ui/static/vendor/LICENSE.htm +202 -0
  71. chronist-0.1.0.dist-info/licenses/chronist/ui/static/vendor/LICENSE.uplot +21 -0
  72. chronist-0.1.0.dist-info/licenses/chronist/ui/static/vendor/hljs/LICENSE +29 -0
  73. chronist-0.1.0.dist-info/top_level.txt +1 -0
chronist/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """Chronist: a lightweight, self-hostable experiment tracker.
2
+
3
+ import chronist
4
+ run = chronist.init(project="bptt-free", config={"model": {"arch": "lstm"}})
5
+ for step in range(n):
6
+ run.log({"loss": loss}, step=step)
7
+ run.finish()
8
+
9
+ runs = chronist.runs('model.arch = "lstm"', project="bptt-free")
10
+ df = runs.history(["loss"], max_points=2000)
11
+ """
12
+ __version__ = "0.1.0"
13
+
14
+ from .client import Run, active, finish, init, log, sync # noqa: E402
15
+ from .client.code import Code # noqa: E402
16
+ from .hist import Histogram # noqa: E402
17
+ from .readback import RunRef, RunSet, code_diff, run, runs # noqa: E402
18
+
19
+ __all__ = ["init", "log", "finish", "active", "Run", "runs", "RunSet", "run", "RunRef", "Code", "Histogram",
20
+ "code_diff", "sync", "__version__"]
chronist/blobs.py ADDED
@@ -0,0 +1,83 @@
1
+ """Content-addressed blob storage (code snapshots, environment info).
2
+
3
+ Blobs are keyed by the sha256 of their *uncompressed* content and stored
4
+ compressed (``codec``). ``FsBlobStore`` lays them out like git objects:
5
+ ``<dir>/ab/cdef...``. Writes are atomic (tmp + rename), so a reader never
6
+ sees a partial blob.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import os
12
+ import re
13
+ from typing import Iterable, List, Optional
14
+
15
+ try:
16
+ from typing import Protocol
17
+ except ImportError: # pragma: no cover
18
+ Protocol = object # type: ignore
19
+
20
+ from .codec import compress, decompress
21
+
22
+ HASH_RE = re.compile(r"^[0-9a-f]{64}$")
23
+
24
+
25
+ def sha256(data: bytes) -> str:
26
+ return hashlib.sha256(data).hexdigest()
27
+
28
+
29
+ def valid_hash(h: str) -> bool:
30
+ return bool(HASH_RE.match(h))
31
+
32
+
33
+ class BlobStore(Protocol):
34
+ def missing(self, hashes: Iterable[str]) -> List[str]: ...
35
+ def put(self, h: str, compressed: bytes) -> None: ... # verifies the hash
36
+ def get(self, h: str) -> Optional[bytes]: ... # compressed bytes
37
+ def read(self, h: str) -> Optional[bytes]: ... # uncompressed content
38
+
39
+
40
+ class FsBlobStore:
41
+ def __init__(self, path: str):
42
+ self.path = os.path.abspath(path)
43
+
44
+ def _p(self, h: str) -> str:
45
+ if not valid_hash(h):
46
+ raise ValueError(f"bad blob hash {h!r}")
47
+ return os.path.join(self.path, h[:2], h[2:])
48
+
49
+ def has(self, h: str) -> bool:
50
+ return os.path.exists(self._p(h))
51
+
52
+ def missing(self, hashes: Iterable[str]) -> List[str]:
53
+ return [h for h in dict.fromkeys(hashes) if not self.has(h)]
54
+
55
+ def put(self, h: str, compressed: bytes, verify: bool = True) -> None:
56
+ if self.has(h):
57
+ return
58
+ if verify and sha256(decompress(compressed)) != h:
59
+ raise ValueError(f"blob content does not match hash {h}")
60
+ p = self._p(h)
61
+ os.makedirs(os.path.dirname(p), exist_ok=True)
62
+ tmp = f"{p}.tmp{os.getpid()}.{id(compressed)}"
63
+ with open(tmp, "wb") as f:
64
+ f.write(compressed)
65
+ os.replace(tmp, p)
66
+
67
+ def put_raw(self, data: bytes) -> str:
68
+ """Store uncompressed content; returns its hash."""
69
+ h = sha256(data)
70
+ if not self.has(h):
71
+ self.put(h, compress(data), verify=False)
72
+ return h
73
+
74
+ def get(self, h: str) -> Optional[bytes]:
75
+ try:
76
+ with open(self._p(h), "rb") as f:
77
+ return f.read()
78
+ except FileNotFoundError:
79
+ return None
80
+
81
+ def read(self, h: str) -> Optional[bytes]:
82
+ c = self.get(h)
83
+ return None if c is None else decompress(c)
chronist/cli.py ADDED
@@ -0,0 +1,373 @@
1
+ """Command line: chronist ui | serve | sync | tokens."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import logging
7
+ import os
8
+ import secrets
9
+ import sys
10
+ import threading
11
+ import time
12
+ import webbrowser
13
+
14
+ DEFAULT_PORT = 7070
15
+
16
+
17
+ def _tokens_path(data: str) -> str:
18
+ return os.path.join(os.path.abspath(os.path.expanduser(data)), "tokens.json")
19
+
20
+
21
+ def _parse_size(v):
22
+ if v is None:
23
+ return None
24
+ s = str(v).strip().upper()
25
+ for unit, mult in (("TB", 10 ** 12), ("GB", 10 ** 9), ("MB", 10 ** 6), ("KB", 10 ** 3), ("B", 1)):
26
+ if s.endswith(unit):
27
+ return int(float(s[: -len(unit)]) * mult)
28
+ return int(float(s))
29
+
30
+
31
+ def token_store(data: str):
32
+ from .server.tokens import TokenStore
33
+ return TokenStore(_tokens_path(data))
34
+
35
+
36
+ def _run_server(core, host: str, port: int, tokens, on_ready=None):
37
+ import uvicorn
38
+
39
+ from .server.app import create_app
40
+ app = create_app(core, tokens=tokens)
41
+ config = uvicorn.Config(app, host=host, port=port, log_level="warning", access_log=False,
42
+ timeout_keep_alive=30)
43
+ server = uvicorn.Server(config)
44
+ if on_ready:
45
+ def waiter():
46
+ while not server.started:
47
+ time.sleep(0.05)
48
+ on_ready()
49
+ threading.Thread(target=waiter, daemon=True).start()
50
+ try:
51
+ server.run()
52
+ finally:
53
+ core.close()
54
+
55
+
56
+ def _watch_local(url: str, root: str, interval: float = 2.0):
57
+ """`chronist ui`: continuously sync offline runs from CHRONIST_DIR into the local server."""
58
+ from .client.sync import find_runs, sync_run
59
+ log = logging.getLogger("chronist")
60
+ while True:
61
+ try:
62
+ for rd in find_runs([root]):
63
+ try:
64
+ sync_run(rd, url)
65
+ except Exception as e: # pragma: no cover
66
+ log.debug("watch: %s: %s", rd.path, e)
67
+ except Exception: # pragma: no cover
68
+ log.exception("watch failed")
69
+ time.sleep(interval)
70
+
71
+
72
+ def cmd_ui(a):
73
+ from .client.rundir import default_dir
74
+ from .server.core import Core
75
+ core = Core(a.data)
76
+ url = f"http://{a.host}:{a.port}"
77
+
78
+ def ready():
79
+ print(f"chronist UI on {url} (data: {core.data_dir})", flush=True)
80
+ if a.watch:
81
+ root = a.watch_dir or default_dir()
82
+ print(f"watching {root} for offline runs", flush=True)
83
+ threading.Thread(target=_watch_local, args=(url, root), daemon=True).start()
84
+ if a.browser:
85
+ webbrowser.open(url)
86
+ _run_server(core, a.host, a.port, {}, on_ready=ready)
87
+
88
+
89
+ def cmd_serve(a):
90
+ from .server.core import Core
91
+ tokens = token_store(a.data)
92
+ for t in a.token or []:
93
+ tokens.add(t, "write")
94
+ for t in a.read_token or []:
95
+ tokens.add(t, "read", code=False)
96
+ if os.environ.get("CHRONIST_SERVER_TOKEN"):
97
+ tokens.add(os.environ["CHRONIST_SERVER_TOKEN"], "write")
98
+ if a.no_auth:
99
+ tokens.clear()
100
+ elif not tokens.enabled and a.host not in ("127.0.0.1", "localhost", "::1"):
101
+ w = tokens.create("write", label="generated by chronist serve")
102
+ print(f"generated a write token (stored in {_tokens_path(a.data)}):\n {w}\n"
103
+ f"create share links in the UI (Share button) or with: chronist tokens --new read [--code]")
104
+ core = Core(a.data, heartbeat_timeout=a.heartbeat_timeout, cache_mb=a.cache_mb, blob_dir=a.blob_dir,
105
+ max_blob_storage=_parse_size(a.max_blob_storage), max_file_size=_parse_size(a.max_file_size))
106
+
107
+ def ready():
108
+ c = tokens.counts()
109
+ auth = (f"{c['write']} write / {c['read']} read / {c['read+code']} read+code tokens"
110
+ if tokens.enabled else "auth OFF")
111
+ print(f"chronist serving on http://{a.host}:{a.port} ({auth}; data: {core.data_dir})", flush=True)
112
+ _run_server(core, a.host, a.port, tokens, on_ready=ready)
113
+
114
+
115
+ def cmd_sync(a):
116
+ from .client.sync import sync
117
+ res = sync(a.paths or None, url=a.url, token=a.token)
118
+ errors = [r for r in res if "error" in r]
119
+ print(f"synced {len(res) - len(errors)} runs" + (f", {len(errors)} errors" if errors else ""))
120
+ return 1 if errors else 0
121
+
122
+
123
+ def cmd_tokens(a):
124
+ import datetime as dt
125
+ tokens = token_store(a.data)
126
+ if a.new:
127
+ t = tokens.create(a.new, code=a.code, label=a.label or "")
128
+ extra = " (can see code)" if a.new == "read" and a.code else ""
129
+ print(f"new {a.new} token{extra}: {t}")
130
+ if a.new == "read":
131
+ print("share as: https://<your-host>/?token=" + t)
132
+ print("a running server picks this up after a restart; tokens made in the UI apply immediately")
133
+ return
134
+ if a.revoke:
135
+ if not tokens.revoke(a.revoke):
136
+ print("no such token", file=sys.stderr)
137
+ return 1
138
+ return
139
+ for e in tokens.list():
140
+ when = dt.datetime.fromtimestamp(e["created"]).strftime("%Y-%m-%d") if e["created"] else "-"
141
+ kind = e["role"] + ("+code" if e["role"] == "read" and e["code"] else "")
142
+ print(f"{e['id']} {kind:10s} {when} {e['label']}")
143
+
144
+
145
+ def _source_args(p):
146
+ p.add_argument("--url", default=None, help="server (default $CHRONIST_URL; else the local data dir)")
147
+ p.add_argument("--token", default=None)
148
+ p.add_argument("--data", default=None, help="local data dir (default ~/.chronist/data)")
149
+
150
+
151
+ def cmd_checkout(a):
152
+ from .readback import run
153
+ r = run(a.run, url=a.url, token=a.token, data_dir=a.data)
154
+ if r.code is None:
155
+ print(f"run {a.run} has no code snapshot", file=sys.stderr)
156
+ return 1
157
+ dest = a.dir or f"chronist-checkout-{r.id}"
158
+ from .client.code import CodeError
159
+ try:
160
+ path = r.code.checkout(dest, force=a.force)
161
+ except CodeError as e:
162
+ print(e, file=sys.stderr)
163
+ return 1
164
+ print(f"restored {len(r.code.files())} files of run {r.id} ({r.name}) into {path}")
165
+ cmd = (r.meta.get("command") or [])
166
+ if cmd:
167
+ print("command:", " ".join(cmd))
168
+
169
+
170
+ def cmd_snapshot(a):
171
+ import os
172
+
173
+ from .blobs import FsBlobStore
174
+ from .client import code as C
175
+ from .client.rundir import default_dir
176
+ C._REFERENCE_OVERRIDE = os.getcwd()
177
+ opts = C.parse_code_arg(a.code if a.code.lower() != "none" else None) or C.Code()
178
+ base = os.path.abspath(os.path.expanduser(default_dir()))
179
+ store = FsBlobStore(os.path.join(base, "blobs"))
180
+ snap = C.take_snapshot(opts, store)
181
+ if "manifest" not in snap:
182
+ print(f"snapshot aborted: {snap.get('aborted')}", file=sys.stderr)
183
+ return 1
184
+ print(f"{snap['manifest']} {snap['files']} files, {snap['bytes'] / 1024:.1f} KB, root {snap['root']} "
185
+ f"({snap['mode']})")
186
+ if a.run:
187
+ import httpx
188
+
189
+ from .client.code import manifest_blobs
190
+ url = a.url or os.environ.get("CHRONIST_URL")
191
+ token = a.token or os.environ.get("CHRONIST_TOKEN")
192
+ if not url:
193
+ print("--run needs a server (--url or CHRONIST_URL)", file=sys.stderr)
194
+ return 1
195
+ h = {"Authorization": f"Bearer {token}"} if token else {}
196
+ with httpx.Client(base_url=url.rstrip("/"), headers=h, timeout=60) as http:
197
+ hashes = manifest_blobs(json.loads(store.read(snap["manifest"]))) + [snap["manifest"]]
198
+ r = http.post("/api/blobs/missing", json={"hashes": hashes})
199
+ r.raise_for_status()
200
+ for bh in r.json()["missing"]:
201
+ http.put(f"/api/blobs/{bh}", content=store.get(bh)).raise_for_status()
202
+ r = http.post(f"/api/runs/{a.run}/code", json={"manifest": snap["manifest"]})
203
+ if r.status_code >= 400:
204
+ print(f"attaching failed: {r.text}", file=sys.stderr)
205
+ return 1
206
+ http.patch(f"/api/runs/{a.run}", json={"meta": {"code": snap}}).raise_for_status()
207
+ print(f"attached to run {a.run}")
208
+
209
+
210
+ def cmd_code_diff(a):
211
+ from .readback import code_diff
212
+ d = code_diff(a.a, a.b, url=a.url, token=a.token, data_dir=a.data, unified=not a.stat)
213
+ for k, sign in (("removed", "-"), ("added", "+"), ("changed", "M")):
214
+ for p in d[k]:
215
+ print(f"{sign} {p}")
216
+ c = d["config"]
217
+ for k in c["removed"]:
218
+ print(f"- config {k}")
219
+ for k in c["added"]:
220
+ print(f"+ config {k}")
221
+ for k, (va, vb) in c["changed"].items():
222
+ print(f"M config {k}: {va!r} -> {vb!r}")
223
+ if not a.stat:
224
+ for p, txt in d["diffs"].items():
225
+ print()
226
+ print(txt, end="" if txt.endswith("\n") else "\n")
227
+
228
+
229
+ def cmd_pull(a):
230
+ from .readback import run
231
+ r = run(a.run, url=a.url, token=a.token, data_dir=a.data)
232
+ try:
233
+ path = r.download(a.name, alias=a.alias, step=a.step, version=a.version, dest=a.dest)
234
+ except KeyError as e:
235
+ print(e.args[0], file=sys.stderr)
236
+ return 1
237
+ print(path)
238
+
239
+
240
+ def cmd_prune(a):
241
+ from .client.prune import prune
242
+ res = prune(a.paths or None, url=a.url, older_than_days=a.older_than, dry_run=a.dry_run)
243
+ verb = "would prune" if a.dry_run else "pruned"
244
+ print(f"{verb} {res['pruned']} runs, kept {res['kept']}; {res['blobs']} unreferenced blobs "
245
+ f"{'would be ' if a.dry_run else ''}removed")
246
+
247
+
248
+ def cmd_gc(a):
249
+ if a.url or os.environ.get("CHRONIST_URL") and not a.data:
250
+ import httpx
251
+ url = (a.url or os.environ["CHRONIST_URL"]).rstrip("/")
252
+ token = a.token or os.environ.get("CHRONIST_TOKEN")
253
+ h = {"Authorization": f"Bearer {token}"} if token else {}
254
+ r = httpx.post(f"{url}/api/admin/gc", json={"vacuum": a.vacuum}, headers=h, timeout=3600)
255
+ if r.status_code >= 400:
256
+ print(f"gc failed: {r.text}", file=sys.stderr)
257
+ return 1
258
+ res = r.json()
259
+ else:
260
+ from .server.core import Core, default_data_dir
261
+ try:
262
+ core = Core(a.data or default_data_dir())
263
+ except RuntimeError as e:
264
+ print(f"{e}\nrun it through the server instead: chronist gc --url <server>", file=sys.stderr)
265
+ return 1
266
+ try:
267
+ res = core.writer.submit(core.op_gc, a.vacuum).result()
268
+ finally:
269
+ core.close()
270
+ print(f"removed {res['blobs_removed']} blobs ({res['blob_bytes_freed'] / 1e6:.1f} MB), "
271
+ f"{res['vacuum']} vacuum freed {res['db_bytes_freed'] / 1e6:.1f} MB")
272
+
273
+
274
+ def main(argv=None):
275
+ from .server.core import default_data_dir
276
+ logging.basicConfig(level=logging.WARNING, format="%(message)s")
277
+ ap = argparse.ArgumentParser(prog="chronist", description="lightweight experiment tracker")
278
+ sub = ap.add_subparsers(dest="cmd", required=True)
279
+
280
+ p = sub.add_parser("ui", help="local server + UI on localhost, no auth")
281
+ p.add_argument("--data", default=default_data_dir(), help="data dir (default: %(default)s)")
282
+ p.add_argument("--host", default="127.0.0.1")
283
+ p.add_argument("--port", type=int, default=DEFAULT_PORT)
284
+ p.add_argument("--no-browser", dest="browser", action="store_false")
285
+ p.add_argument("--no-watch", dest="watch", action="store_false",
286
+ help="don't auto-sync offline runs from CHRONIST_DIR")
287
+ p.add_argument("--watch-dir", default=None)
288
+ p.set_defaults(fn=cmd_ui)
289
+
290
+ p = sub.add_parser("serve", help="server for remote use (put Caddy/nginx in front for TLS)")
291
+ p.add_argument("--data", default=default_data_dir())
292
+ p.add_argument("--host", default="127.0.0.1")
293
+ p.add_argument("--port", type=int, default=DEFAULT_PORT)
294
+ p.add_argument("--token", action="append", help="write token (repeatable)")
295
+ p.add_argument("--read-token", action="append", help="read-only token without code access (repeatable)")
296
+ p.add_argument("--no-auth", action="store_true")
297
+ p.add_argument("--heartbeat-timeout", type=float, default=180.0,
298
+ help="seconds without heartbeat before a running run is marked crashed")
299
+ p.add_argument("--cache-mb", type=float, default=64.0, help="read cache budget (default %(default)s MB)")
300
+ p.add_argument("--blob-dir", default=None, help="where blobs (code, file chunks) live (default <data>/blobs)")
301
+ p.add_argument("--max-blob-storage", default=None, help="quota for blobs, e.g. 50GB: file uploads are "
302
+ "refused beyond it (metrics keep working)")
303
+ p.add_argument("--max-file-size", default="20GB", help="largest accepted file (default %(default)s)")
304
+ p.set_defaults(fn=cmd_serve)
305
+
306
+ p = sub.add_parser("sync", help="upload local (offline or backlogged) runs")
307
+ p.add_argument("paths", nargs="*", help="run dirs or CHRONIST_DIR roots (default: $CHRONIST_DIR)")
308
+ p.add_argument("--url", default=None)
309
+ p.add_argument("--token", default=None)
310
+ p.set_defaults(fn=cmd_sync)
311
+
312
+ p = sub.add_parser("tokens", help="list / create / revoke server tokens")
313
+ p.add_argument("--data", default=default_data_dir())
314
+ p.add_argument("--new", choices=["write", "read"])
315
+ p.add_argument("--code", action="store_true", help="with --new read: the token may also see code snapshots")
316
+ p.add_argument("--label", default=None)
317
+ p.add_argument("--revoke", metavar="TOKEN_OR_ID")
318
+ p.set_defaults(fn=cmd_tokens)
319
+
320
+ p = sub.add_parser("pull", help="download a file attached to a run")
321
+ p.add_argument("run", help="run id or uid")
322
+ p.add_argument("name", help="file name (e.g. model)")
323
+ g = p.add_mutually_exclusive_group()
324
+ g.add_argument("--alias", default=None, help="default: latest")
325
+ g.add_argument("--step", type=int, default=None)
326
+ g.add_argument("--version", type=int, default=None)
327
+ p.add_argument("--dest", default=".", help="directory or file path (default: .)")
328
+ _source_args(p)
329
+ p.set_defaults(fn=cmd_pull)
330
+
331
+ p = sub.add_parser("prune", help="delete local run buffers that are fully uploaded")
332
+ p.add_argument("paths", nargs="*", help="CHRONIST_DIR roots or run dirs (default: $CHRONIST_DIR)")
333
+ p.add_argument("--url", default=None, help="only runs fully uploaded to this server")
334
+ p.add_argument("--older-than", type=float, default=0, metavar="DAYS")
335
+ p.add_argument("--dry-run", action="store_true")
336
+ p.set_defaults(fn=cmd_prune)
337
+
338
+ p = sub.add_parser("gc", help="server: delete unreferenced blobs, vacuum the databases")
339
+ p.add_argument("--data", default=None, help="data dir (server must not be running)")
340
+ p.add_argument("--url", default=None, help="run it inside a running server instead")
341
+ p.add_argument("--token", default=None)
342
+ p.add_argument("--vacuum", action="store_true", help="full VACUUM (rewrites the files; slow on big data)")
343
+ p.set_defaults(fn=cmd_gc)
344
+
345
+ p = sub.add_parser("checkout", help="restore a run's code snapshot into a directory")
346
+ p.add_argument("run", help="run id or uid")
347
+ p.add_argument("dir", nargs="?", default=None, help="default ./chronist-checkout-<id>")
348
+ p.add_argument("--force", action="store_true", help="write into a non-empty directory")
349
+ _source_args(p)
350
+ p.set_defaults(fn=cmd_checkout)
351
+
352
+ p = sub.add_parser("snapshot", help="take a standalone code snapshot (root resolved from the cwd)")
353
+ p.add_argument("--code", default="auto", help="auto | git | <path>")
354
+ p.add_argument("--run", default=None, help="attach to this run id on the server")
355
+ p.add_argument("--url", default=None)
356
+ p.add_argument("--token", default=None)
357
+ p.set_defaults(fn=cmd_snapshot)
358
+
359
+ p = sub.add_parser("code", help="code snapshot tools")
360
+ csub = p.add_subparsers(dest="code_cmd", required=True)
361
+ d = csub.add_parser("diff", help="diff code + config of two runs")
362
+ d.add_argument("a")
363
+ d.add_argument("b")
364
+ d.add_argument("--stat", action="store_true", help="only list changed files and config keys")
365
+ _source_args(d)
366
+ d.set_defaults(fn=cmd_code_diff)
367
+
368
+ a = ap.parse_args(argv)
369
+ sys.exit(a.fn(a) or 0)
370
+
371
+
372
+ if __name__ == "__main__":
373
+ main()
@@ -0,0 +1,4 @@
1
+ from .run import Run, active, finish, init, log
2
+ from .sync import sync
3
+
4
+ __all__ = ["Run", "init", "log", "finish", "active", "sync"]