spatial-computing 0.12.2__tar.gz → 0.13.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 (109) hide show
  1. {spatial_computing-0.12.2/spatial_computing.egg-info → spatial_computing-0.13.0}/PKG-INFO +2 -2
  2. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/README.md +1 -1
  3. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/pyproject.toml +1 -1
  4. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/__init__.py +1 -1
  5. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/cli.py +59 -6
  6. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/core/registry.py +1 -1
  7. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/fleet/agent.py +8 -3
  8. spatial_computing-0.13.0/spatial/fleet/alerts.py +46 -0
  9. spatial_computing-0.13.0/spatial/fleet/dashboard.py +160 -0
  10. spatial_computing-0.13.0/spatial/fleet/ha.py +136 -0
  11. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/fleet/hub.py +52 -10
  12. {spatial_computing-0.12.2 → spatial_computing-0.13.0/spatial_computing.egg-info}/PKG-INFO +2 -2
  13. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial_computing.egg-info/SOURCES.txt +5 -0
  14. spatial_computing-0.13.0/tests/test_dashboard.py +112 -0
  15. spatial_computing-0.13.0/tests/test_ha.py +106 -0
  16. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/LICENSE +0 -0
  17. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/setup.cfg +0 -0
  18. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/ai/__init__.py +0 -0
  19. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/ai/kvcache.py +0 -0
  20. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/compute/__init__.py +0 -0
  21. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/compute/cost.py +0 -0
  22. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/compute/detect.py +0 -0
  23. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/compute/monitor.py +0 -0
  24. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/compute/scheduler.py +0 -0
  25. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/compute/taskqueue.py +0 -0
  26. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/compute/worker.py +0 -0
  27. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/compute/workloads.py +0 -0
  28. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/core/__init__.py +0 -0
  29. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/core/auth.py +0 -0
  30. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/core/energy.py +0 -0
  31. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/core/ledger.py +0 -0
  32. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/core/model.py +0 -0
  33. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/core/protocol.py +0 -0
  34. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/fabric/__init__.py +0 -0
  35. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/fabric/cuda.py +0 -0
  36. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/fabric/devices.py +0 -0
  37. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/fabric/metal.py +0 -0
  38. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/fabric/metal_mandel.swift +0 -0
  39. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/fabric/metal_run.swift +0 -0
  40. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/fleet/__init__.py +0 -0
  41. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/holographic/__init__.py +0 -0
  42. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/holographic/cgh.py +0 -0
  43. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/holographic/model.py +0 -0
  44. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/intelligence/__init__.py +0 -0
  45. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/intelligence/predictor.py +0 -0
  46. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/interconnect/__init__.py +0 -0
  47. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/interconnect/collectives.py +0 -0
  48. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/interconnect/comm.py +0 -0
  49. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/interconnect/model.py +0 -0
  50. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/interconnect/tasks.py +0 -0
  51. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/kernel/__init__.py +0 -0
  52. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/kernel/dsl.py +0 -0
  53. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/kernel/library.py +0 -0
  54. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/memory/__init__.py +0 -0
  55. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/memory/fararray.py +0 -0
  56. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/memory/pageserver.py +0 -0
  57. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/memory/secure.py +0 -0
  58. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/memory/shared.py +0 -0
  59. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/memory/tiered.py +0 -0
  60. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/__init__.py +0 -0
  61. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/__main__.py +0 -0
  62. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/backends/__init__.py +0 -0
  63. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/codegen.py +0 -0
  64. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/compiler.py +0 -0
  65. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/ir.py +0 -0
  66. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/lexer.py +0 -0
  67. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/parser.py +0 -0
  68. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/qir.py +0 -0
  69. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/runtime.py +0 -0
  70. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/q/sim.py +0 -0
  71. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/runtime/__init__.py +0 -0
  72. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/runtime/envs.py +0 -0
  73. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/runtime/inspect.py +0 -0
  74. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/runtime/microvm.py +0 -0
  75. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/runtime/planner.py +0 -0
  76. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/runtime/runner.py +0 -0
  77. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/runtime/toolchain.py +0 -0
  78. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/scientific/__init__.py +0 -0
  79. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/scientific/jobs.py +0 -0
  80. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/simulation/__init__.py +0 -0
  81. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/simulation/heat.py +0 -0
  82. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/simulation/nbody.py +0 -0
  83. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/unified/__init__.py +0 -0
  84. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/unified/model.py +0 -0
  85. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/unified/planner.py +0 -0
  86. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial/unified/providers.py +0 -0
  87. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
  88. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial_computing.egg-info/entry_points.txt +0 -0
  89. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial_computing.egg-info/requires.txt +0 -0
  90. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/spatial_computing.egg-info/top_level.txt +0 -0
  91. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_auth.py +0 -0
  92. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_compute.py +0 -0
  93. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_core.py +0 -0
  94. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_domains.py +0 -0
  95. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_engines.py +0 -0
  96. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_fabric.py +0 -0
  97. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_fleet.py +0 -0
  98. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_hardening.py +0 -0
  99. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_interconnect.py +0 -0
  100. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_kernel.py +0 -0
  101. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_memory.py +0 -0
  102. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_optimizer.py +0 -0
  103. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_q.py +0 -0
  104. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_runtime.py +0 -0
  105. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_unified.py +0 -0
  106. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_v02.py +0 -0
  107. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_v03.py +0 -0
  108. {spatial_computing-0.12.2 → spatial_computing-0.13.0}/tests/test_v05.py +0 -0
  109. {spatial_computing-0.12.2 → spatial_computing-0.13.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.12.2
3
+ Version: 0.13.0
4
4
  Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
5
5
  Author: Spatial Computing contributors
6
6
  License-Expression: Apache-2.0
@@ -37,7 +37,7 @@ Dynamic: license-file
37
37
 
38
38
  One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
39
39
 
40
- > **Status: v0.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).
40
+ > **Status: v0.13.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
 
