spatial-computing 0.7.0__py3-none-any.whl → 0.8.0__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.7.0"
6
+ __version__ = "0.8.0"
spatial/cli.py CHANGED
@@ -83,10 +83,27 @@ def cmd_bench(a):
83
83
  return rc
84
84
 
85
85
 
86
+ def cmd_token(a):
87
+ from .core import auth
88
+ if a.action == "init":
89
+ auth.init_master_key(a.master_key_file)
90
+ print(f"master key written to {a.master_key_file} (mode 600). Keep it private; it can issue any credential.")
91
+ return 0
92
+ az = auth.authorizer_from_file(a.master_key_file)
93
+ print(az.issue(a.name, [s for s in a.scopes.split(",") if s], ttl_s=a.ttl, max_ops=a.max_ops, max_bytes=a.max_bytes))
94
+ return 0
95
+
96
+
86
97
  def cmd_worker(a):
87
98
  mod = {"compute": "spatial.compute.worker", "memory": "spatial.memory.pageserver",
88
99
  "runtime": "spatial.runtime.runner"}[a.kind]
89
- cmd = [sys.executable, "-m", mod, "--token-file", a.token_file, "--host", a.host, "--port", str(a.port)]
100
+ cmd = [sys.executable, "-m", mod, "--host", a.host, "--port", str(a.port)]
101
+ if a.token_file:
102
+ cmd += ["--token-file", a.token_file]
103
+ if a.master_key_file:
104
+ cmd += ["--master-key-file", a.master_key_file]
105
+ if a.audit_log:
106
+ cmd += ["--audit-log", a.audit_log]
90
107
  if a.allow_remote:
91
108
  cmd.append("--allow-remote")
92
109
  return subprocess.run(cmd).returncode
@@ -116,12 +133,25 @@ def main(argv=None):
116
133
  p.set_defaults(fn=cmd_bench)
117
134
  p = sub.add_parser("serve", help="start a compute worker, a page server or a sandboxed binary runner (loopback by default)")
118
135
  p.add_argument("kind", choices=["compute", "memory", "runtime"])
119
- p.add_argument("--token-file", required=True)
136
+ p.add_argument("--token-file", help="shared secret: every client may do everything")
137
+ p.add_argument("--master-key-file", help="scoped credentials with quotas and an audit log (see `spatial token`)")
138
+ p.add_argument("--audit-log")
120
139
  p.add_argument("--host", default="127.0.0.1")
121
140
  p.add_argument("--port", type=int, default=0)
122
141
  p.add_argument("--allow-remote", action="store_true", help="explicit consent to accept LAN connections")
123
142
  p.set_defaults(fn=cmd_worker)
143
+ p = sub.add_parser("token", help="scoped credentials: `init` a master key, `issue` a tenant token")
144
+ p.add_argument("action", choices=["init", "issue"])
145
+ p.add_argument("--master-key-file", required=True)
146
+ p.add_argument("--name", default="tenant")
147
+ p.add_argument("--scopes", default="", help="comma list, e.g. run:mandel_numba,mem:read,exec:elf (trailing * = prefix)")
148
+ p.add_argument("--ttl", type=float, default=3600, help="seconds")
149
+ p.add_argument("--max-ops", type=int)
150
+ p.add_argument("--max-bytes", type=int)
151
+ p.set_defaults(fn=cmd_token)
124
152
  a = ap.parse_args(argv)
153
+ if getattr(a, "cmd", None) == "serve" and bool(a.token_file) == bool(a.master_key_file):
154
+ ap.error("serve needs exactly one of --token-file or --master-key-file")
125
155
  try:
126
156
  return a.fn(a)
127
157
  except (Exception, SystemExit) as e: # user-facing tool: one clean line, no traceback
spatial/compute/worker.py CHANGED
@@ -14,6 +14,7 @@ import sys
14
14
  import time
15
15
  from pathlib import Path
16
16
 
17
+ from ..core.auth import authorizer_from_file, require
17
18
  from ..core.protocol import RpcClient, RpcServer
18
19
  from . import workloads
19
20
 
@@ -23,6 +24,7 @@ def _handler(header: dict, blob: bytes):
23
24
  if op == "ping":
24
25
  return {"pong": True, "pid": os.getpid()}, b""
25
26
  if op == "run":
27
+ require(f"run:{header.get('workload')}")
26
28
  t = os.times()
27
29
  c0, w0 = t.user + t.system, time.perf_counter()
28
30
  result = workloads.run(header["workload"], **header.get("params", {}))
@@ -32,8 +34,9 @@ def _handler(header: dict, blob: bytes):
32
34
  raise ValueError(f"unknown op {op!r}")
33
35
 
34
36
 
35
- def serve(token: bytes, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False) -> RpcServer:
36
- return RpcServer(_handler, token, host=host, port=port, allow_remote=allow_remote)
37
+ def serve(token: bytes | None, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False,
38
+ authorizer=None) -> RpcServer:
39
+ return RpcServer(_handler, token, host=host, port=port, allow_remote=allow_remote, authorizer=authorizer)
37
40
 
38
41
 
39
42
  class LocalWorkerProcess:
@@ -74,13 +77,18 @@ class LocalWorkerProcess:
74
77
 
75
78
  def main():
76
79
  ap = argparse.ArgumentParser()
77
- ap.add_argument("--token-file", required=True)
80
+ ap.add_argument("--token-file", help="shared secret (every client may do everything)")
81
+ ap.add_argument("--master-key-file", help="issue scoped credentials instead (see `spatial token`)")
82
+ ap.add_argument("--audit-log")
78
83
  ap.add_argument("--host", default="127.0.0.1")
