spatial-computing 0.12.0__tar.gz → 0.12.2__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 (104) hide show
  1. {spatial_computing-0.12.0/spatial_computing.egg-info → spatial_computing-0.12.2}/PKG-INFO +2 -2
  2. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/README.md +1 -1
  3. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/pyproject.toml +1 -1
  4. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/__init__.py +1 -1
  5. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/core/protocol.py +17 -2
  6. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/fleet/hub.py +73 -5
  7. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/unified/providers.py +10 -2
  8. {spatial_computing-0.12.0 → spatial_computing-0.12.2/spatial_computing.egg-info}/PKG-INFO +2 -2
  9. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial_computing.egg-info/SOURCES.txt +1 -0
  10. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_fabric.py +16 -13
  11. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_fleet.py +46 -0
  12. spatial_computing-0.12.2/tests/test_hardening.py +172 -0
  13. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/LICENSE +0 -0
  14. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/setup.cfg +0 -0
  15. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/ai/__init__.py +0 -0
  16. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/ai/kvcache.py +0 -0
  17. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/cli.py +0 -0
  18. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/compute/__init__.py +0 -0
  19. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/compute/cost.py +0 -0
  20. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/compute/detect.py +0 -0
  21. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/compute/monitor.py +0 -0
  22. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/compute/scheduler.py +0 -0
  23. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/compute/taskqueue.py +0 -0
  24. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/compute/worker.py +0 -0
  25. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/compute/workloads.py +0 -0
  26. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/core/__init__.py +0 -0
  27. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/core/auth.py +0 -0
  28. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/core/energy.py +0 -0
  29. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/core/ledger.py +0 -0
  30. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/core/model.py +0 -0
  31. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/core/registry.py +0 -0
  32. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/fabric/__init__.py +0 -0
  33. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/fabric/cuda.py +0 -0
  34. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/fabric/devices.py +0 -0
  35. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/fabric/metal.py +0 -0
  36. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/fabric/metal_mandel.swift +0 -0
  37. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/fabric/metal_run.swift +0 -0
  38. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/fleet/__init__.py +0 -0
  39. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/fleet/agent.py +0 -0
  40. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/holographic/__init__.py +0 -0
  41. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/holographic/cgh.py +0 -0
  42. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/holographic/model.py +0 -0
  43. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/intelligence/__init__.py +0 -0
  44. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/intelligence/predictor.py +0 -0
  45. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/interconnect/__init__.py +0 -0
  46. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/interconnect/collectives.py +0 -0
  47. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/interconnect/comm.py +0 -0
  48. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/interconnect/model.py +0 -0
  49. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/interconnect/tasks.py +0 -0
  50. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/kernel/__init__.py +0 -0
  51. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/kernel/dsl.py +0 -0
  52. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/kernel/library.py +0 -0
  53. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/memory/__init__.py +0 -0
  54. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/memory/fararray.py +0 -0
  55. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/memory/pageserver.py +0 -0
  56. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/memory/secure.py +0 -0
  57. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/memory/shared.py +0 -0
  58. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/memory/tiered.py +0 -0
  59. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/__init__.py +0 -0
  60. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/__main__.py +0 -0
  61. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/backends/__init__.py +0 -0
  62. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/codegen.py +0 -0
  63. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/compiler.py +0 -0
  64. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/ir.py +0 -0
  65. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/lexer.py +0 -0
  66. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/parser.py +0 -0
  67. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/qir.py +0 -0
  68. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/runtime.py +0 -0
  69. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/q/sim.py +0 -0
  70. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/runtime/__init__.py +0 -0
  71. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/runtime/envs.py +0 -0
  72. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/runtime/inspect.py +0 -0
  73. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/runtime/microvm.py +0 -0
  74. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/runtime/planner.py +0 -0
  75. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/runtime/runner.py +0 -0
  76. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/runtime/toolchain.py +0 -0
  77. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/scientific/__init__.py +0 -0
  78. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/scientific/jobs.py +0 -0
  79. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/simulation/__init__.py +0 -0
  80. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/simulation/heat.py +0 -0
  81. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/simulation/nbody.py +0 -0
  82. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/unified/__init__.py +0 -0
  83. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/unified/model.py +0 -0
  84. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial/unified/planner.py +0 -0
  85. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial_computing.egg-info/dependency_links.txt +0 -0
  86. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial_computing.egg-info/entry_points.txt +0 -0
  87. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial_computing.egg-info/requires.txt +0 -0
  88. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/spatial_computing.egg-info/top_level.txt +0 -0
  89. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_auth.py +0 -0
  90. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_compute.py +0 -0
  91. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_core.py +0 -0
  92. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_domains.py +0 -0
  93. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_engines.py +0 -0
  94. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_interconnect.py +0 -0
  95. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_kernel.py +0 -0
  96. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_memory.py +0 -0
  97. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_optimizer.py +0 -0
  98. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_q.py +0 -0
  99. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_runtime.py +0 -0
  100. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_unified.py +0 -0
  101. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_v02.py +0 -0
  102. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_v03.py +0 -0
  103. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_v05.py +0 -0
  104. {spatial_computing-0.12.0 → spatial_computing-0.12.2}/tests/test_v07.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spatial-computing
