spatial-computing 0.12.0__py3-none-any.whl → 0.12.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
spatial/__init__.py CHANGED
@@ -3,4 +3,4 @@
3
3
  Status of every engine is declared in spatial.core.registry and must be backed
4
4
  by a test or benchmark before being set to OPERATIONAL.
5
5
  """
6
- __version__ = "0.12.0"
6
+ __version__ = "0.12.2"
spatial/core/protocol.py CHANGED
@@ -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)
spatial/fleet/hub.py CHANGED
@@ -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
 
@@ -1,4 +1,4 @@
1
- spatial/__init__.py,sha256=dIWw7g3oRyvHg17keeGDzjsrt6eKzk3QwHrgAAzBZ9g,208
1
+ spatial/__init__.py,sha256=bAIyZjnwvO9gEyXUrqr8NUw45IXlcmxHkT2CvKTlsO0,208
2
2
  spatial/cli.py,sha256=Gs8JUZFNR4JQ_8No8X0od1fu1HzvgkbUO8OZ2GYn3jc,15331
3
3
  spatial/ai/__init__.py,sha256=qrQZBRNCGwnMp_Rx7HNblvGfgmLApVrdIAPcYVmZdCg,926
4
4
  spatial/ai/kvcache.py,sha256=7xrNI3zBKSoLA9ZjI1U2TZQ7GdXMZDzZq50qBrbWAWY,4054
@@ -15,7 +15,7 @@ spatial/core/auth.py,sha256=AOVoZpW4VcqgAynrieiMZtTi6i3KgDySt2p2Jz2RiQk,6222
15
15
  spatial/core/energy.py,sha256=w8dfk2F3RdmJBi0u3iNZzktDWSG-BdLozp8uFqAKTD8,3471
16
16
  spatial/core/ledger.py,sha256=FZhXIPLoPBqx3PfE2eXpIhaEULf7LkKoQ9pybguaRYE,3201
17
17
  spatial/core/model.py,sha256=UTLv1icOjGBl0L7zFrpz3XfQ2geCiS3HH-RaLuMx6pM,2324
18
- spatial/core/protocol.py,sha256=QZHHbtNZcE-uSLE-NQXNHSDpELT36K1XM5LJPgC8bA8,9882
18
+ spatial/core/protocol.py,sha256=0FU-LLBRdBIOYeUhcBAjMZkEEx4ar-J3ypqlSvlx-NA,10851
19
19
  spatial/core/registry.py,sha256=2uotUqkmdzhzxo1CfkIC87rgVHzJG6KjxlEVKWX6GDY,5051
20
20
  spatial/fabric/__init__.py,sha256=3Hj1G1FJAABJcsgMUlffMycYh_IyS5gFja9oUDq-mxA,491
21
21
  spatial/fabric/cuda.py,sha256=C7gcYRblWhORunXd80bqdnNK-VNZTu2neAlJWBqzOyY,1309
@@ -25,7 +25,7 @@ spatial/fabric/metal_mandel.swift,sha256=-uL49wwx5OGimt727HqGL9sSDobF8N0GJHQye59
25
25
  spatial/fabric/metal_run.swift,sha256=onuHT3yfpqrg5yOGiDpOugG6AovllFYeUer8D3KfnHE,2673
26
26
  spatial/fleet/__init__.py,sha256=LUpn9X_XTGPy8KfZhnYdGVQTIY9IIVfzMeNnw8HcCbs,957
27
27
  spatial/fleet/agent.py,sha256=iPpFZc5ThMb-axPTD3QotL9lsKl-jlnTJODc27aHkPQ,5588
28
- spatial/fleet/hub.py,sha256=KoCRtp1bdksqOaN-N8bQvxWGRhV8okKXQ88QW09o7ls,21781
28
+ spatial/fleet/hub.py,sha256=Qd0TziM1XssBidmrGregbGsTCsti31EMZEsC3XubsZw,25079
29
29
  spatial/holographic/__init__.py,sha256=16C0eQdfD87FeMKVwLAzgOgZ97oHzOfD27sLfmWAhP4,541
30
30
  spatial/holographic/cgh.py,sha256=jiQgs4k5QY03ndjMTVkT6DquJZX2BP6vPLWHTpaG0Uk,1910
31
31
  spatial/holographic/model.py,sha256=t0xtGmE2_gyy3T-HGliIqvqOhXeCTTKuSQas8ujStK8,1434
@@ -71,10 +71,10 @@ spatial/simulation/nbody.py,sha256=WcvcrQ1f4c7wjDsLRyxUFMkMTT1HfJ-Es3kT0uf80Og,1
71
71
  spatial/unified/__init__.py,sha256=jc85fwURTd_6RZymNMjxtLVY51mzTXTXyuvyk0KZrLo,674
72
72
  spatial/unified/model.py,sha256=oTOvf0ImSdXXn75sf92bgMCixju-YmMWHiVkRHQdJGA,7088
73
73
  spatial/unified/planner.py,sha256=kdpzCpZJ-RdjCj8MNaES4TPdSug0skSQ53pKUi2Q-Bo,5429
74
- spatial/unified/providers.py,sha256=Qj1_5QqEQiuNs9tlPkr2an0536yj68hwqfE1afy1CUY,21126
75
- spatial_computing-0.12.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
76
- spatial_computing-0.12.0.dist-info/METADATA,sha256=yY5iVzKGYbOCweMuPdoc7_LGlHz1IV-hSavWPzReox8,6697
77
- spatial_computing-0.12.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
78
- spatial_computing-0.12.0.dist-info/entry_points.txt,sha256=UIFCHJL01u7PIPej7EUHRI7rWEY8uBhufZ-_ulXUPRk,79
79
- spatial_computing-0.12.0.dist-info/top_level.txt,sha256=ZHke8hWgy4qIqEGq7omus3O-T7AhmPoc-cqr7JdGGxQ,8
80
- spatial_computing-0.12.0.dist-info/RECORD,,
74
+ spatial/unified/providers.py,sha256=HBOoIhlJ7nuN6nTvkxEiG004A-HEiaM7PY7qdKJURn0,21664
75
+ spatial_computing-0.12.2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
76
+ spatial_computing-0.12.2.dist-info/METADATA,sha256=F0IQPQqyxOV0s2WExIY6jpWk3APq_Oatg5EvDh5-ThY,6697
77
+ spatial_computing-0.12.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
78
+ spatial_computing-0.12.2.dist-info/entry_points.txt,sha256=UIFCHJL01u7PIPej7EUHRI7rWEY8uBhufZ-_ulXUPRk,79
79
+ spatial_computing-0.12.2.dist-info/top_level.txt,sha256=ZHke8hWgy4qIqEGq7omus3O-T7AhmPoc-cqr7JdGGxQ,8
80
+ spatial_computing-0.12.2.dist-info/RECORD,,