spatial-computing 0.13.0__tar.gz → 0.14.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/PKG-INFO +2 -2
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/README.md +1 -1
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/pyproject.toml +1 -1
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/__init__.py +1 -1
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/core/registry.py +2 -2
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fabric/metal.py +6 -4
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fabric/metal_run.swift +20 -11
- spatial_computing-0.14.0/spatial/fleet/ha.py +334 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fleet/hub.py +35 -6
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/kernel/dsl.py +72 -21
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial_computing.egg-info/PKG-INFO +2 -2
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial_computing.egg-info/SOURCES.txt +1 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_fleet.py +17 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_kernel.py +41 -0
- spatial_computing-0.14.0/tests/test_quorum.py +188 -0
- spatial_computing-0.13.0/spatial/fleet/ha.py +0 -136
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/LICENSE +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/setup.cfg +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/ai/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/ai/kvcache.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/cli.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/compute/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/compute/cost.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/compute/detect.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/compute/monitor.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/compute/scheduler.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/compute/taskqueue.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/compute/worker.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/compute/workloads.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/core/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/core/auth.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/core/energy.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/core/ledger.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/core/model.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/core/protocol.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fabric/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fabric/cuda.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fabric/devices.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fabric/metal_mandel.swift +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fleet/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fleet/agent.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fleet/alerts.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/fleet/dashboard.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/holographic/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/holographic/cgh.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/holographic/model.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/intelligence/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/intelligence/predictor.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/interconnect/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/interconnect/collectives.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/interconnect/comm.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/interconnect/model.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/interconnect/tasks.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/kernel/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/kernel/library.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/memory/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/memory/fararray.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/memory/pageserver.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/memory/secure.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/memory/shared.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/memory/tiered.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/__main__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/backends/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/codegen.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/compiler.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/ir.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/lexer.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/parser.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/qir.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/runtime.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/q/sim.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/runtime/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/runtime/envs.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/runtime/inspect.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/runtime/microvm.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/runtime/planner.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/runtime/runner.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/runtime/toolchain.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/scientific/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/scientific/jobs.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/simulation/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/simulation/heat.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/simulation/nbody.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/unified/__init__.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/unified/model.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/unified/planner.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial/unified/providers.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial_computing.egg-info/entry_points.txt +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial_computing.egg-info/requires.txt +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/spatial_computing.egg-info/top_level.txt +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_auth.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_compute.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_core.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_dashboard.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_domains.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_engines.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_fabric.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_ha.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_hardening.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_interconnect.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_memory.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_optimizer.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_q.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_runtime.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_unified.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_v02.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_v03.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_v05.py +0 -0
- {spatial_computing-0.13.0 → spatial_computing-0.14.0}/tests/test_v07.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: spatial-computing
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.14.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.
|
|
40
|
+
> **Status: v0.14.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.
|
|
7
|
+
> **Status: v0.14.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.
|
|
7
|
+
version = "0.14.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"
|
|
@@ -37,13 +37,13 @@ ENGINES: list[Engine] = [
|
|
|
37
37
|
"N = 4 and 8 processes on one machine over loopback; no real network, RDMA or GPU memory; about 3,000x slower than NVLink 5 (vendor figure); no fault tolerance"),
|
|
38
38
|
Engine("kernel", "Portable kernels", "spatial.kernel", Status.FIRST_COMPONENTS,
|
|
39
39
|
"tests/test_kernel.py, benchmarks/bench_kernel.py (planner right 4 of 6; integer kernel bit-identical CPU vs Metal)",
|
|
40
|
-
"CUDA C generated, never compiled or run;
|
|
40
|
+
"CUDA C and HIP generated, never compiled or run; two kernel shapes (2-D map, whole-grid sum with shared memory), no tiling or tensor cores"),
|
|
41
41
|
Engine("planner", "Spatial Planner (the one objective)", "spatial.unified", Status.OPERATIONAL_PROTOTYPE,
|
|
42
42
|
"tests/test_unified.py",
|
|
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); HA
|
|
46
|
+
"validated on one machine (agents on loopback); HA: active/standby for two hubs, majority election (election safety, no replicated log) for three or more, tested on one machine with simulated clocks; 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"),
|
|
@@ -62,16 +62,16 @@ def _ensure_run_binary() -> Path:
|
|
|
62
62
|
return RUN_BIN
|
|
63
63
|
|
|
64
64
|
|
|
65
|
-
def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = None):
|
|
66
|
-
"""Run a portable Kernel (spatial.kernel) on the Metal GPU; returns the (n, n) uint32 output.
|
|
65
|
+
def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = None, reduce: bool = False):
|
|
66
|
+
"""Run a portable Kernel (spatial.kernel) on the Metal GPU; returns the (n, n) uint32 output, or with reduce=True the sum of all outputs (computed in threadgroup shared memory, partial sums added on the host).
|
|
67
67
|
`timing`, if given, receives the GPU-side median seconds."""
|
|
68
68
|
import numpy as np
|
|
69
69
|
import tempfile
|
|
70
70
|
binary = _ensure_run_binary()
|
|
71
71
|
with tempfile.TemporaryDirectory() as d:
|
|
72
72
|
msl, out = Path(d) / "k.metal", Path(d) / "out.bin"
|
|
73
|
-
msl.write_text(k.to_metal())
|
|
74
|
-
args = [str(binary), str(msl), k.name, str(n), str(reps), str(out)]
|
|
73
|
+
msl.write_text(k.to_metal(reduce=reduce))
|
|
74
|
+
args = [str(binary), str(msl), k.name + ("_sum" if reduce else ""), str(n), str(reps), str(out), "sum" if reduce else "map"]
|
|
75
75
|
args += [f"{t}:{float(params[p]) if t == 'float' else int(params[p])}" for p, t in k.params]
|
|
76
76
|
r = subprocess.run(args, capture_output=True, text=True, timeout=600)
|
|
77
77
|
try:
|
|
@@ -82,4 +82,6 @@ def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = Non
|
|
|
82
82
|
raise RuntimeError(info.get("error", "Metal error"))
|
|
83
83
|
if timing is not None:
|
|
84
84
|
timing.update(info)
|
|
85
|
+
if reduce:
|
|
86
|
+
return int(np.fromfile(out, dtype=np.uint64).sum())
|
|
85
87
|
return np.fromfile(out, dtype=np.uint32).reshape(n, n)
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Generic Metal host for portable kernels generated by spatial.kernel.
|
|
2
|
-
// usage: metal_run <msl_file> <kernel_name> <n> <reps> <out_file> [int:<v> | float:<v> ...]
|
|
3
|
-
// Buffers: 0 = output
|
|
2
|
+
// usage: metal_run <msl_file> <kernel_name> <n> <reps> <out_file> <map|sum> [int:<v> | float:<v> ...]
|
|
3
|
+
// Buffers: 0 = output, 1 = n (int), 2.. = parameters in order.
|
|
4
|
+
// map: output uint[n*n]. sum: one uint64 partial sum per 16x16 threadgroup (the kernel reduces in threadgroup memory).
|
|
4
5
|
import Foundation
|
|
5
6
|
import Metal
|
|
6
7
|
|
|
@@ -8,9 +9,11 @@ func now() -> Double { return Double(DispatchTime.now().uptimeNanoseconds) / 1e9
|
|
|
8
9
|
func fail(_ m: String) -> Never { print("{\"ok\": false, \"error\": \"\(m)\"}"); exit(1) }
|
|
9
10
|
|
|
10
11
|
let a = CommandLine.arguments
|
|
11
|
-
if a.count <
|
|
12
|
+
if a.count < 7 { fail("usage") }
|
|
12
13
|
guard let src = try? String(contentsOfFile: a[1], encoding: .utf8) else { fail("cannot read msl") }
|
|
13
|
-
let name = a[2], n = Int(a[3])!, reps = max(1, Int(a[4])!), outPath = a[5]
|
|
14
|
+
let name = a[2], n = Int(a[3])!, reps = max(1, Int(a[4])!), outPath = a[5], mode = a[6]
|
|
15
|
+
let sumMode = (mode == "sum")
|
|
16
|
+
let gx = (n + 15) / 16
|
|
14
17
|
guard let dev = MTLCreateSystemDefaultDevice() ?? MTLCopyAllDevices().first else { fail("no Metal device") }
|
|
15
18
|
let t0 = now()
|
|
16
19
|
let lib: MTLLibrary
|
|
@@ -21,7 +24,9 @@ do { lib = try dev.makeLibrary(source: src, options: nil) } catch {
|
|
|
21
24
|
guard let fn = lib.makeFunction(name: name) else { fail("kernel not found") }
|
|
22
25
|
let pipe = try! dev.makeComputePipelineState(function: fn)
|
|
23
26
|
let setupS = now() - t0
|
|
24
|
-
|
|
27
|
+
if sumMode && pipe.maxTotalThreadsPerThreadgroup < 256 { fail("device allows fewer than 256 threads per threadgroup") }
|
|
28
|
+
let outLen = sumMode ? gx * gx * 8 : n * n * 4
|
|
29
|
+
let out = dev.makeBuffer(length: outLen, options: .storageModeShared)!
|
|
25
30
|
let queue = dev.makeCommandQueue()!
|
|
26
31
|
var nn = Int32(n)
|
|
27
32
|
|
|
@@ -32,21 +37,25 @@ func run() -> Double {
|
|
|
32
37
|
enc.setComputePipelineState(pipe)
|
|
33
38
|
enc.setBuffer(out, offset: 0, index: 0)
|
|
34
39
|
enc.setBytes(&nn, length: 4, index: 1)
|
|
35
|
-
for (k, spec) in a[
|
|
40
|
+
for (k, spec) in a[7...].enumerated() {
|
|
36
41
|
let parts = spec.split(separator: ":", maxSplits: 1).map(String.init)
|
|
37
42
|
if parts[0] == "int" { var v = Int32(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
38
43
|
else { var v = Float(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
39
44
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
45
|
+
if sumMode {
|
|
46
|
+
enc.dispatchThreadgroups(MTLSize(width: gx, height: gx, depth: 1), threadsPerThreadgroup: MTLSize(width: 16, height: 16, depth: 1))
|
|
47
|
+
} else {
|
|
48
|
+
let w = pipe.threadExecutionWidth
|
|
49
|
+
let h = pipe.maxTotalThreadsPerThreadgroup / w
|
|
50
|
+
enc.dispatchThreadgroups(MTLSize(width: (n + w - 1) / w, height: (n + h - 1) / h, depth: 1),
|
|
51
|
+
threadsPerThreadgroup: MTLSize(width: w, height: h, depth: 1))
|
|
52
|
+
}
|
|
44
53
|
enc.endEncoding(); cb.commit(); cb.waitUntilCompleted()
|
|
45
54
|
return now() - t
|
|
46
55
|
}
|
|
47
56
|
var times: [Double] = []
|
|
48
57
|
for _ in 0..<reps { times.append(run()) }
|
|
49
|
-
let data = Data(bytes: out.contents(), count:
|
|
58
|
+
let data = Data(bytes: out.contents(), count: outLen)
|
|
50
59
|
do { try data.write(to: URL(fileURLWithPath: outPath)) } catch { fail("cannot write output") }
|
|
51
60
|
times.sort()
|
|
52
61
|
print("{\"ok\": true, \"device\": \"\(dev.name)\", \"gpu_s_median\": \(times[times.count / 2]), \"setup_s\": \(setupS)}")
|
|
@@ -0,0 +1,334 @@
|
|
|
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 os
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
import zlib
|
|
22
|
+
|
|
23
|
+
from ..core.protocol import RpcClient
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def parse_addrs(spec: str | list) -> list[tuple[str, int]]:
|
|
27
|
+
"""'h1:7700,h2:7700' -> [('h1', 7700), ('h2', 7700)]."""
|
|
28
|
+
items = spec.split(",") if isinstance(spec, str) else spec
|
|
29
|
+
out = []
|
|
30
|
+
for it in items:
|
|
31
|
+
if isinstance(it, tuple):
|
|
32
|
+
out.append(it)
|
|
33
|
+
continue
|
|
34
|
+
host, _, port = it.strip().rpartition(":")
|
|
35
|
+
out.append((host or "127.0.0.1", int(port)))
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def connect_active(addrs, token: bytes, timeout: float = 30.0) -> RpcClient:
|
|
40
|
+
"""Connect to the first address whose hub reports itself active. Raises ConnectionError if none does."""
|
|
41
|
+
errors = []
|
|
42
|
+
for host, port in parse_addrs(addrs):
|
|
43
|
+
try:
|
|
44
|
+
cli = RpcClient(host, port, token, timeout=timeout)
|
|
45
|
+
except (OSError, ConnectionError) as e:
|
|
46
|
+
errors.append(f"{host}:{port} {type(e).__name__}")
|
|
47
|
+
continue
|
|
48
|
+
try:
|
|
49
|
+
r = cli.call({"op": "role"})[0]
|
|
50
|
+
if r.get("role") == "active" and r.get("lease", True):
|
|
51
|
+
return cli
|
|
52
|
+
errors.append(f"{host}:{port} standby")
|
|
53
|
+
except (OSError, ConnectionError, RuntimeError) as e:
|
|
54
|
+
errors.append(f"{host}:{port} {e}")
|
|
55
|
+
cli.close()
|
|
56
|
+
raise ConnectionError("no active hub: " + "; ".join(errors))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class HAController:
|
|
60
|
+
def __init__(self, hub, token: bytes, peers, name: str, poll_s: float = 1.0, fail_after_s: float = 6.0,
|
|
61
|
+
clock=time.time, on_change=None):
|
|
62
|
+
self.hub, self.token, self.peers = hub, token, parse_addrs(peers)
|
|
63
|
+
self.poll_s, self.fail_after_s, self.clock, self.on_change = poll_s, fail_after_s, clock, on_change
|
|
64
|
+
hub.name = name
|
|
65
|
+
hub.role = "standby" # start passive; promotion needs fail_after_s of silence
|
|
66
|
+
self._since = clock() # when we last saw an active peer (or started)
|
|
67
|
+
self._stop = threading.Event()
|
|
68
|
+
self.last_error: str | None = None
|
|
69
|
+
|
|
70
|
+
def _peer(self, addr) -> tuple[dict | None, RpcClient | None]:
|
|
71
|
+
try:
|
|
72
|
+
cli = RpcClient(addr[0], addr[1], self.token, timeout=max(2.0, self.poll_s * 3))
|
|
73
|
+
return cli.call({"op": "role"})[0], cli
|
|
74
|
+
except (OSError, ConnectionError, RuntimeError) as e:
|
|
75
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
76
|
+
return None, None
|
|
77
|
+
|
|
78
|
+
def _beats(self, role: dict) -> bool:
|
|
79
|
+
"""Does the peer outrank us? Higher epoch wins; at equal epoch the smaller name stays active."""
|
|
80
|
+
mine = (self.hub.epoch, self.hub.name)
|
|
81
|
+
theirs = (int(role["epoch"]), role["name"])
|
|
82
|
+
return theirs[0] > mine[0] or (theirs[0] == mine[0] and theirs[1] < mine[1])
|
|
83
|
+
|
|
84
|
+
def step(self) -> str:
|
|
85
|
+
"""One round: returns the role after it. Called by the thread; callable directly in tests."""
|
|
86
|
+
hub, now = self.hub, self.clock()
|
|
87
|
+
active_peer = None
|
|
88
|
+
for addr in self.peers:
|
|
89
|
+
role, cli = self._peer(addr)
|
|
90
|
+
if role is None:
|
|
91
|
+
continue
|
|
92
|
+
if role["role"] == "active" and (hub.role == "standby" or self._beats(role)):
|
|
93
|
+
active_peer = cli
|
|
94
|
+
break
|
|
95
|
+
cli.close()
|
|
96
|
+
if hub.role == "active":
|
|
97
|
+
if active_peer is not None: # a better active hub exists: step down, adopt its state
|
|
98
|
+
hub.role = "standby"
|
|
99
|
+
self._since = now
|
|
100
|
+
self._follow(active_peer)
|
|
101
|
+
self._changed("demoted")
|
|
102
|
+
return hub.role
|
|
103
|
+
if active_peer is not None:
|
|
104
|
+
self._follow(active_peer)
|
|
105
|
+
self._since = now
|
|
106
|
+
elif now - self._since >= self.fail_after_s: # nobody active for long enough: take over
|
|
107
|
+
hub.epoch += 1
|
|
108
|
+
hub.requeue_running()
|
|
109
|
+
hub.role = "active"
|
|
110
|
+
self._changed("promoted")
|
|
111
|
+
return hub.role
|
|
112
|
+
|
|
113
|
+
def _follow(self, cli: RpcClient) -> None:
|
|
114
|
+
try:
|
|
115
|
+
_, blob = cli.call({"op": "snapshot"})
|
|
116
|
+
self.hub.restore(json.loads(blob), requeue=False)
|
|
117
|
+
except (OSError, ConnectionError, RuntimeError, ValueError) as e:
|
|
118
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
119
|
+
finally:
|
|
120
|
+
cli.close()
|
|
121
|
+
|
|
122
|
+
def _changed(self, what: str) -> None:
|
|
123
|
+
if self.hub.ledger:
|
|
124
|
+
self.hub.ledger.decide("fleet", f"hub {self.hub.name} {what}", f"epoch {self.hub.epoch}")
|
|
125
|
+
if self.on_change:
|
|
126
|
+
self.on_change(what, self.hub)
|
|
127
|
+
|
|
128
|
+
def start(self) -> "HAController":
|
|
129
|
+
def loop():
|
|
130
|
+
while not self._stop.wait(self.poll_s):
|
|
131
|
+
try:
|
|
132
|
+
self.step()
|
|
133
|
+
except Exception as e: # never let the monitor die
|
|
134
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
135
|
+
threading.Thread(target=loop, daemon=True).start()
|
|
136
|
+
return self
|
|
137
|
+
|
|
138
|
+
def stop(self) -> None:
|
|
139
|
+
self._stop.set()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class QuorumController:
|
|
143
|
+
"""Three or more hubs, one leader chosen by majority vote (Raft-style terms and votes).
|
|
144
|
+
|
|
145
|
+
What it guarantees: at most ONE leader per term, and a leader serves requests only while it has heard
|
|
146
|
+
from a majority within the last `fail_after_s / 2` (a lease), so a hub cut off from the others stops
|
|
147
|
+
answering before a new leader can be elected (given clocks that tick at about the same rate). A hub
|
|
148
|
+
restarted with its term file does not vote twice in a term.
|
|
149
|
+
What it does not give: a replicated log. State travels by snapshot polling from the leader, so a
|
|
150
|
+
failover can lose up to one poll of recent changes; a candidate whose newest task id is older than a
|
|
151
|
+
voter's cannot win. This is election safety, not linearizable storage. Not a Raft implementation.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def __init__(self, hub, token: bytes, peers, name: str, poll_s: float = 1.0, fail_after_s: float = 6.0,
|
|
155
|
+
clock=time.time, meta_path: str | None = None, on_change=None):
|
|
156
|
+
self.hub, self.token, self.peers = hub, token, parse_addrs(peers)
|
|
157
|
+
self.poll_s, self.fail_after_s, self.clock, self.on_change = poll_s, fail_after_s, clock, on_change
|
|
158
|
+
self.name, self.meta_path = name, meta_path
|
|
159
|
+
self.majority = (len(self.peers) + 1) // 2 + 1
|
|
160
|
+
jitter = (zlib.crc32(name.encode()) % 1000) / 1000 # spreads elections so they rarely collide
|
|
161
|
+
self.timeout = fail_after_s * (1 + jitter)
|
|
162
|
+
self.term, self.voted_for, self.state = 0, None, "follower"
|
|
163
|
+
self.last_beat = self.last_majority = clock()
|
|
164
|
+
self.offline = False # tests: behave as a hub cut off from the network
|
|
165
|
+
self._lock = threading.RLock()
|
|
166
|
+
self._stop = threading.Event()
|
|
167
|
+
self.last_error: str | None = None
|
|
168
|
+
hub.name, hub.role, hub.ha = name, "standby", self
|
|
169
|
+
self._load()
|
|
170
|
+
hub.epoch = self.term
|
|
171
|
+
|
|
172
|
+
# ------------------------------------------------------------------ persistence of term and vote
|
|
173
|
+
def _load(self):
|
|
174
|
+
if self.meta_path and os.path.exists(self.meta_path):
|
|
175
|
+
try:
|
|
176
|
+
m = json.load(open(self.meta_path))
|
|
177
|
+
self.term, self.voted_for = int(m["term"]), m.get("voted_for")
|
|
178
|
+
except (OSError, ValueError, KeyError):
|
|
179
|
+
pass
|
|
180
|
+
|
|
181
|
+
def _persist(self):
|
|
182
|
+
if self.meta_path:
|
|
183
|
+
tmp = self.meta_path + ".tmp"
|
|
184
|
+
with open(tmp, "w") as f:
|
|
185
|
+
json.dump({"term": self.term, "voted_for": self.voted_for}, f); f.flush(); os.fsync(f.fileno())
|
|
186
|
+
os.replace(tmp, self.meta_path)
|
|
187
|
+
|
|
188
|
+
# ------------------------------------------------------------------ state changes
|
|
189
|
+
def lease_ok(self) -> bool:
|
|
190
|
+
if self.state != "leader":
|
|
191
|
+
return True
|
|
192
|
+
return self.clock() - self.last_majority < self.fail_after_s / 2
|
|
193
|
+
|
|
194
|
+
def _follower(self, term: int):
|
|
195
|
+
with self._lock:
|
|
196
|
+
if term > self.term:
|
|
197
|
+
self.term, self.voted_for = term, None
|
|
198
|
+
self.state = "follower"
|
|
199
|
+
self.hub.role, self.hub.epoch = "standby", self.term
|
|
200
|
+
self._persist()
|
|
201
|
+
|
|
202
|
+
def _changed(self, what: str):
|
|
203
|
+
if self.hub.ledger:
|
|
204
|
+
self.hub.ledger.decide("fleet", f"hub {self.name} {what}", f"term {self.term}")
|
|
205
|
+
if self.on_change:
|
|
206
|
+
self.on_change(what, self.hub)
|
|
207
|
+
|
|
208
|
+
# ------------------------------------------------------------------ handlers for peers
|
|
209
|
+
def on_vote(self, h: dict) -> dict:
|
|
210
|
+
if self.offline:
|
|
211
|
+
raise ConnectionError("offline")
|
|
212
|
+
with self._lock:
|
|
213
|
+
term, cand = int(h["term"]), str(h["candidate"])
|
|
214
|
+
if term > self.term:
|
|
215
|
+
self._follower(term)
|
|
216
|
+
fresh = int(h.get("last_id", 0)) >= self.hub.last_id() # candidate must not be behind us
|
|
217
|
+
grant = term == self.term and self.voted_for in (None, cand) and fresh
|
|
218
|
+
if grant:
|
|
219
|
+
self.voted_for, self.last_beat = cand, self.clock()
|
|
220
|
+
self._persist()
|
|
221
|
+
return {"granted": grant, "term": self.term}
|
|
222
|
+
|
|
223
|
+
def on_beat(self, h: dict) -> dict:
|
|
224
|
+
if self.offline:
|
|
225
|
+
raise ConnectionError("offline")
|
|
226
|
+
with self._lock:
|
|
227
|
+
term = int(h["term"])
|
|
228
|
+
if term < self.term:
|
|
229
|
+
return {"ok": False, "term": self.term}
|
|
230
|
+
if term > self.term or self.state != "follower":
|
|
231
|
+
self._follower(term)
|
|
232
|
+
self.last_beat = self.clock()
|
|
233
|
+
return {"ok": True, "term": self.term}
|
|
234
|
+
|
|
235
|
+
# ------------------------------------------------------------------ outbound
|
|
236
|
+
def _try(self, addr, header: dict):
|
|
237
|
+
if self.offline:
|
|
238
|
+
return None
|
|
239
|
+
try:
|
|
240
|
+
cli = RpcClient(addr[0], addr[1], self.token, timeout=max(2.0, self.poll_s * 3))
|
|
241
|
+
try:
|
|
242
|
+
return cli.call(header)[0]
|
|
243
|
+
finally:
|
|
244
|
+
cli.close()
|
|
245
|
+
except (OSError, ConnectionError, RuntimeError) as e:
|
|
246
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
247
|
+
return None
|
|
248
|
+
|
|
249
|
+
def _pull(self):
|
|
250
|
+
for addr in self.peers:
|
|
251
|
+
if self.offline:
|
|
252
|
+
return
|
|
253
|
+
try:
|
|
254
|
+
cli = RpcClient(addr[0], addr[1], self.token, timeout=max(2.0, self.poll_s * 3))
|
|
255
|
+
except (OSError, ConnectionError):
|
|
256
|
+
continue
|
|
257
|
+
try:
|
|
258
|
+
r = cli.call({"op": "role"})[0]
|
|
259
|
+
if r["role"] == "active" and int(r["epoch"]) == self.term:
|
|
260
|
+
_, blob = cli.call({"op": "snapshot"})
|
|
261
|
+
with self._lock:
|
|
262
|
+
if self.state == "follower":
|
|
263
|
+
self.hub.restore(json.loads(blob), requeue=False)
|
|
264
|
+
self.hub.epoch = self.term
|
|
265
|
+
return
|
|
266
|
+
except (OSError, ConnectionError, RuntimeError, ValueError):
|
|
267
|
+
pass
|
|
268
|
+
finally:
|
|
269
|
+
cli.close()
|
|
270
|
+
|
|
271
|
+
# ------------------------------------------------------------------ one round
|
|
272
|
+
def step(self) -> str:
|
|
273
|
+
now = self.clock()
|
|
274
|
+
if self.state == "leader":
|
|
275
|
+
acks, higher = 1, None
|
|
276
|
+
for addr in self.peers:
|
|
277
|
+
r = self._try(addr, {"op": "beat", "term": self.term, "name": self.name})
|
|
278
|
+
if r is None:
|
|
279
|
+
continue
|
|
280
|
+
if r["term"] > self.term:
|
|
281
|
+
higher = r["term"]
|
|
282
|
+
elif r["ok"]:
|
|
283
|
+
acks += 1
|
|
284
|
+
if higher is not None:
|
|
285
|
+
self._follower(higher); self.last_beat = now; self._changed("stepped down (higher term)")
|
|
286
|
+
elif acks >= self.majority:
|
|
287
|
+
self.last_majority = now
|
|
288
|
+
elif now - self.last_majority >= self.fail_after_s:
|
|
289
|
+
self._follower(self.term); self.last_beat = now; self._changed("stepped down (lost majority)")
|
|
290
|
+
return self.state
|
|
291
|
+
if now - self.last_beat < self.timeout:
|
|
292
|
+
self._pull()
|
|
293
|
+
return self.state
|
|
294
|
+
# no leader heard for a full timeout: stand for election
|
|
295
|
+
with self._lock:
|
|
296
|
+
self.term += 1
|
|
297
|
+
self.voted_for, self.state = self.name, "candidate"
|
|
298
|
+
self.hub.epoch = self.term
|
|
299
|
+
self._persist()
|
|
300
|
+
term = self.term
|
|
301
|
+
votes = 1
|
|
302
|
+
for addr in self.peers:
|
|
303
|
+
r = self._try(addr, {"op": "vote", "term": term, "candidate": self.name, "last_id": self.hub.last_id()})
|
|
304
|
+
if r is None:
|
|
305
|
+
continue
|
|
306
|
+
if r["term"] > term:
|
|
307
|
+
self._follower(r["term"]); self.last_beat = now
|
|
308
|
+
return self.state
|
|
309
|
+
if r["granted"]:
|
|
310
|
+
votes += 1
|
|
311
|
+
with self._lock:
|
|
312
|
+
if self.state == "candidate" and self.term == term and votes >= self.majority and not self.offline:
|
|
313
|
+
self.state = "leader"
|
|
314
|
+
self.hub.role = "active"
|
|
315
|
+
self.hub.requeue_running()
|
|
316
|
+
self.last_majority = self.clock()
|
|
317
|
+
self._changed("elected")
|
|
318
|
+
else:
|
|
319
|
+
self.state = "follower"
|
|
320
|
+
self.last_beat = now # back off for another timeout
|
|
321
|
+
return self.state
|
|
322
|
+
|
|
323
|
+
def start(self) -> "QuorumController":
|
|
324
|
+
def loop():
|
|
325
|
+
while not self._stop.wait(self.poll_s):
|
|
326
|
+
try:
|
|
327
|
+
self.step()
|
|
328
|
+
except Exception as e:
|
|
329
|
+
self.last_error = f"{type(e).__name__}: {e}"
|
|
330
|
+
threading.Thread(target=loop, daemon=True).start()
|
|
331
|
+
return self
|
|
332
|
+
|
|
333
|
+
def stop(self) -> None:
|
|
334
|
+
self._stop.set()
|
|
@@ -31,7 +31,8 @@ HISTORY = 2000 # samples kept per node
|
|
|
31
31
|
|
|
32
32
|
class Hub:
|
|
33
33
|
def __init__(self, ledger: Ledger | None = None, stale_after_s: float = 30.0, clock=time.time,
|
|
34
|
-
busy_cpu_pct: float = 90.0, gang_hold_s: float = 30.0, affinity_wait_s: float = 5.0
|
|
34
|
+
busy_cpu_pct: float = 90.0, gang_hold_s: float = 30.0, affinity_wait_s: float = 5.0,
|
|
35
|
+
max_finished: int = 5000, max_affinity: int = 10000):
|
|
35
36
|
self.nodes: dict[str, dict] = {}
|
|
36
37
|
self.series: dict[str, deque] = {}
|
|
37
38
|
self.tasks: dict[int, dict] = {}
|
|
@@ -51,6 +52,9 @@ class Hub:
|
|
|
51
52
|
self.role = "active" # "standby": answers only ping and role (see fleet/ha.py)
|
|
52
53
|
self.epoch = 1 # raised at every promotion; the higher epoch wins a split brain
|
|
53
54
|
self.name = "hub"
|
|
55
|
+
self.ha = None # a fleet.ha controller, if any
|
|
56
|
+
self.max_finished, self.max_affinity = max_finished, max_affinity # bounded memory: the soak test showed the hub grew without limit
|
|
57
|
+
self._finished: deque = deque() # ids of done/failed tasks, oldest first
|
|
54
58
|
|
|
55
59
|
# ------------------------------------------------------------------ identity
|
|
56
60
|
@staticmethod
|
|
@@ -180,7 +184,7 @@ class Hub:
|
|
|
180
184
|
g["reserved"] = {nd: exp for nd, exp in g["reserved"].items() if exp > now}
|
|
181
185
|
for g in self.gangs.values(): # a node held for a gang serves only that gang
|
|
182
186
|
if node in g["reserved"]:
|
|
183
|
-
mine = [self.tasks[t] for t in g["tasks"] if self.tasks[t]["state"] == "queued" and self._eligible(node, self.tasks[t]["needs"])]
|
|
187
|
+
mine = [self.tasks[t] for t in g["tasks"] if t in self.tasks and self.tasks[t]["state"] == "queued" and self._eligible(node, self.tasks[t]["needs"])]
|
|
184
188
|
if not mine:
|
|
185
189
|
return None
|
|
186
190
|
return self._assign(min(mine, key=lambda t: t["id"]), node, now, g, "held for its gang")
|
|
@@ -199,7 +203,7 @@ class Hub:
|
|
|
199
203
|
continue # the node holding its cache is free: wait for it
|
|
200
204
|
g = self.gangs.get(t["gang"]) if t["gang"] else None
|
|
201
205
|
if g is not None:
|
|
202
|
-
missing = sum(1 for x in g["tasks"] if self.tasks[x]["state"] == "queued")
|
|
206
|
+
missing = sum(1 for x in g["tasks"] if x in self.tasks and self.tasks[x]["state"] == "queued")
|
|
203
207
|
if len(self._gang_nodes(g, t["needs"], now, node)) + 1 < missing:
|
|
204
208
|
continue # not enough idle nodes for the whole gang yet
|
|
205
209
|
tn = t["tenant"]
|
|
@@ -237,13 +241,21 @@ class Hub:
|
|
|
237
241
|
t.update(state="done" if ok else "failed", finished=self.clock(), result=value, error=error, wall_s=wall_s)
|
|
238
242
|
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()))
|
|
239
243
|
if ok and t["needs"].get("affinity"):
|
|
244
|
+
self.affinity.pop(t["needs"]["affinity"], None)
|
|
240
245
|
self.affinity[t["needs"]["affinity"]] = node
|
|
246
|
+
while len(self.affinity) > self.max_affinity:
|
|
247
|
+
self.affinity.pop(next(iter(self.affinity)))
|
|
248
|
+
self._finished.append(task_id)
|
|
249
|
+
while len(self._finished) > self.max_finished: # forget the oldest finished tasks (and gangs with no task left)
|
|
250
|
+
self.tasks.pop(self._finished.popleft(), None)
|
|
251
|
+
if len(self.gangs) > 64:
|
|
252
|
+
self.gangs = {k: g for k, g in self.gangs.items() if any(x in self.tasks for x in g["tasks"])}
|
|
241
253
|
|
|
242
254
|
def task(self, task_id: int) -> dict:
|
|
243
255
|
with self._lock:
|
|
244
256
|
t = self.tasks.get(task_id)
|
|
245
257
|
if t is None:
|
|
246
|
-
raise KeyError(f"unknown task {task_id}")
|
|
258
|
+
raise KeyError(f"unknown task {task_id} (never existed, or finished long ago and was forgotten: the hub keeps the last {self.max_finished} finished tasks)")
|
|
247
259
|
return {k: v for k, v in t.items()}
|
|
248
260
|
|
|
249
261
|
|
|
@@ -256,6 +268,10 @@ class Hub:
|
|
|
256
268
|
"usage": self.usage, "weights": self.weights, "affinity": self.affinity,
|
|
257
269
|
"gangs": [{**g, "reserved": {}} for g in self.gangs.values()]}
|
|
258
270
|
|
|
271
|
+
def last_id(self) -> int:
|
|
272
|
+
with self._lock:
|
|
273
|
+
return max(self.tasks, default=0)
|
|
274
|
+
|
|
259
275
|
def requeue_running(self) -> int:
|
|
260
276
|
"""Put running tasks back in the queue (at-least-once: the allow-listed workloads are pure
|
|
261
277
|
functions); if the agent still finishes one, its result is accepted."""
|
|
@@ -275,6 +291,7 @@ class Hub:
|
|
|
275
291
|
self.tasks = {int(t["id"]): t for t in snap["tasks"]}
|
|
276
292
|
self.queue = deque(int(i) for i in snap["queue"])
|
|
277
293
|
self.epoch = max(self.epoch, int(snap.get("epoch", 1)))
|
|
294
|
+
self._finished = deque(t["id"] for t in sorted(self.tasks.values(), key=lambda t: t["id"]) if t["state"] in ("done", "failed"))
|
|
278
295
|
requeued = self.requeue_running() if requeue else 0
|
|
279
296
|
self.usage, self.weights, self.affinity = dict(snap["usage"]), dict(snap["weights"]), dict(snap["affinity"])
|
|
280
297
|
self.gangs = {int(g["id"]): {**g, "started": [], "reserved": {}} for g in snap["gangs"]}
|
|
@@ -415,9 +432,16 @@ def make_handler(hub: Hub):
|
|
|
415
432
|
if op == "ping":
|
|
416
433
|
return {"pong": True}, b""
|
|
417
434
|
if op == "role":
|
|
418
|
-
return {"role": hub.role, "epoch": hub.epoch, "name": hub.name}, b""
|
|
435
|
+
return {"role": hub.role, "epoch": hub.epoch, "name": hub.name, "lease": hub.ha.lease_ok() if hub.ha else True}, b""
|
|
436
|
+
if op in ("vote", "beat"):
|
|
437
|
+
require("fleet:replicate")
|
|
438
|
+
if not hasattr(hub.ha, "on_" + op):
|
|
439
|
+
raise RuntimeError("this hub is not part of a quorum")
|
|
440
|
+
return getattr(hub.ha, "on_" + op)(h), b""
|
|
419
441
|
if hub.role != "active":
|
|
420
442
|
raise RuntimeError(f"standby: {hub.name} is not the active hub")
|
|
443
|
+
if hub.ha is not None and not hub.ha.lease_ok():
|
|
444
|
+
raise RuntimeError("no quorum: this hub lost contact with a majority and refuses requests")
|
|
421
445
|
if op == "snapshot":
|
|
422
446
|
require("fleet:replicate")
|
|
423
447
|
return {"epoch": hub.epoch}, json.dumps(hub.snapshot()).encode()
|
|
@@ -475,6 +499,7 @@ def main():
|
|
|
475
499
|
ap.add_argument("--state-file", help="save tasks, queue, tenant usage here every 5 s and reload it at start")
|
|
476
500
|
ap.add_argument("--peer", action="append", default=[], help="host:port of another hub (repeatable): active/standby with automatic promotion")
|
|
477
501
|
ap.add_argument("--peer-token-file", help="token this hub presents to its peers (scope fleet:replicate); default: --token-file")
|
|
502
|
+
ap.add_argument("--max-finished", type=int, default=5000, help="finished tasks kept in memory (older ones are forgotten)")
|
|
478
503
|
ap.add_argument("--name", default="hub", help="this hub's name (HA tie-break: the smaller name stays active)")
|
|
479
504
|
ap.add_argument("--fail-after", type=float, default=6.0, help="seconds without an active peer before a standby promotes itself")
|
|
480
505
|
a = ap.parse_args()
|
|
@@ -483,6 +508,7 @@ def main():
|
|
|
483
508
|
srv, hub = serve_hub(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
|
|
484
509
|
authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None,
|
|
485
510
|
ledger=Ledger(a.decision_log))
|
|
511
|
+
hub.max_finished = a.max_finished
|
|
486
512
|
if a.state_file:
|
|
487
513
|
print("restored", hub.load(a.state_file), flush=True)
|
|
488
514
|
if a.peer:
|
|
@@ -490,7 +516,10 @@ def main():
|
|
|
490
516
|
ptf = a.peer_token_file or a.token_file
|
|
491
517
|
if ptf is None:
|
|
492
518
|
raise SystemExit("--peer needs --peer-token-file (a scoped token with fleet:replicate) or --token-file")
|
|
493
|
-
|
|
519
|
+
from .ha import QuorumController
|
|
520
|
+
cls = QuorumController if len(a.peer) >= 2 else HAController # 3 or more hubs: majority election
|
|
521
|
+
kw = {"meta_path": a.state_file + ".term"} if (cls is QuorumController and a.state_file) else {}
|
|
522
|
+
cls(hub, Path(ptf).read_bytes(), a.peer, a.name, fail_after_s=a.fail_after, **kw).start()
|
|
494
523
|
if a.state_file:
|
|
495
524
|
hub.autosave(a.state_file)
|
|
496
525
|
print(f"PORT {srv.port}", flush=True)
|