spatial-computing 0.8.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.
Files changed (81) hide show
  1. {spatial_computing-0.8.0/spatial_computing.egg-info → spatial_computing-0.9.0}/PKG-INFO +3 -2
  2. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/README.md +2 -1
  3. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/pyproject.toml +1 -1
  4. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/__init__.py +1 -1
  5. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/cli.py +73 -2
  6. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/core/ledger.py +9 -4
  7. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/core/registry.py +3 -0
  8. spatial_computing-0.9.0/spatial/fleet/__init__.py +18 -0
  9. spatial_computing-0.9.0/spatial/fleet/agent.py +137 -0
  10. spatial_computing-0.9.0/spatial/fleet/hub.py +279 -0
  11. {spatial_computing-0.8.0 → spatial_computing-0.9.0/spatial_computing.egg-info}/PKG-INFO +3 -2
  12. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/SOURCES.txt +4 -0
  13. spatial_computing-0.9.0/tests/test_fleet.py +163 -0
  14. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_v02.py +14 -0
  15. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/LICENSE +0 -0
  16. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/setup.cfg +0 -0
  17. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/ai/__init__.py +0 -0
  18. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/ai/kvcache.py +0 -0
  19. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/compute/__init__.py +0 -0
  20. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/compute/cost.py +0 -0
  21. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/compute/detect.py +0 -0
  22. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/compute/monitor.py +0 -0
  23. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/compute/scheduler.py +0 -0
  24. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/compute/taskqueue.py +0 -0
  25. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/compute/worker.py +0 -0
  26. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/compute/workloads.py +0 -0
  27. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/core/__init__.py +0 -0
  28. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/core/auth.py +0 -0
  29. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/core/energy.py +0 -0
  30. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/core/model.py +0 -0
  31. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/core/protocol.py +0 -0
  32. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/holographic/__init__.py +0 -0
  33. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/holographic/cgh.py +0 -0
  34. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/holographic/model.py +0 -0
  35. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/intelligence/__init__.py +0 -0
  36. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/intelligence/predictor.py +0 -0
  37. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/memory/__init__.py +0 -0
  38. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/memory/fararray.py +0 -0
  39. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/memory/pageserver.py +0 -0
  40. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/memory/secure.py +0 -0
  41. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/memory/shared.py +0 -0
  42. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/memory/tiered.py +0 -0
  43. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/__init__.py +0 -0
  44. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/__main__.py +0 -0
  45. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/backends/__init__.py +0 -0
  46. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/codegen.py +0 -0
  47. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/compiler.py +0 -0
  48. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/ir.py +0 -0
  49. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/lexer.py +0 -0
  50. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/parser.py +0 -0
  51. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/qir.py +0 -0
  52. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/runtime.py +0 -0
  53. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/q/sim.py +0 -0
  54. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/runtime/__init__.py +0 -0
  55. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/runtime/envs.py +0 -0
  56. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/runtime/inspect.py +0 -0
  57. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/runtime/microvm.py +0 -0
  58. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/runtime/planner.py +0 -0
  59. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/runtime/runner.py +0 -0
  60. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/runtime/toolchain.py +0 -0
  61. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/scientific/__init__.py +0 -0
  62. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/scientific/jobs.py +0 -0
  63. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/simulation/__init__.py +0 -0
  64. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/simulation/heat.py +0 -0
  65. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial/simulation/nbody.py +0 -0
  66. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
  67. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/entry_points.txt +0 -0
  68. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/requires.txt +0 -0
  69. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/spatial_computing.egg-info/top_level.txt +0 -0
  70. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_auth.py +0 -0
  71. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_compute.py +0 -0
  72. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_core.py +0 -0
  73. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_domains.py +0 -0
  74. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_engines.py +0 -0
  75. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_memory.py +0 -0
  76. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_optimizer.py +0 -0
  77. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_q.py +0 -0
  78. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_runtime.py +0 -0
  79. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_v03.py +0 -0
  80. {spatial_computing-0.8.0 → spatial_computing-0.9.0}/tests/test_v05.py +0 -0
  81. {spatial_computing-0.8.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.8.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.8.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).
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.8.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).
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.8.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"
@@ -3,4 +3,4 @@
3
3
  Status of every engine is declared in spatial.core.registry and must be backed
4
4
  by a test or benchmark before being set to OPERATIONAL.
