compactlab 0.2.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.
- compactlab/__init__.py +3 -0
- compactlab/adapters/__init__.py +2 -0
- compactlab/adapters/base.py +212 -0
- compactlab/adapters/cache.py +396 -0
- compactlab/adapters/claude_code.py +226 -0
- compactlab/adapters/codex.py +298 -0
- compactlab/adapters/dsh.py +287 -0
- compactlab/adapters/gemini_cli.py +259 -0
- compactlab/adapters/opencode.py +375 -0
- compactlab/apply/__init__.py +582 -0
- compactlab/cli/__init__.py +5 -0
- compactlab/cli/main.py +2436 -0
- compactlab/data/config_knobs.json +158 -0
- compactlab/data/harness_defaults.json +72 -0
- compactlab/data/harness_formats.json +300 -0
- compactlab/data/pricing.json +51 -0
- compactlab/engine/__init__.py +138 -0
- compactlab/engine/live.py +306 -0
- compactlab/engine/settings.py +175 -0
- compactlab/engine/watch.py +82 -0
- compactlab/eval/__init__.py +1 -0
- compactlab/eval/deep.py +390 -0
- compactlab/eval/executors.py +84 -0
- compactlab/eval/factcheck.py +75 -0
- compactlab/lens.py +80 -0
- compactlab/model/__init__.py +285 -0
- compactlab/pricing/__init__.py +211 -0
- compactlab/pricing/auto.py +118 -0
- compactlab/pricing/ids.py +148 -0
- compactlab/pricing/refresh.py +299 -0
- compactlab/publish.py +125 -0
- compactlab/py.typed +0 -0
- compactlab/recommend/__init__.py +201 -0
- compactlab/recommend/claude_code.py +172 -0
- compactlab/recommend/codex.py +104 -0
- compactlab/recommend/dsh.py +89 -0
- compactlab/recommend/gemini_cli.py +85 -0
- compactlab/recommend/opencode.py +117 -0
- compactlab/recommend/units.py +63 -0
- compactlab/report/__init__.py +3 -0
- compactlab/report/html.py +27 -0
- compactlab/report/template.html +1189 -0
- compactlab/service/__init__.py +1 -0
- compactlab/service/core.py +220 -0
- compactlab/service/http.py +133 -0
- compactlab/service/lock.py +92 -0
- compactlab/service/policy.py +258 -0
- compactlab/service/schedule.py +212 -0
- compactlab/share.py +553 -0
- compactlab/sim/__init__.py +1 -0
- compactlab/sim/baseline.py +214 -0
- compactlab/sim/calibrate.py +108 -0
- compactlab/sim/engine.py +1130 -0
- compactlab/sim/select.py +238 -0
- compactlab/sim/timing.py +134 -0
- compactlab/synth.py +416 -0
- compactlab/term/__init__.py +0 -0
- compactlab/term/style.py +134 -0
- compactlab/term/top.py +531 -0
- compactlab/term/views.py +598 -0
- compactlab/term/widgets.py +238 -0
- compactlab/verify.py +462 -0
- compactlab-0.2.0.dist-info/METADATA +243 -0
- compactlab-0.2.0.dist-info/RECORD +67 -0
- compactlab-0.2.0.dist-info/WHEEL +4 -0
- compactlab-0.2.0.dist-info/entry_points.txt +2 -0
- compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""compactlab as a background service: scheduled lite recalibration, a localhost API and opt-in auto-apply."""
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""The calibrator behind `compactlab serve`, `compactlab recalibrate` and `compactlab engine calibrate`: one lite
|
|
2
|
+
analysis at a time (in this process and across processes, see lock.py), on a schedule, with backoff after failures;
|
|
3
|
+
the last result is kept in memory and on disk (the report, the API and the lens mod read it)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from .. import apply as ap
|
|
16
|
+
from ..lens import summarize
|
|
17
|
+
from ..publish import update
|
|
18
|
+
from .lock import Busy, LockError, single_flight
|
|
19
|
+
from .policy import Consent, Rules, load_applied, load_consent, run_auto_apply
|
|
20
|
+
from .schedule import next_due
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger("compactlab.service")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Calibrator:
|
|
26
|
+
"""Runs `analyze()` (a lite analysis over the incremental scan cache) at most once at a time.
|
|
27
|
+
|
|
28
|
+
`recalibrate()` returns at once with `{"status": "busy"}` while a run is in flight here or another process holds
|
|
29
|
+
the state dir's lock (a calibration or a config write); the schedule loop never overlaps runs either. State (last
|
|
30
|
+
success, failures, next due) is persisted so a restart keeps the cadence, and is re-read under the lock, so runs
|
|
31
|
+
by other processes (the app, the CLI, a scheduler) count too.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, analyze: Callable[[], dict[str, Any]], state_dir: Path, every: float | None,
|
|
35
|
+
lens_out: Path | None = None, consent: Consent | None = None, rules: Rules | None = None,
|
|
36
|
+
dry_run: bool = False, clock: Callable[[], float] = time.time,
|
|
37
|
+
consent_path: Path | None = None) -> None: # fmt: skip
|
|
38
|
+
self.analyze, self.every, self.clock = analyze, every, clock
|
|
39
|
+
self.dir = state_dir / "service"
|
|
40
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
self.lens_out, self.consent, self.rules, self.dry_run = lens_out, consent, rules or Rules(), dry_run
|
|
42
|
+
# with a consent file, the consent is re-read before every auto-apply: clearing or expiring it takes effect
|
|
43
|
+
self.consent_path = consent_path
|
|
44
|
+
self.auto_apply = consent is not None or consent_path is not None
|
|
45
|
+
self._lock = threading.Lock()
|
|
46
|
+
self.result: dict[str, Any] | None = None
|
|
47
|
+
self.last_ok: float | None = None
|
|
48
|
+
self.last_attempt: float | None = None
|
|
49
|
+
self.failures = 0
|
|
50
|
+
self.last_error: str | None = None
|
|
51
|
+
self.last_apply: dict[str, Any] | None = None
|
|
52
|
+
self._load()
|
|
53
|
+
|
|
54
|
+
def _load(self) -> None:
|
|
55
|
+
"""Read the persisted state; the result too when it is newer than the one in memory."""
|
|
56
|
+
st = self._read("state.json") or {}
|
|
57
|
+
last_ok = st.get("last_ok")
|
|
58
|
+
if self.result is None or last_ok != self.last_ok:
|
|
59
|
+
self.result = self._read("result.json")
|
|
60
|
+
self.last_ok = last_ok
|
|
61
|
+
self.last_attempt = st.get("last_attempt")
|
|
62
|
+
self.failures = int(st.get("failures", 0))
|
|
63
|
+
self.last_error = st.get("last_error")
|
|
64
|
+
self.last_apply = st.get("last_apply")
|
|
65
|
+
|
|
66
|
+
def _read(self, name: str) -> Any:
|
|
67
|
+
p = self.dir / name
|
|
68
|
+
try:
|
|
69
|
+
return json.loads(p.read_text()) if p.exists() else None
|
|
70
|
+
except (OSError, ValueError):
|
|
71
|
+
log.warning("ignoring unreadable %s", p)
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
def _write(self, name: str, obj: Any) -> None:
|
|
75
|
+
p = self.dir / name
|
|
76
|
+
tmp = p.with_suffix(".tmp")
|
|
77
|
+
tmp.write_text(json.dumps(obj, sort_keys=True))
|
|
78
|
+
tmp.replace(p)
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def running(self) -> bool:
|
|
82
|
+
return self._lock.locked()
|
|
83
|
+
|
|
84
|
+
def next_due(self) -> float | None:
|
|
85
|
+
return next_due(self.every, self.last_ok, self.last_attempt, self.failures, self.clock())
|
|
86
|
+
|
|
87
|
+
def next_text(self) -> str:
|
|
88
|
+
"""The next scheduled calibration as local time, 'now', or 'manual only'."""
|
|
89
|
+
due = self.next_due()
|
|
90
|
+
if due is None:
|
|
91
|
+
return "manual only"
|
|
92
|
+
if due <= self.clock():
|
|
93
|
+
return "now"
|
|
94
|
+
return time.strftime("%Y-%m-%d %H:%M", time.localtime(due))
|
|
95
|
+
|
|
96
|
+
def status(self) -> dict[str, Any]:
|
|
97
|
+
return {
|
|
98
|
+
"running": self.running,
|
|
99
|
+
"every_s": self.every,
|
|
100
|
+
"last_calibrated": self.last_ok,
|
|
101
|
+
"last_attempt": self.last_attempt,
|
|
102
|
+
"next_calibration": self.next_due(),
|
|
103
|
+
"failures": self.failures,
|
|
104
|
+
"last_error": self.last_error,
|
|
105
|
+
"auto_apply": self.auto_apply and self.consent is not None,
|
|
106
|
+
"last_apply": self.last_apply,
|
|
107
|
+
"applied": {k.split("::", 1)[1]: v for k, v in load_applied(self.dir / "applied.json").items()},
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
def recalibrate(self, reason: str = "manual", if_due: bool = False) -> dict[str, Any]:
|
|
111
|
+
"""One run now. Busy (nothing runs, not a failure) while another run holds this calibrator or the state
|
|
112
|
+
dir's lock. With `if_due` (the schedule), a run that another process made since is enough: `skipped`."""
|
|
113
|
+
if not self._lock.acquire(blocking=False):
|
|
114
|
+
log.info("recalibrate (%s) skipped: a run is already in flight", reason)
|
|
115
|
+
return {"status": "busy"}
|
|
116
|
+
try:
|
|
117
|
+
with single_flight(self.dir.parent, f"calibrate ({reason})"):
|
|
118
|
+
self._load() # another process may have calibrated, or failed, since we last looked
|
|
119
|
+
due = self.next_due()
|
|
120
|
+
if if_due and due is not None and due > self.clock():
|
|
121
|
+
log.info("recalibrate (%s) skipped: calibrated elsewhere; next calibration: %s", reason,
|
|
122
|
+
self.next_text()) # fmt: skip
|
|
123
|
+
return {"status": "skipped"}
|
|
124
|
+
result, last_ok = self.result, self.last_ok
|
|
125
|
+
try:
|
|
126
|
+
return self._run(reason)
|
|
127
|
+
except OSError as e: # a result, lens or state file cannot be written: a failed run
|
|
128
|
+
self.result, self.last_ok = result, last_ok # nothing new was recorded as calibrated
|
|
129
|
+
return self._fail(f"{type(e).__name__}: {e}") # saved while still holding the lock
|
|
130
|
+
except Busy as e:
|
|
131
|
+
log.info("recalibrate (%s) skipped: %s", reason, e)
|
|
132
|
+
return {"status": "busy", "message": str(e)}
|
|
133
|
+
except LockError as e: # the lock cannot be taken: back off here; the shared state is not written without it
|
|
134
|
+
self.last_attempt = self.clock()
|
|
135
|
+
return self._fail(str(e), save=False)
|
|
136
|
+
finally:
|
|
137
|
+
self._lock.release()
|
|
138
|
+
|
|
139
|
+
def _fail(self, error: str, save: bool = True) -> dict[str, Any]:
|
|
140
|
+
self.failures += 1
|
|
141
|
+
self.last_error = error[:500]
|
|
142
|
+
log.error("recalibration failed (%d in a row): %s", self.failures, self.last_error)
|
|
143
|
+
if save:
|
|
144
|
+
try:
|
|
145
|
+
self._save_state()
|
|
146
|
+
except OSError as e:
|
|
147
|
+
log.error("cannot save the calibrator state: %s", e)
|
|
148
|
+
return {"status": "error", "error": self.last_error}
|
|
149
|
+
|
|
150
|
+
def _run(self, reason: str) -> dict[str, Any]:
|
|
151
|
+
start = self.clock()
|
|
152
|
+
self.last_attempt = start
|
|
153
|
+
log.info("recalibrating (%s)", reason)
|
|
154
|
+
try:
|
|
155
|
+
res = self.analyze()
|
|
156
|
+
except Exception as e:
|
|
157
|
+
return self._fail(f"{type(e).__name__}: {e}")
|
|
158
|
+
now = self.clock()
|
|
159
|
+
scan = res.pop("scan", None) or {}
|
|
160
|
+
covered = res.pop("covered", None) # None: this run covers every harness
|
|
161
|
+
res["calibration"] = {"at": now, "every_s": self.every, "reason": reason, "took_s": round(now - start, 1)}
|
|
162
|
+
# the published files keep the harnesses this run did not cover; auto-apply sees only this run's groups
|
|
163
|
+
self.result = update(self.dir / "result.json", res, covered)
|
|
164
|
+
self.last_ok, self.failures, self.last_error = now, 0, None
|
|
165
|
+
if self.lens_out:
|
|
166
|
+
lens = summarize(res)
|
|
167
|
+
lens["calibration"] = res["calibration"]
|
|
168
|
+
update(self.lens_out, lens, covered)
|
|
169
|
+
out: dict[str, Any] = {"status": "ok", "took_s": res["calibration"]["took_s"]}
|
|
170
|
+
if self.auto_apply:
|
|
171
|
+
try:
|
|
172
|
+
applied = self._auto_apply(res, now)
|
|
173
|
+
except Exception as e: # e.g. a malformed settings file: back off like a failed analysis
|
|
174
|
+
self.failures += 1
|
|
175
|
+
self.last_error = f"auto-apply: {type(e).__name__}: {e}"[:500]
|
|
176
|
+
log.error("auto-apply failed (%d in a row): %s", self.failures, self.last_error)
|
|
177
|
+
self.last_apply = {"at": now, "error": self.last_error}
|
|
178
|
+
self._save_state()
|
|
179
|
+
return {"status": "error", "error": self.last_error}
|
|
180
|
+
self.last_apply = {"at": now, **applied}
|
|
181
|
+
out["auto_apply"] = applied
|
|
182
|
+
self._save_state()
|
|
183
|
+
log.info("recalibrated in %.1fs: %s files, %s cached, %s parsed, %d groups%s; next calibration: %s",
|
|
184
|
+
res["calibration"]["took_s"], scan.get("files", "?"), scan.get("cached", "?"), scan.get("parsed", "?"),
|
|
185
|
+
len(res.get("groups", [])), "; analysis reused (nothing changed)" if scan.get("reused") else "",
|
|
186
|
+
self.next_text()) # fmt: skip
|
|
187
|
+
return out
|
|
188
|
+
|
|
189
|
+
def _auto_apply(self, res: dict[str, Any], now: float) -> dict[str, Any]:
|
|
190
|
+
if self.consent_path is not None:
|
|
191
|
+
try:
|
|
192
|
+
self.consent = load_consent(self.consent_path)
|
|
193
|
+
except ap.ApplyError as e: # cleared, expired or unreadable: stop applying, keep calibrating
|
|
194
|
+
self.consent = None
|
|
195
|
+
log.warning("auto-apply is off: %s", e)
|
|
196
|
+
return {"decisions": [], "dry_run": self.dry_run, "diff": "", "manifest": None, "error": str(e)}
|
|
197
|
+
if self.consent is None:
|
|
198
|
+
return {"decisions": [], "dry_run": self.dry_run, "diff": "", "manifest": None,
|
|
199
|
+
"error": "no consent"} # fmt: skip
|
|
200
|
+
applied = run_auto_apply(res, self.consent, self.dir.parent, self.rules, now, dry_run=self.dry_run)
|
|
201
|
+
for d in applied["decisions"]:
|
|
202
|
+
log.info("auto-apply %s: %s (%s)", d["model"], d["action"], d["reason"])
|
|
203
|
+
if applied.get("manifest"):
|
|
204
|
+
log.info("auto-apply wrote %s; undo with compactlab revert", applied["manifest"])
|
|
205
|
+
return applied
|
|
206
|
+
|
|
207
|
+
def _save_state(self) -> None:
|
|
208
|
+
keys = ("last_ok", "last_attempt", "failures", "last_error", "last_apply")
|
|
209
|
+
self._write("state.json", {k: getattr(self, k) for k in keys})
|
|
210
|
+
|
|
211
|
+
def loop(self, stop: threading.Event, tick: float = 60.0) -> None:
|
|
212
|
+
"""Runs due calibrations until `stop` is set; wakes at least every `tick` seconds. While another run holds
|
|
213
|
+
the lock it tries again every `tick`."""
|
|
214
|
+
while not stop.is_set():
|
|
215
|
+
due = self.next_due()
|
|
216
|
+
if due is not None and self.clock() >= due:
|
|
217
|
+
if self.recalibrate("schedule", if_due=True)["status"] == "busy":
|
|
218
|
+
stop.wait(tick)
|
|
219
|
+
continue
|
|
220
|
+
stop.wait(tick if due is None else max(1.0, min(tick, due - self.clock())))
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""The local HTTP face of `compactlab serve` (stdlib only).
|
|
2
|
+
|
|
3
|
+
Bound to loopback unless explicitly told otherwise. GET routes are read only. The one write, POST
|
|
4
|
+
/api/recalibrate, needs the service token (Authorization: Bearer <token>), and every request must name a loopback
|
|
5
|
+
Host, so a web page elsewhere cannot reach the service through DNS rebinding or a cross-site form.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hmac
|
|
11
|
+
import ipaddress
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import secrets
|
|
15
|
+
import threading
|
|
16
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from ..report.html import render_html
|
|
21
|
+
from ..sim.engine import reselect
|
|
22
|
+
from ..sim.select import PROFILE_NAMES
|
|
23
|
+
from .core import Calibrator
|
|
24
|
+
|
|
25
|
+
log = logging.getLogger("compactlab.service")
|
|
26
|
+
LOOPBACK_NAMES = {"localhost", "127.0.0.1", "::1"}
|
|
27
|
+
MAX_BODY = 4096
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_loopback(host: str) -> bool:
|
|
31
|
+
if host in LOOPBACK_NAMES:
|
|
32
|
+
return True
|
|
33
|
+
try:
|
|
34
|
+
return ipaddress.ip_address(host).is_loopback
|
|
35
|
+
except ValueError:
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def check_bind(host: str, unsafe: bool) -> None:
|
|
40
|
+
if not is_loopback(host) and not unsafe:
|
|
41
|
+
raise PermissionError(f"refusing to bind {host}: the service is localhost-only (use --unsafe-bind to override)")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def load_token(path: Path) -> str:
|
|
45
|
+
"""The service token, created once (0600) and reused across restarts."""
|
|
46
|
+
if path.exists():
|
|
47
|
+
return path.read_text().strip()
|
|
48
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
tok = secrets.token_urlsafe(32)
|
|
50
|
+
path.write_text(tok)
|
|
51
|
+
path.chmod(0o600)
|
|
52
|
+
return tok
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _host_ok(header: str | None) -> bool:
|
|
56
|
+
if not header:
|
|
57
|
+
return False
|
|
58
|
+
h = header.strip()
|
|
59
|
+
host = h[1 : h.index("]")] if h.startswith("[") else h.rsplit(":", 1)[0] if h.count(":") == 1 else h
|
|
60
|
+
return is_loopback(host)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def make_server(cal: Calibrator, host: str, port: int, token: str, unsafe_bind: bool = False) -> ThreadingHTTPServer:
|
|
64
|
+
check_bind(host, unsafe_bind)
|
|
65
|
+
|
|
66
|
+
class Handler(BaseHTTPRequestHandler):
|
|
67
|
+
server_version = "compactlab"
|
|
68
|
+
sys_version = ""
|
|
69
|
+
|
|
70
|
+
def log_message(self, format: str, *args: Any) -> None:
|
|
71
|
+
log.debug("%s %s", self.address_string(), format % args)
|
|
72
|
+
|
|
73
|
+
def _send(self, code: int, body: bytes, ctype: str = "application/json") -> None:
|
|
74
|
+
self.send_response(code)
|
|
75
|
+
self.send_header("Content-Type", ctype)
|
|
76
|
+
self.send_header("Content-Length", str(len(body)))
|
|
77
|
+
self.send_header("Cache-Control", "no-store")
|
|
78
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
79
|
+
self.send_header("Referrer-Policy", "no-referrer")
|
|
80
|
+
self.end_headers()
|
|
81
|
+
self.wfile.write(body)
|
|
82
|
+
|
|
83
|
+
def _json(self, code: int, obj: Any) -> None:
|
|
84
|
+
self._send(code, json.dumps(obj).encode())
|
|
85
|
+
|
|
86
|
+
def _guard(self) -> bool:
|
|
87
|
+
if not _host_ok(self.headers.get("Host")) and not unsafe_bind:
|
|
88
|
+
self._json(403, {"error": "host not allowed"})
|
|
89
|
+
return False
|
|
90
|
+
return True
|
|
91
|
+
|
|
92
|
+
def do_GET(self) -> None:
|
|
93
|
+
if not self._guard():
|
|
94
|
+
return
|
|
95
|
+
path = self.path.split("?", 1)[0]
|
|
96
|
+
if path == "/api/health":
|
|
97
|
+
return self._json(200, {"ok": True, **cal.status()})
|
|
98
|
+
if cal.result is None:
|
|
99
|
+
if path == "/":
|
|
100
|
+
return self._send(503, b"<p>compactlab: no calibration yet; it is running.</p>", "text/html")
|
|
101
|
+
return self._json(503, {"error": "no calibration yet", **cal.status()})
|
|
102
|
+
if path == "/":
|
|
103
|
+
res = dict(cal.result)
|
|
104
|
+
res["service"] = {**cal.status(), "token": token}
|
|
105
|
+
return self._send(200, render_html(res).encode(), "text/html; charset=utf-8")
|
|
106
|
+
if path == "/api/result":
|
|
107
|
+
return self._json(200, cal.result)
|
|
108
|
+
if path.startswith("/api/profile/"):
|
|
109
|
+
name = path.rsplit("/", 1)[1]
|
|
110
|
+
if name not in PROFILE_NAMES:
|
|
111
|
+
return self._json(404, {"error": f"unknown profile {name!r}", "profiles": list(PROFILE_NAMES)})
|
|
112
|
+
res = reselect(json.loads(json.dumps(cal.result)), name)
|
|
113
|
+
return self._json(200, {"profile": name, "groups": [
|
|
114
|
+
{k: g[k] for k in ("harness", "model", "role", "profiles", "comparison")} for g in res["groups"]
|
|
115
|
+
]}) # fmt: skip
|
|
116
|
+
return self._json(404, {"error": "not found"})
|
|
117
|
+
|
|
118
|
+
def do_POST(self) -> None:
|
|
119
|
+
if not self._guard():
|
|
120
|
+
return
|
|
121
|
+
if self.path != "/api/recalibrate":
|
|
122
|
+
return self._json(404, {"error": "not found"})
|
|
123
|
+
if int(self.headers.get("Content-Length") or 0) > MAX_BODY:
|
|
124
|
+
return self._json(413, {"error": "body too large"})
|
|
125
|
+
got = (self.headers.get("Authorization") or "").removeprefix("Bearer ").strip()
|
|
126
|
+
if not got or not hmac.compare_digest(got, token):
|
|
127
|
+
return self._json(401, {"error": "token required"})
|
|
128
|
+
if cal.running:
|
|
129
|
+
return self._json(409, {"status": "busy"})
|
|
130
|
+
threading.Thread(target=cal.recalibrate, args=("api",), daemon=True).start()
|
|
131
|
+
return self._json(202, {"status": "started"})
|
|
132
|
+
|
|
133
|
+
return ThreadingHTTPServer((host, port), Handler)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""One compactlab job at a time per state dir, across processes.
|
|
2
|
+
|
|
3
|
+
Every calibration that keeps the calibrator's state (`recalibrate`, `engine calibrate`, a scheduled or requested run
|
|
4
|
+
of `serve`) and every config write (`apply --write`, `retune`, `revert`) runs inside `single_flight()`. It takes an
|
|
5
|
+
exclusive `flock` on `<state-dir>/service/lock` without waiting: whoever gets it runs, everyone else gets `Busy` at
|
|
6
|
+
once and does nothing. The menu bar app, the CLI and a launchd/systemd schedule can therefore start jobs whenever they
|
|
7
|
+
like.
|
|
8
|
+
|
|
9
|
+
There are no stale locks: a `flock` belongs to the open file, so the kernel drops it when the holder closes it or
|
|
10
|
+
exits, however it exits (a crash, `kill -9`). The descriptor is not inherited by child processes (PEP 446), so a
|
|
11
|
+
subprocess cannot keep it alive. The file stays behind on purpose and must never be deleted: a process still holding
|
|
12
|
+
the old file and one that created a new one would both think they hold the lock. What the holder writes into it
|
|
13
|
+
(pid, job, start time) only feeds the `Busy` message.
|
|
14
|
+
|
|
15
|
+
The lock is not reentrant: a second `single_flight()` on the same state dir in the same process is `Busy` too. Take it
|
|
16
|
+
once, at the entry point.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import contextlib
|
|
22
|
+
import errno
|
|
23
|
+
import fcntl
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import time
|
|
27
|
+
from collections.abc import Generator
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Busy(Exception):
|
|
33
|
+
"""Another process holds the lock. `holder` is what it recorded ({pid, job, since}); {} when it is unreadable."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, path: Path, holder: dict[str, Any]) -> None:
|
|
36
|
+
self.path, self.holder = path, holder
|
|
37
|
+
super().__init__(describe(holder))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class LockError(OSError):
|
|
41
|
+
"""The lock file cannot be created, opened or locked (permissions, a file system without `flock`). Not
|
|
42
|
+
contention: nothing else is running because of it."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def lock_path(state_dir: Path) -> Path:
|
|
46
|
+
return state_dir / "service" / "lock"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def describe(holder: dict[str, Any]) -> str:
|
|
50
|
+
job, pid, since = holder.get("job"), holder.get("pid"), holder.get("since")
|
|
51
|
+
who = f"`{job}`" if isinstance(job, str) and job else "a calibration or config write"
|
|
52
|
+
when = []
|
|
53
|
+
if isinstance(pid, int):
|
|
54
|
+
when.append(f"pid {pid}")
|
|
55
|
+
if isinstance(since, (int, float)):
|
|
56
|
+
when.append("since " + time.strftime("%H:%M:%S", time.localtime(since)))
|
|
57
|
+
extra = f" ({', '.join(when)})" if when else ""
|
|
58
|
+
return f"another compactlab process is running {who}{extra}; try again when it finishes"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _holder(fd: int) -> dict[str, Any]:
|
|
62
|
+
try:
|
|
63
|
+
d = json.loads(os.pread(fd, 4096, 0) or b"{}")
|
|
64
|
+
except (OSError, ValueError):
|
|
65
|
+
return {}
|
|
66
|
+
return d if isinstance(d, dict) else {}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@contextlib.contextmanager
|
|
70
|
+
def single_flight(state_dir: Path, job: str) -> Generator[None, None, None]:
|
|
71
|
+
"""Hold `<state-dir>/service/lock` for the duration of the block, or raise `Busy` at once (`LockError` when the
|
|
72
|
+
lock cannot be taken at all)."""
|
|
73
|
+
path = lock_path(state_dir)
|
|
74
|
+
try:
|
|
75
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
|
|
77
|
+
except OSError as e:
|
|
78
|
+
raise LockError(f"cannot open the lock {path}: {e.strerror or e}") from e
|
|
79
|
+
try:
|
|
80
|
+
try:
|
|
81
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
82
|
+
except OSError as e:
|
|
83
|
+
if e.errno not in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES):
|
|
84
|
+
raise LockError(f"cannot lock {path}: {e.strerror or e}") from e
|
|
85
|
+
raise Busy(path, _holder(fd)) from None
|
|
86
|
+
rec = json.dumps({"pid": os.getpid(), "job": job, "since": time.time()}).encode()
|
|
87
|
+
with contextlib.suppress(OSError): # only for the busy message; never a reason not to run
|
|
88
|
+
os.ftruncate(fd, 0)
|
|
89
|
+
os.pwrite(fd, rec, 0)
|
|
90
|
+
yield
|
|
91
|
+
finally:
|
|
92
|
+
os.close(fd) # releases the lock
|