@@ -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.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).
7
+ > **Status: v0.13.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
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "spatial-computing"
7
- version = "0.12.2"
7
+ version = "0.13.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.12.2"
6
+ __version__ = "0.13.0"
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
  import argparse
5
5
  import json
6
6
  import subprocess
7
+ import time
7
8
  import sys
8
9
  from pathlib import Path
9
10
 
@@ -89,21 +90,60 @@ def _read_token(path: str) -> bytes:
89
90
 
90
91
 
91
92
  def _hub_client(a):
92
- from .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)
93
+ from .fleet.ha import connect_active
94
+ return connect_active(a.hub, _read_token(a.token_file), timeout=30) # a.hub may be "h1:p,h2:p": the active one is used
95
95
 
96
96
 
97
97
  def cmd_agent(a):
98
98
  from .fleet import Agent
99
- 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,
99
+ ag = Agent(a.hub, None, _read_token(a.token_file), name=a.name, interval_s=a.interval,
101
100
  usd_per_hour=a.usd_per_hour, labels=[x for x in a.labels.split(",") if x], run_tasks=not a.no_tasks)
102
- print(f"agent '{ag.name}' reporting to {a.hub} every {a.interval:g} s" + ("" if a.no_tasks else "; accepts allow-listed tasks"))
101
+ print(f"agent '{ag.name}' reporting to {a.hub} every {a.interval:g} s" + ("" if a.no_tasks else "; accepts allow-listed tasks"), flush=True)
103
102
  ag.run_forever()
104
103
  return 0
105
104
 
106
105
 
106
+ def cmd_dashboard(a):
107
+ from .fleet.dashboard import Dashboard
108
+ d = Dashboard(a.hub, _read_token(a.token_file), port=a.port, min_severity=a.min_severity, webhook=a.webhook).start()
109
+ print(f"dashboard (read-only, this machine only): {d.url}", flush=True)
110
+ if a.webhook:
111
+ print(f"alert events are POSTed to {a.webhook}")
112
+ try:
113
+ while True:
114
+ time.sleep(3600)
115
+ except KeyboardInterrupt:
116
+ d.stop()
117
+ return 0
118
+
119
+
120
+ def cmd_watch(a):
121
+ from .fleet.alerts import AlertEngine, post_webhook
122
+ eng, cli = AlertEngine(a.min_severity), None
123
+ print(f"watching {a.hub} every {a.interval:g} s (alert level: {a.min_severity} and above)", flush=True)
124
+ while True:
125
+ try:
126
+ cli = cli or _hub_client(a)
127
+ events = eng.update(cli.call({"op": "advise", "window_s": a.window})[0]["recommendations"])
128
+ except Exception as e:
129
+ cli = None
130
+ events = [{"event": "hub_unreachable", "key": "hub", "ts": time.time(), "severity": "high", "text": f"{type(e).__name__}: {e}"}] if "hub" not in eng.firing else []
131
+ eng.firing.setdefault("hub", {"since": time.time(), "severity": "high", "text": "hub unreachable"})
132
+ else:
133
+ if "hub" in eng.firing:
134
+ eng.firing.pop("hub"); events.append({"event": "resolved", "key": "hub", "ts": time.time(), "severity": "high", "text": "hub reachable again"})
135
+ for e in events:
136
+ print(f"{time.strftime('%H:%M:%S', time.localtime(e['ts']))} {e['event']:<9} [{e['severity']}] {e['text']}", flush=True)
137
+ if a.webhook:
138
+ try:
139
+ post_webhook(a.webhook, e)
140
+ except Exception as err:
141
+ print(f"webhook failed: {err}", flush=True)
142
+ if a.once:
143
+ return 0
144
+ time.sleep(a.interval)
145
+
146
+
107
147
  def cmd_fleet(a):