79
84
  ap.add_argument("--port", type=int, default=0)
80
85
  ap.add_argument("--allow-remote", action="store_true",
81
86
  help="explicit consent to accept non-loopback connections")
82
87
  a = ap.parse_args()
83
- srv = serve(Path(a.token_file).read_bytes(), a.host, a.port, a.allow_remote)
88
+ if bool(a.token_file) == bool(a.master_key_file):
89
+ raise SystemExit("give exactly one of --token-file or --master-key-file")
90
+ srv = serve(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
91
+ authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None)
84
92
  print(f"PORT {srv.port}", flush=True)
85
93
  srv.serve_forever()
86
94
 
spatial/core/auth.py ADDED
@@ -0,0 +1,170 @@
1
+ """Scoped credentials, quotas and an audit trail for SWP/2 services.
2
+
3
+ A server started with a master key issues credentials to tenants. A credential names the
4
+ tenant, the scopes it may use, an expiry and optional quotas; it is signed with the master
5
+ key, so the server needs no database. The tenant's per-credential secret is
6
+ HMAC(master, credential): only the issuer can derive it, and it is what authenticates the
7
+ handshake. The token handed to a tenant is "<credential>~<secret hex>".
8
+
9
+ Scopes are strings such as "run:mandel_numba", "mem:read", "mem:write", "exec:elf"; a trailing
10
+ "*" matches a prefix ("run:*", "*"). Services call require(scope) before acting.
11
+ Every request (allowed or denied) is appended to a hash-chained audit ledger.
12
+
13
+ Limits: revocation and usage counters live in the server process (restart resets counters);
14
+ a stolen token works until it expires or is revoked.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import base64
19
+ import hashlib
20
+ import hmac
21
+ import json
22
+ import threading
23
+ import time
24
+ from dataclasses import dataclass, field
25
+
26
+ from .ledger import Ledger
27
+
28
+ PREFIX = "spc1"
29
+
30
+
31
+ class QuotaExceeded(Exception):
32
+ pass
33
+
34
+
35
+ class AuthError(Exception):
36
+ pass
37
+
38
+
39
+ @dataclass
40
+ class Principal:
41
+ name: str
42
+ scopes: tuple[str, ...]
43
+ expires: float
44
+ max_ops: int | None = None
45
+ max_bytes: int | None = None
46
+ cred: str = ""
47
+ ops: int = 0
48
+ nbytes: int = 0
49
+ lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
50
+
51
+ def allows(self, scope: str) -> bool:
52
+ for s in self.scopes:
53
+ if s == "*" or s == scope or (s.endswith("*") and scope.startswith(s[:-1])):
54
+ return True
55
+ return False
56
+
57
+
58
+ _ctx = threading.local()
59
+
60
+
61
+ def current() -> Principal | None:
62
+ return getattr(_ctx, "principal", None)
63
+
64
+
65
+ def set_current(p: Principal | None) -> None:
66
+ _ctx.principal = p
67
+
68
+
69
+ def require(scope: str) -> None:
70
+ """Raise PermissionError unless the calling tenant holds `scope` (always true without auth)."""
71
+ p = current()
72
+ if p is not None and not p.allows(scope):
73
+ raise PermissionError(f"scope '{scope}' not granted to '{p.name}'")
74
+
75
+
76
+ def _b64(b: bytes) -> str:
77
+ return base64.urlsafe_b64encode(b).decode().rstrip("=")
78
+
79
+
80
+ def _unb64(s: str) -> bytes:
81
+ return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
82
+
83
+
84
+ class Authorizer:
85
+ def __init__(self, master_key: bytes, audit: Ledger | None = None):
86
+ if len(master_key) < 16:
87
+ raise ValueError("master key must be at least 16 bytes")
88
+ self._master = master_key
89
+ self.audit = audit
90
+ self._revoked: set[str] = set()
91
+ self._seen: dict[str, Principal] = {}
92
+
93
+ def _sig(self, payload: str) -> str:
94
+ return hmac.new(self._master, b"sig|" + payload.encode(), hashlib.sha256).hexdigest()[:32]
95
+
96
+ def secret_for(self, cred: str) -> bytes:
97
+ return hmac.new(self._master, b"secret|" + cred.encode(), hashlib.sha256).digest()
98
+
99
+ def issue(self, name: str, scopes: list[str], ttl_s: float = 3600, max_ops: int | None = None,
100
+ max_bytes: int | None = None) -> str:
101
+ body = {"n": name, "s": list(scopes), "e": time.time() + ttl_s}
102
+ if max_ops is not None:
103
+ body["o"] = max_ops
104
+ if max_bytes is not None:
105
+ body["b"] = max_bytes
106
+ payload = _b64(json.dumps(body, separators=(",", ":")).encode())
107
+ cred = f"{PREFIX}.{payload}.{self._sig(payload)}"
108
+ return f"{cred}~{self.secret_for(cred).hex()}"
109
+
110
+ def revoke(self, name: str) -> None:
111
+ self._revoked.add(name)
112
+
113
+ def principal(self, cred: str) -> Principal:
114
+ """Verify signature, expiry and revocation. Raises AuthError."""
115
+ try:
116
+ prefix, payload, sig = cred.split(".")
117
+ except ValueError:
118
+ raise AuthError("malformed credential")
119
+ if prefix != PREFIX or not hmac.compare_digest(sig, self._sig(payload)):
120
+ raise AuthError("bad credential signature")
121
+ body = json.loads(_unb64(payload))
122
+ if body["e"] < time.time():
123
+ raise AuthError("credential expired")
124
+ if body["n"] in self._revoked:
125
+ raise AuthError("credential revoked")
126
+ if cred not in self._seen:
127
+ self._seen[cred] = Principal(body["n"], tuple(body["s"]), body["e"], body.get("o"), body.get("b"), cred)
128
+ return self._seen[cred]
129
+
130
+ def charge(self, p: Principal, nbytes: int) -> None:
131
+ with p.lock:
132
+ if p.max_ops is not None and p.ops + 1 > p.max_ops:
133
+ raise QuotaExceeded(f"'{p.name}' exceeded {p.max_ops} operations")
134
+ if p.max_bytes is not None and p.nbytes + nbytes > p.max_bytes:
135
+ raise QuotaExceeded(f"'{p.name}' exceeded {p.max_bytes} bytes")
136
+ p.ops += 1
137
+ p.nbytes += nbytes
138
+
139
+ def log(self, p: Principal | None, op: str, ok: bool, detail: str = "", nbytes: int = 0) -> None:
140
+ if self.audit is not None:
141
+ self.audit.decide("auth", f"{p.name if p else '?'}:{op}", "allowed" if ok else f"denied: {detail}",
142
+ ok=ok, bytes=nbytes)
143
+
144
+
145
+ def parse_token(token: bytes) -> tuple[bytes, bytes]:
146
+ """(credential, secret) from a client token. A plain shared token has no credential."""
147
+ t = token.decode(errors="ignore") if token.startswith(PREFIX.encode() + b".") else ""
148
+ if t and "~" in t:
149
+ cred, secret_hex = t.split("~", 1)
150
+ return cred.encode(), bytes.fromhex(secret_hex.strip())
151
+ return b"", token
152
+
153
+
154
+ def init_master_key(path) -> None:
155
+ """Create a random 32-byte master key file (mode 600). Refuses to overwrite."""
156
+ import os
157
+ from pathlib import Path
158
+ p = Path(path)
159
+ if p.exists():
160
+ raise FileExistsError(f"{p} already exists; refusing to overwrite a master key")
161
+ p.parent.mkdir(parents=True, exist_ok=True)
162
+ fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
163
+ with os.fdopen(fd, "wb") as f:
164
+ f.write(os.urandom(32))
165
+
166
+
167
+ def authorizer_from_file(master_key_file, audit_path=None) -> Authorizer:
168
+ from pathlib import Path
169
+ audit = Ledger(audit_path) if audit_path else Ledger(Path.home() / ".spatial" / "audit.jsonl")
170
+ return Authorizer(Path(master_key_file).read_bytes(), audit)
spatial/core/protocol.py CHANGED
@@ -1,18 +1,22 @@
1
- """SPATIAL wire protocol v1 (SWP/1): authenticated AND encrypted RPC over TCP.
2
-
3
- Handshake server -> client : nonce_s (16 bytes)
4
- client -> server : HMAC-SHA256(token, nonce_s) (32 bytes) | nonce_c (16 bytes)
5
- Keys HKDF-SHA256(token, salt = nonce_s | nonce_c) -> one AES-256-GCM key per direction
1
+ """SPATIAL wire protocol v2 (SWP/2): authenticated, encrypted, forward-secret RPC over TCP.
2
+
3
+ Handshake server -> client : nonce_s (16) | server ephemeral X25519 public key (32)
4
+ client -> server : u16 cred_len | credential | client ephemeral public key (32) | nonce_c (16)
5
+ | HMAC-SHA256(secret, "SWP2c" | nonce_s | pub_s | pub_c | nonce_c | credential) (32)
6
+ Secret the shared token, or, with scoped credentials, HMAC(master, credential) (see auth.py)
7
+ Keys HKDF-SHA256(ikm = X25519 shared secret | secret, salt = nonce_s | nonce_c)
8
+ -> one AES-256-GCM key per direction
6
9
  Record u32 length | AES-GCM(ciphertext | tag), nonce = 4 zero bytes | u64 record counter
7
10
  Plaintext u32 header_len | u32 blob_len | header (JSON utf-8) | blob (raw bytes)
8
11
 
9
- Properties: the token never crosses the wire; every record is confidential and
10
- integrity-protected; a replayed, reordered or modified record fails authentication.
11
- Not provided: forward secrecy (a stolen token decrypts recorded sessions) and peer
12
- identity beyond "knows the token". Use TLS/WireGuard on top for stronger guarantees.
12
+ Properties: the secret never crosses the wire; every record is confidential and integrity-
13
+ protected; replayed, reordered or modified records fail authentication; the ephemeral keys
14
+ are discarded after the handshake, so recorded sessions stay unreadable even if the secret is
15
+ stolen later (FORWARD SECRECY). A party that holds the secret *during* a session can still
16
+ impersonate (the secret is the only identity). Use TLS/WireGuard when you need certificates.
13
17
 
14
18
  Safety: servers bind to 127.0.0.1 unless allow_remote=True is passed explicitly.
15
- No code is ever transferred: requests name allow-listed operations.
19
+ No code is ever transferred except by the sandboxed runner: requests name allow-listed operations.
16
20
  """