3
- Version: 0.12.0
3
+ Version: 0.12.2
4
4
  Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
5
5
  Author: Spatial Computing contributors
6
6
  License-Expression: Apache-2.0
@@ -37,7 +37,7 @@ Dynamic: license-file
37
37
 
38
38
  One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
39
39
 
40
- > **Status: v0.12.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.12.2, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
41
41
 
42
42
  [Français](README.fr.md)
43
43
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  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.
6
6
 
7
- > **Status: v0.12.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.12.2, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
8
8
 
9
9
  [Français](README.fr.md)
10
10
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "spatial-computing"
7
- version = "0.12.0"
7
+ version = "0.12.2"
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.12.0"
6
+ __version__ = "0.12.2"
@@ -86,6 +86,8 @@ class SecureChannel:
86
86
  if _HDR.size + hl + bl != len(plain):
87
87
  raise ValueError("malformed record")
88
88
  header = json.loads(plain[_HDR.size:_HDR.size + hl]) if hl else {}
89
+ if not isinstance(header, dict):
90
+ raise ValueError("header must be a JSON object")
89
91
  return header, plain[_HDR.size + hl:]
90
92
 
91
93
 
@@ -104,7 +106,8 @@ class RpcServer:
104
106
  """
105
107
 
106
108
  def __init__(self, handler: Handler, token: bytes | None = None, host: str = "127.0.0.1",
107
- port: int = 0, allow_remote: bool = False, authorizer: "auth.Authorizer | None" = None):
109
+ port: int = 0, allow_remote: bool = False, authorizer: "auth.Authorizer | None" = None,
110
+ handshake_timeout_s: float = 10.0, max_connections: int = 512):
108
111
  if host not in ("127.0.0.1", "localhost", "::1") and not allow_remote:
109
112
  raise PermissionError(
110
113
  "refusing to bind a non-loopback address without allow_remote=True "
@@ -112,11 +115,21 @@ class RpcServer:
112
115
  if token is None and authorizer is None:
113
116
  raise ValueError("RpcServer needs a token or an authorizer")
114
117
  outer = self
118
+ slots = threading.BoundedSemaphore(max_connections) # one thread per connection: cap them
115
119
 
116
120
  class _H(socketserver.BaseRequestHandler):
117
121
  def handle(self):
122
+ if not slots.acquire(blocking=False):
123
+ return # over the cap: drop before any work
124
+ try:
125
+ self._serve()
126
+ finally:
127
+ slots.release()
128
+
129
+ def _serve(self):
118
130
  s = self.request
119
131
  s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
132
+ s.settimeout(handshake_timeout_s) # a silent peer must not hold a thread forever
120
133
  eph = X25519PrivateKey.generate()
121
134
  pub_s = eph.public_key().public_bytes(**_RAW)
122
135
  nonce_s = os.urandom(16)
@@ -142,10 +155,11 @@ class RpcServer:
142
155
  return # silent drop on bad auth
143
156
  shared = eph.exchange(X25519PublicKey.from_public_bytes(pub_c))
144
157
  ch = SecureChannel(s, shared + secret, nonce_s, nonce_c, is_server=True)
158
+ s.settimeout(None) # authenticated peers may stay idle (agents poll)
145
159
  while True:
146
160
  try:
147
161
  header, blob = ch.recv()
148
- except (ConnectionError, OSError, ValueError):
162
+ except (ConnectionError, OSError, ValueError, struct.error):
149
163
  return
150
164
  op = str(header.get("op"))
151
165
  try:
@@ -167,6 +181,7 @@ class RpcServer:
167
181
  class _S(socketserver.ThreadingTCPServer):
168
182
  allow_reuse_address = True
169
183
  daemon_threads = True
184
+ request_queue_size = 1024 # the default backlog of 5 refused simultaneous reconnects (found by the scale test)
170
185
 
171
186
  self.handler = handler
172
187
  self._srv = _S((host, port), _H)
@@ -12,6 +12,8 @@ from __future__ import annotations
12
12
 
13
13
  import argparse
14
14
  import itertools
15
+ import json
16
+ import os
15
17
  import math
16
18
  import threading
17
19
  import time
@@ -218,6 +220,8 @@ class Hub:
218
220
  t = self.tasks.get(task_id)
219
221
  if t is None or t.get("node") != node:
220
222
  raise PermissionError("task is not assigned to this node")
223
+ if t["state"] == "queued": # requeued after a hub restart, but its agent finished it anyway
224
+ self.queue.remove(task_id)
221
225
  t.update(state="done" if ok else "failed", finished=self.clock(), result=value, error=error, wall_s=wall_s)
222
226
  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()))
223
227
  if ok and t["needs"].get("affinity"):
@@ -230,6 +234,66 @@ class Hub:
230
234
  raise KeyError(f"unknown task {task_id}")
231
235
  return {k: v for k, v in t.items()}
232
236
 
237
+
238
+ # ------------------------------------------------------------------ persistence
239
+ def snapshot(self) -> dict:
240
+ """Durable state: tasks, queue order, tenant usage and weights, gangs, cache owners. Node
241
+ measurements are not saved: agents rebuild them within one report interval."""
242
+ with self._lock:
243
+ return {"version": 1, "next_id": next(self._ids), "tasks": list(self.tasks.values()), "queue": list(self.queue),
244
+ "usage": self.usage, "weights": self.weights, "affinity": self.affinity,
245
+ "gangs": [{**g, "reserved": {}} for g in self.gangs.values()]}
246
+
247
+ def restore(self, snap: dict) -> dict:
248
+ """Load a snapshot. A task that was running is put back in the queue (at-least-once: the
249
+ allow-listed workloads are pure functions); if its agent still finishes it, that result is accepted."""
250
+ with self._lock:
251
+ self.tasks = {int(t["id"]): t for t in snap["tasks"]}
252
+ self.queue = deque(int(i) for i in snap["queue"])
253
+ requeued = 0
254
+ for t in self.tasks.values():
255
+ if t["state"] == "running":
256
+ t["state"] = "queued"
257
+ t["requeued_after_restart"] = True
258
+ self.queue.append(t["id"])
259
+ requeued += 1
260
+ self.usage, self.weights, self.affinity = dict(snap["usage"]), dict(snap["weights"]), dict(snap["affinity"])
261
+ self.gangs = {int(g["id"]): {**g, "started": [], "reserved": {}} for g in snap["gangs"]}
262
+ self._ids = itertools.count(int(snap["next_id"]))
263
+ return {"tasks": len(self.tasks), "queued": len(self.queue), "requeued_running": requeued}
264
+
265
+ def save(self, path: str | Path) -> None:
266
+ tmp = f"{path}.tmp"
267
+ with open(tmp, "w") as f:
268
+ json.dump(self.snapshot(), f)
269
+ f.flush()
270
+ os.fsync(f.fileno())
271
+ os.replace(tmp, path) # atomic: a crash leaves the old or the new file, never half
272
+
273
+ def load(self, path: str | Path) -> dict | None:
274
+ try:
275
+ snap = json.loads(Path(path).read_text())
276
+ except FileNotFoundError:
277
+ return None
278
+ return self.restore(snap)
279
+
280
+ def autosave(self, path: str | Path, every_s: float = 5.0) -> threading.Event:
281
+ """Save every `every_s` seconds in a daemon thread; set the returned event to stop (one last save is made)."""
282
+ stop = threading.Event()
283
+
284
+ def loop():
285
+ while not stop.wait(every_s):
286
+ try:
287
+ self.save(path)
288
+ except OSError:
289
+ pass
290
+ try:
291
+ self.save(path)
292
+ except OSError:
293
+ pass
294
+ threading.Thread(target=loop, daemon=True).start()
295
+ return stop
296
+
233
297
  # ------------------------------------------------------------------ views
234
298
  def _window(self, node: str, window_s: float, now: float) -> list:
235
299
  return [m for ts, m in self.series.get(node, ()) if now - window_s <= ts <= now]
@@ -363,9 +427,9 @@ def make_handler(hub: Hub):
363
427
 
364
428
 
365
429
  def serve_hub(token: bytes | None = None, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False,
366
- authorizer=None, hub: Hub | None = None, ledger: Ledger | None = None) -> tuple[RpcServer, Hub]:
430
+ authorizer=None, hub: Hub | None = None, ledger: Ledger | None = None, **server_kw) -> tuple[RpcServer, Hub]:
367
431
  hub = hub or Hub(ledger=ledger)
368
- return RpcServer(make_handler(hub), token, host=host, port=port, allow_remote=allow_remote, authorizer=authorizer), hub
432
+ return RpcServer(make_handler(hub), token, host=host, port=port, allow_remote=allow_remote, authorizer=authorizer, **server_kw), hub
369
433
 
370
434
 
371
435
  def main():
@@ -377,12 +441,16 @@ def main():
377
441
  ap.add_argument("--port", type=int, default=0)
378
442
  ap.add_argument("--allow-remote", action="store_true")
379
443
  ap.add_argument("--decision-log", default=str(Path.home() / ".spatial" / "fleet-decisions.jsonl"))
444
+ ap.add_argument("--state-file", help="save tasks, queue, tenant usage here every 5 s and reload it at start")
380
445
  a = ap.parse_args()
381
446
  if bool(a.token_file) == bool(a.master_key_file):
382
447
  raise SystemExit("give exactly one of --token-file or --master-key-file")
383
- srv, _ = serve_hub(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
384
- authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None,
385
- ledger=Ledger(a.decision_log))
448
+ srv, hub = serve_hub(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
449
+ authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None,
450
+ ledger=Ledger(a.decision_log))
451
+ if a.state_file:
452
+ print("restored", hub.load(a.state_file), flush=True)
453
+ hub.autosave(a.state_file)
386
454
  print(f"PORT {srv.port}", flush=True)
387
455
  srv.serve_forever()
388
456
 
@@ -107,8 +107,16 @@ class ComputeProvider(Provider):
107
107
  a_ = t1 - b_ * w1
108
108
  if b_ > 0 and a_ >= 0: # time = fixed cost + per-work cost: separates JIT/thread start-up from speed
109
109
  est, basis = a_ + b_ * wf, f"probe 1/8+1/4, affine fit"
110
- else: # noisy probes: fall back to proportional scaling from the larger one
111
- est, basis = t2 * wf / w2, "probe 1/4, proportional"
110
+ else: # the two probes cannot separate fixed cost from speed: probe once more, larger
111
+ s3 = max(s2 * 2, s // 2)
112
+ t3, _ = _best_of(lambda: workloads.run(wname, **{**params, scale: s3}))
113
+ w3 = s3 ** fam["exp"]
114
+ b3 = (t3 - t2) / (w3 - w2) if w3 > w2 else 0.0
115
+ a3 = t2 - b3 * w2
116
+ if b3 > 0 and a3 >= 0:
117
+ est, basis = a3 + b3 * wf, "probe 1/4+1/2, affine fit"
118
+ else: # still noisy: proportional scaling from the largest probe
119
+ est, basis = t3 * wf / w3, "probe 1/2, proportional"
112
120
  o = Option("compute", vname, True, est_time_s=est, rate_usd_h=planner.prices.device_usd_h.get(vname, planner.prices.local_usd_per_hour),
113
121
  isolated=None, basis=basis,
114
122
  run=(lambda wn=wname: workloads.run(wn, **params)), meta={"workload": wname, "params": params})
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spatial-computing
3
- Version: 0.12.0
3
+ Version: 0.12.2
4
4
  Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
5
5
  Author: Spatial Computing contributors
6
6
  License-Expression: Apache-2.0
@@ -37,7 +37,7 @@ Dynamic: license-file
37
37
 
38
38
  One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
39
39
 
40
- > **Status: v0.12.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.12.2, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
41
41
 
42
42
  [Français](README.fr.md)
43
43
 
@@ -88,6 +88,7 @@ tests/test_domains.py
88
88
  tests/test_engines.py
89
89
  tests/test_fabric.py
90
90
  tests/test_fleet.py
91
+ tests/test_hardening.py
91
92
  tests/test_interconnect.py
92
93
  tests/test_kernel.py
93
94
  tests/test_memory.py
@@ -38,19 +38,22 @@ def test_same_job_on_cpu_and_gpu_agrees_and_the_planner_picks_the_really_faster_
38
38
  ref = workloads.mandel_f32_cpu(256, 120)
39
39
  assert abs(ref - workloads.mandel_f32_metal(256, 120)) / ref < 1e-3 # both devices compute the same thing
40
40
  for n, iters in ((32, 100), (2048, 200)):
41
- plan = planner.plan(Job.compute("mandel_f32", n=n, iters=iters))
42
- real = {}
43
- for o in plan.options:
44
- if o.feasible:
45
- o.run() # warm
46
- best = float("inf")
47
- for _ in range(3):
48
- t0 = time.perf_counter()
49
- o.run()
50
- best = min(best, time.perf_counter() - t0)
51
- real[o.name] = best
52
- # machine-independent property: whatever device wins HERE, the planner's choice must be near the real best
53
- assert real[plan.chosen.name] <= 1.5 * min(real.values()), (n, real, plan.chosen.name)
41
+ for attempt in range(3): # probes are sub-10 ms on a shared CI runner: one noisy probe may mislead once
42
+ plan = planner.plan(Job.compute("mandel_f32", n=n, iters=iters))
43
+ real = {}
44
+ for o in plan.options:
45
+ if o.feasible:
46
+ o.run() # warm
47
+ best = float("inf")
48
+ for _ in range(3):
49
+ t0 = time.perf_counter()
50
+ o.run()
51
+ best = min(best, time.perf_counter() - t0)
52
+ real[o.name] = best
53
+ # machine-independent property: whatever device wins HERE, the planner's choice must be near the real best
54
+ if real[plan.chosen.name] <= 1.5 * min(real.values()):
55
+ break
56
+ assert real[plan.chosen.name] <= 1.5 * min(real.values()), (n, real, plan.chosen.name, plan.explain())
54
57
  ex = planner.execute(plan)
55
58
  assert abs(ex.result - workloads.mandel_f32_cpu(2048, 200)) / ex.result < 1e-3
56
59
  assert abs(ex.time_error_pct) < 400 # one run: process start-up jitter; accuracy is measured in bench_unified.py
@@ -225,3 +225,49 @@ def test_cache_affinity_prefers_the_node_that_holds_the_cache_then_gives_up_wait
225
225
  t3 = hub.submit("montecarlo_pi", {"samples": 1}, needs={"affinity": "prompt-42"})
226
226
  clk.t += 6; feed(hub, "n1", 10, clk=clk); feed(hub, "n2", 10, clk=clk)
227
227
  assert hub.poll("n2")["id"] == t3 # after the wait, anyone may take it
228
+
229
+
230
+ def test_snapshot_restore_requeues_running_tasks_and_accepts_a_late_result(tmp_path):
231
+ clk = Clock(); hub = Hub(clock=clk)
232
+ feed(hub, "n1", 10, clk=clk)
233
+ hub.set_weight("B", 2)
234
+ done = hub.submit("montecarlo_pi", {"samples": 1}, tenant="A")
235
+ t = hub.poll("n1"); hub.result("n1", t["id"], True, 3.14, wall_s=2.0)
236
+ running = hub.submit("montecarlo_pi", {"samples": 1}, tenant="B"); hub.poll("n1")
237
+ queued = hub.submit("montecarlo_pi", {"samples": 1}, tenant="A")
238
+ path = tmp_path / "hub.json"
239
+ hub.save(path)
240
+ assert not (tmp_path / "hub.json.tmp").exists()
241
+ new = Hub(clock=clk)
242
+ info = new.load(path)
243
+ assert info == {"tasks": 3, "queued": 2, "requeued_running": 1}
244
+ assert new.task(done)["state"] == "done" and new.task(done)["result"] == 3.14
245
+ assert new.usage["A"] == 2.0 and new.weights["B"] == 2.0 # fair-share history survives
246
+ assert new.submit("montecarlo_pi", {"samples": 1}) > queued # ids never repeat
247
+ feed(new, "n1", 10, clk=clk)
248
+ new.result("n1", running, True, 1.0, wall_s=1.0) # the old agent finished it after all
249
+ assert new.task(running)["state"] == "done" and running not in new.queue
250
+ assert Hub().load(tmp_path / "missing.json") is None
251
+
252
+
253
+ def test_hub_restart_on_the_same_port_agents_reconnect_and_queued_work_survives(tmp_path):
254
+ port = _free_port()
255
+ path = tmp_path / "state.json"
256
+ srv, hub = serve_hub(b"tok", port=port); srv.start()
257
+ ids = [hub.submit("montecarlo_pi", {"samples": 2000, "seed": i}) for i in range(4)]
258
+ hub.save(path)
259
+ srv.stop() # the hub dies with 4 tasks queued
260
+ agent = Agent("127.0.0.1", port, b"tok", name="a1", interval_s=0.3).start()
261
+ try:
262
+ assert wait(lambda: agent.last_error is not None, 10) # the agent notices
263
+ t0 = time.time()
264
+ srv2, hub2 = serve_hub(b"tok", port=port)
265
+ assert hub2.load(path)["queued"] == 4
266
+ srv2.start()
267
+ try:
268
+ assert wait(lambda: all(hub2.task(i)["state"] == "done" for i in ids), 40)
269
+ assert time.time() - t0 < 30 # reconnect plus four tasks
270
+ finally:
271
+ srv2.stop()
272
+ finally:
273
+ agent.stop()
@@ -0,0 +1,172 @@
1
+ """D5 / G-8: hostile input against the wire protocol, the hub and the SPATIAL Q parser. Pass = no crash,
2
+ no hang, the server keeps answering honest clients."""
3
+ import os
4
+ import random
5
+ import socket
6
+ import struct
7
+ import time
8
+
9
+ import pytest
10
+
11
+ from spatial.core.protocol import RpcClient, RpcServer, _mac
12
+ from spatial.q import parse
13
+ from spatial.q.compiler import SQCompileError
14
+ from spatial.q.lexer import SQSyntaxError
15
+ from spatial.q.runtime import SQRuntimeError
16
+
17
+ TOKEN = b"k" * 32
18
+
19
+
20
+ @pytest.fixture
21
+ def srv():
22
+ s = RpcServer(lambda h, b: ({"pong": True, "echo": h.get("x")}, b""), token=TOKEN, handshake_timeout_s=1.0, max_connections=8).start()
23
+ yield s
24
+ s.stop()
25
+
26
+
27
+ def alive(s) -> bool:
28
+ c = RpcClient("127.0.0.1", s.port, TOKEN, timeout=5)
29
+ try:
30
+ return c.call({"op": "ping"})[0]["pong"]
31
+ finally:
32
+ c.close()
33
+
34
+
35
+ def test_silent_peers_are_dropped_after_the_handshake_timeout_and_slots_are_freed(srv):
36
+ socks = [socket.create_connection(("127.0.0.1", srv.port)) for _ in range(8)] # fills every slot, sends nothing
37
+ time.sleep(0.3)
38
+ with pytest.raises(Exception): # a 9th honest client is refused while full
39
+ alive(srv)
40
+ time.sleep(1.5) # handshake timeout frees them
41
+ assert alive(srv)
42
+ for x in socks:
43
+ x.close()
44
+
45
+
46
+ def test_connections_over_the_cap_are_dropped_not_queued_forever(srv):
47
+ held = [RpcClient("127.0.0.1", srv.port, TOKEN) for _ in range(8)]
48
+ with pytest.raises(Exception):
49
+ RpcClient("127.0.0.1", srv.port, TOKEN, timeout=2).call({"op": "ping"})
50
+ for c in held:
51
+ c.close()
52
+ time.sleep(0.3)
53
+ assert alive(srv)
54
+
55
+
56
+ def test_replayed_handshake_is_rejected(srv):
57
+ # record a valid client handshake against one server nonce, replay it on a new connection
58
+ a = socket.create_connection(("127.0.0.1", srv.port))
59
+ hello = a.recv(48, socket.MSG_WAITALL)
60
+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
61
+ from spatial.core.protocol import _RAW
62
+ eph = X25519PrivateKey.generate()
63
+ pub_c, nonce_c = eph.public_key().public_bytes(**_RAW), os.urandom(16)
64
+ blob = struct.pack(">H", 0) + pub_c + nonce_c + _mac(TOKEN, hello[:16], hello[16:], pub_c, nonce_c, b"")
65
+ a.close()
66
+ b = socket.create_connection(("127.0.0.1", srv.port))
67
+ b.recv(48, socket.MSG_WAITALL)
68
+ b.sendall(blob) # new server nonce: the MAC cannot match
69
+ b.settimeout(3)
70
+ assert b.recv(1) == b"" # silent drop
71
+ b.close()
72
+ assert alive(srv)
73
+
74
+
75
+ def test_random_garbage_before_and_after_the_handshake_never_hurts_the_server(srv):
76
+ rng = random.Random(5)
77
+ for _ in range(60):
78
+ s = socket.create_connection(("127.0.0.1", srv.port))
79
+ try:
80
+ s.sendall(bytes(rng.getrandbits(8) for _ in range(rng.randrange(0, 200))))
81
+ s.shutdown(socket.SHUT_WR)
82
+ except OSError:
83
+ pass
84
+ s.close()
85
+ assert alive(srv)
86
+
87
+
88
+ def test_tampered_records_and_malformed_plaintext_from_an_authenticated_peer(srv):
89
+ c = RpcClient("127.0.0.1", srv.port, TOKEN)
90
+ ch = c._ch
91
+ ct = bytearray(ch._tx.encrypt(b"\0\0\0\0" + struct.pack(">Q", ch._ntx), b"x" * 40, None))
92
+ ct[5] ^= 1 # flip a bit
93
+ c.sock.sendall(struct.pack(">I", len(ct)) + bytes(ct))
94
+ c.sock.settimeout(3)
95
+ assert c.sock.recv(1) == b"" # connection dropped
96
+ # authenticated and well-encrypted but structurally wrong plaintexts
97
+ for plain in (b"", b"abc", struct.pack(">II", 5, 5) + b"zz", struct.pack(">II", 2, 0) + b"[]", struct.pack(">II", 3, 0) + b"\xff\xfe\xfd"):
98
+ c2 = RpcClient("127.0.0.1", srv.port, TOKEN)
99
+ e = c2._ch._tx.encrypt(b"\0\0\0\0" + struct.pack(">Q", 0), plain, None)
100
+ c2.sock.sendall(struct.pack(">I", len(e)) + e)
101
+ c2.sock.settimeout(3)
102
+ assert c2.sock.recv(1) == b""
103
+ c2.sock.close()
104
+ assert alive(srv)
105
+
106
+
107
+ def test_oversized_declared_frame_is_refused_without_allocating_it(srv):
108
+ c = RpcClient("127.0.0.1", srv.port, TOKEN)
109
+ c.sock.sendall(struct.pack(">I", 2 ** 31))
110
+ c.sock.settimeout(3)
111
+ assert c.sock.recv(1) == b""
112
+ assert alive(srv)
113
+
114
+
115
+ def test_hub_survives_random_requests_from_an_authenticated_client():
116
+ from spatial.fleet import Hub
117
+ from spatial.fleet.hub import make_handler
118
+ rng = random.Random(9)
119
+ hub = Hub()
120
+ h = make_handler(hub)
121
+ ops = ["ping", "report", "poll", "result", "submit", "submit_gang", "task", "nodes", "advise", "tenants", "nope", None, 5]
122
+ vals = [None, 0, -1, 2 ** 70, "x", "", [], {}, [1, 2], {"a": 1}, 1.5, float("nan"), "n" * 200, True]
123
+ bad = 0
124
+ for _ in range(1500):
125
+ hd = {"op": rng.choice(ops)}
126
+ for k in rng.sample(["node", "metrics", "workload", "params", "params_list", "needs", "task_id", "ok", "window_s", "priority", "tenant"], rng.randrange(0, 5)):
127
+ hd[k] = rng.choice(vals)
128
+ try:
129
+ h(hd, b"")
130
+ except Exception:
131
+ bad += 1 # the server turns these into {"ok": false}
132
+ assert bad > 0 and isinstance(hub.tenants(), list) # raised cleanly, state still readable
133
+
134
+
135
+ def test_sq_parser_only_ever_fails_with_its_own_errors_and_never_hangs():
136
+ base = ("quantum bell() { qubit q[2]; h q[0]; cx q[0], q[1]; measure q; } "
137
+ "main { r = bell(); print(r); for i in range(3) { } }")
138
+ rng = random.Random(3)
139
+ alphabet = "{}()[];,.=+-*/<>!&|\"' \n\t0123456789abcxyzhqubit#@$%^~\\"
140
+ t0 = time.time()
141
+ for _ in range(1500):
142
+ s = list(base)
143
+ for _ in range(rng.randrange(1, 6)):
144
+ op = rng.random()
145
+ i = rng.randrange(len(s)) if s else 0
146
+ if op < 0.4 and s:
147
+ s[i] = rng.choice(alphabet)
148
+ elif op < 0.7 and s:
149
+ del s[i]
150
+ else:
151
+ s.insert(i, rng.choice(alphabet))
152
+ try:
153
+ parse("".join(s))
154
+ except (SQSyntaxError, SQCompileError, SQRuntimeError):
155
+ pass
156
+ assert time.time() - t0 < 60
157
+
158
+
159
+ def test_a_burst_of_simultaneous_connections_all_succeed():
160
+ import threading
161
+ s = RpcServer(lambda h, b: ({"pong": True}, b""), token=TOKEN).start()
162
+ fails = []
163
+
164
+ def go():
165
+ try:
166
+ c = RpcClient("127.0.0.1", s.port, TOKEN, timeout=30); c.call({"op": "ping"}); c.close()
167
+ except Exception as e:
168
+ fails.append(repr(e))
169
+ ths = [threading.Thread(target=go) for _ in range(100)]
170
+ [t.start() for t in ths]; [t.join() for t in ths]
171
+ s.stop()
172
+ assert not fails, fails[:3] # with the old listen backlog of 5, many of these were refused