108
148
  cli = _hub_client(a)
109
149
  if a.action == "status":
@@ -273,6 +313,19 @@ def main(argv=None):
273
313
  p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
274
314
  p.add_argument("--task-id", type=int)
275
315
  p.set_defaults(fn=cmd_fleet)
316
+ p = sub.add_parser("dashboard", help="read-only fleet dashboard in your browser (served on 127.0.0.1 only, behind a random key)")
317
+ p.add_argument("--hub", required=True, help="host:port, or h1:p,h2:p for a hub pair")
318
+ p.add_argument("--token-file", required=True, help="scoped token with fleet:read")
319
+ p.add_argument("--port", type=int, default=0)
320
+ p.add_argument("--min-severity", default="high", choices=["low", "medium", "high"])
321
+ p.add_argument("--webhook", help="POST each alert event (JSON) to this http(s) URL: this sends fleet data off the machine")
322
+ p.set_defaults(fn=cmd_dashboard)
323
+ p = sub.add_parser("watch", help="print alerts as they fire and clear; optional webhook")
324
+ p.add_argument("--hub", required=True); p.add_argument("--token-file", required=True)
325
+ p.add_argument("--interval", type=float, default=10.0); p.add_argument("--window", type=float, default=60.0)
326
+ p.add_argument("--min-severity", default="high", choices=["low", "medium", "high"])
327
+ p.add_argument("--webhook"); p.add_argument("--once", action="store_true")
328
+ p.set_defaults(fn=cmd_watch)
276
329
  p = sub.add_parser("token", help="scoped credentials: `init` a master key, `issue` a tenant token")
277
330
  p.add_argument("action", choices=["init", "issue"])
278
331
  p.add_argument("--master-key-file", required=True)
@@ -43,7 +43,7 @@ ENGINES: list[Engine] = [
43
43
  "estimates come from probes and measured constants on one machine; calibration is a median of past ratios; no learned model; fleet and QPU pricing need the caller's prices"),
44
44
  Engine("fleet", "Spatial Fleet (agent + hub)", "spatial.fleet", Status.OPERATIONAL_PROTOTYPE,
45
45
  "tests/test_fleet.py, benchmarks/bench_fleet.py",
46
- "validated on one machine (agents on loopback); no dashboard UI; recommendations are estimates; never applies changes by itself"),
46
+ "validated on one machine (agents on loopback); HA is active/standby without consensus, tested with two hubs and a clean kill only; dashboard is read-only and local; recommendations are estimates; never applies changes by itself"),
47
47
  Engine("runtime", "Spatial Runtime Engine", "spatial.runtime", Status.OPERATIONAL_PROTOTYPE,
48
48
  "tests/test_runtime.py, benchmarks/bench_runtime.py",
49
49
  "Windows apps not demonstrated (no Wine / Windows image); no containers; no GUI streaming"),
@@ -18,13 +18,16 @@ from ..compute import workloads
18
18
  from ..compute.detect import _nvidia_gpus, detect_node
19
19
  from ..compute.monitor import snapshot
20
20
  from ..core.protocol import RpcClient
21
+ from .ha import connect_active, parse_addrs
21
22
 
22
23
 
23
24
  class Agent:
24
- def __init__(self, host: str, port: int, token: bytes, name: str | None = None, interval_s: float = 5.0,
25
+ def __init__(self, host: "str | list", port: int | None, token: bytes, name: str | None = None, interval_s: float = 5.0,
25
26
  usd_per_hour: float | None = None, labels: list | None = None, run_tasks: bool = True,
26
27
  poll_s: float = 1.0, buffer: int = 720):
27
- self.host, self.port, self.token = host, port, token
28
+ # one hub, or several (host as a list or "h1:p,h2:p"): the agent talks to whichever reports itself active
29
+ self.hubs = parse_addrs(host) if port is None else [(host, port)]
30
+ self.host, self.port, self.token = self.hubs[0][0], self.hubs[0][1], token
28
31
  self.name = name or socket.gethostname()
29
32
  self.interval_s, self.poll_s = interval_s, poll_s
30
33
  self.usd_per_hour, self.labels, self.run_tasks = usd_per_hour, labels or [], run_tasks
@@ -46,7 +49,9 @@ class Agent:
46
49
 
47
50
  # ---------------------------------------------------------------- loops
48
51
  def _connect(self) -> RpcClient:
49
- return RpcClient(self.host, self.port, self.token, timeout=30)
52
+ if len(self.hubs) == 1:
53
+ return RpcClient(self.host, self.port, self.token, timeout=30)
54
+ return connect_active(self.hubs, self.token, timeout=30)
50
55
 
51
56
  def _report_loop(self):
52
57
  cli = None
@@ -0,0 +1,46 @@
1
+ """Alerts from the hub's recommendations: edge-triggered (a condition alerts once when it appears and
2
+ once when it clears), optional webhook. Nothing leaves this machine unless a webhook URL is given."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ import urllib.parse
8
+ import urllib.request
9
+
10
+ RANK = {"low": 0, "medium": 1, "high": 2}
11
+
12
+
13
+ def key_of(r: dict) -> str:
14
+ return f"{r['kind']}:{r.get('node') or ','.join(r.get('nodes_to_free', []))}"
15
+
16
+
17
+ class AlertEngine:
18
+ def __init__(self, min_severity: str = "high", clock=time.time):
19
+ if min_severity not in RANK:
20
+ raise ValueError("min_severity must be low, medium or high")
21
+ self.min_rank, self.clock = RANK[min_severity], clock
22
+ self.firing: dict[str, dict] = {}
23
+ self.history: list[dict] = [] # newest last, capped
24
+
25
+ def update(self, recommendations: list[dict]) -> list[dict]:
26
+ """Feed the current recommendations; returns the events produced by this update."""
27
+ now, events = self.clock(), []
28
+ current = {key_of(r): r for r in recommendations if RANK.get(r.get("severity"), 0) >= self.min_rank}
29
+ for k, r in current.items():
30
+ if k not in self.firing:
31
+ self.firing[k] = {"since": now, **r}
32
+ events.append({"event": "firing", "key": k, "ts": now, "severity": r["severity"], "text": r["text"]})
33
+ for k in [k for k in self.firing if k not in current]:
34
+ old = self.firing.pop(k)
35
+ events.append({"event": "resolved", "key": k, "ts": now, "severity": old["severity"], "text": old["text"],
36
+ "lasted_s": now - old["since"]})
37
+ self.history = (self.history + events)[-200:]
38
+ return events
39
+
40
+
41
+ def post_webhook(url: str, event: dict, timeout: float = 5.0) -> None:
42
+ u = urllib.parse.urlparse(url)
43
+ if u.scheme not in ("http", "https") or not u.netloc:
44
+ raise ValueError("webhook must be an http(s) URL")
45
+ req = urllib.request.Request(url, data=json.dumps(event).encode(), headers={"Content-Type": "application/json"}, method="POST")
46
+ urllib.request.urlopen(req, timeout=timeout).read()
@@ -0,0 +1,160 @@
1
+ """Fleet dashboard: a local, read-only web page over the hub.
2
+
3
+ The process holds the hub credential and serves HTTP on 127.0.0.1 ONLY (no option to bind elsewhere).
4
+ Every request needs a random key printed at start; the Host header must be loopback (blocks DNS
5
+ rebinding); only GET is accepted; the page can read the fleet and cannot change anything.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import http.server
10
+ import json
11
+ import secrets
12
+ import threading
13
+ import time
14
+ from urllib.parse import parse_qs, urlparse
15
+
16
+ from .alerts import AlertEngine, post_webhook
17
+ from .ha import connect_active
18
+
19
+ PAGE = r"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
20
+ <title>Spatial Fleet</title><style>
21
+ :root{--paper:#f6f4ec;--ink:#12233f;--mute:#4f5f7a;--mark:#ffd84a;--ok:#2f8f3a;--bad:#c0392b;--warn:#b7791f;--grid:#12233f14;
22
+ --serif:"Instrument Serif",Georgia,serif;--mono:"DM Mono",ui-monospace,Menlo,monospace}
23
+ @media (prefers-color-scheme:dark){:root{--paper:#0e1a30;--ink:#f6f4ec;--mute:#9fb0cc;--grid:#f6f4ec14;--ok:#b8f171;--bad:#ff8a7a;--warn:#ffd84a}}
24
+ *{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:14px/1.5 var(--mono);
25
+ background-image:linear-gradient(var(--grid) 1px,transparent 1px),linear-gradient(90deg,var(--grid) 1px,transparent 1px);background-size:24px 24px}
26
+ header{display:flex;justify-content:space-between;align-items:baseline;padding:18px 24px;border-bottom:1px solid var(--ink);background:var(--paper)}
27
+ h1{font:400 32px var(--serif);margin:0}h2{font:400 22px var(--serif);margin:0 0 8px}
28
+ main{max-width:1180px;margin:0 auto;padding:16px 24px;display:grid;gap:16px}
29
+ section{background:var(--paper);border:1px solid var(--ink);padding:14px 16px;overflow-x:auto}
30
+ table{border-collapse:collapse;width:100%}th,td{text-align:left;padding:4px 10px 4px 0;white-space:nowrap}th{color:var(--mute);font-weight:400}
31
+ .bar{display:inline-block;width:90px;height:8px;border:1px solid var(--ink);vertical-align:middle;margin-right:6px}.bar i{display:block;height:100%;background:var(--ink)}
32
+ .tag{padding:1px 6px;border:1px solid currentColor}.ok{color:var(--ok)}.bad{color:var(--bad)}.warn{color:var(--warn)}.mute{color:var(--mute)}
33
+ #banner{display:none;background:var(--bad);color:#fff;padding:10px 24px}
34
+ .kpis{display:flex;gap:28px;flex-wrap:wrap}.kpis b{font:400 30px var(--serif);display:block}
35
+ </style></head><body>
36
+ <div id="banner" role="alert"></div>
37
+ <header><h1>Spatial Fleet</h1><span id="meta" class="mute">connecting…</span></header>
38
+ <main>
39
+ <section><div class="kpis" id="kpis"></div></section>
40
+ <section><h2>Alerts</h2><div id="alerts" class="mute">none</div></section>
41
+ <section><h2>Nodes</h2><table id="nodes"></table></section>
42
+ <section><h2>Recommendations</h2><div id="recs" class="mute">none</div></section>
43
+ <section><h2>Tenants and queue</h2><table id="tenants"></table><p></p><table id="tasks"></table></section>
44
+ </main>
45
+ <script>
46
+ const key=new URLSearchParams(location.search).get("key")||"";
47
+ const esc=s=>String(s??"-").replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
48
+ const f=(v,n=0)=>v==null?"-":Number(v).toFixed(n);
49
+ const bar=v=>`<span class="bar"><i style="width:${Math.max(0,Math.min(100,v||0))}%"></i></span>${f(v)}%`;
50
+ async function tick(){
51
+ try{
52
+ const r=await fetch("api/state?key="+encodeURIComponent(key),{cache:"no-store"});
53
+ if(!r.ok) throw new Error(r.status);
54
+ const s=await r.json();
55
+ document.getElementById("meta").textContent=`hub ${s.hub.name} · ${s.hub.role} · epoch ${s.hub.epoch} · updated ${new Date(s.ts*1000).toLocaleTimeString()}`;
56
+ const u=s.utilization;
57
+ document.getElementById("kpis").innerHTML=[["nodes",u.nodes],["cores",u.cores],["CPU",u.cpu_utilization_pct==null?"-":f(u.cpu_utilization_pct,1)+"%"],
58
+ ["queued",s.queue.counts.queued||0],["running",s.queue.counts.running||0],["done",s.queue.counts.done||0],["failed",s.queue.counts.failed||0]].map(([k,v])=>`<div><b>${esc(v)}</b>${k}</div>`).join("");
59
+ document.getElementById("nodes").innerHTML="<tr><th>node</th><th>up</th><th>cores</th><th>cpu</th><th>ram free</th><th>gpus</th><th>$/h</th><th>samples</th></tr>"+
60
+ s.nodes.map(n=>`<tr><td>${esc(n.node)}</td><td class="${n.alive?"ok":"bad"}">${n.alive?"yes":"NO"}</td><td>${f(n.cores)}</td><td>${bar(n.cpu_avg)}</td><td>${f(n.ram_avail_pct)}%</td><td>${esc(n.gpu_count)}</td><td>${f(n.usd_per_hour,2)}</td><td>${esc(n.samples)}</td></tr>`).join("");
61
+ const firing=Object.values(s.alerts.firing);
62
+ const b=document.getElementById("banner");b.style.display=firing.length?"block":"none";b.textContent=firing.map(a=>a.text).join(" · ");
63
+ document.getElementById("alerts").innerHTML=(firing.length?firing.map(a=>`<div class="bad">● ${esc(a.severity)} ${esc(a.text)}</div>`).join(""):"<span class='ok'>nothing firing</span>")+
64
+ s.alerts.history.slice(-5).reverse().map(e=>`<div class="mute">${new Date(e.ts*1000).toLocaleTimeString()} ${esc(e.event)} ${esc(e.key)}</div>`).join("");
65
+ document.getElementById("recs").innerHTML=s.recommendations.length?s.recommendations.map(r=>`<p><span class="tag ${r.severity=="high"?"bad":"warn"}">${esc(r.severity)}</span> <b>${esc(r.kind)}</b> ${esc(r.text)}${r.est_saving_usd_per_month?` <span class="mute">(estimated saving ${f(r.est_saving_usd_per_month)} $/month: an estimate, not a result)</span>`:""}</p>`).join(""):"no recommendation: nothing in the measurements justifies a change";
66
+ document.getElementById("tenants").innerHTML="<tr><th>tenant</th><th>weight</th><th>finished s</th><th>weighted load</th><th>queued</th><th>running</th></tr>"+
67
+ s.tenants.map(t=>`<tr><td>${esc(t.tenant)}</td><td>${f(t.weight,1)}</td><td>${f(t.finished_s,1)}</td><td>${f(t.weighted_load,1)}</td><td>${esc(t.queued)}</td><td>${esc(t.running)}</td></tr>`).join("");
68
+ document.getElementById("tasks").innerHTML="<tr><th>task</th><th>workload</th><th>state</th><th>node</th><th>tenant</th><th>wall s</th></tr>"+
69
+ s.queue.recent.map(t=>`<tr><td>${esc(t.id)}${t.gang?" (gang)":""}</td><td>${esc(t.workload)}</td><td class="${t.state=="failed"?"bad":t.state=="done"?"ok":""}">${esc(t.state)}</td><td>${esc(t.node)}</td><td>${esc(t.tenant)}</td><td>${f(t.wall_s,2)}</td></tr>`).join("");
70
+ }catch(e){document.getElementById("meta").textContent="no data: "+e.message}
71
+ }
72
+ tick();setInterval(tick,3000);
73
+ </script></body></html>"""
74
+
75
+
76
+ class Dashboard:
77
+ def __init__(self, hubs, token: bytes, port: int = 0, interval_s: float = 3.0, window_s: float = 60.0,
78
+ min_severity: str = "high", webhook: str | None = None):
79
+ self.hubs, self.token, self.interval_s, self.window_s, self.webhook = hubs, token, interval_s, window_s, webhook
80
+ self.alerts = AlertEngine(min_severity)
81
+ self.key = secrets.token_urlsafe(16)
82
+ self.state: dict = {"error": "starting"}
83
+ self._cli = None
84
+ self._stop = threading.Event()
85
+ dash = self
86
+
87
+ class H(http.server.BaseHTTPRequestHandler):
88
+ def log_message(self, *a):
89
+ pass
90
+
91
+ def _deny(self, code, msg):
92
+ self.send_response(code); self.send_header("Content-Type", "text/plain"); self.end_headers(); self.wfile.write(msg.encode())
93
+
94
+ def do_GET(self):
95
+ host = (self.headers.get("Host") or "").rsplit(":", 1)[0].strip("[]")
96
+ if host not in ("127.0.0.1", "localhost", "::1"):
97
+ return self._deny(403, "bad host") # DNS rebinding
98
+ u = urlparse(self.path)
99
+ k = (parse_qs(u.query).get("key") or [""])[0]
100
+ if not secrets.compare_digest(k, dash.key):
101
+ return self._deny(403, "missing or wrong key")
102
+ if u.path == "/api/state":
103
+ body = json.dumps(dash.state).encode(); ctype = "application/json"
104
+ elif u.path in ("/", "/index.html"):
105
+ body = PAGE.encode(); ctype = "text/html; charset=utf-8"
106
+ else:
107
+ return self._deny(404, "not found")
108
+ self.send_response(200)
109
+ self.send_header("Content-Type", ctype); self.send_header("Cache-Control", "no-store")
110
+ self.send_header("X-Frame-Options", "DENY"); self.send_header("Referrer-Policy", "no-referrer")
111
+ self.send_header("Content-Security-Policy", "default-src 'self'; style-src 'unsafe-inline'; script-src 'unsafe-inline'")
112
+ self.end_headers(); self.wfile.write(body)
113
+
114
+ do_POST = do_PUT = do_DELETE = lambda self: self._deny(405, "read-only")
115
+
116
+ self._http = http.server.ThreadingHTTPServer(("127.0.0.1", port), H) # loopback only, by construction
117
+ self.port = self._http.server_address[1]
118
+
119
+ @property
120
+ def url(self) -> str:
121
+ return f"http://127.0.0.1:{self.port}/?key={self.key}"
122
+
123
+ def refresh(self) -> dict:
124
+ try:
125
+ if self._cli is None:
126
+ self._cli = connect_active(self.hubs, self.token, timeout=10)
127
+ c = self._cli
128
+ role = c.call({"op": "role"})[0]
129
+ nodes = c.call({"op": "nodes", "window_s": self.window_s})[0]
130
+ recs = c.call({"op": "advise", "window_s": self.window_s})[0]["recommendations"]
131
+ events = self.alerts.update(recs)
132
+ self.state = {"ts": time.time(), "hub": role, "nodes": nodes["nodes"], "utilization": nodes["utilization"],
133
+ "recommendations": recs, "tenants": c.call({"op": "tenants"})[0]["tenants"], "queue": c.call({"op": "queue"})[0],
134
+ "alerts": {"firing": self.alerts.firing, "history": self.alerts.history}}
135
+ if self.webhook:
136
+ for e in events:
137
+ try:
138
+ post_webhook(self.webhook, e)
139
+ except Exception:
140
+ pass
141
+ except Exception as e: # keep serving; reconnect (and fail over) next round
142
+ if self._cli is not None:
143
+ try: self._cli.close()
144
+ except Exception: pass
145
+ self._cli = None
146
+ self.state = {**{k: v for k, v in self.state.items() if k != "error"}, "error": f"{type(e).__name__}: {e}"} if "nodes" in self.state else {"error": f"{type(e).__name__}: {e}"}
147
+ return self.state
148
+
149
+ def start(self) -> "Dashboard":
150
+ def loop():
151
+ while not self._stop.is_set():
152
+ self.refresh()
153
+ self._stop.wait(self.interval_s)
154
+ threading.Thread(target=loop, daemon=True).start()
155
+ threading.Thread(target=self._http.serve_forever, daemon=True).start()
156
+ return self
157
+
158
+ def stop(self) -> None:
159
+ self._stop.set()
160
+ self._http.shutdown(); self._http.server_close()
@@ -0,0 +1,136 @@
1
+ """Hub high availability: one active hub, standby hubs that follow it, automatic promotion.
2
+
3
+ What it is: active/standby replication by polling. The standby pulls the active hub's state (op
4
+ `snapshot`, scope fleet:replicate) every `poll_s` seconds. If no active hub answers for
5
+ `fail_after_s`, the standby promotes itself (epoch + 1, running tasks requeued). Agents and clients
6
+ take a list of hub addresses and use the one that says it is active.
7
+
8
+ What it is NOT: consensus. There is no quorum and no leader lease. Under a network partition two hubs
9
+ can both be active for a while; when they see each other again the one with the lower epoch (or, at
10
+ equal epoch, the larger name) steps down and DISCARDS its divergent state. Tasks that ran on the
11
+ losing side may run twice (workloads are pure, so that is safe) and results recorded only there are
12
+ lost. Up to `poll_s` of state is lost at a failover. Use an odd-numbered quorum system (etcd, Raft)
13
+ when that is not acceptable.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import threading
19
+ import time
20
+
21
+ from ..core.protocol import RpcClient
22
+
23
+
24
+ def parse_addrs(spec: str | list) -> list[tuple[str, int]]:
25
+ """'h1:7700,h2:7700' -> [('h1', 7700), ('h2', 7700)]."""
26
+ items = spec.split(",") if isinstance(spec, str) else spec
27
+ out = []
28
+ for it in items:
29
+ if isinstance(it, tuple):
30
+ out.append(it)
31
+ continue
32
+ host, _, port = it.strip().rpartition(":")
33
+ out.append((host or "127.0.0.1", int(port)))
34
+ return out
35
+
36
+
37
+ def connect_active(addrs, token: bytes, timeout: float = 30.0) -> RpcClient:
38
+ """Connect to the first address whose hub reports itself active. Raises ConnectionError if none does."""
39
+ errors = []
40
+ for host, port in parse_addrs(addrs):
41
+ try:
42
+ cli = RpcClient(host, port, token, timeout=timeout)
43
+ except (OSError, ConnectionError) as e:
44
+ errors.append(f"{host}:{port} {type(e).__name__}")
45
+ continue
46
+ try:
47
+ if cli.call({"op": "role"})[0].get("role") == "active":
48
+ return cli
49
+ errors.append(f"{host}:{port} standby")
50
+ except (OSError, ConnectionError, RuntimeError) as e:
51
+ errors.append(f"{host}:{port} {e}")
52
+ cli.close()
53
+ raise ConnectionError("no active hub: " + "; ".join(errors))
54
+
55
+
56
+ class HAController:
57
+ def __init__(self, hub, token: bytes, peers, name: str, poll_s: float = 1.0, fail_after_s: float = 6.0,
58
+ clock=time.time, on_change=None):
59
+ self.hub, self.token, self.peers = hub, token, parse_addrs(peers)
60
+ self.poll_s, self.fail_after_s, self.clock, self.on_change = poll_s, fail_after_s, clock, on_change
61
+ hub.name = name
62
+ hub.role = "standby" # start passive; promotion needs fail_after_s of silence
63
+ self._since = clock() # when we last saw an active peer (or started)
64
+ self._stop = threading.Event()
65
+ self.last_error: str | None = None
66
+
67
+ def _peer(self, addr) -> tuple[dict | None, RpcClient | None]:
68
+ try:
69
+ cli = RpcClient(addr[0], addr[1], self.token, timeout=max(2.0, self.poll_s * 3))
70
+ return cli.call({"op": "role"})[0], cli
71
+ except (OSError, ConnectionError, RuntimeError) as e:
72
+ self.last_error = f"{type(e).__name__}: {e}"
73
+ return None, None
74
+
75
+ def _beats(self, role: dict) -> bool:
76
+ """Does the peer outrank us? Higher epoch wins; at equal epoch the smaller name stays active."""
77
+ mine = (self.hub.epoch, self.hub.name)
78
+ theirs = (int(role["epoch"]), role["name"])
79
+ return theirs[0] > mine[0] or (theirs[0] == mine[0] and theirs[1] < mine[1])
80
+
81
+ def step(self) -> str:
82
+ """One round: returns the role after it. Called by the thread; callable directly in tests."""
83
+ hub, now = self.hub, self.clock()
84
+ active_peer = None
85
+ for addr in self.peers:
86
+ role, cli = self._peer(addr)
87
+ if role is None:
88
+ continue
89
+ if role["role"] == "active" and (hub.role == "standby" or self._beats(role)):
90
+ active_peer = cli
91
+ break
92
+ cli.close()
93
+ if hub.role == "active":
94
+ if active_peer is not None: # a better active hub exists: step down, adopt its state
95
+ hub.role = "standby"
96
+ self._since = now
97
+ self._follow(active_peer)
98
+ self._changed("demoted")
99
+ return hub.role
100
+ if active_peer is not None:
101
+ self._follow(active_peer)
102
+ self._since = now
103
+ elif now - self._since >= self.fail_after_s: # nobody active for long enough: take over
104
+ hub.epoch += 1
105
+ hub.requeue_running()
106
+ hub.role = "active"
107
+ self._changed("promoted")
108
+ return hub.role
109
+
110
+ def _follow(self, cli: RpcClient) -> None:
111
+ try:
112
+ _, blob = cli.call({"op": "snapshot"})
113
+ self.hub.restore(json.loads(blob), requeue=False)
114
+ except (OSError, ConnectionError, RuntimeError, ValueError) as e:
115
+ self.last_error = f"{type(e).__name__}: {e}"
116
+ finally:
117
+ cli.close()
118
+
119
+ def _changed(self, what: str) -> None:
120
+ if self.hub.ledger:
121
+ self.hub.ledger.decide("fleet", f"hub {self.hub.name} {what}", f"epoch {self.hub.epoch}")
122
+ if self.on_change:
123
+ self.on_change(what, self.hub)
124
+
125
+ def start(self) -> "HAController":
126
+ def loop():
127
+ while not self._stop.wait(self.poll_s):
128
+ try:
129
+ self.step()
130
+ except Exception as e: # never let the monitor die
131
+ self.last_error = f"{type(e).__name__}: {e}"
132
+ threading.Thread(target=loop, daemon=True).start()
133
+ return self
134
+
135
+ def stop(self) -> None:
136
+ self._stop.set()