17
21
  from __future__ import annotations
18
22
 
@@ -27,13 +31,17 @@ import threading
27
31
  from typing import Callable
28
32
 
29
33
  from cryptography.exceptions import InvalidTag
30
- from cryptography.hazmat.primitives import hashes
34
+ from cryptography.hazmat.primitives import hashes, serialization
35
+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
31
36
  from cryptography.hazmat.primitives.ciphers.aead import AESGCM
32
37
  from cryptography.hazmat.primitives.kdf.hkdf import HKDF
33
38
 
39
+ from . import auth
40
+
34
41
  _HDR = struct.Struct(">II")
35
42
  _LEN = struct.Struct(">I")
36
43
  MAX_FRAME = 256 * 1024 * 1024
44
+ _RAW = dict(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw)
37
45
 
38
46
 
39
47
  def _recv_exact(sock: socket.socket, n: int) -> bytes:
@@ -51,8 +59,8 @@ def _recv_exact(sock: socket.socket, n: int) -> bytes:
51
59
  class SecureChannel:
52
60
  """Encrypted, ordered record channel over a connected socket."""
53
61
 
54
- def __init__(self, sock: socket.socket, token: bytes, nonce_s: bytes, nonce_c: bytes, is_server: bool):
55
- okm = HKDF(algorithm=hashes.SHA256(), length=64, salt=nonce_s + nonce_c, info=b"SWP/1 keys").derive(token)
62
+ def __init__(self, sock: socket.socket, ikm: bytes, nonce_s: bytes, nonce_c: bytes, is_server: bool):
63
+ okm = HKDF(algorithm=hashes.SHA256(), length=64, salt=nonce_s + nonce_c, info=b"SWP/2 keys").derive(ikm)
56
64
  c2s, s2c = AESGCM(okm[:32]), AESGCM(okm[32:])
