spatial-computing 0.12.2__py3-none-any.whl → 0.13.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.
spatial/__init__.py CHANGED
@@ -3,4 +3,4 @@
3
3
  Status of every engine is declared in spatial.core.registry and must be backed
4
4
  by a test or benchmark before being set to OPERATIONAL.
5
5
  """
6
- __version__ = "0.12.2"
6
+ __version__ = "0.13.0"
spatial/cli.py CHANGED
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
  import argparse
5
5
  import json
6
6
  import subprocess
7
+ import time
7
8
  import sys
8
9
  from pathlib import Path
9
10
 
@@ -89,21 +90,60 @@ def _read_token(path: str) -> bytes:
89
90
 
90
91
 
91
92
  def _hub_client(a):
92
- from .core.protocol import RpcClient
93
- host, _, port = a.hub.rpartition(":")
94
- return RpcClient(host or "127.0.0.1", int(port), _read_token(a.token_file), timeout=30)
93
+ from .fleet.ha import connect_active
94
+ return connect_active(a.hub, _read_token(a.token_file), timeout=30) # a.hub may be "h1:p,h2:p": the active one is used
95
95
 
96
96
 
97
97
  def cmd_agent(a):
98
98
  from .fleet import Agent
99
- host, _, port = a.hub.rpartition(":")
100
- ag = Agent(host or "127.0.0.1", int(port), _read_token(a.token_file), name=a.name, interval_s=a.interval,
99
+ ag = Agent(a.hub, None, _read_token(a.token_file), name=a.name, interval_s=a.interval,
101
100
  usd_per_hour=a.usd_per_hour, labels=[x for x in a.labels.split(",") if x], run_tasks=not a.no_tasks)
102
- print(f"agent '{ag.name}' reporting to {a.hub} every {a.interval:g} s" + ("" if a.no_tasks else "; accepts allow-listed tasks"))
101
+ print(f"agent '{ag.name}' reporting to {a.hub} every {a.interval:g} s" + ("" if a.no_tasks else "; accepts allow-listed tasks"), flush=True)
103
102
  ag.run_forever()
104
103
  return 0
105
104
 
106
105
 
106
+ def cmd_dashboard(a):
107
+ from .fleet.dashboard import Dashboard
108
+ d = Dashboard(a.hub, _read_token(a.token_file), port=a.port, min_severity=a.min_severity, webhook=a.webhook).start()
109
+ print(f"dashboard (read-only, this machine only): {d.url}", flush=True)
110
+ if a.webhook:
111
+ print(f"alert events are POSTed to {a.webhook}")
112
+ try:
113
+ while True:
114
+ time.sleep(3600)
115
+ except KeyboardInterrupt:
116
+ d.stop()
117
+ return 0
118
+
119
+
120
+ def cmd_watch(a):
121
+ from .fleet.alerts import AlertEngine, post_webhook
122
+ eng, cli = AlertEngine(a.min_severity), None
123
+ print(f"watching {a.hub} every {a.interval:g} s (alert level: {a.min_severity} and above)", flush=True)
124
+ while True:
125
+ try:
126
+ cli = cli or _hub_client(a)
127
+ events = eng.update(cli.call({"op": "advise", "window_s": a.window})[0]["recommendations"])
128
+ except Exception as e:
129
+ cli = None
130
+ events = [{"event": "hub_unreachable", "key": "hub", "ts": time.time(), "severity": "high", "text": f"{type(e).__name__}: {e}"}] if "hub" not in eng.firing else []
131
+ eng.firing.setdefault("hub", {"since": time.time(), "severity": "high", "text": "hub unreachable"})
132
+ else:
133
+ if "hub" in eng.firing:
134
+ eng.firing.pop("hub"); events.append({"event": "resolved", "key": "hub", "ts": time.time(), "severity": "high", "text": "hub reachable again"})
135
+ for e in events:
136
+ print(f"{time.strftime('%H:%M:%S', time.localtime(e['ts']))} {e['event']:<9} [{e['severity']}] {e['text']}", flush=True)
137
+ if a.webhook:
138
+ try:
139
+ post_webhook(a.webhook, e)
140
+ except Exception as err:
141
+ print(f"webhook failed: {err}", flush=True)
142
+ if a.once:
143
+ return 0
144
+ time.sleep(a.interval)
145
+
146
+
107
147
  def cmd_fleet(a):
108
148
  cli = _hub_client(a)
109
149
  if a.action == "status":
@@ -273,6 +313,19 @@ def main(argv=None):
273
313
  p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
274
314
  p.add_argument("--task-id", type=int)
275
315
  p.set_defaults(fn=cmd_fleet)
316
+ p = sub.add_parser("dashboard", help="read-only fleet dashboard in your browser (served on 127.0.0.1 only, behind a random key)")
317
+ p.add_argument("--hub", required=True, help="host:port, or h1:p,h2:p for a hub pair")
318
+ p.add_argument("--token-file", required=True, help="scoped token with fleet:read")
319
+ p.add_argument("--port", type=int, default=0)
320
+ p.add_argument("--min-severity", default="high", choices=["low", "medium", "high"])
321
+ p.add_argument("--webhook", help="POST each alert event (JSON) to this http(s) URL: this sends fleet data off the machine")
322
+ p.set_defaults(fn=cmd_dashboard)
323
+ p = sub.add_parser("watch", help="print alerts as they fire and clear; optional webhook")
324
+ p.add_argument("--hub", required=True); p.add_argument("--token-file", required=True)
325
+ p.add_argument("--interval", type=float, default=10.0); p.add_argument("--window", type=float, default=60.0)
326
+ p.add_argument("--min-severity", default="high", choices=["low", "medium", "high"])
327
+ p.add_argument("--webhook"); p.add_argument("--once", action="store_true")
328
+ p.set_defaults(fn=cmd_watch)
276
329
  p = sub.add_parser("token", help="scoped credentials: `init` a master key, `issue` a tenant token")
277
330
  p.add_argument("action", choices=["init", "issue"])
278
331
  p.add_argument("--master-key-file", required=True)
spatial/core/registry.py CHANGED
@@ -43,7 +43,7 @@ ENGINES: list[Engine] = [
43
43
  "estimates come from probes and measured constants on one machine; calibration is a median of past ratios; no learned model; fleet and QPU pricing need the caller's prices"),
44
44
  Engine("fleet", "Spatial Fleet (agent + hub)", "spatial.fleet", Status.OPERATIONAL_PROTOTYPE,
45
45
  "tests/test_fleet.py, benchmarks/bench_fleet.py",
46
- "validated on one machine (agents on loopback); no dashboard UI; recommendations are estimates; never applies changes by itself"),
46
+ "validated on one machine (agents on loopback); HA is active/standby without consensus, tested with two hubs and a clean kill only; dashboard is read-only and local; recommendations are estimates; never applies changes by itself"),
47
47
  Engine("runtime", "Spatial Runtime Engine", "spatial.runtime", Status.OPERATIONAL_PROTOTYPE,
48
48
  "tests/test_runtime.py, benchmarks/bench_runtime.py",
49
49
  "Windows apps not demonstrated (no Wine / Windows image); no containers; no GUI streaming"),
spatial/fleet/agent.py CHANGED
@@ -18,13 +18,16 @@ from ..compute import workloads
18
18
  from ..compute.detect import _nvidia_gpus, detect_node
19
19
  from ..compute.monitor import snapshot
20
20
  from ..core.protocol import RpcClient
21
+ from .ha import connect_active, parse_addrs
21
22
 
22
23
 
23
24
  class Agent:
24
- def __init__(self, host: str, port: int, token: bytes, name: str | None = None, interval_s: float = 5.0,
25
+ def __init__(self, host: "str | list", port: int | None, token: bytes, name: str | None = None, interval_s: float = 5.0,
25
26
  usd_per_hour: float | None = None, labels: list | None = None, run_tasks: bool = True,
26
27
  poll_s: float = 1.0, buffer: int = 720):
27
- self.host, self.port, self.token = host, port, token
28
+ # one hub, or several (host as a list or "h1:p,h2:p"): the agent talks to whichever reports itself active
29
+ self.hubs = parse_addrs(host) if port is None else [(host, port)]
30
+ self.host, self.port, self.token = self.hubs[0][0], self.hubs[0][1], token
28
31
  self.name = name or socket.gethostname()
29
32
  self.interval_s, self.poll_s = interval_s, poll_s
30
33
  self.usd_per_hour, self.labels, self.run_tasks = usd_per_hour, labels or [], run_tasks
@@ -46,7 +49,9 @@ class Agent:
46
49
 
47
50
  # ---------------------------------------------------------------- loops
48
51
  def _connect(self) -> RpcClient:
49
- return RpcClient(self.host, self.port, self.token, timeout=30)
52
+ if len(self.hubs) == 1:
53
+ return RpcClient(self.host, self.port, self.token, timeout=30)
54
+ return connect_active(self.hubs, self.token, timeout=30)
50
55
 
51
56
  def _report_loop(self):
52
57
  cli = None
@@ -0,0 +1,46 @@
1
+ """Alerts from the hub's recommendations: edge-triggered (a condition alerts once when it appears and
2
+ once when it clears), optional webhook. Nothing leaves this machine unless a webhook URL is given."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ import urllib.parse
8
+ import urllib.request
9
+
10
+ RANK = {"low": 0, "medium": 1, "high": 2}
11
+
12
+
13
+ def key_of(r: dict) -> str:
14
+ return f"{r['kind']}:{r.get('node') or ','.join(r.get('nodes_to_free', []))}"
15
+
16
+
17
+ class AlertEngine:
18
+ def __init__(self, min_severity: str = "high", clock=time.time):
19
+ if min_severity not in RANK:
20
+ raise ValueError("min_severity must be low, medium or high")
21
+ self.min_rank, self.clock = RANK[min_severity], clock
22
+ self.firing: dict[str, dict] = {}
23
+ self.history: list[dict] = [] # newest last, capped
24
+
25
+ def update(self, recommendations: list[dict]) -> list[dict]:
26
+ """Feed the current recommendations; returns the events produced by this update."""
27
+ now, events = self.clock(), []
28
+ current = {key_of(r): r for r in recommendations if RANK.get(r.get("severity"), 0) >= self.min_rank}
29
+ for k, r in current.items():
30
+ if k not in self.firing:
31
+ self.firing[k] = {"since": now, **r}
32
+ events.append({"event": "firing", "key": k, "ts": now, "severity": r["severity"], "text": r["text"]})
33
+ for k in [k for k in self.firing if k not in current]:
34
+ old = self.firing.pop(k)
35
+ events.append({"event": "resolved", "key": k, "ts": now, "severity": old["severity"], "text": old["text"],
36
+ "lasted_s": now - old["since"]})
37
+ self.history = (self.history + events)[-200:]
38
+ return events
39
+
40
+
41
+ def post_webhook(url: str, event: dict, timeout: float = 5.0) -> None:
42
+ u = urllib.parse.urlparse(url)
43
+ if u.scheme not in ("http", "https") or not u.netloc:
44
+ raise ValueError("webhook must be an http(s) URL")
45
+ req = urllib.request.Request(url, data=json.dumps(event).encode(), headers={"Content-Type": "application/json"}, method="POST")
46
+ urllib.request.urlopen(req, timeout=timeout).read()
@@ -0,0 +1,160 @@
1
+ """Fleet dashboard: a local, read-only web page over the hub.
2
+
3
+ The process holds the hub credential and serves HTTP on 127.0.0.1 ONLY (no option to bind elsewhere).
4
+ Every request needs a random key printed at start; the Host header must be loopback (blocks DNS
5
+ rebinding); only GET is accepted; the page can read the fleet and cannot change anything.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import http.server
10
+ import json
11
+ import secrets
12
+ import threading
13
+ import time
14
+ from urllib.parse import parse_qs, urlparse
15
+
16
+ from .alerts import AlertEngine, post_webhook
17
+ from .ha import connect_active
18
+
19
+ PAGE = r"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
20
+ <title>Spatial Fleet</title><style>
21
+ :root{--paper:#f6f4ec;--ink:#12233f;--mute:#4f5f7a;--mark:#ffd84a;--ok:#2f8f3a;--bad:#c0392b;--warn:#b7791f;--grid:#12233f14;
22
+ --serif:"Instrument Serif",Georgia,serif;--mono:"DM Mono",ui-monospace,Menlo,monospace}
23
+ @media (prefers-color-scheme:dark){:root{--paper:#0e1a30;--ink:#f6f4ec;--mute:#9fb0cc;--grid:#f6f4ec14;--ok:#b8f171;--bad:#ff8a7a;--warn:#ffd84a}}
24
+ *{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:14px/1.5 var(--mono);
25
+ background-image:linear-gradient(var(--grid) 1px,transparent 1px),linear-gradient(90deg,var(--grid) 1px,transparent 1px);background-size:24px 24px}
26
+ header{display:flex;justify-content:space-between;align-items:baseline;padding:18px 24px;border-bottom:1px solid var(--ink);background:var(--paper)}
27
+ h1{font:400 32px var(--serif);margin:0}h2{font:400 22px var(--serif);margin:0 0 8px}
28
+ main{max-width:1180px;margin:0 auto;padding:16px 24px;display:grid;gap:16px}
29
+ section{background:var(--paper);border:1px solid var(--ink);padding:14px 16px;overflow-x:auto}
30
+ table{border-collapse:collapse;width:100%}th,td{text-align:left;padding:4px 10px 4px 0;white-space:nowrap}th{color:var(--mute);font-weight:400}
31
+ .bar{display:inline-block;width:90px;height:8px;border:1px solid var(--ink);vertical-align:middle;margin-right:6px}.bar i{display:block;height:100%;background:var(--ink)}
32
+ .tag{padding:1px 6px;border:1px solid currentColor}.ok{color:var(--ok)}.bad{color:var(--bad)}.warn{color:var(--warn)}.mute{color:var(--mute)}
33
+ #banner{display:none;background:var(--bad);color:#fff;padding:10px 24px}
34
+ .kpis{display:flex;gap:28px;flex-wrap:wrap}.kpis b{font:400 30px var(--serif);display:block}
35
+ </style></head><body>
36
+ <div id="banner" role="alert"></div>
37
+ <header><h1>Spatial Fleet</h1><span id="meta" class="mute">connecting…</span></header>
38
+ <main>
39
+ <section><div class="kpis" id="kpis"></div></section>
40
+ <section><h2>Alerts</h2><div id="alerts" class="mute">none</div></section>
41
+ <section><h2>Nodes</h2><table id="nodes"></table></section>
42
+ <section><h2>Recommendations</h2><div id="recs" class="mute">none</div></section>
43
+ <section><h2>Tenants and queue</h2><table id="tenants"></table><p></p><table id="tasks"></table></section>
44
+ </main>
45
+ <script>
46
+ const key=new URLSearchParams(location.search).get("key")||"";
47
+ const esc=s=>String(s??"-").replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
48
+ const f=(v,n=0)=>v==null?"-":Number(v).toFixed(n);
49
+ const bar=v=>`<span class="bar"><i style="width:${Math.max(0,Math.min(100,v||0))}%"></i></span>${f(v)}%`;
50
+ async function tick(){
51
+ try{
52
+ const r=await fetch("api/state?key="+encodeURIComponent(key),{cache:"no-store"});
53
+ if(!r.ok) throw new Error(r.status);
54
+ const s=await r.json();
55
+ document.getElementById("meta").textContent=`hub ${s.hub.name} · ${s.hub.role} · epoch ${s.hub.epoch} · updated ${new Date(s.ts*1000).toLocaleTimeString()}`;
56
+ const u=s.utilization;
57
+ document.getElementById("kpis").innerHTML=[["nodes",u.nodes],["cores",u.cores],["CPU",u.cpu_utilization_pct==null?"-":f(u.cpu_utilization_pct,1)+"%"],
58
+ ["queued",s.queue.counts.queued||0],["running",s.queue.counts.running||0],["done",s.queue.counts.done||0],["failed",s.queue.counts.failed||0]].map(([k,v])=>`<div><b>${esc(v)}</b>${k}</div>`).join("");
59
+ document.getElementById("nodes").innerHTML="<tr><th>node</th><th>up</th><th>cores</th><th>cpu</th><th>ram free</th><th>gpus</th><th>$/h</th><th>samples</th></tr>"+
60
+ s.nodes.map(n=>`<tr><td>${esc(n.node)}</td><td class="${n.alive?"ok":"bad"}">${n.alive?"yes":"NO"}</td><td>${f(n.cores)}</td><td>${bar(n.cpu_avg)}</td><td>${f(n.ram_avail_pct)}%</td><td>${esc(n.gpu_count)}</td><td>${f(n.usd_per_hour,2)}</td><td>${esc(n.samples)}</td></tr>`).join("");
61
+ const firing=Object.values(s.alerts.firing);
62
+ const b=document.getElementById("banner");b.style.display=firing.length?"block":"none";b.textContent=firing.map(a=>a.text).join(" · ");
63
+ document.getElementById("alerts").innerHTML=(firing.length?firing.map(a=>`<div class="bad">● ${esc(a.severity)} ${esc(a.text)}</div>`).join(""):"<span class='ok'>nothing firing</span>")+
64
+ s.alerts.history.slice(-5).reverse().map(e=>`<div class="mute">${new Date(e.ts*1000).toLocaleTimeString()} ${esc(e.event)} ${esc(e.key)}</div>`).join("");
65
+ document.getElementById("recs").innerHTML=s.recommendations.length?s.recommendations.map(r=>`<p><span class="tag ${r.severity=="high"?"bad":"warn"}">${esc(r.severity)}</span> <b>${esc(r.kind)}</b> ${esc(r.text)}${r.est_saving_usd_per_month?` <span class="mute">(estimated saving ${f(r.est_saving_usd_per_month)} $/month: an estimate, not a result)</span>`:""}</p>`).join(""):"no recommendation: nothing in the measurements justifies a change";
66
+ document.getElementById("tenants").innerHTML="<tr><th>tenant</th><th>weight</th><th>finished s</th><th>weighted load</th><th>queued</th><th>running</th></tr>"+
67
+ s.tenants.map(t=>`<tr><td>${esc(t.tenant)}</td><td>${f(t.weight,1)}</td><td>${f(t.finished_s,1)}</td><td>${f(t.weighted_load,1)}</td><td>${esc(t.queued)}</td><td>${esc(t.running)}</td></tr>`).join("");
68
+ document.getElementById("tasks").innerHTML="<tr><th>task</th><th>workload</th><th>state</th><th>node</th><th>tenant</th><th>wall s</th></tr>"+
69
+ s.queue.recent.map(t=>`<tr><td>${esc(t.id)}${t.gang?" (gang)":""}</td><td>${esc(t.workload)}</td><td class="${t.state=="failed"?"bad":t.state=="done"?"ok":""}">${esc(t.state)}</td><td>${esc(t.node)}</td><td>${esc(t.tenant)}</td><td>${f(t.wall_s,2)}</td></tr>`).join("");
70
+ }catch(e){document.getElementById("meta").textContent="no data: "+e.message}
71
+ }
72
+ tick();setInterval(tick,3000);
73
+ </script></body></html>"""
74
+
75
+
76
+ class Dashboard:
77
+ def __init__(self, hubs, token: bytes, port: int = 0, interval_s: float = 3.0, window_s: float = 60.0,
78
+ min_severity: str = "high", webhook: str | None = None):
79
+ self.hubs, self.token, self.interval_s, self.window_s, self.webhook = hubs, token, interval_s, window_s, webhook
80
+ self.alerts = AlertEngine(min_severity)
81
+ self.key = secrets.token_urlsafe(16)
82
+ self.state: dict = {"error": "starting"}
83
+ self._cli = None
84
+ self._stop = threading.Event()
85
+ dash = self
86
+
87
+ class H(http.server.BaseHTTPRequestHandler):
88
+ def log_message(self, *a):
89
+ pass
90
+
91
+ def _deny(self, code, msg):
92
+ self.send_response(code); self.send_header("Content-Type", "text/plain"); self.end_headers(); self.wfile.write(msg.encode())
93
+
94
+ def do_GET(self):
95
+ host = (self.headers.get("Host") or "").rsplit(":", 1)[0].strip("[]")
96
+ if host not in ("127.0.0.1", "localhost", "::1"):
97
+ return self._deny(403, "bad host") # DNS rebinding
98
+ u = urlparse(self.path)
99
+ k = (parse_qs(u.query).get("key") or [""])[0]
100
+ if not secrets.compare_digest(k, dash.key):
101
+ return self._deny(403, "missing or wrong key")
102
+ if u.path == "/api/state":
103
+ body = json.dumps(dash.state).encode(); ctype = "application/json"
104
+ elif u.path in ("/", "/index.html"):
105
+ body = PAGE.encode(); ctype = "text/html; charset=utf-8"
106
+ else:
107
+ return self._deny(404, "not found")
108
+ self.send_response(200)
109
+ self.send_header("Content-Type", ctype); self.send_header("Cache-Control", "no-store")
110
+ self.send_header("X-Frame-Options", "DENY"); self.send_header("Referrer-Policy", "no-referrer")
111
+ self.send_header("Content-Security-Policy", "default-src 'self'; style-src 'unsafe-inline'; script-src 'unsafe-inline'")
112
+ self.end_headers(); self.wfile.write(body)
113
+
114
+ do_POST = do_PUT = do_DELETE = lambda self: self._deny(405, "read-only")
115
+
116
+ self._http = http.server.ThreadingHTTPServer(("127.0.0.1", port), H) # loopback only, by construction
117
+ self.port = self._http.server_address[1]
118
+
119
+ @property
120
+ def url(self) -> str:
121
+ return f"http://127.0.0.1:{self.port}/?key={self.key}"
122
+
123
+ def refresh(self) -> dict:
124
+ try:
125
+ if self._cli is None:
126
+ self._cli = connect_active(self.hubs, self.token, timeout=10)
127
+ c = self._cli
128
+ role = c.call({"op": "role"})[0]
129
+ nodes = c.call({"op": "nodes", "window_s": self.window_s})[0]
130
+ recs = c.call({"op": "advise", "window_s": self.window_s})[0]["recommendations"]
131
+ events = self.alerts.update(recs)
132
+ self.state = {"ts": time.time(), "hub": role, "nodes": nodes["nodes"], "utilization": nodes["utilization"],
133
+ "recommendations": recs, "tenants": c.call({"op": "tenants"})[0]["tenants"], "queue": c.call({"op": "queue"})[0],
134
+ "alerts": {"firing": self.alerts.firing, "history": self.alerts.history}}
135
+ if self.webhook:
136
+ for e in events:
137
+ try:
138
+ post_webhook(self.webhook, e)
139
+ except Exception:
140
+ pass
141
+ except Exception as e: # keep serving; reconnect (and fail over) next round
142
+ if self._cli is not None:
143
+ try: self._cli.close()
144
+ except Exception: pass
145
+ self._cli = None
146
+ self.state = {**{k: v for k, v in self.state.items() if k != "error"}, "error": f"{type(e).__name__}: {e}"} if "nodes" in self.state else {"error": f"{type(e).__name__}: {e}"}
147
+ return self.state
148
+
149
+ def start(self) -> "Dashboard":
150
+ def loop():
151
+ while not self._stop.is_set():
152
+ self.refresh()
153
+ self._stop.wait(self.interval_s)
154
+ threading.Thread(target=loop, daemon=True).start()
155
+ threading.Thread(target=self._http.serve_forever, daemon=True).start()
156
+ return self
157
+
158
+ def stop(self) -> None:
159
+ self._stop.set()
160
+ self._http.shutdown(); self._http.server_close()
spatial/fleet/ha.py ADDED
@@ -0,0 +1,136 @@
1
+ """Hub high availability: one active hub, standby hubs that follow it, automatic promotion.
2
+
3
+ What it is: active/standby replication by polling. The standby pulls the active hub's state (op
4
+ `snapshot`, scope fleet:replicate) every `poll_s` seconds. If no active hub answers for
5
+ `fail_after_s`, the standby promotes itself (epoch + 1, running tasks requeued). Agents and clients
6
+ take a list of hub addresses and use the one that says it is active.
7
+
8
+ What it is NOT: consensus. There is no quorum and no leader lease. Under a network partition two hubs
9
+ can both be active for a while; when they see each other again the one with the lower epoch (or, at
10
+ equal epoch, the larger name) steps down and DISCARDS its divergent state. Tasks that ran on the
11
+ losing side may run twice (workloads are pure, so that is safe) and results recorded only there are
12
+ lost. Up to `poll_s` of state is lost at a failover. Use an odd-numbered quorum system (etcd, Raft)
13
+ when that is not acceptable.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import threading
19
+ import time
20
+
21
+ from ..core.protocol import RpcClient
22
+
23
+
24
+ def parse_addrs(spec: str | list) -> list[tuple[str, int]]:
25
+ """'h1:7700,h2:7700' -> [('h1', 7700), ('h2', 7700)]."""
26
+ items = spec.split(",") if isinstance(spec, str) else spec
27
+ out = []
28
+ for it in items:
29
+ if isinstance(it, tuple):
30
+ out.append(it)
31
+ continue
32
+ host, _, port = it.strip().rpartition(":")
33
+ out.append((host or "127.0.0.1", int(port)))
34
+ return out
35
+
36
+
37
+ def connect_active(addrs, token: bytes, timeout: float = 30.0) -> RpcClient:
38
+ """Connect to the first address whose hub reports itself active. Raises ConnectionError if none does."""
39
+ errors = []
40
+ for host, port in parse_addrs(addrs):
41
+ try:
42
+ cli = RpcClient(host, port, token, timeout=timeout)
43
+ except (OSError, ConnectionError) as e:
44
+ errors.append(f"{host}:{port} {type(e).__name__}")
45
+ continue
46
+ try:
47
+ if cli.call({"op": "role"})[0].get("role") == "active":
48
+ return cli
49
+ errors.append(f"{host}:{port} standby")
50
+ except (OSError, ConnectionError, RuntimeError) as e:
51
+ errors.append(f"{host}:{port} {e}")
52
+ cli.close()
53
+ raise ConnectionError("no active hub: " + "; ".join(errors))
54
+
55
+
56
+ class HAController:
57
+ def __init__(self, hub, token: bytes, peers, name: str, poll_s: float = 1.0, fail_after_s: float = 6.0,
58
+ clock=time.time, on_change=None):
59
+ self.hub, self.token, self.peers = hub, token, parse_addrs(peers)
60
+ self.poll_s, self.fail_after_s, self.clock, self.on_change = poll_s, fail_after_s, clock, on_change
61
+ hub.name = name
62
+ hub.role = "standby" # start passive; promotion needs fail_after_s of silence
63
+ self._since = clock() # when we last saw an active peer (or started)
64
+ self._stop = threading.Event()
65
+ self.last_error: str | None = None
66
+
67
+ def _peer(self, addr) -> tuple[dict | None, RpcClient | None]:
68
+ try:
69
+ cli = RpcClient(addr[0], addr[1], self.token, timeout=max(2.0, self.poll_s * 3))
70
+ return cli.call({"op": "role"})[0], cli
71
+ except (OSError, ConnectionError, RuntimeError) as e:
72
+ self.last_error = f"{type(e).__name__}: {e}"
73
+ return None, None
74
+
75
+ def _beats(self, role: dict) -> bool:
76
+ """Does the peer outrank us? Higher epoch wins; at equal epoch the smaller name stays active."""
77
+ mine = (self.hub.epoch, self.hub.name)
78
+ theirs = (int(role["epoch"]), role["name"])
79
+ return theirs[0] > mine[0] or (theirs[0] == mine[0] and theirs[1] < mine[1])
80
+
81
+ def step(self) -> str:
82
+ """One round: returns the role after it. Called by the thread; callable directly in tests."""
83
+ hub, now = self.hub, self.clock()
84
+ active_peer = None
85
+ for addr in self.peers:
86
+ role, cli = self._peer(addr)
87
+ if role is None:
88
+ continue
89
+ if role["role"] == "active" and (hub.role == "standby" or self._beats(role)):
90
+ active_peer = cli
91
+ break
92
+ cli.close()
93
+ if hub.role == "active":
94
+ if active_peer is not None: # a better active hub exists: step down, adopt its state
95
+ hub.role = "standby"
96
+ self._since = now
97
+ self._follow(active_peer)
98
+ self._changed("demoted")
99
+ return hub.role
100
+ if active_peer is not None:
101
+ self._follow(active_peer)
102
+ self._since = now
103
+ elif now - self._since >= self.fail_after_s: # nobody active for long enough: take over
104
+ hub.epoch += 1
105
+ hub.requeue_running()
106
+ hub.role = "active"
107
+ self._changed("promoted")
108
+ return hub.role
109
+
110
+ def _follow(self, cli: RpcClient) -> None:
111
+ try:
112
+ _, blob = cli.call({"op": "snapshot"})
113
+ self.hub.restore(json.loads(blob), requeue=False)
114
+ except (OSError, ConnectionError, RuntimeError, ValueError) as e:
115
+ self.last_error = f"{type(e).__name__}: {e}"
116
+ finally:
117
+ cli.close()
118
+
119
+ def _changed(self, what: str) -> None:
120
+ if self.hub.ledger:
121
+ self.hub.ledger.decide("fleet", f"hub {self.hub.name} {what}", f"epoch {self.hub.epoch}")
122
+ if self.on_change:
123
+ self.on_change(what, self.hub)
124
+
125
+ def start(self) -> "HAController":
126
+ def loop():
127
+ while not self._stop.wait(self.poll_s):
128
+ try:
129
+ self.step()
130
+ except Exception as e: # never let the monitor die
131
+ self.last_error = f"{type(e).__name__}: {e}"
132
+ threading.Thread(target=loop, daemon=True).start()
133
+ return self
134
+
135
+ def stop(self) -> None:
136
+ self._stop.set()
spatial/fleet/hub.py CHANGED
@@ -48,6 +48,9 @@ class Hub:
48
48
  self.usage: dict[str, float] = {} # tenant -> finished compute-seconds
49
49
  self.gangs: dict[int, dict] = {}
50
50
  self.affinity: dict[str, str] = {} # cache key -> node that last ran it
51
+ self.role = "active" # "standby": answers only ping and role (see fleet/ha.py)
52
+ self.epoch = 1 # raised at every promotion; the higher epoch wins a split brain
53
+ self.name = "hub"
51
54
 
52
55
  # ------------------------------------------------------------------ identity
53
56
  @staticmethod
@@ -113,6 +116,15 @@ class Hub:
113
116
  running = sum(now - t.get("started", now) for t in self.tasks.values() if t["state"] == "running" and t["tenant"] == tenant)
114
117
  return (self.usage.get(tenant, 0.0) + running) / self.weights.get(tenant, 1.0)
115
118
 
119
+ def queue_view(self, recent: int = 12) -> dict:
120
+ """Counts per state plus the most recent tasks (no parameters or results: those can be large)."""
121
+ with self._lock:
122
+ counts: dict[str, int] = {}
123
+ for t in self.tasks.values():
124
+ counts[t["state"]] = counts.get(t["state"], 0) + 1
125
+ last = sorted(self.tasks.values(), key=lambda t: t["id"], reverse=True)[:recent]
126
+ return {"counts": counts, "recent": [{k: t.get(k) for k in ("id", "workload", "state", "node", "tenant", "gang", "wall_s")} for t in last]}
127
+
116
128
  def tenants(self) -> list[dict]:
117
129
  with self._lock:
118
130
  now = self.clock()
@@ -240,23 +252,30 @@ class Hub:
240
252
  """Durable state: tasks, queue order, tenant usage and weights, gangs, cache owners. Node
