spatial-computing 0.7.0__tar.gz → 0.9.0__tar.gz
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_computing-0.7.0/spatial_computing.egg-info → spatial_computing-0.9.0}/PKG-INFO +3 -2
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/README.md +2 -1
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/pyproject.toml +1 -1
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/__init__.py +1 -1
- spatial_computing-0.9.0/spatial/cli.py +236 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/compute/worker.py +12 -4
- spatial_computing-0.9.0/spatial/core/auth.py +170 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/core/ledger.py +9 -4
- spatial_computing-0.9.0/spatial/core/protocol.py +218 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/core/registry.py +3 -0
- spatial_computing-0.9.0/spatial/fleet/__init__.py +18 -0
- spatial_computing-0.9.0/spatial/fleet/agent.py +137 -0
- spatial_computing-0.9.0/spatial/fleet/hub.py +279 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/memory/pageserver.py +9 -2
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/compiler.py +65 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/runtime/runner.py +12 -4
- {spatial_computing-0.7.0 → spatial_computing-0.9.0/spatial_computing.egg-info}/PKG-INFO +3 -2
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/SOURCES.txt +7 -0
- spatial_computing-0.9.0/tests/test_auth.py +142 -0
- spatial_computing-0.9.0/tests/test_fleet.py +163 -0
- spatial_computing-0.9.0/tests/test_optimizer.py +63 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_v02.py +15 -1
- spatial_computing-0.7.0/spatial/cli.py +0 -135
- spatial_computing-0.7.0/spatial/core/protocol.py +0 -167
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/LICENSE +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/setup.cfg +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/ai/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/ai/kvcache.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/compute/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/compute/cost.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/compute/detect.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/compute/monitor.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/compute/scheduler.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/compute/taskqueue.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/compute/workloads.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/core/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/core/energy.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/core/model.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/holographic/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/holographic/cgh.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/holographic/model.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/intelligence/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/intelligence/predictor.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/memory/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/memory/fararray.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/memory/secure.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/memory/shared.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/memory/tiered.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/__main__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/backends/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/codegen.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/ir.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/lexer.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/parser.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/qir.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/runtime.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/q/sim.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/runtime/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/runtime/envs.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/runtime/inspect.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/runtime/microvm.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/runtime/planner.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/runtime/toolchain.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/scientific/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/scientific/jobs.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/simulation/__init__.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/simulation/heat.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial/simulation/nbody.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/entry_points.txt +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/requires.txt +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/top_level.txt +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_compute.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_core.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_domains.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_engines.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_memory.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_q.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_runtime.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_v03.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_v05.py +0 -0
- {spatial_computing-0.7.0 → spatial_computing-0.9.0}/tests/test_v07.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: spatial-computing
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.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
|
Spatial Computing chooses where and how a workload should run from measurements, and claims a gain 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.9.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
|
|
|
@@ -93,6 +93,7 @@ st.put(0, b"..." * 1000); st.get(0); print(st.stats())
|
|
|
93
93
|
|
|
94
94
|
| Engine | Level | Evidence |
|
|
95
95
|
|---|---|---|
|
|
96
|
+
| Fleet (agent on every machine + hub: measure, place, recommend, audit) | operational prototype | `tests/test_fleet.py`, `benchmarks/bench_fleet.py` |
|
|
96
97
|
| Compute Engine (detect, monitor, compare strategies, offload, cost) | operational prototype | `tests/test_compute.py`, `benchmarks/bench_cpu.py` |
|
|
97
98
|
| Tiered memory (hot / compressed / far) | operational prototype | `tests/test_memory.py`, `benchmarks/bench_memory.py` |
|
|
98
99
|
| Runtime Engine (inspect binaries, route, micro-VM, WASI) | operational prototype | `tests/test_runtime.py`, `benchmarks/bench_runtime.py` |
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
Spatial Computing chooses where and how a workload should run from measurements, and claims a gain 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.
|
|
6
6
|
|
|
7
|
-
> **Status: v0.
|
|
7
|
+
> **Status: v0.9.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).
|
|
8
8
|
|
|
9
9
|
[Français](README.fr.md)
|
|
10
10
|
|
|
@@ -60,6 +60,7 @@ st.put(0, b"..." * 1000); st.get(0); print(st.stats())
|
|
|
60
60
|
|
|
61
61
|
| Engine | Level | Evidence |
|
|
62
62
|
|---|---|---|
|
|
63
|
+
| Fleet (agent on every machine + hub: measure, place, recommend, audit) | operational prototype | `tests/test_fleet.py`, `benchmarks/bench_fleet.py` |
|
|
63
64
|
| Compute Engine (detect, monitor, compare strategies, offload, cost) | operational prototype | `tests/test_compute.py`, `benchmarks/bench_cpu.py` |
|
|
64
65
|
| Tiered memory (hot / compressed / far) | operational prototype | `tests/test_memory.py`, `benchmarks/bench_memory.py` |
|
|
65
66
|
| Runtime Engine (inspect binaries, route, micro-VM, WASI) | operational prototype | `tests/test_runtime.py`, `benchmarks/bench_runtime.py` |
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "spatial-computing"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.9.0"
|
|
8
8
|
description = "Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""`spatial` command line: one entry point for the three operational engines."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
11
|
+
BENCHES = {"cpu": "bench_cpu", "memory": "bench_memory", "gpu": "bench_gpu",
|
|
12
|
+
"runtime": "bench_runtime", "q": "bench_q"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def cmd_audit(a):
|
|
16
|
+
from .compute import detect_node, limitations, snapshot
|
|
17
|
+
from .compute.monitor import underused
|
|
18
|
+
node, snap = detect_node(), snapshot()
|
|
19
|
+
if a.json:
|
|
20
|
+
print(json.dumps({"node": node.to_dict(), "snapshot": snap, "limitations": limitations(node)},
|
|
21
|
+
indent=1, default=str))
|
|
22
|
+
return 0
|
|
23
|
+
print(f"{node.attrs.get('model')} | {node.attrs.get('cpu_brand')} | {node.os} | {node.arch}")
|
|
24
|
+
for r in node.resources:
|
|
25
|
+
cap = f"{r.capacity / 2**30:.1f} GiB" if r.unit == "bytes" else f"{r.capacity:g} {r.unit}"
|
|
26
|
+
if "utilization_percent" in r.attrs:
|
|
27
|
+
cap += f" ({r.attrs['utilization_percent']:.0f}% busy)"
|
|
28
|
+
print(f" {r.kind.value:<11} {r.name:<42} {cap}")
|
|
29
|
+
print(f"memory pressure: {snap.get('memory_pressure')} | compressor ratio: {snap.get('compressor_ratio')} "
|
|
30
|
+
f"| swap used: {snap['swap_used'] / 2**30:.2f} GiB")
|
|
31
|
+
for u in underused(snap):
|
|
32
|
+
print(" idle:", u)
|
|
33
|
+
print("limitations:")
|
|
34
|
+
for x in limitations(node):
|
|
35
|
+
print(" -", x)
|
|
36
|
+
return 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cmd_status(a):
|
|
40
|
+
from .core.registry import ENGINES
|
|
41
|
+
for e in ENGINES:
|
|
42
|
+
print(f"{e.name:<42} {e.status.value:<24} not done: {e.not_done}")
|
|
43
|
+
return 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def cmd_plan(a):
|
|
47
|
+
from .runtime import inspect, plan
|
|
48
|
+
art = inspect(a.file)
|
|
49
|
+
print(f"{a.file}: {art.format} / {art.os} / {','.join(art.arch)} {art.detail}")
|
|
50
|
+
for r in plan(art):
|
|
51
|
+
print(f" [{'x' if r.feasible else ' '}] {r.name:<16} {r.reason}")
|
|
52
|
+
return 0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def cmd_run(a):
|
|
56
|
+
from .runtime import execute
|
|
57
|
+
e = execute(a.file, a.args, route=a.route, timeout_s=a.timeout)
|
|
58
|
+
if e.stdout:
|
|
59
|
+
print(e.stdout)
|
|
60
|
+
print(f"[spatial] route={e.route} ok={e.ok} wall={e.wall_s:.2f}s "
|
|
61
|
+
+ (f"reason: {e.extra.get('not_runnable')}" if not e.ok and e.extra.get("not_runnable") else ""),
|
|
62
|
+
file=sys.stderr)
|
|
63
|
+
return 0 if e.ok else 1
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def cmd_q(a):
|
|
67
|
+
from .q import runtime
|
|
68
|
+
sys.argv = ["spatialq", *a.rest]
|
|
69
|
+
runtime.main()
|
|
70
|
+
return 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def cmd_bench(a):
|
|
74
|
+
names = list(BENCHES) if a.name == "all" else [a.name]
|
|
75
|
+
bdir = ROOT / "benchmarks"
|
|
76
|
+
if not bdir.exists():
|
|
77
|
+
print("benchmarks/ not found: run from a source checkout", file=sys.stderr)
|
|
78
|
+
return 2
|
|
79
|
+
rc = 0
|
|
80
|
+
for n in names:
|
|
81
|
+
rc |= subprocess.run([sys.executable, f"{BENCHES[n]}.py"], cwd=bdir).returncode
|
|
82
|
+
rc |= subprocess.run([sys.executable, "report.py"], cwd=bdir).returncode
|
|
83
|
+
return rc
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _read_token(path: str) -> bytes:
|
|
87
|
+
raw = Path(path).read_bytes()
|
|
88
|
+
return raw.strip() if raw.startswith(b"spc1.") else raw # scoped tokens are text, shared secrets are raw bytes
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
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)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_agent(a):
|
|
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,
|
|
101
|
+
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"))
|
|
103
|
+
ag.run_forever()
|
|
104
|
+
return 0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def cmd_fleet(a):
|
|
108
|
+
cli = _hub_client(a)
|
|
109
|
+
if a.action == "status":
|
|
110
|
+
rh, _ = cli.call({"op": "nodes", "window_s": a.window})
|
|
111
|
+
print(f"{'node':<22}{'up':<4}{'cores':>6}{'cpu%':>7}{'ram free%':>10}{'gpus':>5}{'gpu%':>6}{'$/h':>7} samples")
|
|
112
|
+
f = lambda v, n=0: "-" if v is None else f"{v:.{n}f}"
|
|
113
|
+
for r in rh["nodes"]:
|
|
114
|
+
print(f"{r['node']:<22}{'yes' if r['alive'] else 'NO':<4}{f(r['cores']):>6}{f(r['cpu_avg']):>7}{f(r['ram_avail_pct']):>10}"
|
|
115
|
+
f"{r['gpu_count']:>5}{f(r['gpu_util_avg']):>6}{f(r['usd_per_hour'], 2):>7} {r['samples']}")
|
|
116
|
+
u = rh["utilization"]
|
|
117
|
+
print(f"fleet: {u['nodes']} node(s), {u['cores']} cores, CPU utilization "
|
|
118
|
+
f"{'-' if u['cpu_utilization_pct'] is None else format(u['cpu_utilization_pct'], '.1f') + '%'} (last {a.window:g} s)")
|
|
119
|
+
elif a.action == "advise":
|
|
120
|
+
rh, _ = cli.call({"op": "advise", "window_s": a.window})
|
|
121
|
+
if not rh["recommendations"]:
|
|
122
|
+
print("no recommendation: nothing in the measurements justifies a change")
|
|
123
|
+
for r in rh["recommendations"]:
|
|
124
|
+
extra = f" [estimated saving {r['est_saving_usd_per_hour']:.2f} $/h, {r['est_saving_usd_per_month']:.0f} $/month]" if "est_saving_usd_per_hour" in r else ""
|
|
125
|
+
print(f"[{r['severity']}] {r['kind']}: {r['text']}{extra}")
|
|
126
|
+
print(f" evidence: {r['evidence']}")
|
|
127
|
+
elif a.action == "submit":
|
|
128
|
+
import json as _json
|
|
129
|
+
rh, _ = cli.call({"op": "submit", "workload": a.workload, "params": _json.loads(a.params),
|
|
130
|
+
"needs": _json.loads(a.needs)})
|
|
131
|
+
print(rh["task_id"])
|
|
132
|
+
else:
|
|
133
|
+
rh, _ = cli.call({"op": "task", "task_id": a.task_id})
|
|
134
|
+
t = rh["task"]
|
|
135
|
+
print({k: t.get(k) for k in ("id", "state", "node", "result", "error", "wall_s")})
|
|
136
|
+
cli.close()
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def cmd_token(a):
|
|
141
|
+
from .core import auth
|
|
142
|
+
if a.action == "init":
|
|
143
|
+
auth.init_master_key(a.master_key_file)
|
|
144
|
+
print(f"master key written to {a.master_key_file} (mode 600). Keep it private; it can issue any credential.")
|
|
145
|
+
return 0
|
|
146
|
+
az = auth.authorizer_from_file(a.master_key_file)
|
|
147
|
+
print(az.issue(a.name, [s for s in a.scopes.split(",") if s], ttl_s=a.ttl, max_ops=a.max_ops, max_bytes=a.max_bytes))
|
|
148
|
+
return 0
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def cmd_worker(a):
|
|
152
|
+
mod = {"compute": "spatial.compute.worker", "memory": "spatial.memory.pageserver",
|
|
153
|
+
"runtime": "spatial.runtime.runner", "hub": "spatial.fleet.hub"}[a.kind]
|
|
154
|
+
cmd = [sys.executable, "-m", mod, "--host", a.host, "--port", str(a.port)]
|
|
155
|
+
if a.token_file:
|
|
156
|
+
cmd += ["--token-file", a.token_file]
|
|
157
|
+
if a.master_key_file:
|
|
158
|
+
cmd += ["--master-key-file", a.master_key_file]
|
|
159
|
+
if a.audit_log:
|
|
160
|
+
cmd += ["--audit-log", a.audit_log]
|
|
161
|
+
if a.allow_remote:
|
|
162
|
+
cmd.append("--allow-remote")
|
|
163
|
+
return subprocess.run(cmd).returncode
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def main(argv=None):
|
|
167
|
+
ap = argparse.ArgumentParser(prog="spatial", description="SPATIAL COMPUTING — measure, decide, prove")
|
|
168
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
169
|
+
p = sub.add_parser("audit", help="detect hardware, usage and limits of this machine")
|
|
170
|
+
p.add_argument("--json", action="store_true")
|
|
171
|
+
p.set_defaults(fn=cmd_audit)
|
|
172
|
+
sub.add_parser("status", help="honest status of every engine").set_defaults(fn=cmd_status)
|
|
173
|
+
p = sub.add_parser("plan", help="inspect a binary and list execution routes")
|
|
174
|
+
p.add_argument("file")
|
|
175
|
+
p.set_defaults(fn=cmd_plan)
|
|
176
|
+
p = sub.add_parser("run", help="run a binary through the best feasible route")
|
|
177
|
+
p.add_argument("file")
|
|
178
|
+
p.add_argument("args", nargs="*")
|
|
179
|
+
p.add_argument("--route")
|
|
180
|
+
p.add_argument("--timeout", type=float, default=300)
|
|
181
|
+
p.set_defaults(fn=cmd_run)
|
|
182
|
+
p = sub.add_parser("q", help="SPATIAL Q: run|check|qasm|ir <file.sq>")
|
|
183
|
+
p.add_argument("rest", nargs=argparse.REMAINDER)
|
|
184
|
+
p.set_defaults(fn=cmd_q)
|
|
185
|
+
p = sub.add_parser("bench", help="run benchmarks and regenerate docs/RESULTATS.md")
|
|
186
|
+
p.add_argument("name", choices=[*BENCHES, "all"])
|
|
187
|
+
p.set_defaults(fn=cmd_bench)
|
|
188
|
+
p = sub.add_parser("serve", help="start a compute worker, a page server or a sandboxed binary runner (loopback by default)")
|
|
189
|
+
p.add_argument("kind", choices=["compute", "memory", "runtime", "hub"])
|
|
190
|
+
p.add_argument("--token-file", help="shared secret: every client may do everything")
|
|
191
|
+
p.add_argument("--master-key-file", help="scoped credentials with quotas and an audit log (see `spatial token`)")
|
|
192
|
+
p.add_argument("--audit-log")
|
|
193
|
+
p.add_argument("--host", default="127.0.0.1")
|
|
194
|
+
p.add_argument("--port", type=int, default=0)
|
|
195
|
+
p.add_argument("--allow-remote", action="store_true", help="explicit consent to accept LAN connections")
|
|
196
|
+
p.set_defaults(fn=cmd_worker)
|
|
197
|
+
p = sub.add_parser("agent", help="run a fleet agent: measure this machine, report to a hub, run allow-listed tasks")
|
|
198
|
+
p.add_argument("--hub", required=True, help="host:port of the hub")
|
|
199
|
+
p.add_argument("--token-file", required=True, help="shared secret file, or a scoped token with fleet:report,fleet:work")
|
|
200
|
+
p.add_argument("--name")
|
|
201
|
+
p.add_argument("--interval", type=float, default=5.0)
|
|
202
|
+
p.add_argument("--usd-per-hour", type=float, help="what this machine costs per hour (for estimates only)")
|
|
203
|
+
p.add_argument("--labels", default="")
|
|
204
|
+
p.add_argument("--no-tasks", action="store_true", help="measure only; never run tasks")
|
|
205
|
+
p.set_defaults(fn=cmd_agent)
|
|
206
|
+
p = sub.add_parser("fleet", help="see and use the fleet through a hub")
|
|
207
|
+
p.add_argument("action", choices=["status", "advise", "submit", "result"])
|
|
208
|
+
p.add_argument("--hub", required=True)
|
|
209
|
+
p.add_argument("--token-file", required=True, help="scoped token with fleet:read (status/advise) or fleet:submit")
|
|
210
|
+
p.add_argument("--window", type=float, default=60.0)
|
|
211
|
+
p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
|
|
212
|
+
p.add_argument("--task-id", type=int)
|
|
213
|
+
p.set_defaults(fn=cmd_fleet)
|
|
214
|
+
p = sub.add_parser("token", help="scoped credentials: `init` a master key, `issue` a tenant token")
|
|
215
|
+
p.add_argument("action", choices=["init", "issue"])
|
|
216
|
+
p.add_argument("--master-key-file", required=True)
|
|
217
|
+
p.add_argument("--name", default="tenant")
|
|
218
|
+
p.add_argument("--scopes", default="", help="comma list, e.g. run:mandel_numba,mem:read,exec:elf (trailing * = prefix)")
|
|
219
|
+
p.add_argument("--ttl", type=float, default=3600, help="seconds")
|
|
220
|
+
p.add_argument("--max-ops", type=int)
|
|
221
|
+
p.add_argument("--max-bytes", type=int)
|
|
222
|
+
p.set_defaults(fn=cmd_token)
|
|
223
|
+
a = ap.parse_args(argv)
|
|
224
|
+
if getattr(a, "cmd", None) == "serve" and bool(a.token_file) == bool(a.master_key_file):
|
|
225
|
+
ap.error("serve needs exactly one of --token-file or --master-key-file")
|
|
226
|
+
try:
|
|
227
|
+
return a.fn(a)
|
|
228
|
+
except (Exception, SystemExit) as e: # user-facing tool: one clean line, no traceback
|
|
229
|
+
if isinstance(e, SystemExit) and not isinstance(e.code, str):
|
|
230
|
+
raise
|
|
231
|
+
print(f"spatial: {type(e).__name__}: {e}", file=sys.stderr)
|
|
232
|
+
return 1
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
if __name__ == "__main__":
|
|
236
|
+
sys.exit(main())
|
|
@@ -14,6 +14,7 @@ import sys
|
|
|
14
14
|
import time
|
|
15
15
|
from pathlib import Path
|
|
16
16
|
|
|
17
|
+
from ..core.auth import authorizer_from_file, require
|
|
17
18
|
from ..core.protocol import RpcClient, RpcServer
|
|
18
19
|
from . import workloads
|
|
19
20
|
|
|
@@ -23,6 +24,7 @@ def _handler(header: dict, blob: bytes):
|
|
|
23
24
|
if op == "ping":
|
|
24
25
|
return {"pong": True, "pid": os.getpid()}, b""
|
|
25
26
|
if op == "run":
|
|
27
|
+
require(f"run:{header.get('workload')}")
|
|
26
28
|
t = os.times()
|
|
27
29
|
c0, w0 = t.user + t.system, time.perf_counter()
|
|
28
30
|
result = workloads.run(header["workload"], **header.get("params", {}))
|
|
@@ -32,8 +34,9 @@ def _handler(header: dict, blob: bytes):
|
|
|
32
34
|
raise ValueError(f"unknown op {op!r}")
|
|
33
35
|
|
|
34
36
|
|
|
35
|
-
def serve(token: bytes, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False
|
|
36
|
-
|
|
37
|
+
def serve(token: bytes | None, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False,
|
|
38
|
+
authorizer=None) -> RpcServer:
|
|
39
|
+
return RpcServer(_handler, token, host=host, port=port, allow_remote=allow_remote, authorizer=authorizer)
|
|
37
40
|
|
|
38
41
|
|
|
39
42
|
class LocalWorkerProcess:
|
|
@@ -74,13 +77,18 @@ class LocalWorkerProcess:
|
|
|
74
77
|
|
|
75
78
|
def main():
|
|
76
79
|
ap = argparse.ArgumentParser()
|
|
77
|
-
ap.add_argument("--token-file",
|
|
80
|
+
ap.add_argument("--token-file", help="shared secret (every client may do everything)")
|
|
81
|
+
ap.add_argument("--master-key-file", help="issue scoped credentials instead (see `spatial token`)")
|
|
82
|
+
ap.add_argument("--audit-log")
|
|
78
83
|
ap.add_argument("--host", default="127.0.0.1")
|
|
79
84
|
ap.add_argument("--port", type=int, default=0)
|
|
80
85
|
ap.add_argument("--allow-remote", action="store_true",
|
|
81
86
|
help="explicit consent to accept non-loopback connections")
|
|
82
87
|
a = ap.parse_args()
|
|
83
|
-
|
|
88
|
+
if bool(a.token_file) == bool(a.master_key_file):
|
|
89
|
+
raise SystemExit("give exactly one of --token-file or --master-key-file")
|
|
90
|
+
srv = serve(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
|
|
91
|
+
authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None)
|
|
84
92
|
print(f"PORT {srv.port}", flush=True)
|
|
85
93
|
srv.serve_forever()
|
|
86
94
|
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Scoped credentials, quotas and an audit trail for SWP/2 services.
|
|
2
|
+
|
|
3
|
+
A server started with a master key issues credentials to tenants. A credential names the
|
|
4
|
+
tenant, the scopes it may use, an expiry and optional quotas; it is signed with the master
|
|
5
|
+
key, so the server needs no database. The tenant's per-credential secret is
|
|
6
|
+
HMAC(master, credential): only the issuer can derive it, and it is what authenticates the
|
|
7
|
+
handshake. The token handed to a tenant is "<credential>~<secret hex>".
|
|
8
|
+
|
|
9
|
+
Scopes are strings such as "run:mandel_numba", "mem:read", "mem:write", "exec:elf"; a trailing
|
|
10
|
+
"*" matches a prefix ("run:*", "*"). Services call require(scope) before acting.
|
|
11
|
+
Every request (allowed or denied) is appended to a hash-chained audit ledger.
|
|
12
|
+
|
|
13
|
+
Limits: revocation and usage counters live in the server process (restart resets counters);
|
|
14
|
+
a stolen token works until it expires or is revoked.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import base64
|
|
19
|
+
import hashlib
|
|
20
|
+
import hmac
|
|
21
|
+
import json
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
|
|
26
|
+
from .ledger import Ledger
|
|
27
|
+
|
|
28
|
+
PREFIX = "spc1"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class QuotaExceeded(Exception):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AuthError(Exception):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Principal:
|
|
41
|
+
name: str
|
|
42
|
+
scopes: tuple[str, ...]
|
|
43
|
+
expires: float
|
|
44
|
+
max_ops: int | None = None
|
|
45
|
+
max_bytes: int | None = None
|
|
46
|
+
cred: str = ""
|
|
47
|
+
ops: int = 0
|
|
48
|
+
nbytes: int = 0
|
|
49
|
+
lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
|
|
50
|
+
|
|
51
|
+
def allows(self, scope: str) -> bool:
|
|
52
|
+
for s in self.scopes:
|
|
53
|
+
if s == "*" or s == scope or (s.endswith("*") and scope.startswith(s[:-1])):
|
|
54
|
+
return True
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
_ctx = threading.local()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def current() -> Principal | None:
|
|
62
|
+
return getattr(_ctx, "principal", None)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def set_current(p: Principal | None) -> None:
|
|
66
|
+
_ctx.principal = p
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def require(scope: str) -> None:
|
|
70
|
+
"""Raise PermissionError unless the calling tenant holds `scope` (always true without auth)."""
|
|
71
|
+
p = current()
|
|
72
|
+
if p is not None and not p.allows(scope):
|
|
73
|
+
raise PermissionError(f"scope '{scope}' not granted to '{p.name}'")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _b64(b: bytes) -> str:
|
|
77
|
+
return base64.urlsafe_b64encode(b).decode().rstrip("=")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _unb64(s: str) -> bytes:
|
|
81
|
+
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Authorizer:
|
|
85
|
+
def __init__(self, master_key: bytes, audit: Ledger | None = None):
|
|
86
|
+
if len(master_key) < 16:
|
|
87
|
+
raise ValueError("master key must be at least 16 bytes")
|
|
88
|
+
self._master = master_key
|
|
89
|
+
self.audit = audit
|
|
90
|
+
self._revoked: set[str] = set()
|
|
91
|
+
self._seen: dict[str, Principal] = {}
|
|
92
|
+
|
|
93
|
+
def _sig(self, payload: str) -> str:
|
|
94
|
+
return hmac.new(self._master, b"sig|" + payload.encode(), hashlib.sha256).hexdigest()[:32]
|
|
95
|
+
|
|
96
|
+
def secret_for(self, cred: str) -> bytes:
|
|
97
|
+
return hmac.new(self._master, b"secret|" + cred.encode(), hashlib.sha256).digest()
|
|
98
|
+
|
|
99
|
+
def issue(self, name: str, scopes: list[str], ttl_s: float = 3600, max_ops: int | None = None,
|
|
100
|
+
max_bytes: int | None = None) -> str:
|
|
101
|
+
body = {"n": name, "s": list(scopes), "e": time.time() + ttl_s}
|
|
102
|
+
if max_ops is not None:
|
|
103
|
+
body["o"] = max_ops
|
|
104
|
+
if max_bytes is not None:
|
|
105
|
+
body["b"] = max_bytes
|
|
106
|
+
payload = _b64(json.dumps(body, separators=(",", ":")).encode())
|
|
107
|
+
cred = f"{PREFIX}.{payload}.{self._sig(payload)}"
|
|
108
|
+
return f"{cred}~{self.secret_for(cred).hex()}"
|
|
109
|
+
|
|
110
|
+
def revoke(self, name: str) -> None:
|
|
111
|
+
self._revoked.add(name)
|
|
112
|
+
|
|
113
|
+
def principal(self, cred: str) -> Principal:
|
|
114
|
+
"""Verify signature, expiry and revocation. Raises AuthError."""
|
|
115
|
+
try:
|
|
116
|
+
prefix, payload, sig = cred.split(".")
|
|
117
|
+
except ValueError:
|
|
118
|
+
raise AuthError("malformed credential")
|
|
119
|
+
if prefix != PREFIX or not hmac.compare_digest(sig, self._sig(payload)):
|
|
120
|
+
raise AuthError("bad credential signature")
|
|
121
|
+
body = json.loads(_unb64(payload))
|
|
122
|
+
if body["e"] < time.time():
|
|
123
|
+
raise AuthError("credential expired")
|
|
124
|
+
if body["n"] in self._revoked:
|
|
125
|
+
raise AuthError("credential revoked")
|
|
126
|
+
if cred not in self._seen:
|
|
127
|
+
self._seen[cred] = Principal(body["n"], tuple(body["s"]), body["e"], body.get("o"), body.get("b"), cred)
|
|
128
|
+
return self._seen[cred]
|
|
129
|
+
|
|
130
|
+
def charge(self, p: Principal, nbytes: int) -> None:
|
|
131
|
+
with p.lock:
|
|
132
|
+
if p.max_ops is not None and p.ops + 1 > p.max_ops:
|
|
133
|
+
raise QuotaExceeded(f"'{p.name}' exceeded {p.max_ops} operations")
|
|
134
|
+
if p.max_bytes is not None and p.nbytes + nbytes > p.max_bytes:
|
|
135
|
+
raise QuotaExceeded(f"'{p.name}' exceeded {p.max_bytes} bytes")
|
|
136
|
+
p.ops += 1
|
|
137
|
+
p.nbytes += nbytes
|
|
138
|
+
|
|
139
|
+
def log(self, p: Principal | None, op: str, ok: bool, detail: str = "", nbytes: int = 0) -> None:
|
|
140
|
+
if self.audit is not None:
|
|
141
|
+
self.audit.decide("auth", f"{p.name if p else '?'}:{op}", "allowed" if ok else f"denied: {detail}",
|
|
142
|
+
ok=ok, bytes=nbytes)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def parse_token(token: bytes) -> tuple[bytes, bytes]:
|
|
146
|
+
"""(credential, secret) from a client token. A plain shared token has no credential."""
|
|
147
|
+
t = token.decode(errors="ignore") if token.startswith(PREFIX.encode() + b".") else ""
|
|
148
|
+
if t and "~" in t:
|
|
149
|
+
cred, secret_hex = t.split("~", 1)
|
|
150
|
+
return cred.encode(), bytes.fromhex(secret_hex.strip())
|
|
151
|
+
return b"", token
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def init_master_key(path) -> None:
|
|
155
|
+
"""Create a random 32-byte master key file (mode 600). Refuses to overwrite."""
|
|
156
|
+
import os
|
|
157
|
+
from pathlib import Path
|
|
158
|
+
p = Path(path)
|
|
159
|
+
if p.exists():
|
|
160
|
+
raise FileExistsError(f"{p} already exists; refusing to overwrite a master key")
|
|
161
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
162
|
+
fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
163
|
+
with os.fdopen(fd, "wb") as f:
|
|
164
|
+
f.write(os.urandom(32))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def authorizer_from_file(master_key_file, audit_path=None) -> Authorizer:
|
|
168
|
+
from pathlib import Path
|
|
169
|
+
audit = Ledger(audit_path) if audit_path else Ledger(Path.home() / ".spatial" / "audit.jsonl")
|
|
170
|
+
return Authorizer(Path(master_key_file).read_bytes(), audit)
|
|
@@ -3,12 +3,15 @@
|
|
|
3
3
|
Every row carries `prev` (hash of the previous row) and `hash` = SHA-256(prev | canonical
|
|
4
4
|
JSON of the row). `verify()` detects an edited, removed or reordered row. This is tamper
|
|
5
5
|
EVIDENCE, not a signature: someone who can rewrite the whole file can rebuild the chain.
|
|
6
|
+
Thread-safe within one process. Two PROCESSES writing the same file would fork the chain: give each
|
|
7
|
+
process its own ledger file.
|
|
6
8
|
"""
|
|
7
9
|
from __future__ import annotations
|
|
8
10
|
|
|
9
11
|
import hashlib
|
|
10
12
|
import json
|
|
11
13
|
import os
|
|
14
|
+
import threading
|
|
12
15
|
import time
|
|
13
16
|
from pathlib import Path
|
|
14
17
|
|
|
@@ -29,6 +32,7 @@ class Ledger:
|
|
|
29
32
|
self.path = Path(path) if path else RESULTS / "ledger.jsonl"
|
|
30
33
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
31
34
|
self._last = self._tail_hash()
|
|
35
|
+
self._lock = threading.Lock() # services write from one thread per connection
|
|
32
36
|
|
|
33
37
|
def _tail_hash(self) -> str:
|
|
34
38
|
last = GENESIS
|
|
@@ -40,10 +44,11 @@ class Ledger:
|
|
|
40
44
|
|
|
41
45
|
def _append(self, row: dict) -> None:
|
|
42
46
|
row = json.loads(json.dumps(row, default=str)) # normalise before hashing
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
with self._lock: # read-last / hash / write must be one step
|
|
48
|
+
h = _digest(self._last, row)
|
|
49
|
+
with open(self.path, "a") as f:
|
|
50
|
+
f.write(json.dumps({**row, "prev": self._last, "hash": h}) + "\n")
|
|
51
|
+
self._last = h
|
|
47
52
|
|
|
48
53
|
def record(self, m: Measurement) -> Measurement:
|
|
49
54
|
self._append({"type": "measurement", **m.to_dict()})
|