57
65
  self._tx, self._rx = (s2c, c2s) if is_server else (c2s, s2c)
58
66
  self._ntx = self._nrx = 0
@@ -81,43 +89,79 @@ class SecureChannel:
81
89
  return header, plain[_HDR.size + hl:]
82
90
 
83
91
 
92
+ def _mac(secret: bytes, nonce_s: bytes, pub_s: bytes, pub_c: bytes, nonce_c: bytes, cred: bytes) -> bytes:
93
+ return hmac.new(secret, b"SWP2c" + nonce_s + pub_s + pub_c + nonce_c + cred, hashlib.sha256).digest()
94
+
95
+
84
96
  Handler = Callable[[dict, bytes], tuple[dict, bytes]]
85
97
 
86
98
 
87
99
  class RpcServer:
88
- """Threaded RPC server. Loopback-only by default."""
100
+ """Threaded RPC server. Loopback-only by default.
89
101
 
90
- def __init__(self, handler: Handler, token: bytes, host: str = "127.0.0.1",
91
- port: int = 0, allow_remote: bool = False):
102
+ token : shared secret (every client is trusted with every scope), or None
103
+ authorizer : scoped credentials, quotas, audit (see auth.py); takes precedence over token
104
+ """
105
+
106
+ 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):
92
108
  if host not in ("127.0.0.1", "localhost", "::1") and not allow_remote:
93
109
  raise PermissionError(
94
110
  "refusing to bind a non-loopback address without allow_remote=True "
95
111
  "(explicit user consent required to expose this machine)")
112
+ if token is None and authorizer is None:
113
+ raise ValueError("RpcServer needs a token or an authorizer")
96
114
  outer = self
97
115
 
98
116
  class _H(socketserver.BaseRequestHandler):
99
117
  def handle(self):
100
118
  s = self.request
101
119
  s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
120
+ eph = X25519PrivateKey.generate()
121
+ pub_s = eph.public_key().public_bytes(**_RAW)
102
122
  nonce_s = os.urandom(16)
103
- s.sendall(nonce_s)
104
123
  try:
105
- hello = _recv_exact(s, 48)
106
- except ConnectionError:
124
+ s.sendall(nonce_s + pub_s)
125
+ (cl,) = struct.unpack(">H", _recv_exact(s, 2))
126
+ cred = _recv_exact(s, cl)
127
+ pub_c, nonce_c, mac = _recv_exact(s, 32), _recv_exact(s, 16), _recv_exact(s, 32)
128
+ except (ConnectionError, OSError):
107
129
  return
108
- if not hmac.compare_digest(hello[:32], hmac.new(token, nonce_s, hashlib.sha256).digest()):
109
- return # silent drop on bad auth
110
- ch = SecureChannel(s, token, nonce_s, hello[32:], is_server=True)
130
+ principal = None
131
+ if authorizer is not None:
132
+ try:
133
+ principal = authorizer.principal(cred.decode())
134
+ except (auth.AuthError, ValueError, UnicodeDecodeError, KeyError):
135
+ return # silent drop
136
+ secret = authorizer.secret_for(cred.decode())
137
+ else:
138
+ if cred:
139
+ return
140
+ secret = token
141
+ if not hmac.compare_digest(mac, _mac(secret, nonce_s, pub_s, pub_c, nonce_c, cred)):
142
+ return # silent drop on bad auth
143
+ shared = eph.exchange(X25519PublicKey.from_public_bytes(pub_c))
144
+ ch = SecureChannel(s, shared + secret, nonce_s, nonce_c, is_server=True)
111
145
  while True:
112
146
  try:
113
147
  header, blob = ch.recv()
114
148
  except (ConnectionError, OSError, ValueError):
115
149
  return
150
+ op = str(header.get("op"))
116
151
  try:
