spatial-computing 0.12.2__py3-none-any.whl → 0.14.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 +1 -1
- spatial/cli.py +59 -6
- spatial/core/registry.py +2 -2
- spatial/fabric/metal.py +6 -4
- spatial/fabric/metal_run.swift +20 -11
- spatial/fleet/agent.py +8 -3
- spatial/fleet/alerts.py +46 -0
- spatial/fleet/dashboard.py +160 -0
- spatial/fleet/ha.py +334 -0
- spatial/fleet/hub.py +85 -14
- spatial/kernel/dsl.py +72 -21
- {spatial_computing-0.12.2.dist-info → spatial_computing-0.14.0.dist-info}/METADATA +2 -2
- {spatial_computing-0.12.2.dist-info → spatial_computing-0.14.0.dist-info}/RECORD +17 -14
- {spatial_computing-0.12.2.dist-info → spatial_computing-0.14.0.dist-info}/WHEEL +0 -0
- {spatial_computing-0.12.2.dist-info → spatial_computing-0.14.0.dist-info}/entry_points.txt +0 -0
- {spatial_computing-0.12.2.dist-info → spatial_computing-0.14.0.dist-info}/licenses/LICENSE +0 -0
- {spatial_computing-0.12.2.dist-info → spatial_computing-0.14.0.dist-info}/top_level.txt +0 -0
spatial/__init__.py
CHANGED
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 .
|
|
93
|
-
|
|
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
|
-
|
|
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
|
@@ -37,13 +37,13 @@ ENGINES: list[Engine] = [
|
|
|
37
37
|
"N = 4 and 8 processes on one machine over loopback; no real network, RDMA or GPU memory; about 3,000x slower than NVLink 5 (vendor figure); no fault tolerance"),
|
|
38
38
|
Engine("kernel", "Portable kernels", "spatial.kernel", Status.FIRST_COMPONENTS,
|
|
39
39
|
"tests/test_kernel.py, benchmarks/bench_kernel.py (planner right 4 of 6; integer kernel bit-identical CPU vs Metal)",
|
|
40
|
-
"CUDA C generated, never compiled or run;
|
|
40
|
+
"CUDA C and HIP generated, never compiled or run; two kernel shapes (2-D map, whole-grid sum with shared memory), no tiling or tensor cores"),
|
|
41
41
|
Engine("planner", "Spatial Planner (the one objective)", "spatial.unified", Status.OPERATIONAL_PROTOTYPE,
|
|
42
42
|
"tests/test_unified.py",
|
|
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
|
|
46
|
+
"validated on one machine (agents on loopback); HA: active/standby for two hubs, majority election (election safety, no replicated log) for three or more, tested on one machine with simulated clocks; 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/fabric/metal.py
CHANGED
|
@@ -62,16 +62,16 @@ def _ensure_run_binary() -> Path:
|
|
|
62
62
|
return RUN_BIN
|
|
63
63
|
|
|
64
64
|
|
|
65
|
-
def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = None):
|
|
66
|
-
"""Run a portable Kernel (spatial.kernel) on the Metal GPU; returns the (n, n) uint32 output.
|
|
65
|
+
def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = None, reduce: bool = False):
|
|
66
|
+
"""Run a portable Kernel (spatial.kernel) on the Metal GPU; returns the (n, n) uint32 output, or with reduce=True the sum of all outputs (computed in threadgroup shared memory, partial sums added on the host).
|
|
67
67
|
`timing`, if given, receives the GPU-side median seconds."""
|
|
68
68
|
import numpy as np
|
|
69
69
|
import tempfile
|
|
70
70
|
binary = _ensure_run_binary()
|
|
71
71
|
with tempfile.TemporaryDirectory() as d:
|
|
72
72
|
msl, out = Path(d) / "k.metal", Path(d) / "out.bin"
|
|
73
|
-
msl.write_text(k.to_metal())
|
|
74
|
-
args = [str(binary), str(msl), k.name, str(n), str(reps), str(out)]
|
|
73
|
+
msl.write_text(k.to_metal(reduce=reduce))
|
|
74
|
+
args = [str(binary), str(msl), k.name + ("_sum" if reduce else ""), str(n), str(reps), str(out), "sum" if reduce else "map"]
|
|
75
75
|
args += [f"{t}:{float(params[p]) if t == 'float' else int(params[p])}" for p, t in k.params]
|
|
76
76
|
r = subprocess.run(args, capture_output=True, text=True, timeout=600)
|
|
77
77
|
try:
|
|
@@ -82,4 +82,6 @@ def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = Non
|
|
|
82
82
|
raise RuntimeError(info.get("error", "Metal error"))
|
|
83
83
|
if timing is not None:
|
|
84
84
|
timing.update(info)
|
|
85
|
+
if reduce:
|
|
86
|
+
return int(np.fromfile(out, dtype=np.uint64).sum())
|
|
85
87
|
return np.fromfile(out, dtype=np.uint32).reshape(n, n)
|
spatial/fabric/metal_run.swift
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Generic Metal host for portable kernels generated by spatial.kernel.
|
|
2
|
-
// usage: metal_run <msl_file> <kernel_name> <n> <reps> <out_file> [int:<v> | float:<v> ...]
|
|
3
|
-
// Buffers: 0 = output
|
|
2
|
+
// usage: metal_run <msl_file> <kernel_name> <n> <reps> <out_file> <map|sum> [int:<v> | float:<v> ...]
|
|
3
|
+
// Buffers: 0 = output, 1 = n (int), 2.. = parameters in order.
|
|
4
|
+
// map: output uint[n*n]. sum: one uint64 partial sum per 16x16 threadgroup (the kernel reduces in threadgroup memory).
|
|
4
5
|
import Foundation
|
|
5
6
|
import Metal
|
|
6
7
|
|
|
@@ -8,9 +9,11 @@ func now() -> Double { return Double(DispatchTime.now().uptimeNanoseconds) / 1e9
|
|
|
8
9
|
func fail(_ m: String) -> Never { print("{\"ok\": false, \"error\": \"\(m)\"}"); exit(1) }
|
|
9
10
|
|
|
10
11
|
let a = CommandLine.arguments
|
|
11
|
-
if a.count <
|
|
12
|
+
if a.count < 7 { fail("usage") }
|
|
12
13
|
guard let src = try? String(contentsOfFile: a[1], encoding: .utf8) else { fail("cannot read msl") }
|
|
13
|
-
let name = a[2], n = Int(a[3])!, reps = max(1, Int(a[4])!), outPath = a[5]
|
|
14
|
+
let name = a[2], n = Int(a[3])!, reps = max(1, Int(a[4])!), outPath = a[5], mode = a[6]
|
|
15
|
+
let sumMode = (mode == "sum")
|
|
16
|
+
let gx = (n + 15) / 16
|
|
14
17
|
guard let dev = MTLCreateSystemDefaultDevice() ?? MTLCopyAllDevices().first else { fail("no Metal device") }
|
|
15
18
|
let t0 = now()
|
|
16
19
|
let lib: MTLLibrary
|
|
@@ -21,7 +24,9 @@ do { lib = try dev.makeLibrary(source: src, options: nil) } catch {
|
|
|
21
24
|
guard let fn = lib.makeFunction(name: name) else { fail("kernel not found") }
|
|
22
25
|
let pipe = try! dev.makeComputePipelineState(function: fn)
|
|
23
26
|
let setupS = now() - t0
|
|
24
|
-
|
|
27
|
+
if sumMode && pipe.maxTotalThreadsPerThreadgroup < 256 { fail("device allows fewer than 256 threads per threadgroup") }
|
|
28
|
+
let outLen = sumMode ? gx * gx * 8 : n * n * 4
|
|
29
|
+
let out = dev.makeBuffer(length: outLen, options: .storageModeShared)!
|
|
25
30
|
let queue = dev.makeCommandQueue()!
|
|
26
31
|
var nn = Int32(n)
|
|
27
32
|
|
|
@@ -32,21 +37,25 @@ func run() -> Double {
|
|
|
32
37
|
enc.setComputePipelineState(pipe)
|
|
33
38
|
enc.setBuffer(out, offset: 0, index: 0)
|
|
34
39
|
enc.setBytes(&nn, length: 4, index: 1)
|
|
35
|
-
for (k, spec) in a[
|
|
40
|
+
for (k, spec) in a[7...].enumerated() {
|
|
36
41
|
let parts = spec.split(separator: ":", maxSplits: 1).map(String.init)
|
|
37
42
|
if parts[0] == "int" { var v = Int32(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
38
43
|
else { var v = Float(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
39
44
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
45
|
+
if sumMode {
|
|
46
|
+
enc.dispatchThreadgroups(MTLSize(width: gx, height: gx, depth: 1), threadsPerThreadgroup: MTLSize(width: 16, height: 16, depth: 1))
|
|
47
|
+
} else {
|
|
48
|
+
let w = pipe.threadExecutionWidth
|
|
49
|
+
let h = pipe.maxTotalThreadsPerThreadgroup / w
|
|
50
|
+
enc.dispatchThreadgroups(MTLSize(width: (n + w - 1) / w, height: (n + h - 1) / h, depth: 1),
|
|
51
|
+
threadsPerThreadgroup: MTLSize(width: w, height: h, depth: 1))
|
|
52
|
+
}
|
|
44
53
|
enc.endEncoding(); cb.commit(); cb.waitUntilCompleted()
|
|
45
54
|
return now() - t
|
|
46
55
|
}
|
|
47
56
|
var times: [Double] = []
|
|
48
57
|
for _ in 0..<reps { times.append(run()) }
|
|
49
|
-
let data = Data(bytes: out.contents(), count:
|
|
58
|
+
let data = Data(bytes: out.contents(), count: outLen)
|
|
50
59
|
do { try data.write(to: URL(fileURLWithPath: outPath)) } catch { fail("cannot write output") }
|
|
51
60
|
times.sort()
|
|
52
61
|
print("{\"ok\": true, \"device\": \"\(dev.name)\", \"gpu_s_median\": \(times[times.count / 2]), \"setup_s\": \(setupS)}")
|
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
|
-
|
|
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
|
-
|
|
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
|
spatial/fleet/alerts.py
ADDED
|
@@ -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=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[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,334 @@
|
|
|
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 os
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
import zlib
|
|
22
|
+
|
|
23
|
+
from ..core.protocol import RpcClient
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def parse_addrs(spec: str | list) -> list[tuple[str, int]]:
|
|
27
|
+
"""'h1:7700,h2:7700' -> [('h1', 7700), ('h2', 7700)]."""
|
|
28
|
+
items = spec.split(",") if isinstance(spec, str) else spec
|
|
29
|
+
out = []
|
|
30
|
+
for it in items:
|
|
31
|
+
if isinstance(it, tuple):
|
|
32
|
+
out.append(it)
|
|
33
|
+
continue
|
|
34
|
+
host, _, port = it.strip().rpartition(":")
|
|
35
|
+
out.append((host or "127.0.0.1", int(port)))
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def connect_active(addrs, token: bytes, timeout: float = 30.0) -> RpcClient:
|
|
40
|
+
"""Connect to the first address whose hub reports itself active. Raises ConnectionError if none does."""
|
|
41
|
+
errors = []
|
|
42
|
+
for host, port in parse_addrs(addrs):
|
|
43
|
+
try:
|
|
44
|
+
cli = RpcClient(host, port, token, timeout=timeout)
|
|
45
|
+
except (OSError, ConnectionError) as e:
|
|
46
|
+
errors.append(f"{host}:{port} {type(e).__name__}")
|
|
47
|
+
continue
|
|
48
|
+
try:
|
|
49
|
+
r = cli.call({"op": "role"})[0]
|
|
50
|
+
if r.get("role") == "active" and r.get("lease", True):
|
|
51
|
+
return cli
|
|
52
|
+
errors.append(f"{host}:{port} standby")
|
|
53
|
+
except (OSError, ConnectionError, RuntimeError) as e:
|
|
54
|
+
errors.append(f"{host}:{port} {e}")
|
|
55
|
+
cli.close()
|
|
56
|
+
raise ConnectionError("no active hub: " + "; ".join(errors))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class HAController:
|
|
60
|
+
def __init__(self, hub, token: bytes, peers, name: str, poll_s: float = 1.0, fail_after_s: float = 6.0,
|
|
61
|
+
clock=time.time, on_change=None):
|
|
62
|
+
self.hub, self.token, self.peers = hub, token, parse_addrs(peers)
|
|
63
|
+
self.poll_s, self.fail_after_s, self.clock, self.on_change = poll_s, fail_after_s, clock, on_change
|
|
64
|
+
hub.name = name
|
|
65
|
+
hub.role = "standby" # start passive; promotion needs fail_after_s of silence
|
|
66
|
+
self._since = clock() # when we last saw an active peer (or started)
|
|
67
|
+
self._stop = threading.Event()
|
|
68
|
+
self.last_error: str | None = None
|
|
69
|
+
|
|
70
|
+
def _peer(self, addr) -> tuple[dict | None, RpcClient | None]:
|
|
71
|
+
try:
|
|
72
|
+
cli = RpcClient(addr[0], addr[1], self.token, timeout=max(2.0, self.poll_s * 3))
|
|
73
|
+
return cli.call({"op": "role"})[0], cli
|
|
74
|
+
except (OSError, ConnectionError, RuntimeError) as e:
|
|
75
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
76
|
+
return None, None
|
|
77
|
+
|
|
78
|
+
def _beats(self, role: dict) -> bool:
|
|
79
|
+
"""Does the peer outrank us? Higher epoch wins; at equal epoch the smaller name stays active."""
|
|
80
|
+
mine = (self.hub.epoch, self.hub.name)
|
|
81
|
+
theirs = (int(role["epoch"]), role["name"])
|
|
82
|
+
return theirs[0] > mine[0] or (theirs[0] == mine[0] and theirs[1] < mine[1])
|
|
83
|
+
|
|
84
|
+
def step(self) -> str:
|
|
85
|
+
"""One round: returns the role after it. Called by the thread; callable directly in tests."""
|
|
86
|
+
hub, now = self.hub, self.clock()
|
|
87
|
+
active_peer = None
|
|
88
|
+
for addr in self.peers:
|
|
89
|
+
role, cli = self._peer(addr)
|
|
90
|
+
if role is None:
|
|
91
|
+
continue
|
|
92
|
+
if role["role"] == "active" and (hub.role == "standby" or self._beats(role)):
|
|
93
|
+
active_peer = cli
|
|
94
|
+
break
|
|
95
|
+
cli.close()
|
|
96
|
+
if hub.role == "active":
|
|
97
|
+
if active_peer is not None: # a better active hub exists: step down, adopt its state
|
|
98
|
+
hub.role = "standby"
|
|
99
|
+
self._since = now
|
|
100
|
+
self._follow(active_peer)
|
|
101
|
+
self._changed("demoted")
|
|
102
|
+
return hub.role
|
|
103
|
+
if active_peer is not None:
|
|
104
|
+
self._follow(active_peer)
|
|
105
|
+
self._since = now
|
|
106
|
+
elif now - self._since >= self.fail_after_s: # nobody active for long enough: take over
|
|
107
|
+
hub.epoch += 1
|
|
108
|
+
hub.requeue_running()
|
|
109
|
+
hub.role = "active"
|
|
110
|
+
self._changed("promoted")
|
|
111
|
+
return hub.role
|
|
112
|
+
|
|
113
|
+
def _follow(self, cli: RpcClient) -> None:
|
|
114
|
+
try:
|
|
115
|
+
_, blob = cli.call({"op": "snapshot"})
|
|
116
|
+
self.hub.restore(json.loads(blob), requeue=False)
|
|
117
|
+
except (OSError, ConnectionError, RuntimeError, ValueError) as e:
|
|
118
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
119
|
+
finally:
|
|
120
|
+
cli.close()
|
|
121
|
+
|
|
122
|
+
def _changed(self, what: str) -> None:
|
|
123
|
+
if self.hub.ledger:
|
|
124
|
+
self.hub.ledger.decide("fleet", f"hub {self.hub.name} {what}", f"epoch {self.hub.epoch}")
|
|
125
|
+
if self.on_change:
|
|
126
|
+
self.on_change(what, self.hub)
|
|
127
|
+
|
|
128
|
+
def start(self) -> "HAController":
|
|
129
|
+
def loop():
|
|
130
|
+
while not self._stop.wait(self.poll_s):
|
|
131
|
+
try:
|
|
132
|
+
self.step()
|
|
133
|
+
except Exception as e: # never let the monitor die
|
|
134
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
135
|
+
threading.Thread(target=loop, daemon=True).start()
|
|
136
|
+
return self
|
|
137
|
+
|
|
138
|
+
def stop(self) -> None:
|
|
139
|
+
self._stop.set()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class QuorumController:
|
|
143
|
+
"""Three or more hubs, one leader chosen by majority vote (Raft-style terms and votes).
|
|
144
|
+
|
|
145
|
+
What it guarantees: at most ONE leader per term, and a leader serves requests only while it has heard
|
|
146
|
+
from a majority within the last `fail_after_s / 2` (a lease), so a hub cut off from the others stops
|
|
147
|
+
answering before a new leader can be elected (given clocks that tick at about the same rate). A hub
|
|
148
|
+
restarted with its term file does not vote twice in a term.
|
|
149
|
+
What it does not give: a replicated log. State travels by snapshot polling from the leader, so a
|
|
150
|
+
failover can lose up to one poll of recent changes; a candidate whose newest task id is older than a
|
|
151
|
+
voter's cannot win. This is election safety, not linearizable storage. Not a Raft implementation.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def __init__(self, hub, token: bytes, peers, name: str, poll_s: float = 1.0, fail_after_s: float = 6.0,
|
|
155
|
+
clock=time.time, meta_path: str | None = None, on_change=None):
|
|
156
|
+
self.hub, self.token, self.peers = hub, token, parse_addrs(peers)
|
|
157
|
+
self.poll_s, self.fail_after_s, self.clock, self.on_change = poll_s, fail_after_s, clock, on_change
|
|
158
|
+
self.name, self.meta_path = name, meta_path
|
|
159
|
+
self.majority = (len(self.peers) + 1) // 2 + 1
|
|
160
|
+
jitter = (zlib.crc32(name.encode()) % 1000) / 1000 # spreads elections so they rarely collide
|
|
161
|
+
self.timeout = fail_after_s * (1 + jitter)
|
|
162
|
+
self.term, self.voted_for, self.state = 0, None, "follower"
|
|
163
|
+
self.last_beat = self.last_majority = clock()
|
|
164
|
+
self.offline = False # tests: behave as a hub cut off from the network
|
|
165
|
+
self._lock = threading.RLock()
|
|
166
|
+
self._stop = threading.Event()
|
|
167
|
+
self.last_error: str | None = None
|
|
168
|
+
hub.name, hub.role, hub.ha = name, "standby", self
|
|
169
|
+
self._load()
|
|
170
|
+
hub.epoch = self.term
|
|
171
|
+
|
|
172
|
+
# ------------------------------------------------------------------ persistence of term and vote
|
|
173
|
+
def _load(self):
|
|
174
|
+
if self.meta_path and os.path.exists(self.meta_path):
|
|
175
|
+
try:
|
|
176
|
+
m = json.load(open(self.meta_path))
|
|
177
|
+
self.term, self.voted_for = int(m["term"]), m.get("voted_for")
|
|
178
|
+
except (OSError, ValueError, KeyError):
|
|
179
|
+
pass
|
|
180
|
+
|
|
181
|
+
def _persist(self):
|
|
182
|
+
if self.meta_path:
|
|
183
|
+
tmp = self.meta_path + ".tmp"
|
|
184
|
+
with open(tmp, "w") as f:
|
|
185
|
+
json.dump({"term": self.term, "voted_for": self.voted_for}, f); f.flush(); os.fsync(f.fileno())
|
|
186
|
+
os.replace(tmp, self.meta_path)
|
|
187
|
+
|
|
188
|
+
# ------------------------------------------------------------------ state changes
|
|
189
|
+
def lease_ok(self) -> bool:
|
|
190
|
+
if self.state != "leader":
|
|
191
|
+
return True
|
|
192
|
+
return self.clock() - self.last_majority < self.fail_after_s / 2
|
|
193
|
+
|
|
194
|
+
def _follower(self, term: int):
|
|
195
|
+
with self._lock:
|
|
196
|
+
if term > self.term:
|
|
197
|
+
self.term, self.voted_for = term, None
|
|
198
|
+
self.state = "follower"
|
|
199
|
+
self.hub.role, self.hub.epoch = "standby", self.term
|
|
200
|
+
self._persist()
|
|
201
|
+
|
|
202
|
+
def _changed(self, what: str):
|
|
203
|
+
if self.hub.ledger:
|
|
204
|
+
self.hub.ledger.decide("fleet", f"hub {self.name} {what}", f"term {self.term}")
|
|
205
|
+
if self.on_change:
|
|
206
|
+
self.on_change(what, self.hub)
|
|
207
|
+
|
|
208
|
+
# ------------------------------------------------------------------ handlers for peers
|
|
209
|
+
def on_vote(self, h: dict) -> dict:
|
|
210
|
+
if self.offline:
|
|
211
|
+
raise ConnectionError("offline")
|
|
212
|
+
with self._lock:
|
|
213
|
+
term, cand = int(h["term"]), str(h["candidate"])
|
|
214
|
+
if term > self.term:
|
|
215
|
+
self._follower(term)
|
|
216
|
+
fresh = int(h.get("last_id", 0)) >= self.hub.last_id() # candidate must not be behind us
|
|
217
|
+
grant = term == self.term and self.voted_for in (None, cand) and fresh
|
|
218
|
+
if grant:
|
|
219
|
+
self.voted_for, self.last_beat = cand, self.clock()
|
|
220
|
+
self._persist()
|
|
221
|
+
return {"granted": grant, "term": self.term}
|
|
222
|
+
|
|
223
|
+
def on_beat(self, h: dict) -> dict:
|
|
224
|
+
if self.offline:
|
|
225
|
+
raise ConnectionError("offline")
|
|
226
|
+
with self._lock:
|
|
227
|
+
term = int(h["term"])
|
|
228
|
+
if term < self.term:
|
|
229
|
+
return {"ok": False, "term": self.term}
|
|
230
|
+
if term > self.term or self.state != "follower":
|
|
231
|
+
self._follower(term)
|
|
232
|
+
self.last_beat = self.clock()
|
|
233
|
+
return {"ok": True, "term": self.term}
|
|
234
|
+
|
|
235
|
+
# ------------------------------------------------------------------ outbound
|
|
236
|
+
def _try(self, addr, header: dict):
|
|
237
|
+
if self.offline:
|
|
238
|
+
return None
|
|
239
|
+
try:
|
|
240
|
+
cli = RpcClient(addr[0], addr[1], self.token, timeout=max(2.0, self.poll_s * 3))
|
|
241
|
+
try:
|
|
242
|
+
return cli.call(header)[0]
|
|
243
|
+
finally:
|
|
244
|
+
cli.close()
|
|
245
|
+
except (OSError, ConnectionError, RuntimeError) as e:
|
|
246
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
247
|
+
return None
|
|
248
|
+
|
|
249
|
+
def _pull(self):
|
|
250
|
+
for addr in self.peers:
|
|
251
|
+
if self.offline:
|
|
252
|
+
return
|
|
253
|
+
try:
|
|
254
|
+
cli = RpcClient(addr[0], addr[1], self.token, timeout=max(2.0, self.poll_s * 3))
|
|
255
|
+
except (OSError, ConnectionError):
|
|
256
|
+
continue
|
|
257
|
+
try:
|
|
258
|
+
r = cli.call({"op": "role"})[0]
|
|
259
|
+
if r["role"] == "active" and int(r["epoch"]) == self.term:
|
|
260
|
+
_, blob = cli.call({"op": "snapshot"})
|
|
261
|
+
with self._lock:
|
|
262
|
+
if self.state == "follower":
|
|
263
|
+
self.hub.restore(json.loads(blob), requeue=False)
|
|
264
|
+
self.hub.epoch = self.term
|
|
265
|
+
return
|
|
266
|
+
except (OSError, ConnectionError, RuntimeError, ValueError):
|
|
267
|
+
pass
|
|
268
|
+
finally:
|
|
269
|
+
cli.close()
|
|
270
|
+
|
|
271
|
+
# ------------------------------------------------------------------ one round
|
|
272
|
+
def step(self) -> str:
|
|
273
|
+
now = self.clock()
|
|
274
|
+
if self.state == "leader":
|
|
275
|
+
acks, higher = 1, None
|
|
276
|
+
for addr in self.peers:
|
|
277
|
+
r = self._try(addr, {"op": "beat", "term": self.term, "name": self.name})
|
|
278
|
+
if r is None:
|
|
279
|
+
continue
|
|
280
|
+
if r["term"] > self.term:
|
|
281
|
+
higher = r["term"]
|
|
282
|
+
elif r["ok"]:
|
|
283
|
+
acks += 1
|
|
284
|
+
if higher is not None:
|
|
285
|
+
self._follower(higher); self.last_beat = now; self._changed("stepped down (higher term)")
|
|
286
|
+
elif acks >= self.majority:
|
|
287
|
+
self.last_majority = now
|
|
288
|
+
elif now - self.last_majority >= self.fail_after_s:
|
|
289
|
+
self._follower(self.term); self.last_beat = now; self._changed("stepped down (lost majority)")
|
|
290
|
+
return self.state
|
|
291
|
+
if now - self.last_beat < self.timeout:
|
|
292
|
+
self._pull()
|
|
293
|
+
return self.state
|
|
294
|
+
# no leader heard for a full timeout: stand for election
|
|
295
|
+
with self._lock:
|
|
296
|
+
self.term += 1
|
|
297
|
+
self.voted_for, self.state = self.name, "candidate"
|
|
298
|
+
self.hub.epoch = self.term
|
|
299
|
+
self._persist()
|
|
300
|
+
term = self.term
|
|
301
|
+
votes = 1
|
|
302
|
+
for addr in self.peers:
|
|
303
|
+
r = self._try(addr, {"op": "vote", "term": term, "candidate": self.name, "last_id": self.hub.last_id()})
|
|
304
|
+
if r is None:
|
|
305
|
+
continue
|
|
306
|
+
if r["term"] > term:
|
|
307
|
+
self._follower(r["term"]); self.last_beat = now
|
|
308
|
+
return self.state
|
|
309
|
+
if r["granted"]:
|
|
310
|
+
votes += 1
|
|
311
|
+
with self._lock:
|
|
312
|
+
if self.state == "candidate" and self.term == term and votes >= self.majority and not self.offline:
|
|
313
|
+
self.state = "leader"
|
|
314
|
+
self.hub.role = "active"
|
|
315
|
+
self.hub.requeue_running()
|
|
316
|
+
self.last_majority = self.clock()
|
|
317
|
+
self._changed("elected")
|
|
318
|
+
else:
|
|
319
|
+
self.state = "follower"
|
|
320
|
+
self.last_beat = now # back off for another timeout
|
|
321
|
+
return self.state
|
|
322
|
+
|
|
323
|
+
def start(self) -> "QuorumController":
|
|
324
|
+
def loop():
|
|
325
|
+
while not self._stop.wait(self.poll_s):
|
|
326
|
+
try:
|
|
327
|
+
self.step()
|
|
328
|
+
except Exception as e:
|
|
329
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
330
|
+
threading.Thread(target=loop, daemon=True).start()
|
|
331
|
+
return self
|
|
332
|
+
|
|
333
|
+
def stop(self) -> None:
|
|
334
|
+
self._stop.set()
|
spatial/fleet/hub.py
CHANGED
|
@@ -31,7 +31,8 @@ HISTORY = 2000 # samples kept per node
|
|
|
31
31
|
|
|
32
32
|
class Hub:
|
|
33
33
|
def __init__(self, ledger: Ledger | None = None, stale_after_s: float = 30.0, clock=time.time,
|
|
34
|
-
busy_cpu_pct: float = 90.0, gang_hold_s: float = 30.0, affinity_wait_s: float = 5.0
|
|
34
|
+
busy_cpu_pct: float = 90.0, gang_hold_s: float = 30.0, affinity_wait_s: float = 5.0,
|
|
35
|
+
max_finished: int = 5000, max_affinity: int = 10000):
|
|
35
36
|
self.nodes: dict[str, dict] = {}
|
|
36
37
|
self.series: dict[str, deque] = {}
|
|
37
38
|
self.tasks: dict[int, dict] = {}
|
|
@@ -48,6 +49,12 @@ class Hub:
|
|
|
48
49
|
self.usage: dict[str, float] = {} # tenant -> finished compute-seconds
|
|
49
50
|
self.gangs: dict[int, dict] = {}
|
|
50
51
|
self.affinity: dict[str, str] = {} # cache key -> node that last ran it
|
|
52
|
+
self.role = "active" # "standby": answers only ping and role (see fleet/ha.py)
|
|
53
|
+
self.epoch = 1 # raised at every promotion; the higher epoch wins a split brain
|
|
54
|
+
self.name = "hub"
|
|
55
|
+
self.ha = None # a fleet.ha controller, if any
|
|
56
|
+
self.max_finished, self.max_affinity = max_finished, max_affinity # bounded memory: the soak test showed the hub grew without limit
|
|
57
|
+
self._finished: deque = deque() # ids of done/failed tasks, oldest first
|
|
51
58
|
|
|
52
59
|
# ------------------------------------------------------------------ identity
|
|
53
60
|
@staticmethod
|
|
@@ -113,6 +120,15 @@ class Hub:
|
|
|
113
120
|
running = sum(now - t.get("started", now) for t in self.tasks.values() if t["state"] == "running" and t["tenant"] == tenant)
|
|
114
121
|
return (self.usage.get(tenant, 0.0) + running) / self.weights.get(tenant, 1.0)
|
|
115
122
|
|
|
123
|
+
def queue_view(self, recent: int = 12) -> dict:
|
|
124
|
+
"""Counts per state plus the most recent tasks (no parameters or results: those can be large)."""
|
|
125
|
+
with self._lock:
|
|
126
|
+
counts: dict[str, int] = {}
|
|
127
|
+
for t in self.tasks.values():
|
|
128
|
+
counts[t["state"]] = counts.get(t["state"], 0) + 1
|
|
129
|
+
last = sorted(self.tasks.values(), key=lambda t: t["id"], reverse=True)[:recent]
|
|
130
|
+
return {"counts": counts, "recent": [{k: t.get(k) for k in ("id", "workload", "state", "node", "tenant", "gang", "wall_s")} for t in last]}
|
|
131
|
+
|
|
116
132
|
def tenants(self) -> list[dict]:
|
|
117
133
|
with self._lock:
|
|
118
134
|
now = self.clock()
|
|
@@ -168,7 +184,7 @@ class Hub:
|
|
|
168
184
|
g["reserved"] = {nd: exp for nd, exp in g["reserved"].items() if exp > now}
|
|
169
185
|
for g in self.gangs.values(): # a node held for a gang serves only that gang
|
|
170
186
|
if node in g["reserved"]:
|
|
171
|
-
mine = [self.tasks[t] for t in g["tasks"] if self.tasks[t]["state"] == "queued" and self._eligible(node, self.tasks[t]["needs"])]
|
|
187
|
+
mine = [self.tasks[t] for t in g["tasks"] if t in self.tasks and self.tasks[t]["state"] == "queued" and self._eligible(node, self.tasks[t]["needs"])]
|
|
172
188
|
if not mine:
|
|
173
189
|
return None
|
|
174
190
|
return self._assign(min(mine, key=lambda t: t["id"]), node, now, g, "held for its gang")
|
|
@@ -187,7 +203,7 @@ class Hub:
|
|
|
187
203
|
continue # the node holding its cache is free: wait for it
|
|
188
204
|
g = self.gangs.get(t["gang"]) if t["gang"] else None
|
|
189
205
|
if g is not None:
|
|
190
|
-
missing = sum(1 for x in g["tasks"] if self.tasks[x]["state"] == "queued")
|
|
206
|
+
missing = sum(1 for x in g["tasks"] if x in self.tasks and self.tasks[x]["state"] == "queued")
|
|
191
207
|
if len(self._gang_nodes(g, t["needs"], now, node)) + 1 < missing:
|
|
192
208
|
continue # not enough idle nodes for the whole gang yet
|
|
193
209
|
tn = t["tenant"]
|
|
@@ -225,13 +241,21 @@ class Hub:
|
|
|
225
241
|
t.update(state="done" if ok else "failed", finished=self.clock(), result=value, error=error, wall_s=wall_s)
|
|
226
242
|
self.usage[t["tenant"]] = self.usage.get(t["tenant"], 0.0) + (wall_s if wall_s is not None else self.clock() - t.get("started", self.clock()))
|
|
227
243
|
if ok and t["needs"].get("affinity"):
|
|
244
|
+
self.affinity.pop(t["needs"]["affinity"], None)
|
|
228
245
|
self.affinity[t["needs"]["affinity"]] = node
|
|
246
|
+
while len(self.affinity) > self.max_affinity:
|
|
247
|
+
self.affinity.pop(next(iter(self.affinity)))
|
|
248
|
+
self._finished.append(task_id)
|
|
249
|
+
while len(self._finished) > self.max_finished: # forget the oldest finished tasks (and gangs with no task left)
|
|
250
|
+
self.tasks.pop(self._finished.popleft(), None)
|
|
251
|
+
if len(self.gangs) > 64:
|
|
252
|
+
self.gangs = {k: g for k, g in self.gangs.items() if any(x in self.tasks for x in g["tasks"])}
|
|
229
253
|
|
|
230
254
|
def task(self, task_id: int) -> dict:
|
|
231
255
|
with self._lock:
|
|
232
256
|
t = self.tasks.get(task_id)
|
|
233
257
|
if t is None:
|
|
234
|
-
raise KeyError(f"unknown task {task_id}")
|
|
258
|
+
raise KeyError(f"unknown task {task_id} (never existed, or finished long ago and was forgotten: the hub keeps the last {self.max_finished} finished tasks)")
|
|
235
259
|
return {k: v for k, v in t.items()}
|
|
236
260
|
|
|
237
261
|
|
|
@@ -240,23 +264,35 @@ class Hub:
|
|
|
240
264
|
"""Durable state: tasks, queue order, tenant usage and weights, gangs, cache owners. Node
|
|
241
265
|
measurements are not saved: agents rebuild them within one report interval."""
|
|
242
266
|
with self._lock:
|
|
243
|
-
return {"version": 1, "next_id": next(self._ids), "tasks": list(self.tasks.values()), "queue": list(self.queue),
|
|
267
|
+
return {"version": 1, "epoch": self.epoch, "next_id": next(self._ids), "tasks": list(self.tasks.values()), "queue": list(self.queue),
|
|
244
268
|
"usage": self.usage, "weights": self.weights, "affinity": self.affinity,
|
|
245
269
|
"gangs": [{**g, "reserved": {}} for g in self.gangs.values()]}
|
|
246
270
|
|
|
247
|
-
def
|
|
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."""
|
|
271
|
+
def last_id(self) -> int:
|
|
250
272
|
with self._lock:
|
|
251
|
-
self.tasks =
|
|
252
|
-
|
|
253
|
-
|
|
273
|
+
return max(self.tasks, default=0)
|
|
274
|
+
|
|
275
|
+
def requeue_running(self) -> int:
|
|
276
|
+
"""Put running tasks back in the queue (at-least-once: the allow-listed workloads are pure
|
|
277
|
+
functions); if the agent still finishes one, its result is accepted."""
|
|
278
|
+
with self._lock:
|
|
279
|
+
n = 0
|
|
254
280
|
for t in self.tasks.values():
|
|
255
281
|
if t["state"] == "running":
|
|
256
282
|
t["state"] = "queued"
|
|
257
283
|
t["requeued_after_restart"] = True
|
|
258
284
|
self.queue.append(t["id"])
|
|
259
|
-
|
|
285
|
+
n += 1
|
|
286
|
+
return n
|
|
287
|
+
|
|
288
|
+
def restore(self, snap: dict, requeue: bool = True) -> dict:
|
|
289
|
+
"""Load a snapshot (requeue=False for a standby that only follows the active hub)."""
|
|
290
|
+
with self._lock:
|
|
291
|
+
self.tasks = {int(t["id"]): t for t in snap["tasks"]}
|
|
292
|
+
self.queue = deque(int(i) for i in snap["queue"])
|
|
293
|
+
self.epoch = max(self.epoch, int(snap.get("epoch", 1)))
|
|
294
|
+
self._finished = deque(t["id"] for t in sorted(self.tasks.values(), key=lambda t: t["id"]) if t["state"] in ("done", "failed"))
|
|
295
|
+
requeued = self.requeue_running() if requeue else 0
|
|
260
296
|
self.usage, self.weights, self.affinity = dict(snap["usage"]), dict(snap["weights"]), dict(snap["affinity"])
|
|
261
297
|
self.gangs = {int(g["id"]): {**g, "started": [], "reserved": {}} for g in snap["gangs"]}
|
|
262
298
|
self._ids = itertools.count(int(snap["next_id"]))
|
|
@@ -284,11 +320,13 @@ class Hub:
|
|
|
284
320
|
def loop():
|
|
285
321
|
while not stop.wait(every_s):
|
|
286
322
|
try:
|
|
287
|
-
self.
|
|
323
|
+
if self.role == "active": # a standby holds a copy, never the master file
|
|
324
|
+
self.save(path)
|
|
288
325
|
except OSError:
|
|
289
326
|
pass
|
|
290
327
|
try:
|
|
291
|
-
self.
|
|
328
|
+
if self.role == "active":
|
|
329
|
+
self.save(path)
|
|
292
330
|
except OSError:
|
|
293
331
|
pass
|
|
294
332
|
threading.Thread(target=loop, daemon=True).start()
|
|
@@ -393,6 +431,20 @@ def make_handler(hub: Hub):
|
|
|
393
431
|
op = h.get("op")
|
|
394
432
|
if op == "ping":
|
|
395
433
|
return {"pong": True}, b""
|
|
434
|
+
if op == "role":
|
|
435
|
+
return {"role": hub.role, "epoch": hub.epoch, "name": hub.name, "lease": hub.ha.lease_ok() if hub.ha else True}, b""
|
|
436
|
+
if op in ("vote", "beat"):
|
|
437
|
+
require("fleet:replicate")
|
|
438
|
+
if not hasattr(hub.ha, "on_" + op):
|
|
439
|
+
raise RuntimeError("this hub is not part of a quorum")
|
|
440
|
+
return getattr(hub.ha, "on_" + op)(h), b""
|
|
441
|
+
if hub.role != "active":
|
|
442
|
+
raise RuntimeError(f"standby: {hub.name} is not the active hub")
|
|
443
|
+
if hub.ha is not None and not hub.ha.lease_ok():
|
|
444
|
+
raise RuntimeError("no quorum: this hub lost contact with a majority and refuses requests")
|
|
445
|
+
if op == "snapshot":
|
|
446
|
+
require("fleet:replicate")
|
|
447
|
+
return {"epoch": hub.epoch}, json.dumps(hub.snapshot()).encode()
|
|
396
448
|
if op == "report":
|
|
397
449
|
require("fleet:report")
|
|
398
450
|
hub.report(Hub._who(h), h["metrics"], h.get("inventory"), h.get("usd_per_hour"), h.get("labels"))
|
|
@@ -410,6 +462,9 @@ def make_handler(hub: Hub):
|
|
|
410
462
|
if op == "submit_gang":
|
|
411
463
|
require("fleet:submit")
|
|
412
464
|
return hub.submit_gang(h["workload"], h["params_list"], h.get("needs"), h.get("priority", 10), _tenant(h)), b""
|
|
465
|
+
if op == "queue":
|
|
466
|
+
require("fleet:read")
|
|
467
|
+
return hub.queue_view(int(h.get("recent", 12))), b""
|
|
413
468
|
if op == "tenants":
|
|
414
469
|
require("fleet:read")
|
|
415
470
|
return {"tenants": hub.tenants()}, b""
|
|
@@ -442,14 +497,30 @@ def main():
|
|
|
442
497
|
ap.add_argument("--allow-remote", action="store_true")
|
|
443
498
|
ap.add_argument("--decision-log", default=str(Path.home() / ".spatial" / "fleet-decisions.jsonl"))
|
|
444
499
|
ap.add_argument("--state-file", help="save tasks, queue, tenant usage here every 5 s and reload it at start")
|
|
500
|
+
ap.add_argument("--peer", action="append", default=[], help="host:port of another hub (repeatable): active/standby with automatic promotion")
|
|
501
|
+
ap.add_argument("--peer-token-file", help="token this hub presents to its peers (scope fleet:replicate); default: --token-file")
|
|
502
|
+
ap.add_argument("--max-finished", type=int, default=5000, help="finished tasks kept in memory (older ones are forgotten)")
|
|
503
|
+
ap.add_argument("--name", default="hub", help="this hub's name (HA tie-break: the smaller name stays active)")
|
|
504
|
+
ap.add_argument("--fail-after", type=float, default=6.0, help="seconds without an active peer before a standby promotes itself")
|
|
445
505
|
a = ap.parse_args()
|
|
446
506
|
if bool(a.token_file) == bool(a.master_key_file):
|
|
447
507
|
raise SystemExit("give exactly one of --token-file or --master-key-file")
|
|
448
508
|
srv, hub = serve_hub(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
|
|
449
509
|
authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None,
|
|
450
510
|
ledger=Ledger(a.decision_log))
|
|
511
|
+
hub.max_finished = a.max_finished
|
|
451
512
|
if a.state_file:
|
|
452
513
|
print("restored", hub.load(a.state_file), flush=True)
|
|
514
|
+
if a.peer:
|
|
515
|
+
from .ha import HAController
|
|
516
|
+
ptf = a.peer_token_file or a.token_file
|
|
517
|
+
if ptf is None:
|
|
518
|
+
raise SystemExit("--peer needs --peer-token-file (a scoped token with fleet:replicate) or --token-file")
|
|
519
|
+
from .ha import QuorumController
|
|
520
|
+
cls = QuorumController if len(a.peer) >= 2 else HAController # 3 or more hubs: majority election
|
|
521
|
+
kw = {"meta_path": a.state_file + ".term"} if (cls is QuorumController and a.state_file) else {}
|
|
522
|
+
cls(hub, Path(ptf).read_bytes(), a.peer, a.name, fail_after_s=a.fail_after, **kw).start()
|
|
523
|
+
if a.state_file:
|
|
453
524
|
hub.autosave(a.state_file)
|
|
454
525
|
print(f"PORT {srv.port}", flush=True)
|
|
455
526
|
srv.serve_forever()
|
spatial/kernel/dsl.py
CHANGED
|
@@ -99,7 +99,15 @@ class Kernel:
|
|
|
99
99
|
self._err(e, f"unknown function '{f}'")
|
|
100
100
|
self._err(e, f"unsupported expression ({type(e).__name__})")
|
|
101
101
|
|
|
102
|
+
RESERVED = {"out", "partial", "gid", "lid", "tgid", "ngroups", "blockIdx", "blockDim", "threadIdx", "gridDim", "total"}
|
|
103
|
+
|
|
104
|
+
def _check_names(self, names) -> None:
|
|
105
|
+
for nm in names:
|
|
106
|
+
if nm in self.RESERVED or nm.startswith("_sp_") or nm.startswith("__"):
|
|
107
|
+
raise KernelError(f"{self.name}: '{nm}' is reserved by the generated code; rename it")
|
|
108
|
+
|
|
102
109
|
def analyse(self) -> None:
|
|
110
|
+
self._check_names([p for p, _ in self.params])
|
|
103
111
|
env = {"i": "int", "j": "int", "n": "int", **dict(self.params)}
|
|
104
112
|
for _ in range(2): # second pass: a variable later assigned a float becomes float
|
|
105
113
|
self._walk(self.body, env)
|
|
@@ -112,6 +120,7 @@ class Kernel:
|
|
|
112
120
|
if len(s.targets) != 1 or not isinstance(s.targets[0], ast.Name):
|
|
113
121
|
self._err(s, "assign to a single name")
|
|
114
122
|
name, t = s.targets[0].id, self.type_of(s.value, env)
|
|
123
|
+
self._check_names([name])
|
|
115
124
|
if name in ("i", "j", "n") or name in dict(self.params):
|
|
116
125
|
self._err(s, f"'{name}' is an input and cannot be assigned")
|
|
117
126
|
env[name] = "float" if "float" in (env.get(name), t) else t
|
|
@@ -224,30 +233,51 @@ class Kernel:
|
|
|
224
233
|
def _env(self):
|
|
225
234
|
return {"i": "int", "j": "int", "n": "int", **dict(self.params), **self.types}
|
|
226
235
|
|
|
227
|
-
def to_c(self, cuda: bool) -> str:
|
|
236
|
+
def to_c(self, cuda: bool, reduce: bool = False, hip: bool = False) -> str:
|
|
228
237
|
env = self._env()
|
|
229
238
|
decls = [f" {t} {v};" for v, t in self.types.items()]
|
|
230
|
-
body = "\n".join(self._stmts_c(self.body, env, cuda, " "))
|
|
239
|
+
body = "\n".join(self._stmts_c(self.body, env, cuda, " " if reduce else " "))
|
|
231
240
|
ret = f"(unsigned int)({self._expr_c(self.ret, env, cuda)})"
|
|
232
241
|
if cuda:
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
242
|
+
name = self.name + ("_sum" if reduce else "")
|
|
243
|
+
first = "unsigned long long *partial" if reduce else "unsigned int *out"
|
|
244
|
+
sig = ", ".join([first, "int n"] + [f"{t} {p}" for p, t in self.params])
|
|
245
|
+
head = f'extern "C" __global__ void {name}({sig}) {{\n int j = blockIdx.x * blockDim.x + threadIdx.x;\n int i = blockIdx.y * blockDim.y + threadIdx.y;'
|
|
246
|
+
pre = "#include <hip/hip_runtime.h>\n" if hip else ""
|
|
236
247
|
else:
|
|
237
|
-
|
|
248
|
+
name = self.name + ("_sum" if reduce else "")
|
|
249
|
+
args = ["device ulong *partial [[buffer(0)]]" if reduce else "device uint *out [[buffer(0)]]", "constant int &n [[buffer(1)]]"]
|
|
238
250
|
args += [f"constant {t} &{p} [[buffer({k + 2})]]" for k, (p, t) in enumerate(self.params)]
|
|
239
251
|
args.append("uint2 gid [[thread_position_in_grid]]")
|
|
240
|
-
|
|
252
|
+
if reduce:
|
|
253
|
+
args += ["uint lid [[thread_index_in_threadgroup]]", "uint2 tgid [[threadgroup_position_in_grid]]", "uint2 ngroups [[threadgroups_per_grid]]"]
|
|
254
|
+
head = f"kernel void {name}({', '.join(args)}) {{\n int j = (int)gid.x;\n int i = (int)gid.y;"
|
|
241
255
|
pre = "#include <metal_stdlib>\nusing namespace metal;\n"
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
return
|
|
247
|
-
|
|
248
|
-
|
|
256
|
+
d = "\n".join(decls) + ("\n" if decls else "")
|
|
257
|
+
if not reduce:
|
|
258
|
+
return (f"{pre}{head}\n if (i >= n || j >= n) return;\n" + d + (body + "\n" if body else "") + f" out[i * n + j] = {ret};\n}}\n")
|
|
259
|
+
# Reduction: 16 x 16 threads per block share a 256-entry array and add pairwise; every thread must reach the
|
|
260
|
+
# barriers, so there is no early return. One partial sum per block; the host adds the partials.
|
|
261
|
+
ull = "unsigned long long" if cuda else "ulong"
|
|
262
|
+
shared = f" __shared__ {ull} _sp_sh[256];" if cuda else f" threadgroup {ull} _sp_sh[256];"
|
|
263
|
+
t = "int _sp_t = threadIdx.y * blockDim.x + threadIdx.x;" if cuda else "int _sp_t = (int)lid;"
|
|
264
|
+
bar = "__syncthreads();" if cuda else "threadgroup_barrier(mem_flags::mem_threadgroup);"
|
|
265
|
+
gid = "blockIdx.y * gridDim.x + blockIdx.x" if cuda else "tgid.y * ngroups.x + tgid.x"
|
|
266
|
+
return (f"{pre}{head}\n{shared}\n {t}\n" + d + f" {ull} _sp_v = 0;\n if (i < n && j < n) {{\n" + (body + "\n" if body else "")
|
|
267
|
+
+ f" _sp_v = ({ull}){ret};\n }}\n _sp_sh[_sp_t] = _sp_v;\n {bar}\n for (int _sp_s = 128; _sp_s > 0; _sp_s >>= 1) {{\n"
|
|
268
|
+
f" if (_sp_t < _sp_s) _sp_sh[_sp_t] += _sp_sh[_sp_t + _sp_s];\n {bar}\n }}\n if (_sp_t == 0) partial[{gid}] = _sp_sh[0];\n}}\n")
|
|
269
|
+
|
|
270
|
+
def to_metal(self, reduce: bool = False) -> str:
|
|
271
|
+
return self.to_c(cuda=False, reduce=reduce)
|
|
272
|
+
|
|
273
|
+
def to_cuda_c(self, reduce: bool = False) -> str:
|
|
249
274
|
"""CUDA C source for NVRTC/nvcc. Generated, never compiled or run: no NVIDIA toolchain here."""
|
|
250
|
-
return self.to_c(cuda=True)
|
|
275
|
+
return self.to_c(cuda=True, reduce=reduce)
|
|
276
|
+
|
|
277
|
+
def to_hip(self, reduce: bool = False) -> str:
|
|
278
|
+
"""HIP source for AMD GPUs (hipcc). Same syntax tree, the CUDA-style kernel dialect that HIP accepts.
|
|
279
|
+
Generated only: no AMD GPU, no ROCm here, so it has never been compiled or run."""
|
|
280
|
+
return self.to_c(cuda=True, reduce=reduce, hip=True)
|
|
251
281
|
|
|
252
282
|
def _expr_py(self, e, env) -> str:
|
|
253
283
|
t = lambda x: self.type_of(x, env)
|
|
@@ -314,18 +344,36 @@ class Kernel:
|
|
|
314
344
|
out += self._stmts_py(s.body, env, ind + " ") or [ind + " pass"]
|
|
315
345
|
return out
|
|
316
346
|
|
|
317
|
-
def to_python(self) -> str:
|
|
347
|
+
def to_python(self, reduce: bool = False) -> str:
|
|
318
348
|
"""Numba-compilable source with explicit float32 arithmetic (matches the GPU back ends)."""
|
|
319
349
|
env = self._env()
|
|
320
350
|
inits = [f" {v} = np.float32(0.0)" if t == "float" else f" {v} = 0" for v, t in self.types.items()]
|
|
321
|
-
sig = ", ".join(["out"
|
|
351
|
+
sig = ", ".join(([] if reduce else ["out"]) + ["n"] + [p for p, _ in self.params])
|
|
322
352
|
body = "\n".join(self._stmts_py(self.body, env, " "))
|
|
323
353
|
ret = self._expr_py(self.ret, env)
|
|
324
354
|
ret = f"_w32({ret}) & 0xFFFFFFFF" if self.type_of(self.ret, env) == "int" else ret
|
|
355
|
+
if reduce:
|
|
356
|
+
return ("def _kernel(" + sig + "):\n total = np.uint64(0)\n for i in prange(n):\n for j in range(n):\n" + "\n".join(inits)
|
|
357
|
+
+ ("\n" if inits else "") + (body + "\n" if body else "") + f" total += np.uint64({ret})\n return total\n")
|
|
325
358
|
return ("def _kernel(" + sig + "):\n for i in prange(n):\n for j in range(n):\n" + "\n".join(inits)
|
|
326
359
|
+ ("\n" if inits else "") + (body + "\n" if body else "") + f" out[i, j] = {ret}\n")
|
|
327
360
|
|
|
328
361
|
# ------------------------------------------------------------------ execution
|
|
362
|
+
def reduce(self, device: str, n: int, **params) -> int:
|
|
363
|
+
"""Sum of the kernel's output over the whole n x n grid, as an int (uint64 accumulation). On Metal this
|
|
364
|
+
uses threadgroup shared memory and barriers; on the CPU a Numba parallel reduction."""
|
|
365
|
+
for p, t in self.params:
|
|
366
|
+
if p not in params:
|
|
367
|
+
raise KernelError(f"{self.name}: missing parameter '{p}'")
|
|
368
|
+
if device == "cpu":
|
|
369
|
+
return self._run_cpu(n, params, reduce=True)
|
|
370
|
+
if device == "metal":
|
|
371
|
+
from ..fabric import metal
|
|
372
|
+
return metal.run_kernel(self, n, params, reduce=True)
|
|
373
|
+
if device in ("cuda", "hip"):
|
|
374
|
+
raise KernelError(f"the {device} back end only generates source; it has never been run on that hardware")
|
|
375
|
+
raise KernelError(f"unknown device '{device}'")
|
|
376
|
+
|
|
329
377
|
def run(self, device: str, n: int, **params):
|
|
330
378
|
"""Run on `device` ("cpu" or "metal"); returns an (n, n) uint32 array."""
|
|
331
379
|
import numpy as np
|
|
@@ -341,13 +389,16 @@ class Kernel:
|
|
|
341
389
|
raise KernelError("the CUDA back end only generates source (to_cuda_c); it has never been run on NVIDIA hardware")
|
|
342
390
|
raise KernelError(f"unknown device '{device}'")
|
|
343
391
|
|
|
344
|
-
def _run_cpu(self, n, params):
|
|
392
|
+
def _run_cpu(self, n, params, reduce: bool = False):
|
|
345
393
|
import numpy as np
|
|
346
394
|
from numba import njit, prange
|
|
347
|
-
if
|
|
395
|
+
attr = "_cpu_sum" if reduce else "_cpu"
|
|
396
|
+
if not hasattr(self, attr):
|
|
348
397
|
ns = {"np": np, "prange": prange, "_cint": njit(_cint), "_cmod": njit(_cmod), "_w32": njit(_w32)}
|
|
349
|
-
exec(compile(self.to_python(), f"<kernel {self.name}>", "exec"), ns) # generated from OUR restricted AST only
|
|
350
|
-
self
|
|
398
|
+
exec(compile(self.to_python(reduce=reduce), f"<kernel {self.name}>", "exec"), ns) # generated from OUR restricted AST only
|
|
399
|
+
setattr(self, attr, njit(parallel=True)(ns["_kernel"]))
|
|
400
|
+
if reduce:
|
|
401
|
+
return int(getattr(self, attr)(n, *[np.float32(params[p]) if t == "float" else int(params[p]) for p, t in self.params]))
|
|
351
402
|
out = np.zeros((n, n), dtype=np.uint32)
|
|
352
403
|
args = [np.float32(params[p]) if t == "float" else int(params[p]) for p, t in self.params]
|
|
353
404
|
self._cpu(out, n, *args)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: spatial-computing
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.14.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.
|
|
40
|
+
> **Status: v0.14.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=
|
|
2
|
-
spatial/cli.py,sha256=
|
|
1
|
+
spatial/__init__.py,sha256=xDBiU1LY2BazHx18mskb2H0VbpAbKGWKjjuKcTO8JNo,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,16 +16,19 @@ 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=
|
|
19
|
+
spatial/core/registry.py,sha256=NIWV4MpmdP16rRhxlUBGUOajyKbO7F6gvhN40gKas9E,5251
|
|
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
|
|
23
|
-
spatial/fabric/metal.py,sha256=
|
|
23
|
+
spatial/fabric/metal.py,sha256=HkofkuNlHFbwcdhhsGwd1XDAQ7CndxaOu4462uU6nxU,3632
|
|
24
24
|
spatial/fabric/metal_mandel.swift,sha256=-uL49wwx5OGimt727HqGL9sSDobF8N0GJHQye59upyw,3132
|
|
25
|
-
spatial/fabric/metal_run.swift,sha256=
|
|
25
|
+
spatial/fabric/metal_run.swift,sha256=tyQHMqK9oIEnwOvo7aEnkubqcr3FIyl9tRfblGUq4G4,3179
|
|
26
26
|
spatial/fleet/__init__.py,sha256=LUpn9X_XTGPy8KfZhnYdGVQTIY9IIVfzMeNnw8HcCbs,957
|
|
27
|
-
spatial/fleet/agent.py,sha256=
|
|
28
|
-
spatial/fleet/
|
|
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=q3GqnJVQ7ImmAC0W0pw_9CF6HgoJEzAYbVx44gtaO6Y,14713
|
|
31
|
+
spatial/fleet/hub.py,sha256=SHdidAi4VdXYnZopOehP_JbfhA3zKcdyLN8kknaX8uc,29995
|
|
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
|
|
@@ -37,7 +40,7 @@ spatial/interconnect/comm.py,sha256=a0VuXjeqEQBom6Cy5THLftOWi_OrPb2mhg69I9cgxKg,
|
|
|
37
40
|
spatial/interconnect/model.py,sha256=084YSRera2fpWWifkeY7FKnlmZVe3ubHcKQvDfCAy0o,3636
|
|
38
41
|
spatial/interconnect/tasks.py,sha256=oUl1sY7F8mJtZ3rzqkfsrJXvyvG2xgDunspif8vnqwI,3079
|
|
39
42
|
spatial/kernel/__init__.py,sha256=4nAgSZRBAoRUFlTx2vp0CK8QG8AD2SyySCRbcGsKiwI,199
|
|
40
|
-
spatial/kernel/dsl.py,sha256=
|
|
43
|
+
spatial/kernel/dsl.py,sha256=O-r9JprJNl6JDkTq89XrHAJFUVbdHZ8sGhl_RFX3T-o,24465
|
|
41
44
|
spatial/kernel/library.py,sha256=FcaFMh_-5AUczAxsGpPLJGyw_KnAm8UBiI1oP28aKiE,1262
|
|
42
45
|
spatial/memory/__init__.py,sha256=Jy5xVfm9mmLaE6qaJ-UhIfqrOPJJFA9kDc-pvexJo0k,335
|
|
43
46
|
spatial/memory/fararray.py,sha256=USpFPorGveZ2LVc_2JkePD2dHJKBl9gyfxb5lbwp2HI,1689
|
|
@@ -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.
|
|
76
|
-
spatial_computing-0.
|
|
77
|
-
spatial_computing-0.
|
|
78
|
-
spatial_computing-0.
|
|
79
|
-
spatial_computing-0.
|
|
80
|
-
spatial_computing-0.
|
|
78
|
+
spatial_computing-0.14.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
79
|
+
spatial_computing-0.14.0.dist-info/METADATA,sha256=nXR0RDh8CVKWkjtIHf-Pelc-5wj4zJdZx11PQdiaqM4,6697
|
|
80
|
+
spatial_computing-0.14.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
81
|
+
spatial_computing-0.14.0.dist-info/entry_points.txt,sha256=UIFCHJL01u7PIPej7EUHRI7rWEY8uBhufZ-_ulXUPRk,79
|
|
82
|
+
spatial_computing-0.14.0.dist-info/top_level.txt,sha256=ZHke8hWgy4qIqEGq7omus3O-T7AhmPoc-cqr7JdGGxQ,8
|
|
83
|
+
spatial_computing-0.14.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|