241
253
  measurements are not saved: agents rebuild them within one report interval."""
242
254
  with self._lock:
243
- return {"version": 1, "next_id": next(self._ids), "tasks": list(self.tasks.values()), "queue": list(self.queue),
255
+ return {"version": 1, "epoch": self.epoch, "next_id": next(self._ids), "tasks": list(self.tasks.values()), "queue": list(self.queue),
244
256
  "usage": self.usage, "weights": self.weights, "affinity": self.affinity,
245
257
  "gangs": [{**g, "reserved": {}} for g in self.gangs.values()]}
246
258
 
247
- def restore(self, snap: dict) -> dict:
248
- """Load a snapshot. A task that was running is put back in the queue (at-least-once: the
249
- allow-listed workloads are pure functions); if its agent still finishes it, that result is accepted."""
259
+ def requeue_running(self) -> int:
260
+ """Put running tasks back in the queue (at-least-once: the allow-listed workloads are pure
261
+ functions); if the agent still finishes one, its result is accepted."""
250
262
  with self._lock:
251
- self.tasks = {int(t["id"]): t for t in snap["tasks"]}
252
- self.queue = deque(int(i) for i in snap["queue"])
253
- requeued = 0
263
+ n = 0
254
264
  for t in self.tasks.values():
255
265
  if t["state"] == "running":
256
266
  t["state"] = "queued"
257
267
  t["requeued_after_restart"] = True
258
268
  self.queue.append(t["id"])
259
- requeued += 1
269
+ n += 1
270
+ return n
271
+
272
+ def restore(self, snap: dict, requeue: bool = True) -> dict:
273
+ """Load a snapshot (requeue=False for a standby that only follows the active hub)."""
274
+ with self._lock:
275
+ self.tasks = {int(t["id"]): t for t in snap["tasks"]}
276
+ self.queue = deque(int(i) for i in snap["queue"])
277
+ self.epoch = max(self.epoch, int(snap.get("epoch", 1)))
278
+ requeued = self.requeue_running() if requeue else 0
260
279
  self.usage, self.weights, self.affinity = dict(snap["usage"]), dict(snap["weights"]), dict(snap["affinity"])
261
280
  self.gangs = {int(g["id"]): {**g, "started": [], "reserved": {}} for g in snap["gangs"]}
262
281
  self._ids = itertools.count(int(snap["next_id"]))
@@ -284,11 +303,13 @@ class Hub:
284
303
  def loop():
285
304
  while not stop.wait(every_s):
286
305
  try:
287
- self.save(path)
306
+ if self.role == "active": # a standby holds a copy, never the master file
307
+ self.save(path)
288
308
  except OSError:
289
309
  pass
290
310
  try:
291
- self.save(path)
311
+ if self.role == "active":
312
+ self.save(path)
292
313
  except OSError:
293
314
  pass
294
315
  threading.Thread(target=loop, daemon=True).start()
@@ -393,6 +414,13 @@ def make_handler(hub: Hub):
393
414
  op = h.get("op")
394
415
  if op == "ping":
395
416
  return {"pong": True}, b""
417
+ if op == "role":
418
+ return {"role": hub.role, "epoch": hub.epoch, "name": hub.name}, b""
419
+ if hub.role != "active":
420
+ raise RuntimeError(f"standby: {hub.name} is not the active hub")
421
+ if op == "snapshot":
422
+ require("fleet:replicate")
423
+ return {"epoch": hub.epoch}, json.dumps(hub.snapshot()).encode()
396
424
  if op == "report":
397
425
  require("fleet:report")
398
426
  hub.report(Hub._who(h), h["metrics"], h.get("inventory"), h.get("usd_per_hour"), h.get("labels"))
@@ -410,6 +438,9 @@ def make_handler(hub: Hub):
410
438
  if op == "submit_gang":
411
439
  require("fleet:submit")
412
440
  return hub.submit_gang(h["workload"], h["params_list"], h.get("needs"), h.get("priority", 10), _tenant(h)), b""
441
+ if op == "queue":
442
+ require("fleet:read")
443
+ return hub.queue_view(int(h.get("recent", 12))), b""
413
444
  if op == "tenants":
414
445
  require("fleet:read")
415
446
  return {"tenants": hub.tenants()}, b""
@@ -442,6 +473,10 @@ def main():
442
473
  ap.add_argument("--allow-remote", action="store_true")
443
474
  ap.add_argument("--decision-log", default=str(Path.home() / ".spatial" / "fleet-decisions.jsonl"))
444
475
  ap.add_argument("--state-file", help="save tasks, queue, tenant usage here every 5 s and reload it at start")
476
+ ap.add_argument("--peer", action="append", default=[], help="host:port of another hub (repeatable): active/standby with automatic promotion")
477
+ ap.add_argument("--peer-token-file", help="token this hub presents to its peers (scope fleet:replicate); default: --token-file")
478
+ ap.add_argument("--name", default="hub", help="this hub's name (HA tie-break: the smaller name stays active)")
479
+ ap.add_argument("--fail-after", type=float, default=6.0, help="seconds without an active peer before a standby promotes itself")
445
480
  a = ap.parse_args()
446
481
  if bool(a.token_file) == bool(a.master_key_file):
447
482
  raise SystemExit("give exactly one of --token-file or --master-key-file")
@@ -450,6 +485,13 @@ def main():
450
485
  ledger=Ledger(a.decision_log))
451
486
  if a.state_file:
452
487
  print("restored", hub.load(a.state_file), flush=True)
488
+ if a.peer:
489
+ from .ha import HAController
490
+ ptf = a.peer_token_file or a.token_file
491
+ if ptf is None:
492
+ raise SystemExit("--peer needs --peer-token-file (a scoped token with fleet:replicate) or --token-file")
493
+ HAController(hub, Path(ptf).read_bytes(), a.peer, a.name, fail_after_s=a.fail_after).start()
494
+ if a.state_file:
453
495
  hub.autosave(a.state_file)
454
496
  print(f"PORT {srv.port}", flush=True)
455
497
  srv.serve_forever()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spatial-computing
3
- Version: 0.12.2
3
+ Version: 0.13.0
4
4
  Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
5
5
  Author: Spatial Computing contributors
6
6
  License-Expression: Apache-2.0
@@ -37,7 +37,7 @@ Dynamic: license-file
37
37
 
38
38
  One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
39
39
 
40
- > **Status: v0.12.2, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
40
+ > **Status: v0.13.0, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
41
41
 
42
42
  [Français](README.fr.md)
43
43
 
@@ -1,5 +1,5 @@
1
- spatial/__init__.py,sha256=bAIyZjnwvO9gEyXUrqr8NUw45IXlcmxHkT2CvKTlsO0,208
2
- spatial/cli.py,sha256=Gs8JUZFNR4JQ_8No8X0od1fu1HzvgkbUO8OZ2GYn3jc,15331
1
+ spatial/__init__.py,sha256=7ljELrv0YhCTw9BJTvHId8hyhzRjANcbmlqizgqVA-E,208
2
+ spatial/cli.py,sha256=SV0sdPqhIabNp_5tnP167J-0QAWq3iwkxpf3NXT7hqc,18243
3
3
  spatial/ai/__init__.py,sha256=qrQZBRNCGwnMp_Rx7HNblvGfgmLApVrdIAPcYVmZdCg,926
4
4
  spatial/ai/kvcache.py,sha256=7xrNI3zBKSoLA9ZjI1U2TZQ7GdXMZDzZq50qBrbWAWY,4054
5
5
  spatial/compute/__init__.py,sha256=VKrQED3KJOTve1dVS25AC0nPRTTcfQokXJYpPUngXMs,194
@@ -16,7 +16,7 @@ spatial/core/energy.py,sha256=w8dfk2F3RdmJBi0u3iNZzktDWSG-BdLozp8uFqAKTD8,3471
16
16
  spatial/core/ledger.py,sha256=FZhXIPLoPBqx3PfE2eXpIhaEULf7LkKoQ9pybguaRYE,3201
17
17
  spatial/core/model.py,sha256=UTLv1icOjGBl0L7zFrpz3XfQ2geCiS3HH-RaLuMx6pM,2324
18
18
  spatial/core/protocol.py,sha256=0FU-LLBRdBIOYeUhcBAjMZkEEx4ar-J3ypqlSvlx-NA,10851
19
- spatial/core/registry.py,sha256=2uotUqkmdzhzxo1CfkIC87rgVHzJG6KjxlEVKWX6GDY,5051
19
+ spatial/core/registry.py,sha256=Tfq3yo4TpeDcgbDZKIhUA6RJSk6TA0QefjqPHAbg6VA,5152
20
20
  spatial/fabric/__init__.py,sha256=3Hj1G1FJAABJcsgMUlffMycYh_IyS5gFja9oUDq-mxA,491
21
21
  spatial/fabric/cuda.py,sha256=C7gcYRblWhORunXd80bqdnNK-VNZTu2neAlJWBqzOyY,1309
22
22
  spatial/fabric/devices.py,sha256=6wd6c-3JH5QQXI44dOB9ysTOAI9ef0PgNT5V79sKgco,1317
@@ -24,8 +24,11 @@ spatial/fabric/metal.py,sha256=RvQVShWHF981KuDav0J0lMlKwrhMi8sZPg8flI08W5Q,3341
24
24
  spatial/fabric/metal_mandel.swift,sha256=-uL49wwx5OGimt727HqGL9sSDobF8N0GJHQye59upyw,3132
25
25
  spatial/fabric/metal_run.swift,sha256=onuHT3yfpqrg5yOGiDpOugG6AovllFYeUer8D3KfnHE,2673
26
26
  spatial/fleet/__init__.py,sha256=LUpn9X_XTGPy8KfZhnYdGVQTIY9IIVfzMeNnw8HcCbs,957
27
- spatial/fleet/agent.py,sha256=iPpFZc5ThMb-axPTD3QotL9lsKl-jlnTJODc27aHkPQ,5588
28
- spatial/fleet/hub.py,sha256=Qd0TziM1XssBidmrGregbGsTCsti31EMZEsC3XubsZw,25079
27
+ spatial/fleet/agent.py,sha256=4nbHPP0pyiNH8DUAgn5Ma-6qadbd0FGUu12LBJHWV28,5959
28
+ spatial/fleet/alerts.py,sha256=PG37Z_1lIci_MImbjGI66Pkd2WnIjtCrGMSLXLwSZZY,2166
29
+ spatial/fleet/dashboard.py,sha256=7IwuJAC331EceNCE15pNI-WM_Nql05i5gFyoyWToEA0,10803
30
+ spatial/fleet/ha.py,sha256=GgW-JON4A9o5b4KAKjVlhcEXi_q1WvNcbFrtxJjagVE,5962
31
+ spatial/fleet/hub.py,sha256=ikxHNREueHgSamIB8e1UZz9yy571qao3JMwekQ_RM-c,27755
29
32
  spatial/holographic/__init__.py,sha256=16C0eQdfD87FeMKVwLAzgOgZ97oHzOfD27sLfmWAhP4,541
30
33
  spatial/holographic/cgh.py,sha256=jiQgs4k5QY03ndjMTVkT6DquJZX2BP6vPLWHTpaG0Uk,1910
31
34
  spatial/holographic/model.py,sha256=t0xtGmE2_gyy3T-HGliIqvqOhXeCTTKuSQas8ujStK8,1434
@@ -72,9 +75,9 @@ spatial/unified/__init__.py,sha256=jc85fwURTd_6RZymNMjxtLVY51mzTXTXyuvyk0KZrLo,6
72
75
  spatial/unified/model.py,sha256=oTOvf0ImSdXXn75sf92bgMCixju-YmMWHiVkRHQdJGA,7088
73
76
  spatial/unified/planner.py,sha256=kdpzCpZJ-RdjCj8MNaES4TPdSug0skSQ53pKUi2Q-Bo,5429
74
77
  spatial/unified/providers.py,sha256=HBOoIhlJ7nuN6nTvkxEiG004A-HEiaM7PY7qdKJURn0,21664
75
- spatial_computing-0.12.2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
76
- spatial_computing-0.12.2.dist-info/METADATA,sha256=F0IQPQqyxOV0s2WExIY6jpWk3APq_Oatg5EvDh5-ThY,6697
77
- spatial_computing-0.12.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
78
- spatial_computing-0.12.2.dist-info/entry_points.txt,sha256=UIFCHJL01u7PIPej7EUHRI7rWEY8uBhufZ-_ulXUPRk,79
79
- spatial_computing-0.12.2.dist-info/top_level.txt,sha256=ZHke8hWgy4qIqEGq7omus3O-T7AhmPoc-cqr7JdGGxQ,8
80
- spatial_computing-0.12.2.dist-info/RECORD,,
78
+ spatial_computing-0.13.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
79
+ spatial_computing-0.13.0.dist-info/METADATA,sha256=yMYQpzipdcjUfTsmSvl86Xrue9Mc5vPARWT29m4gvnE,6697
80
+ spatial_computing-0.13.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
81
+ spatial_computing-0.13.0.dist-info/entry_points.txt,sha256=UIFCHJL01u7PIPej7EUHRI7rWEY8uBhufZ-_ulXUPRk,79
82
+ spatial_computing-0.13.0.dist-info/top_level.txt,sha256=ZHke8hWgy4qIqEGq7omus3O-T7AhmPoc-cqr7JdGGxQ,8
83
+ spatial_computing-0.13.0.dist-info/RECORD,,