152
+ if principal is not None:
153
+ authorizer.charge(principal, len(blob))
154
+ auth.set_current(principal)
117
155
  rh, rb = outer.handler(header, blob)
118
156
  rh.setdefault("ok", True)
157
+ if authorizer is not None:
158
+ authorizer.log(principal, op, True, nbytes=len(blob))
119
159
  except Exception as e: # report, never crash the server
120
160
  rh, rb = {"ok": False, "error": f"{type(e).__name__}: {e}"}, b""
161
+ if authorizer is not None:
162
+ authorizer.log(principal, op, False, f"{type(e).__name__}: {e}", len(blob))
163
+ finally:
164
+ auth.set_current(None)
121
165
  ch.send(rh, rb)
122
166
 
123
167
  class _S(socketserver.ThreadingTCPServer):
@@ -143,13 +187,20 @@ class RpcServer:
143
187
 
144
188
 
145
189
  class RpcClient:
190
+ """token: the shared secret, or a scoped token string from Authorizer.issue()."""
191
+
146
192
  def __init__(self, host: str, port: int, token: bytes, timeout: float = 120.0):
193
+ cred, secret = auth.parse_token(token)
147
194
  self.sock = socket.create_connection((host, port), timeout=timeout)
148
195
  self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
149
- nonce_s = _recv_exact(self.sock, 16)
150
- nonce_c = os.urandom(16)
151
- self.sock.sendall(hmac.new(token, nonce_s, hashlib.sha256).digest() + nonce_c)
152
- self._ch = SecureChannel(self.sock, token, nonce_s, nonce_c, is_server=False)
196
+ hello = _recv_exact(self.sock, 48)
197
+ nonce_s, pub_s = hello[:16], hello[16:]
198
+ eph = X25519PrivateKey.generate()
199
+ pub_c, nonce_c = eph.public_key().public_bytes(**_RAW), os.urandom(16)
200
+ self.sock.sendall(struct.pack(">H", len(cred)) + cred + pub_c + nonce_c
201
+ + _mac(secret, nonce_s, pub_s, pub_c, nonce_c, cred))
202
+ shared = eph.exchange(X25519PublicKey.from_public_bytes(pub_s))
203
+ self._ch = SecureChannel(self.sock, shared + secret, nonce_s, nonce_c, is_server=False)
153
204
  self._lock = threading.Lock()
154
205
 
155
206
  def call(self, header: dict, blob: bytes = b"") -> tuple[dict, bytes]:
@@ -17,6 +17,7 @@ import threading
17
17
  import time
18
18
  from pathlib import Path
19
19
 
20
+ from ..core.auth import authorizer_from_file, require
20
21
  from ..core.protocol import RpcClient, RpcServer
21
22
 
22
23
 
@@ -41,6 +42,7 @@ class PageStore:
41
42
 
42
43
  def handle(self, h: dict, blob: bytes):
43
44
  op = h["op"]
45
+ require("mem:write" if op in ("put", "del", "vput") else "mem:read")
44
46
  if op == "put":
45
47
  if self.bytes + len(blob) > self.max_bytes:
46
48
  raise MemoryError("page server quota exceeded")
@@ -124,7 +126,9 @@ class LocalPageServer:
124
126
 
125
127
  def main():
126
128
  ap = argparse.ArgumentParser()
127
- ap.add_argument("--token-file", required=True)
129
+ ap.add_argument("--token-file", help="shared secret (every client may do everything)")
130
+ ap.add_argument("--master-key-file", help="issue scoped credentials instead (see `spatial token`)")
131
+ ap.add_argument("--audit-log")
128
132
  ap.add_argument("--host", default="127.0.0.1")
129
133
  ap.add_argument("--port", type=int, default=0)
130
134
  ap.add_argument("--delay-ms", type=float, default=0.0)
@@ -132,7 +136,10 @@ def main():
132
136
  ap.add_argument("--allow-remote", action="store_true")
133
137
  a = ap.parse_args()
134
138
  store = PageStore(a.delay_ms, a.mbps)
135
- srv = RpcServer(store.handle, Path(a.token_file).read_bytes(), a.host, a.port, a.allow_remote)
139
+ if bool(a.token_file) == bool(a.master_key_file):
140
+ raise SystemExit("give exactly one of --token-file or --master-key-file")
141
+ srv = RpcServer(store.handle, Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port,
142
+ a.allow_remote, authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None)
136
143
  print(f"PORT {srv.port}", flush=True)
137
144
  srv.serve_forever()
138
145
 
spatial/q/compiler.py CHANGED
@@ -211,6 +211,69 @@ def _key(o: Op):
211
211
  return tuple(sorted(o.qubits)) if o.name in _SYMMETRIC else o.qubits
212
212
 
213
213
 