5
5
  """
6
- __version__ = "0.8.0"
6
+ __version__ = "0.9.0"
@@ -83,6 +83,60 @@ def cmd_bench(a):
83
83
  return rc
84
84
 
85
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
+
86
140
  def cmd_token(a):
87
141
  from .core import auth
88
142
  if a.action == "init":
@@ -96,7 +150,7 @@ def cmd_token(a):
96
150
 
97
151
  def cmd_worker(a):
98
152
  mod = {"compute": "spatial.compute.worker", "memory": "spatial.memory.pageserver",
99
- "runtime": "spatial.runtime.runner"}[a.kind]
153
+ "runtime": "spatial.runtime.runner", "hub": "spatial.fleet.hub"}[a.kind]
100
154
  cmd = [sys.executable, "-m", mod, "--host", a.host, "--port", str(a.port)]
101
155
  if a.token_file:
102
156
  cmd += ["--token-file", a.token_file]
@@ -132,7 +186,7 @@ def main(argv=None):
132
186
  p.add_argument("name", choices=[*BENCHES, "all"])
133
187
  p.set_defaults(fn=cmd_bench)
134
188
  p = sub.add_parser("serve", help="start a compute worker, a page server or a sandboxed binary runner (loopback by default)")
135
- p.add_argument("kind", choices=["compute", "memory", "runtime"])
189
+ p.add_argument("kind", choices=["compute", "memory", "runtime", "hub"])
136
190
  p.add_argument("--token-file", help="shared secret: every client may do everything")
137
191
  p.add_argument("--master-key-file", help="scoped credentials with quotas and an audit log (see `spatial token`)")
138
192
  p.add_argument("--audit-log")
@@ -140,6 +194,23 @@ def main(argv=None):
140
194
  p.add_argument("--port", type=int, default=0)
141
195
  p.add_argument("--allow-remote", action="store_true", help="explicit consent to accept LAN connections")
142
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)
143
214
  p = sub.add_parser("token", help="scoped credentials: `init` a master key, `issue` a tenant token")
144
215
  p.add_argument("action", choices=["init", "issue"])
145
216
  p.add_argument("--master-key-file", required=True)
@@ -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
- h = _digest(self._last, row)
44
- with open(self.path, "a") as f:
45
- f.write(json.dumps({**row, "prev": self._last, "hash": h}) + "\n")
46
- self._last = h
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()})
@@ -29,6 +29,9 @@ ENGINES: list[Engine] = [
29
29
  Status.OPERATIONAL_PROTOTYPE,
30
30
  "tests/test_memory.py, benchmarks/bench_memory.py",
31
31
  "user-space object store only; not kernel paging; single writer; no RDMA/CXL hardware"),
32
+ Engine("fleet", "Spatial Fleet (agent + hub)", "spatial.fleet", Status.OPERATIONAL_PROTOTYPE,
33
+ "tests/test_fleet.py, benchmarks/bench_fleet.py",
34
+ "validated on one machine (agents on loopback); no dashboard UI; recommendations are estimates; never applies changes by itself"),
32
35
  Engine("runtime", "Spatial Runtime Engine", "spatial.runtime", Status.OPERATIONAL_PROTOTYPE,
33
36
  "tests/test_runtime.py, benchmarks/bench_runtime.py",
34
37
  "Windows apps not demonstrated (no Wine / Windows image); no containers; no GUI streaming"),
@@ -0,0 +1,18 @@
1
+ """Spatial Fleet: an agent on every machine, a hub that sees the whole fleet.
2
+
3
+ agent.py measures its machine continuously, reports to the hub, and runs allow-listed workloads
4
+ the hub hands out (pull model: the agent asks for work, nothing is pushed to it).
5
+ hub.py stores the fleet's measurements, places tasks, and turns the measurements into
6
+ recommendations whose evidence is shown. It never changes a machine by itself.
7
+
8
+ Everything travels over SWP/2 (encrypted, forward-secret, scoped credentials, audit log).
9
+ Savings are only ever ESTIMATES until a recommendation is applied and the fleet is measured again.
10
+ """
11
+ def __getattr__(name): # lazy: `python -m spatial.fleet.hub` must not import itself twice
12
+ if name == "Agent":
13
+ from .agent import Agent
14
+ return Agent
15
+ if name in ("Hub", "serve_hub"):
16
+ from . import hub
17
+ return getattr(hub, name)
18
+ raise AttributeError(name)
@@ -0,0 +1,137 @@
1
+ """Fleet agent: measure this machine continuously, report to the hub, run the hub's tasks.
2
+
3
+ Design points:
4
+ * outbound connections only (the agent never listens);
5
+ * a ring buffer keeps measurements while the hub is unreachable and delivers them, in order,
6
+ on reconnection (each keeps its own timestamp);
7
+ * the agent only runs workloads from the allow-list in compute/workloads.py: it never executes
8
+ code that came from the network.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import socket
13
+ import threading
14
+ import time
15
+ from collections import deque
16
+
17
+ from ..compute import workloads
18
+ from ..compute.detect import _nvidia_gpus, detect_node
19
+ from ..compute.monitor import snapshot
20
+ from ..core.protocol import RpcClient
21
+
22
+
23
+ class Agent:
24
+ def __init__(self, host: str, port: int, token: bytes, name: str | None = None, interval_s: float = 5.0,
25
+ usd_per_hour: float | None = None, labels: list | None = None, run_tasks: bool = True,
26
+ poll_s: float = 1.0, buffer: int = 720):
27
+ self.host, self.port, self.token = host, port, token
28
+ self.name = name or socket.gethostname()
29
+ self.interval_s, self.poll_s = interval_s, poll_s
30
+ self.usd_per_hour, self.labels, self.run_tasks = usd_per_hour, labels or [], run_tasks
31
+ self._buf: deque = deque(maxlen=buffer)
32
+ self._stop = threading.Event()
33
+ self._threads: list[threading.Thread] = []
34
+ self.sent = self.reconnects = self.tasks_done = 0
35
+ self.last_error: str | None = None
36
+ self._inventory = None
37
+
38
+ # ---------------------------------------------------------------- measurement
39
+ def collect(self) -> dict:
40
+ s = snapshot()
41
+ return {"ts": s["ts"], "cpu_percent": s["cpu_percent"], "cpu_count": _cores(), "load1": s["load1"],
42
+ "ram_total": s["ram_total"], "ram_available": s["ram_available"], "swap_used": s["swap_used"],
43
+ "memory_pressure": s.get("memory_pressure"),
44
+ "gpus": [{"name": g["name"], "util": g["utilization_percent"], "vram_total": g["vram_bytes"],
45
+ "vram_used": g["vram_used_bytes"]} for g in _nvidia_gpus()]}
46
+
47
+ # ---------------------------------------------------------------- loops
48
+ def _connect(self) -> RpcClient:
49
+ return RpcClient(self.host, self.port, self.token, timeout=30)
50
+
51
+ def _report_loop(self):
52
+ cli = None
53
+ while not self._stop.is_set():
54
+ self._buf.append(self.collect())
55
+ try:
56
+ if cli is None:
57
+ cli = self._connect()
58
+ self.reconnects += 1
59
+ while self._buf:
60
+ m = self._buf[0]
61
+ extra = {}
62
+ if self._inventory is None:
63
+ self._inventory = detect_node().to_dict()
64
+ if self.sent == 0 or self.reconnects_changed:
65
+ extra["inventory"] = self._inventory
66
+ cli.call({"op": "report", "node": self.name, "metrics": m, "usd_per_hour": self.usd_per_hour,
67
+ "labels": self.labels, **extra})
68
+ self._buf.popleft()
69
+ self.sent += 1
70
+ self.reconnects_changed = False
71
+ self.last_error = None
72
+ except (OSError, ConnectionError, RuntimeError) as e:
73
+ self.last_error = f"{type(e).__name__}: {e}"
74
+ if cli is not None:
75
+ cli.close()
76
+ cli = None
77
+ self.reconnects_changed = True
78
+ self._stop.wait(self.interval_s)
79
+ if cli is not None:
80
+ cli.close()
81
+
82
+ reconnects_changed = True
83
+
84
+ def _work_loop(self):
85
+ cli = None
86
+ while not self._stop.is_set():
87
+ try:
88
+ if cli is None:
89
+ cli = self._connect()
90
+ task = cli.call({"op": "poll", "node": self.name})[0].get("task")
91
+ except (OSError, ConnectionError, RuntimeError):
92
+ if cli is not None:
93
+ cli.close()
94
+ cli = None
95
+ self._stop.wait(self.poll_s * 2)
96
+ continue
97
+ if not task:
98
+ self._stop.wait(self.poll_s)
99
+ continue
100
+ t0 = time.perf_counter()
101
+ try:
102
+ value = workloads.run(task["workload"], **task["params"])
103
+ msg = {"ok": True, "value": value}
104
+ except Exception as e:
105
+ msg = {"ok": False, "error": f"{type(e).__name__}: {e}"}
106
+ try:
107
+ cli.call({"op": "result", "node": self.name, "task_id": task["id"], "wall_s": time.perf_counter() - t0, **msg})
108
+ self.tasks_done += 1
109
+ except (OSError, ConnectionError, RuntimeError):
110
+ cli = None
111
+
112
+ # ---------------------------------------------------------------- lifecycle
113
+ def start(self) -> "Agent":
114
+ self._threads = [threading.Thread(target=self._report_loop, daemon=True)]
115
+ if self.run_tasks:
116
+ self._threads.append(threading.Thread(target=self._work_loop, daemon=True))
117
+ for t in self._threads:
118
+ t.start()
119
+ return self
120
+
121
+ def stop(self):
122
+ self._stop.set()
123
+ for t in self._threads:
124
+ t.join(timeout=10)
125
+
126
+ def run_forever(self):
127
+ self.start()
128
+ try:
129
+ while True:
130
+ time.sleep(3600)
131
+ except KeyboardInterrupt:
132
+ self.stop()
133
+
134
+
135
+ def _cores() -> int:
136
+ import psutil
137
+ return psutil.cpu_count(logical=True) or 1
@@ -0,0 +1,279 @@
1
+ """Fleet hub: nodes, time series, task queue, placement and recommendations.
2
+
3
+ Scopes (scoped credentials, see core/auth.py):
4
+ fleet:report an agent sends its measurements
5
+ fleet:work an agent polls for tasks and posts results
6
+ fleet:submit a client submits tasks and reads their results
7
+ fleet:read a client reads nodes, recommendations and utilization
8
+ With scoped credentials a node's identity is the credential name: an agent cannot report as
9
+ another node. With a plain shared token the agent's self-declared name is used.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import itertools
15
+ import math
16
+ import threading
17
+ import time
18
+ from collections import deque
19
+ from pathlib import Path
20
+
21
+ from ..compute import workloads
22
+ from ..core import auth
23
+ from ..core.auth import authorizer_from_file, require
24
+ from ..core.ledger import Ledger
25
+ from ..core.protocol import RpcServer
26
+
27
+ HISTORY = 2000 # samples kept per node
28
+
29
+
30
+ class Hub:
31
+ def __init__(self, ledger: Ledger | None = None, stale_after_s: float = 30.0, clock=time.time,
32
+ busy_cpu_pct: float = 90.0):
33
+ self.nodes: dict[str, dict] = {}
34
+ self.series: dict[str, deque] = {}
35
+ self.tasks: dict[int, dict] = {}
36
+ self.queue: deque[int] = deque()
37
+ self.ledger = ledger
38
+ self.stale_after_s = stale_after_s
39
+ self.clock = clock
40
+ self.busy_cpu_pct = busy_cpu_pct
41
+ self._ids = itertools.count(1)
42
+ self._lock = threading.RLock()
43
+
44
+ # ------------------------------------------------------------------ identity
45
+ @staticmethod
46
+ def _who(header: dict) -> str:
47
+ p = auth.current()
48
+ name = p.name if p is not None else header.get("node")
49
+ if not name or not isinstance(name, str) or len(name) > 128:
50
+ raise ValueError("a node name is required")
51
+ return name
52
+
53
+ # ------------------------------------------------------------------ ops
54
+ def report(self, node: str, metrics: dict, inventory: dict | None = None, usd_per_hour: float | None = None,
55
+ labels: list | None = None) -> None:
56
+ now = self.clock()
57
+ ts = min(float(metrics.get("ts", now)), now) # a buffered report keeps its own time, never the future
58
+ with self._lock:
59
+ n = self.nodes.setdefault(node, {"first_seen": now})
60
+ n["last_seen"] = now
61
+ if inventory is not None:
62
+ n["inventory"] = inventory
63
+ if usd_per_hour is not None:
64
+ n["usd_per_hour"] = float(usd_per_hour)
65
+ if labels is not None:
66
+ n["labels"] = list(labels)[:16]
67
+ m = {k: metrics.get(k) for k in ("cpu_percent", "cpu_count", "load1", "ram_total", "ram_available",
68
+ "swap_used", "memory_pressure", "gpus")}
69
+ n["latest"] = {**m, "ts": ts}
70
+ self.series.setdefault(node, deque(maxlen=HISTORY)).append((ts, m))
71
+
72
+ def submit(self, workload: str, params: dict, needs: dict | None = None, priority: int = 10) -> int:
73
+ if workload not in workloads.REGISTRY:
74
+ raise KeyError(f"workload '{workload}' is not allow-listed")
75
+ with self._lock:
76
+ tid = next(self._ids)
77
+ self.tasks[tid] = {"id": tid, "workload": workload, "params": params, "needs": needs or {},
78
+ "priority": int(priority), "state": "queued", "submitted": self.clock()}
79
+ self.queue.append(tid)
80
+ return tid
81
+
82
+ def _eligible(self, node: str, needs: dict) -> bool:
83
+ n = self.nodes.get(node)
84
+ if not n or "latest" not in n:
85
+ return False
86
+ lat = n["latest"]
87
+ if needs.get("node") and needs["node"] != node:
88
+ return False
89
+ if needs.get("label") and needs["label"] not in n.get("labels", []):
90
+ return False
91
+ if needs.get("gpu") and not lat.get("gpus"):
92
+ return False
93
+ if needs.get("min_ram_gb") and (lat.get("ram_available") or 0) < needs["min_ram_gb"] * 2 ** 30:
94
+ return False
95
+ return True
96
+
97
+ def poll(self, node: str) -> dict | None:
98
+ """Hand the best eligible queued task to an agent that asks for work. Backpressure: a node
99
+ that reports itself saturated gets nothing."""
100
+ with self._lock:
101
+ n = self.nodes.get(node)
102
+ if not n or "latest" not in n:
103
+ return None
104
+ if (n["latest"].get("cpu_percent") or 0) >= self.busy_cpu_pct:
105
+ return None
106
+ best = None
107
+ for tid in self.queue:
108
+ t = self.tasks[tid]
109
+ if self._eligible(node, t["needs"]) and (best is None or (t["priority"], tid) < (best["priority"], best["id"])):
110
+ best = t
111
+ if best is None:
112
+ return None
113
+ self.queue.remove(best["id"])
114
+ best.update(state="running", node=node, started=self.clock())
115
+ if self.ledger:
116
+ self.ledger.decide("fleet", f"task {best['id']} -> {node}", "agent asked for work and is eligible",
117
+ workload=best["workload"], node_cpu=n["latest"].get("cpu_percent"))
118
+ return {"id": best["id"], "workload": best["workload"], "params": best["params"]}
119
+
120
+ def result(self, node: str, task_id: int, ok: bool, value=None, error: str | None = None, wall_s: float | None = None):
121
+ with self._lock:
122
+ t = self.tasks.get(task_id)
123
+ if t is None or t.get("node") != node:
124
+ raise PermissionError("task is not assigned to this node")
125
+ t.update(state="done" if ok else "failed", finished=self.clock(), result=value, error=error, wall_s=wall_s)
126
+
127
+ def task(self, task_id: int) -> dict:
128
+ with self._lock:
129
+ t = self.tasks.get(task_id)
130
+ if t is None:
131
+ raise KeyError(f"unknown task {task_id}")
132
+ return {k: v for k, v in t.items()}
133
+
134
+ # ------------------------------------------------------------------ views
135
+ def _window(self, node: str, window_s: float, now: float) -> list:
136
+ return [m for ts, m in self.series.get(node, ()) if now - window_s <= ts <= now]
137
+
138
+ def node_table(self, window_s: float = 60.0) -> list[dict]:
139
+ now = self.clock()
140
+ rows = []
141
+ with self._lock:
142
+ for name, n in sorted(self.nodes.items()):
143
+ w = self._window(name, window_s, now)
144
+ lat = n.get("latest", {})
145
+ age = now - n["last_seen"]
146
+ gpus = [g for m in w for g in (m.get("gpus") or [])]
147
+ rows.append({
148
+ "node": name, "alive": age <= self.stale_after_s, "age_s": age, "samples": len(w),
149
+ "cores": lat.get("cpu_count"), "cpu_avg": _avg([m["cpu_percent"] for m in w]),
150
+ "ram_total": lat.get("ram_total"),
151
+ "ram_avail_pct": _avg([100 * m["ram_available"] / m["ram_total"] for m in w if m.get("ram_total")]),
152
+ "gpu_count": len(lat.get("gpus") or []), "gpu_util_avg": _avg([g["util"] for g in gpus]),
153
+ "usd_per_hour": n.get("usd_per_hour"), "labels": n.get("labels", [])})
154
+ return rows
155
+
156
+ def utilization(self, window_s: float = 60.0) -> dict:
157
+ """Fleet CPU utilization = busy cores / cores over the window (alive nodes with data only)."""
158
+ rows = [r for r in self.node_table(window_s) if r["alive"] and r["samples"] and r["cores"]]
159
+ cores = sum(r["cores"] for r in rows)
160
+ busy = sum(r["cpu_avg"] / 100 * r["cores"] for r in rows)
161
+ return {"nodes": len(rows), "cores": cores, "busy_cores": busy,
162
+ "cpu_utilization_pct": 100 * busy / cores if cores else None}
163
+
164
+ def advise(self, window_s: float = 60.0, idle_pct: float = 15.0, busy_pct: float = 80.0,
165
+ target_pct: float = 60.0, min_samples: int = 3) -> list[dict]:
166
+ """Recommendations with their evidence. Nothing is applied. Estimates assume the work can be
167
+ moved and that the load pattern of the window continues; they are NOT measured savings."""
168
+ rows = self.node_table(window_s)
169
+ rec: list[dict] = []
170
+ for r in rows:
171
+ if not r["alive"]:
172
+ rec.append({"kind": "node_down", "severity": "high", "node": r["node"],
173
+ "text": f"{r['node']} has been silent for {r['age_s']:.0f} s", "evidence": {"age_s": r["age_s"]}})
174
+ ok = [r for r in rows if r["alive"] and r["samples"] >= min_samples and r["cores"]]
175
+ for r in ok:
176
+ if r["ram_avail_pct"] is not None and r["ram_avail_pct"] < 10:
177
+ rec.append({"kind": "memory_pressure", "severity": "high", "node": r["node"],
178
+ "text": f"{r['node']} has only {r['ram_avail_pct']:.0f}% RAM available",
179
+ "evidence": {"ram_avail_pct": r["ram_avail_pct"]}})
180
+ if r["gpu_count"] and r["gpu_util_avg"] is not None and r["gpu_util_avg"] < 20:
181
+ rec.append({"kind": "gpu_underused", "severity": "medium", "node": r["node"],
182
+ "text": f"{r['node']}: {r['gpu_count']} GPU(s) at {r['gpu_util_avg']:.0f}% on average",
183
+ "evidence": {"gpu_util_avg": r["gpu_util_avg"], "gpus": r["gpu_count"]},
184
+ **({"est_cost_idle_usd_per_hour": r["usd_per_hour"]} if r["usd_per_hour"] else {})})
185
+ busy = sorted((r for r in ok if r["cpu_avg"] >= busy_pct), key=lambda r: -r["cpu_avg"])
186
+ idle = sorted((r for r in ok if r["cpu_avg"] <= idle_pct), key=lambda r: r["cpu_avg"])
187
+ if busy and idle:
188
+ rec.append({"kind": "rebalance", "severity": "medium", "node": busy[0]["node"], "to": idle[0]["node"],
189
+ "text": f"{busy[0]['node']} is at {busy[0]['cpu_avg']:.0f}% CPU while {idle[0]['node']} is at {idle[0]['cpu_avg']:.0f}%: move work from the first to the second",
190
+ "evidence": {"busy": busy[0]["cpu_avg"], "idle": idle[0]["cpu_avg"]}})
191
+ if len(ok) >= 2:
192
+ load = sum(r["cpu_avg"] / 100 * r["cores"] for r in ok)
193
+ ram_used = sum((1 - (r["ram_avail_pct"] or 0) / 100) * (r["ram_total"] or 0) for r in ok)
194
+ keep, cap, ram_cap = [], 0.0, 0.0
195
+ for r in sorted(ok, key=lambda r: -r["cores"]): # keep the biggest nodes
196
+ if cap >= load / (target_pct / 100) and ram_cap * 0.85 >= ram_used:
197
+ break
198
+ keep.append(r)
199
+ cap += r["cores"]
200
+ ram_cap += r["ram_total"] or 0
201
+ freed = [r for r in ok if r not in keep]
202
+ if freed:
203
+ prices = [r["usd_per_hour"] for r in freed if r["usd_per_hour"]]
204
+ item = {"kind": "consolidate", "severity": "medium", "nodes_to_free": [r["node"] for r in freed],
205
+ "text": f"The fleet's load ({load:.1f} busy cores of {sum(r['cores'] for r in ok)}) would fit on {len(keep)} node(s) at {target_pct:.0f}% target utilization: {len(freed)} node(s) could be freed",
206
+ "evidence": {"busy_cores": load, "total_cores": sum(r["cores"] for r in ok), "kept": [r["node"] for r in keep],
207
+ "assumes": "work is movable; memory checked at 85% of the kept nodes; load pattern continues"}}
208
+ if len(prices) == len(freed):
209
+ item["est_saving_usd_per_hour"] = sum(prices)
210
+ item["est_saving_usd_per_month"] = sum(prices) * 730
211
+ rec.append(item)
212
+ return rec
213
+
214
+
215
+ def _avg(xs):
216
+ xs = [x for x in xs if x is not None]
217
+ return sum(xs) / len(xs) if xs else None
218
+
219
+
220
+ # ---------------------------------------------------------------------- service
221
+ def make_handler(hub: Hub):
222
+ def handle(h: dict, blob: bytes):
223
+ op = h.get("op")
224
+ if op == "ping":
225
+ return {"pong": True}, b""
226
+ if op == "report":
227
+ require("fleet:report")
228
+ hub.report(Hub._who(h), h["metrics"], h.get("inventory"), h.get("usd_per_hour"), h.get("labels"))
229
+ return {}, b""
230
+ if op == "poll":
231
+ require("fleet:work")
232
+ return {"task": hub.poll(Hub._who(h))}, b""
233
+ if op == "result":
234
+ require("fleet:work")
235
+ hub.result(Hub._who(h), int(h["task_id"]), bool(h["ok"]), h.get("value"), h.get("error"), h.get("wall_s"))
236
+ return {}, b""
237
+ if op == "submit":
238
+ require("fleet:submit")
239
+ return {"task_id": hub.submit(h["workload"], h.get("params", {}), h.get("needs"), h.get("priority", 10))}, b""
240
+ if op == "task":
241
+ require("fleet:submit")
242
+ return {"task": hub.task(int(h["task_id"]))}, b""
243
+ if op == "nodes":
244
+ require("fleet:read")
245
+ return {"nodes": hub.node_table(float(h.get("window_s", 60))), "utilization": hub.utilization(float(h.get("window_s", 60)))}, b""
246
+ if op == "advise":
247
+ require("fleet:read")
248
+ return {"recommendations": hub.advise(float(h.get("window_s", 60)), target_pct=float(h.get("target_pct", 60)))}, b""
249
+ raise ValueError(f"unknown op {op!r}")
250
+ return handle
251
+
252
+
253
+ def serve_hub(token: bytes | None = None, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False,
254
+ authorizer=None, hub: Hub | None = None, ledger: Ledger | None = None) -> tuple[RpcServer, Hub]:
255
+ hub = hub or Hub(ledger=ledger)
256
+ return RpcServer(make_handler(hub), token, host=host, port=port, allow_remote=allow_remote, authorizer=authorizer), hub
257
+
258
+
259
+ def main():
260
+ ap = argparse.ArgumentParser()
261
+ ap.add_argument("--token-file")
262
+ ap.add_argument("--master-key-file")
263
+ ap.add_argument("--audit-log")
264
+ ap.add_argument("--host", default="127.0.0.1")
265
+ ap.add_argument("--port", type=int, default=0)
266
+ ap.add_argument("--allow-remote", action="store_true")
267
+ ap.add_argument("--decision-log", default=str(Path.home() / ".spatial" / "fleet-decisions.jsonl"))
268
+ a = ap.parse_args()
269
+ if bool(a.token_file) == bool(a.master_key_file):
270
+ raise SystemExit("give exactly one of --token-file or --master-key-file")
271
+ srv, _ = serve_hub(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
272
+ authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None,
273
+ ledger=Ledger(a.decision_log))
274
+ print(f"PORT {srv.port}", flush=True)
275
+ srv.serve_forever()
276
+
277
+
278
+ if __name__ == "__main__":
279
+ main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spatial-computing
3
- Version: 0.8.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.8.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).
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` |
@@ -20,6 +20,9 @@ spatial/core/ledger.py
20
20
  spatial/core/model.py
21
21
  spatial/core/protocol.py
22
22
  spatial/core/registry.py
23
+ spatial/fleet/__init__.py
24
+ spatial/fleet/agent.py
25
+ spatial/fleet/hub.py
23
26
  spatial/holographic/__init__.py
24
27
  spatial/holographic/cgh.py
25
28
  spatial/holographic/model.py
@@ -65,6 +68,7 @@ tests/test_compute.py
65
68
  tests/test_core.py
66
69
  tests/test_domains.py
67
70
  tests/test_engines.py
71
+ tests/test_fleet.py
68
72
  tests/test_memory.py
69
73
  tests/test_optimizer.py
70
74
  tests/test_q.py
@@ -0,0 +1,163 @@
1
+ """Fleet: hub logic on injected measurements, then real agents over the encrypted protocol."""
2
+ import socket
3
+ import time
4
+
5
+ import pytest
6
+
7
+ from spatial.compute import workloads
8
+ from spatial.core import auth
9
+ from spatial.core.ledger import Ledger
10
+ from spatial.core.protocol import RpcClient
11
+ from spatial.fleet import Agent, Hub, serve_hub
12
+
13
+ GB = 2 ** 30
14
+
15
+
16
+ class Clock:
17
+ def __init__(self): self.t = 1_000_000.0
18
+ def __call__(self): return self.t
19
+
20
+
21
+ def feed(hub, name, cpu, cores=4, ram_free_pct=60, gpus=None, price=None, n=5, clk=None, ram_total=16 * GB):
22
+ for i in range(n):
23
+ ts = clk.t - (n - 1 - i) * 5
24
+ hub.report(name, {"ts": ts, "cpu_percent": cpu, "cpu_count": cores, "load1": 1.0, "ram_total": ram_total,
25
+ "ram_available": ram_total * ram_free_pct / 100, "swap_used": 0, "memory_pressure": "normal",
26
+ "gpus": gpus or []}, usd_per_hour=price)
27
+
28
+
29
+ def kinds(recs):
30
+ return [r["kind"] for r in recs]
31
+
32
+
33
+ def test_advice_rebalance_and_consolidation_with_savings():
34
+ clk = Clock(); hub = Hub(clock=clk)
35
+ feed(hub, "a", 95, price=2.0, clk=clk); feed(hub, "b", 5, price=2.0, clk=clk); feed(hub, "c", 5, price=2.0, clk=clk)
36
+ recs = hub.advise()
37
+ assert "rebalance" in kinds(recs)
38
+ reb = next(r for r in recs if r["kind"] == "rebalance")
39
+ assert reb["node"] == "a" and reb["to"] in ("b", "c")
40
+ con = next(r for r in recs if r["kind"] == "consolidate")
41
+ assert len(con["nodes_to_free"]) == 1 and con["est_saving_usd_per_hour"] == pytest.approx(2.0)
42
+ assert con["est_saving_usd_per_month"] == pytest.approx(1460.0)
43
+ assert con["evidence"]["busy_cores"] == pytest.approx(0.95 * 4 + 0.05 * 8) and "assumes" in con["evidence"]
44
+ u = hub.utilization()
45
+ assert u["cores"] == 12 and u["cpu_utilization_pct"] == pytest.approx(100 * (0.95 * 4 + 0.4) / 12)
46
+
47
+
48
+ def test_no_advice_when_the_measurements_do_not_justify_it():
49
+ clk = Clock(); hub = Hub(clock=clk)
50
+ feed(hub, "a", 55, clk=clk); feed(hub, "b", 60, clk=clk)
51
+ assert hub.advise() == [] # balanced and well used: say nothing
52
+ feed(hub, "c", 5, n=2, clk=clk); feed(hub, "d", 99, n=2, clk=clk)
53
+ assert all(r.get("node") not in ("c", "d") for r in hub.advise()) # fewer than 3 samples: no conclusion
54
+
55
+
56
+ def test_consolidation_refuses_when_memory_would_not_fit_and_flags_gpus_pressure_and_down_nodes():
57
+ clk = Clock(); hub = Hub(clock=clk)
58
+ feed(hub, "a", 5, ram_free_pct=20, clk=clk); feed(hub, "b", 5, ram_free_pct=20, clk=clk) # tiny CPU load, RAM 80% used
59
+ assert "consolidate" not in kinds(hub.advise())
60
+ feed(hub, "g", 50, gpus=[{"name": "T4", "util": 3, "vram_total": 16 * GB, "vram_used": 0}], price=0.5, clk=clk)
61
+ feed(hub, "m", 50, ram_free_pct=4, clk=clk)
62
+ recs = hub.advise()
63
+ assert {"gpu_underused", "memory_pressure"} <= set(kinds(recs))
64
+ clk.t += 120
65
+ assert next(r for r in hub.advise() if r["kind"] == "node_down")["severity"] == "high"
66
+ assert not any(r["alive"] for r in hub.node_table()) and hub.utilization()["nodes"] == 0
67
+
68
+
69
+ def test_buffered_reports_keep_their_time_and_the_future_is_clamped():
70
+ clk = Clock(); hub = Hub(clock=clk)
71
+ hub.report("a", {"ts": clk.t - 50, "cpu_percent": 10, "cpu_count": 2, "ram_total": GB, "ram_available": GB // 2})
72
+ hub.report("a", {"ts": clk.t + 9999, "cpu_percent": 20, "cpu_count": 2, "ram_total": GB, "ram_available": GB // 2})
73
+ ts = [t for t, _ in hub.series["a"]]
74
+ assert ts[0] == clk.t - 50 and ts[1] == clk.t
75
+
76
+
77
+ def test_placement_respects_needs_backpressure_and_priority():
78
+ clk = Clock(); hub = Hub(clock=clk)
79
+ feed(hub, "cpu1", 20, clk=clk); feed(hub, "gpu1", 20, gpus=[{"name": "A", "util": 0, "vram_total": 1, "vram_used": 0}], clk=clk)
80
+ feed(hub, "hot", 97, clk=clk)
81
+ with pytest.raises(KeyError):
82
+ hub.submit("not_allowed", {})
83
+ low = hub.submit("montecarlo_pi", {"samples": 10}, priority=9)
84
+ hi = hub.submit("montecarlo_pi", {"samples": 10}, priority=1)
85
+ needs_gpu = hub.submit("montecarlo_pi", {"samples": 10}, needs={"gpu": True})
86
+ pinned = hub.submit("montecarlo_pi", {"samples": 10}, needs={"node": "gpu1"}, priority=0)
87
+ assert hub.poll("hot") is None # saturated node gets nothing
88
+ assert hub.poll("nobody") is None
89
+ assert hub.poll("cpu1")["id"] == hi # pinned task is not for it; best priority wins
90
+ assert hub.poll("cpu1")["id"] == low
91
+ assert hub.poll("gpu1")["id"] == pinned and hub.poll("gpu1")["id"] == needs_gpu
92
+ assert hub.poll("gpu1") is None
93
+ with pytest.raises(PermissionError):
94
+ hub.result("cpu1", pinned, True, 1) # a node cannot finish another node's task
95
+
96
+
97
+ def _free_port():
98
+ s = socket.socket(); s.bind(("127.0.0.1", 0)); p = s.getsockname()[1]; s.close(); return p
99
+
100
+
101
+ def wait(pred, timeout=30):
102
+ t = time.time()
103
+ while time.time() - t < timeout:
104
+ if pred():
105
+ return True
106
+ time.sleep(0.1)
107
+ return False
108
+
109
+
110
+ def test_real_agents_over_the_encrypted_protocol_scopes_identity_and_audit(tmp_path):
111
+ az = auth.Authorizer(b"f" * 32, Ledger(tmp_path / "audit.jsonl"))
112
+ srv, hub = serve_hub(authorizer=az, ledger=Ledger(tmp_path / "decisions.jsonl"))
113
+ srv.start()
114
+ tok = lambda name, scopes: az.issue(name, scopes).encode()
115
+ agents = [Agent("127.0.0.1", srv.port, tok(f"node-{i}", ["fleet:report", "fleet:work"]), name=f"spoof-{i}",
116
+ interval_s=0.3, poll_s=0.1, usd_per_hour=1.0).start() for i in range(2)]
117
+ ops = RpcClient("127.0.0.1", srv.port, tok("ops", ["fleet:submit", "fleet:read"]), timeout=30)
118
+ try:
119
+ assert wait(lambda: len([r for r in hub.node_table(30) if r["samples"] >= 2]) == 2)
120
+ assert {r["node"] for r in hub.node_table()} == {"node-0", "node-1"} # identity = credential, not self-declared name
121
+ ids = [ops.call({"op": "submit", "workload": "mandel_numba", "params": {"n": 200, "iters": 150}})[0]["task_id"] for _ in range(8)]
122
+ assert wait(lambda: all(hub.task(i)["state"] == "done" for i in ids), 60)
123
+ ref = workloads.mandel_numba(200, 150)
124
+ assert all(hub.task(i)["result"] == ref for i in ids) # distributed results equal the reference
125
+ assert sum(a.tasks_done for a in agents) == 8
126
+ rows = ops.call({"op": "nodes"})[0]
127
+ assert len(rows["nodes"]) == 2 and rows["utilization"]["nodes"] == 2
128
+ assert all(isinstance(r, dict) for r in ops.call({"op": "advise"})[0]["recommendations"])
129
+ with pytest.raises(RuntimeError, match="PermissionError.*fleet:report"): # a reader cannot inject measurements
130
+ ops.call({"op": "report", "metrics": {"cpu_percent": 1}})
131
+ ag = RpcClient("127.0.0.1", srv.port, tok("node-9", ["fleet:report", "fleet:work"]), timeout=30)
132
+ with pytest.raises(RuntimeError, match="PermissionError.*fleet:read"): # an agent cannot read the fleet
133
+ ag.call({"op": "nodes"})
134
+ with pytest.raises(RuntimeError, match="PermissionError.*fleet:submit"):
135
+ ag.call({"op": "submit", "workload": "mandel_numba", "params": {}})
136
+ ag.close()
137
+ finally:
138
+ for a in agents:
139
+ a.stop()
140
+ ops.close(); srv.stop()
141
+ audit = [r for r in Ledger(tmp_path / "audit.jsonl").rows("decision") if r["engine"] == "auth"]
142
+ assert any(r["decision"] == "ops:report" and r["reason"].startswith("denied") for r in audit)
143
+ assert Ledger(tmp_path / "audit.jsonl").verify() == (True, None)
144
+ assert Ledger(tmp_path / "decisions.jsonl").verify() == (True, None)
145
+ assert len(Ledger(tmp_path / "decisions.jsonl").rows("decision")) == 8 # every placement is on record
146
+
147
+
148
+ def test_agent_buffers_while_the_hub_is_down_and_delivers_on_reconnect():
149
+ port = _free_port()
150
+ agent = Agent("127.0.0.1", port, b"tok", name="lonely", interval_s=0.3, run_tasks=False).start()
151
+ try:
152
+ assert wait(lambda: agent.last_error is not None, 10) and agent.sent == 0
153
+ time.sleep(1.2) # a few measurements pile up in the buffer
154
+ srv, hub = serve_hub(b"tok", port=port)
155
+ srv.start()
156
+ try:
157
+ assert wait(lambda: len(hub.series.get("lonely", ())) >= 4, 20) and agent.last_error is None
158
+ stamps = [t for t, _ in hub.series["lonely"]]
159
+ assert stamps == sorted(stamps) and stamps[0] < time.time() - 1.0 # old measurements kept their own time
160
+ finally:
161
+ srv.stop()
162
+ finally:
163
+ agent.stop()
@@ -239,3 +239,17 @@ def test_qir_lowering_is_exact_up_to_global_phase_and_parses():
239
239
  entry = next(f for f in m.functions if pyqir.is_entry_point(f))
240
240
  assert pyqir.required_num_qubits(entry) == 3 and pyqir.required_num_results(entry) == 3
241
241
  assert '"qir_profiles"="base_profile"' in ir
242
+
243
+
244
+ def test_ledger_chain_survives_concurrent_writers(tmp_path):
245
+ import threading
246
+ led = Ledger(tmp_path / "c.jsonl")
247
+
248
+ def work(k):
249
+ for i in range(60):
250
+ led.decide("e", f"t{k}-{i}", "concurrent")
251
+
252
+ ts = [threading.Thread(target=work, args=(k,)) for k in range(8)]
253
+ [t.start() for t in ts]
254
+ [t.join() for t in ts]
255
+ assert len(led.rows()) == 480 and led.verify() == (True, None)