214
+ _DIAG_1Q = {"z", "s", "sdg", "t", "tdg", "rz", "p"}
215
+ _DIAG_ANY = _DIAG_1Q | {"cz", "cp", "crz"}
216
+ _X_1Q = {"x", "rx"}
217
+
218
+
219
+ def _commutes(g: Op, o: Op, q: int) -> bool:
220
+ """Does single-qubit gate `g` (acting on q) commute with `o`, which also touches q?"""
221
+ if o.cond or o.name in ("measure", "reset"):
222
+ return False
223
+ if g.name in _DIAG_1Q: # diagonal: commutes with diagonal gates and with controls
224
+ if o.name in _DIAG_ANY:
225
+ return True
226
+ if o.name == "cx":
227
+ return o.qubits[0] == q # control
228
+ if o.name == "ccx":
229
+ return q in o.qubits[:2]
230
+ return False
231
+ if g.name in _X_1Q: # X-type: commutes with X-type and with a CX/CCX target
232
+ if o.name in _X_1Q:
233
+ return True
234
+ if o.name == "cx":
235
+ return o.qubits[1] == q
236
+ if o.name == "ccx":
237
+ return o.qubits[2] == q
238
+ return False
239
+
240
+
241
+ def _merge(prev: Op, g: Op):
242
+ """Result of applying prev then g on the same qubit: Op, None (cancel) or "no" (not mergeable)."""
243
+ if prev.cond or prev.qubits != g.qubits:
244
+ return "no"
245
+ if prev.name == g.name and g.name in _SELF_INVERSE:
246
+ return None
247
+ if (prev.name, g.name) in _INVERSE_PAIR:
248
+ return None
249
+ if prev.name == g.name and g.name in ("rz", "rx", "p"):
250
+ return Op(g.name, g.qubits, (prev.params[0] + g.params[0],))
251
+ return "no"
252
+
253
+
254
+ def _commute_pass(ops: list) -> tuple[list, bool]:
255
+ """Move single-qubit gates backwards across gates they commute with, to meet and merge with
256
+ an earlier gate of the same kind (e.g. rz a; cx q0,q1; rz b -> rz (a+b); cx q0,q1)."""
257
+ ops, changed = list(ops), False
258
+ for i, g in enumerate(ops):
259
+ if g is None or g.cond or len(g.qubits) != 1 or g.name not in (_DIAG_1Q | _X_1Q):
260
+ continue
261
+ q = g.qubits[0]
262
+ for j in range(i - 1, -1, -1):
263
+ o = ops[j]
264
+ if o is None or q not in o.qubits:
265
+ continue
266
+ m = _merge(o, g) if len(o.qubits) == 1 else "no"
267
+ if m != "no":
268
+ ops[j] = m
269
+ ops[i] = None
270
+ changed = True
271
+ break
272
+ if not _commutes(g, o, q):
273
+ break
274
+ return [o for o in ops if o is not None], changed
275
+
276
+
214
277
  def optimize(c: Circuit) -> tuple[Circuit, dict]:
215
278
  """Peephole passes to a fixed point: cancel adjacent inverse pairs, merge same-axis
216
279
  rotations, drop identity rotations. 'Adjacent' = no other op touches those qubits in
@@ -264,6 +327,8 @@ def optimize(c: Circuit) -> tuple[Circuit, dict]:
264
327
  changed = True
265
328
  continue
266
329
  ops.append(o)
330
+ ops, moved = _commute_pass(ops)
331
+ changed = changed or moved
267
332
  oc = Circuit(c.name, c.n_qubits, c.n_cbits, ops)
268
333
  return oc, {"ops_before": before, "ops_after": len(ops), "passes": passes}
269
334
 
spatial/runtime/runner.py CHANGED
@@ -14,6 +14,7 @@ import sys
14
14
  import tempfile
15
15
  from pathlib import Path
16
16
 
17
+ from ..core.auth import authorizer_from_file, require
17
18
  from ..core.protocol import RpcClient, RpcServer
18
19
  from . import microvm
19
20
  from .inspect import inspect
@@ -28,6 +29,7 @@ def _handler(h: dict, blob: bytes):
28
29
  return {"pong": True, "microvm": microvm.available()}, b""
29
30
  if op != "run_elf":
30
31
  raise ValueError(f"unknown op {op!r}")
32
+ require("exec:elf")
31
33
  if len(blob) > MAX_ELF:
32
34
  raise ValueError("binary too large")
33
35
  args = [str(a) for a in h.get("args", [])]
@@ -49,8 +51,9 @@ def _handler(h: dict, blob: bytes):
49
51
  "total_wall_s": r.total_wall_s, "accel": r.accel}, b""
50
52
 
51
53
 
52
- def serve(token: bytes, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False) -> RpcServer:
53
- return RpcServer(_handler, token, host=host, port=port, allow_remote=allow_remote)
54
+ def serve(token: bytes | None, host: str = "127.0.0.1", port: int = 0, allow_remote: bool = False,
55
+ authorizer=None) -> RpcServer:
56
+ return RpcServer(_handler, token, host=host, port=port, allow_remote=allow_remote, authorizer=authorizer)
54
57
 
55
58
 
56
59
  def run_remote(client: RpcClient, elf_path: str, args: list[str] | None = None, **opts) -> dict:
@@ -94,12 +97,17 @@ class LocalRunnerProcess:
94
97
  def main():
95
98
  import argparse
96
99
  ap = argparse.ArgumentParser()
97
- ap.add_argument("--token-file", required=True)
100
+ ap.add_argument("--token-file", help="shared secret (every client may do everything)")
101
+ ap.add_argument("--master-key-file", help="issue scoped credentials instead (see `spatial token`)")
102
+ ap.add_argument("--audit-log")
98
103
  ap.add_argument("--host", default="127.0.0.1")
99
104
  ap.add_argument("--port", type=int, default=0)
100
105
  ap.add_argument("--allow-remote", action="store_true")
101
106
  a = ap.parse_args()
102
- srv = serve(Path(a.token_file).read_bytes(), a.host, a.port, a.allow_remote)
107
+ if bool(a.token_file) == bool(a.master_key_file):
108
+ raise SystemExit("give exactly one of --token-file or --master-key-file")
109
+ srv = serve(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
110
+ authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None)
103
111
  print(f"PORT {srv.port}", flush=True)
104
112
  srv.serve_forever()
105
113
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spatial-computing
3
- Version: 0.7.0
3
+ Version: 0.8.0
4
4
  Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
5
5
  Author: Spatial Computing contributors
6
6
  License-Expression: Apache-2.0
@@ -37,7 +37,7 @@ Dynamic: license-file
37
37
 
38
38
  Spatial Computing chooses where and how a workload should run from measurements, and claims a gain only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
39
39
 
40
- > **Status: v0.7.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.8.0, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
41
41
 
42
42
  [Français](README.fr.md)
43
43
 
@@ -1,5 +1,5 @@
1
- spatial/__init__.py,sha256=jXXZSAhbQX0VXwHotl6_9oHXZFYg5i-HkqLzNTGVXGM,207
2
- spatial/cli.py,sha256=qpQA41C9Va3SQ9AX7bPOBXGXrbWhgt05qUoLqDD-EFs,5288
1
+ spatial/__init__.py,sha256=rupco3Ibfkhq7vlvmaPuvcH3GKssL4VD2X7qCjPVm7o,207
2
+ spatial/cli.py,sha256=OTJu6DgV1a_WZO0r2Yi7VYueXrzP1b6SCMzmcZstIvw,6858
3
3
  spatial/ai/__init__.py,sha256=qrQZBRNCGwnMp_Rx7HNblvGfgmLApVrdIAPcYVmZdCg,926
4
4
  spatial/ai/kvcache.py,sha256=7xrNI3zBKSoLA9ZjI1U2TZQ7GdXMZDzZq50qBrbWAWY,4054
5
5
  spatial/compute/__init__.py,sha256=VKrQED3KJOTve1dVS25AC0nPRTTcfQokXJYpPUngXMs,194
@@ -8,13 +8,14 @@ spatial/compute/detect.py,sha256=audAi9PSYbvrGNpSjz8oWIs34SXtMCjX95Q-wIk8f5k,636
8
8
  spatial/compute/monitor.py,sha256=YrgWY9HcGzel8Vv9LiqTLNPoQTmjRNkuLV88jWJT9UM,4210
9
9
  spatial/compute/scheduler.py,sha256=FXsdmP2kcwRSECF_RM0DRdkCiLSSbDa2KMnLwTb2lw4,7315
10
10
  spatial/compute/taskqueue.py,sha256=vbaHFvLy3FyezIHtfsU91m4873b5vv8mrUjTi1Iw6Qo,4334
11
- spatial/compute/worker.py,sha256=iniFNnBlgp9JmqotIdz348LugZPkNk9Z4LgzebSuYGY,3060
11
+ spatial/compute/worker.py,sha256=E5MD7wKmdr9Gy8XpN_vtthZm0FL3NvFMUtGojKmlY-s,3662
12
12
  spatial/compute/workloads.py,sha256=9qZoQSVU4USHXVXRWsRbBvH03Op0EMs0ziQRlz9DKgQ,4502
13
13
  spatial/core/__init__.py,sha256=rZAEaJb9mVnKa4e8tu1tjRQ2bMz34H3JHz08IzAt4Ys,81
14
+ spatial/core/auth.py,sha256=AOVoZpW4VcqgAynrieiMZtTi6i3KgDySt2p2Jz2RiQk,6222
14
15
  spatial/core/energy.py,sha256=w8dfk2F3RdmJBi0u3iNZzktDWSG-BdLozp8uFqAKTD8,3471
15
16
  spatial/core/ledger.py,sha256=jGv1zVSK8jkVGVxmjLPnfy0Kw444xUoR2lp-tfzZrR0,2838
16
17
  spatial/core/model.py,sha256=UTLv1icOjGBl0L7zFrpz3XfQ2geCiS3HH-RaLuMx6pM,2324
17
- spatial/core/protocol.py,sha256=7ew8jWgt300nxoyXWfXOUfBYAA4QQLQz110a5NFsDec,6661
18
+ spatial/core/protocol.py,sha256=QZHHbtNZcE-uSLE-NQXNHSDpELT36K1XM5LJPgC8bA8,9882
18
19
  spatial/core/registry.py,sha256=uetAQvKr4ryTFIgrKfxVw2hRlob8ngowizQxydmWDJg,3286
19
20
  spatial/holographic/__init__.py,sha256=16C0eQdfD87FeMKVwLAzgOgZ97oHzOfD27sLfmWAhP4,541
20
21
  spatial/holographic/cgh.py,sha256=jiQgs4k5QY03ndjMTVkT6DquJZX2BP6vPLWHTpaG0Uk,1910
@@ -23,14 +24,14 @@ spatial/intelligence/__init__.py,sha256=WPRgKRfs8uejj7OAHvd_u4hEHxMv3oELivmJs5qd
23
24
  spatial/intelligence/predictor.py,sha256=M-JQ_0tktKoC7MrAhM9lYxJkol_7xQEAz42sWaAXF1w,2063
24
25
  spatial/memory/__init__.py,sha256=Jy5xVfm9mmLaE6qaJ-UhIfqrOPJJFA9kDc-pvexJo0k,335
25
26
  spatial/memory/fararray.py,sha256=USpFPorGveZ2LVc_2JkePD2dHJKBl9gyfxb5lbwp2HI,1689
26
- spatial/memory/pageserver.py,sha256=T99Ad7onqHTFAaLVwLcbILCfbqZRzGwKToa0RG8JOyU,5190
27
+ spatial/memory/pageserver.py,sha256=mIMmvoQRAFYPwRdZqy3YAatfkiI-XzOMUkFoihJl8Hw,5767
27
28
  spatial/memory/secure.py,sha256=9WftFbomH9enh-Yqv6Gkqkd3HRiCba1FEEnSDP1QX54,3295
28
29
  spatial/memory/shared.py,sha256=_Wut7epR1-l7UUFr82ClKc2me_xJcdEezG8suLnCLKE,1648
29
30
  spatial/memory/tiered.py,sha256=X9Qmk7dRUctBSeou7-LmTiWlV-EUgsF5e5XFxlP3E3g,12336
30
31
  spatial/q/__init__.py,sha256=peBmLPYCEb1fA_4_sAAQm1rdlyxfdSFtZ2HY9fm76xs,246
31
32
  spatial/q/__main__.py,sha256=41AfzSdKBMVUDuiNX6b7H5DMUoYVOOmoi-P_P3eEIp4,298
32
33
  spatial/q/codegen.py,sha256=h2KoO_mKRmNecqKhW-ygAWjiYb2RodficUrvImOXqT4,6975
33
- spatial/q/compiler.py,sha256=CxopgG0ku6GXm1qEUbjBFspIX25-FF-LsNDkhwbp0d4,12091
34
+ spatial/q/compiler.py,sha256=o6gQrWKnfXvrue1E_GpkVgJHzabXvhdSZfBKZ8QneI0,14504
34
35
  spatial/q/ir.py,sha256=fLHLz1Cp7J-9N9a7tcZ9_Qriv9y3TEex-X7v11M56J0,5353
35
36
  spatial/q/lexer.py,sha256=duWOYLPwNZ4Je1gYza0dF6uro8WD-PXIFIUUr-PmGE4,1777
36
37
  spatial/q/parser.py,sha256=Jp0qpiualGxmS6_cJ9rCrsCOSJ2DQow1L-KeFQVtUjA,11589
@@ -43,16 +44,16 @@ spatial/runtime/envs.py,sha256=_k9pImrL25-vHHr6Bcn6Ab8wjPBec026MRpQK-0PeVA,3496
43
44
  spatial/runtime/inspect.py,sha256=avluvbij6Kc0_1zo32LIm9ciKwRN35ggqR48oL6_Sqg,2387
44
45
  spatial/runtime/microvm.py,sha256=X2WnPnTuRprf0HonMKBnee1IziMIx74KnBKTPUKh8R0,5577
45
46
  spatial/runtime/planner.py,sha256=w_-q-7Bw9lI2TWSLxPsGOfv_j5RFBVaBJqhMX0N9A6Q,7596
46
- spatial/runtime/runner.py,sha256=aQeh8gmKk2sU0vl8RlzmT8zOWQscDWqYB1zgkWBKtQQ,3996
47
+ spatial/runtime/runner.py,sha256=uropYfsenBJLvdRqD0igs0qn3lbevcicH5Dn9LpNo94,4573
47
48
  spatial/runtime/toolchain.py,sha256=W_gDIenyWPQurt5lYqry1bfEjpg-w785C_kOcaHsfgc,1372
48
49
  spatial/scientific/__init__.py,sha256=xip18tOkGOPZZiu4Yxx4YEWkeolxR1oAPf-RwONwLr4,483
49
50
  spatial/scientific/jobs.py,sha256=KFNfzEwH-gipiq16i3pNUHbb6ov-0b_ge--egyktyC0,2948
50
51
  spatial/simulation/__init__.py,sha256=HqJB3WHViehwrHSoMf9TzLekGvrHs6e-I2p62TeVX5A,331
51
52
  spatial/simulation/heat.py,sha256=g3ShRBNOwkb3UNIGMmsVxmsz1K0zISp4ftyM6BWtJFE,1594
52
53
  spatial/simulation/nbody.py,sha256=WcvcrQ1f4c7wjDsLRyxUFMkMTT1HfJ-Es3kT0uf80Og,1094
53
- spatial_computing-0.7.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
54
- spatial_computing-0.7.0.dist-info/METADATA,sha256=_XjBUp3_J0YoS19BLKzlBYSqynYfpwj6zPwvaascgdU,5973
55
- spatial_computing-0.7.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
56
- spatial_computing-0.7.0.dist-info/entry_points.txt,sha256=UIFCHJL01u7PIPej7EUHRI7rWEY8uBhufZ-_ulXUPRk,79
57
- spatial_computing-0.7.0.dist-info/top_level.txt,sha256=ZHke8hWgy4qIqEGq7omus3O-T7AhmPoc-cqr7JdGGxQ,8
58
- spatial_computing-0.7.0.dist-info/RECORD,,
54
+ spatial_computing-0.8.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
55
+ spatial_computing-0.8.0.dist-info/METADATA,sha256=Gy2qph8f1hlv1cmEY5krfaOhPih1s2WFqkyOCrrd4-U,5973
56
+ spatial_computing-0.8.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
57
+ spatial_computing-0.8.0.dist-info/entry_points.txt,sha256=UIFCHJL01u7PIPej7EUHRI7rWEY8uBhufZ-_ulXUPRk,79
58
+ spatial_computing-0.8.0.dist-info/top_level.txt,sha256=ZHke8hWgy4qIqEGq7omus3O-T7AhmPoc-cqr7JdGGxQ,8
59
+ spatial_computing-0.8.0.dist-info/RECORD,,