From 427872c2edb8ff0c0cba48bf44e534bb3f2aee47 Mon Sep 17 00:00:00 2001 From: Hasan Basbunar Date: Tue, 3 Nov 2026 06:25:33 +0100 Subject: [PATCH] pair: what the code review at max effort and a pair simulated on the box found Each found by the code review of feat/dual-spark at eda19f8 (9 finders, 4 verifiers, 2026-11-03) or by two proxies of this branch paired on the reference box with the real clients, checked in the code, and fixed with a test that fails before it: - pair.py add read each way through the other box's engine (GET /v1/models on its pair port): a lane loading, stopped or switching on either box failed the check, and add undid the pair on both boxes, a working one included. A box whose proxy answers over the pair's TLS, even with its engine's 503, is reached. - No TCP keepalive between the boxes: a box that lost power or its cable held a request in flight to it for up to MAX_SILENCE_S (an hour in the unit), its client hearing nothing. Probes after 10 s, every 5 s, gone after 25 s, both ways. - An error answer of the other box over 1 MiB went out cut to 1 MiB as if whole: error answers have the cap of a 200 now, and a 502 past it. - A request the other box sent on could be held through a whole boot, then refused with a 409 inside the held stream, which its entry relayed as an answer: it is never held, its entry gets the 503 at once. - pair.py remove asked the other box to forget a name, said it had whatever it answered, and a box renamed since was never forgotten: the other box forgets by the certificate it pins, and remove says when there was nothing to forget. - NaN, Infinity and 1e400 in what the other box sends (its list, its summary) went into this box's answers and cockpit state, which a browser cannot parse: every view of the cockpit froze. Both read it as JSON.parse does now. - The other box's cockpit stopped or not installed made its whole tile "HTTP 503": its summary says what it serves without its cockpit, and why. - The tile's reads every 5 s wrote a journal line on both boxes, and pushed a paired box's requests out of the 800 lines the cockpit reads in about 34 minutes: a read of the tile writes no line, a box that does not answer is said once a minute. - /api/chat, /api/generate and /invocations were not routed: a lane name there was answered by this box's model under the other's name. - The first GET /v1/models after a start or a pairing listed this box's models alone: each peer's list is read as soon as the pair is. - The docs say the pair port serves the tile's summary too, and what it holds. Left for decisions: a lane name served by no box (404, decision 961) and GET /v1/models while this box's engine is down (503), both against what a box alone does; add run again on a working pair can leave it one way after a failure. Co-Authored-By: Claude Opus 5.5 --- SECURITY.md | 5 +- dashboard/cockpit.py | 15 ++- dashboard/static/js/now.js | 2 + dashboard/tests/test_cockpit_collectors.py | 14 +++ dashboard/tests/test_page_behaviour.py | 5 + docs/pair.md | 6 +- keepalive-proxy.py | 103 +++++++++++++--- pair.py | 70 +++++++---- tests/test_pair_tool.py | 53 +++++++++ tests/test_proxy_pair.py | 129 ++++++++++++++++++++- 10 files changed, 354 insertions(+), 48 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 4683861a..10acbd42 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -159,8 +159,9 @@ request is read. The certificate is the pair's only credential: no box holds the other's API key, which is also its cockpit's login (root on a box, as above), and the pair port takes the generation routes and `GET /v1/models` only (403 for any other), admitted to the engine with this box's own key, and `GET /pair/cockpit/state`: -a summary of this box (what serves, memory, GPU, the job under way, the version), -which the proxy reads from its own cockpit with its own key, never relayed whole. +a summary of this box (what serves, its lanes' units, memory, CPU, GPU, the job under way, +the version, whether its cockpit answers, the time), which the proxy reads from its own +cockpit with its own key, never relayed whole. This box's cockpit reads the other's through `/proxy/pair//state`, a route of this machine only, as `/proxy/stop`. A request that gets past it is a hop from the box of that certificate: served there or refused, never sent diff --git a/dashboard/cockpit.py b/dashboard/cockpit.py index a4b5b7e3..9c5880cd 100644 --- a/dashboard/cockpit.py +++ b/dashboard/cockpit.py @@ -1360,6 +1360,17 @@ def serving_text_key(units=None): return None +def _not_json(what): + raise ValueError(f"{what} is not JSON") + + +def _finite_float(text): + v = float(text) + if v != v or v in (float("inf"), float("-inf")): + raise ValueError(f"{text[:20]} is out of range") + return v + + @guard def collect_pair(): """5 s tier, a thread of its own: the other boxes of this box's pair (docs/pair.md), each summed up by its own @@ -1379,7 +1390,9 @@ def collect_pair(): headers={"Authorization": f"Bearer {api_key()}"}) try: with opener.open(req, timeout=8) as r: - state = json.loads(r.read(1 << 20)) + # no NaN or Infinity: json.dumps(STATE) would write them, and every view of this cockpit froze on + # a frame the browser cannot parse (found in review, 2026-11-03) + state = json.loads(r.read(1 << 20), parse_constant=_not_json, parse_float=_finite_float) boxes[name] = {"state": state if isinstance(state, dict) else {}} except urllib.error.HTTPError as e: try: diff --git a/dashboard/static/js/now.js b/dashboard/static/js/now.js index 18f5e367..939c4c04 100644 --- a/dashboard/static/js/now.js +++ b/dashboard/static/js/now.js @@ -369,6 +369,8 @@ function renderPair(){ } const models = (Array.isArray(s.models) ? s.models : []).join(', '); rows.push([n, models ? `serves ${models}` : 'serves nothing now']); + // its cockpit stopped or not installed: what it serves is still known, the rest is not + if (s.cockpit) rows.push(['cockpit', `does not answer: ${s.cockpit}`]); // the same figures as this box's own memory card: 121.6 GiB, not 122 if (s.mem_total) rows.push(['memory', `${fmtGiB(s.mem_total - (s.mem_available || 0))} of ${fmtGiB(s.mem_total)} in use`]); if (s.gpu_temp_c != null || s.gpu_power_w != null) diff --git a/dashboard/tests/test_cockpit_collectors.py b/dashboard/tests/test_cockpit_collectors.py index 14e1779b..598d43a4 100644 --- a/dashboard/tests/test_cockpit_collectors.py +++ b/dashboard/tests/test_cockpit_collectors.py @@ -487,6 +487,11 @@ class TheOtherBoxOfAPair(Base): Proxy.seen.append((self.path, self.headers.get("Authorization"))) if self.path == "/proxy/pair/spark2/state": code, obj = 200, {"name": "spark2", "models": ["qwen3.8-flash-next-fp4"], "mem_total": 1 << 37} + elif self.path in ("/proxy/pair/spark-nan/state", "/proxy/pair/spark-big/state"): + out = (b'{"gpu_temp_c": NaN}' if "nan" in self.path else b'{"mem_total": 1e400}') + self.send_response(200); self.send_header("Content-Length", str(len(out))); self.end_headers() + self.wfile.write(out) + return elif self.path == "/proxy/pair/spark3/state": code, obj = 503, {"error": {"type": "engine_unavailable", "message": "keepalive-proxy: box spark3 does not answer: no answer in time"}} @@ -519,6 +524,15 @@ class TheOtherBoxOfAPair(Base): self.assertEqual(boxes["spark3"]["error"], "box spark3 does not answer: no answer in time") self.assertEqual({auth for _, auth in self.Proxy.seen}, {"Bearer k"}, "this box's key, to its own proxy only") + def test_what_a_browser_cannot_parse_never_enters_the_state(self): + # json.dumps(STATE) wrote the NaN back, and every view of this cockpit froze on a frame JSON.parse refuses + # (review, 2026-11-03) + self.pair.write_text(json.dumps({"name": "spark1", "peers": [{"name": "spark-nan"}, {"name": "spark-big"}]})) + boxes = self.cp.collect_pair()["boxes"] + self.assertEqual(sorted(boxes), ["spark-big", "spark-nan"]) + self.assertTrue(all("error" in b and "state" not in b for b in boxes.values()), boxes) + json.dumps(boxes, allow_nan=False) + def test_a_box_alone_reads_nothing(self): self.assertEqual(self.cp.collect_pair(), {"node_id": "local", "boxes": {}}) self.pair.write_text("{not json") diff --git a/dashboard/tests/test_page_behaviour.py b/dashboard/tests/test_page_behaviour.py index 870310c5..c12a65b8 100644 --- a/dashboard/tests/test_page_behaviour.py +++ b/dashboard/tests/test_page_behaviour.py @@ -2580,6 +2580,11 @@ class TheOtherBoxOfAPairIsShownInNow(unittest.TestCase): r = run(self, self.BODY % json.dumps({"node_id": "local", "boxes": {"spark9": {"error": "HTTP 401"}}})) self.assertEqual(r["rows"], ["spark9: does not answer: HTTP 401"], r) + def test_a_box_whose_cockpit_does_not_answer_still_says_what_it_serves(self): + r = run(self, self.BODY % json.dumps({"node_id": "local", "boxes": {"spark2": {"state": { + "models": ["qwen3.8-27b"], "cockpit": "Connection refused", "job": None}}}})) + self.assertEqual(r["rows"], ["spark2: serves qwen3.8-27b", "cockpit: does not answer: Connection refused"], r) + def test_what_the_other_box_says_is_text_never_markup(self): hostile = '' r = run(self, self.BODY % json.dumps({"node_id": "local", "boxes": {"spark2": {"state": { diff --git a/docs/pair.md b/docs/pair.md index cf18e4db..1c04e585 100644 --- a/docs/pair.md +++ b/docs/pair.md @@ -70,9 +70,9 @@ cockpit for now. never sends a request to an address that does not present it. This is how the nodes of [NVIDIA PAIR](https://github.com/NVIDIA/Personal-AI-Router) trust each other. - The certificate is the pair's only credential. No box ever holds the other's API key, which is also the - login of its cockpit: a box of a pair can only send the other generations and read its list of models. - Port 30002 refuses every other route, and the box that serves a request admits it to its own engine - with its own key. + login of its cockpit: a box of a pair can only send the other generations, read its list of models and + read the summary its tile shows. Port 30002 refuses every other route, and the box that serves a request + admits it to its own engine with its own key. - `pair.py` swaps the certificates over SSH, with the host key checked whatever your SSH configuration says, and nothing secret on a command line, where `ps` shows it to every user, or on the screen. - Port 30002 is open only while the box is paired, and only the paired box gets past it. Once you diff --git a/keepalive-proxy.py b/keepalive-proxy.py index b87e5611..0b34839c 100755 --- a/keepalive-proxy.py +++ b/keepalive-proxy.py @@ -69,7 +69,7 @@ without a pinned certificate refused right after its handshake. A request that c hop from the box of its certificate: served where it lands or refused (409), never sent on again. The certificate is the pair's only credential: no box holds the other's API key, which is also its cockpit's login, and the pair port takes the generation routes and GET /v1/models only, admitted -to this box's engine with this box's own key. The port is opened within seconds of pair.json +to this box's engine with this box's own key, and the summary of this box its tile shows. The port is opened within seconds of pair.json naming a peer and closed once it names none: nothing restarts. Nothing changes on a box without pair.json. @@ -3167,8 +3167,10 @@ _PAIR_SAFE_ID = re.compile(r"[\x21-\x7e]{1,200}") PAIR_COCKPIT_STATE = "/pair/cockpit/state" PAIR_PEER_STATE = re.compile(r"/proxy/pair/([A-Za-z0-9][A-Za-z0-9._-]{0,39})/state") COCKPIT_UNIT_FILE = "/etc/systemd/system/qwen38-dashboard.service" +# every generation route whose body names a model: Ollama's and SageMaker's stayed on the entry box, whose model +# answered under the other box's name (found in review, 2026-11-03) PAIR_ROUTES = frozenset({"/v1/chat/completions", "/v1/completions", "/v1/messages", - "/v1/messages/count_tokens", "/v1/responses"}) + "/v1/messages/count_tokens", "/v1/responses", "/api/chat", "/api/generate", "/invocations"}) PAIR_HOP = "X-Alzeo-Pair-Hop" PAIR_TTL_S = float(os.environ.get("PAIR_TTL_S", "5") or 5) PAIR_CONNECT_S = float(os.environ.get("PAIR_CONNECT_S", "10") or 10) @@ -3295,6 +3297,7 @@ def pair_conf(): read again when it changes. A file that does not parse is said once in the journal and leaves the box alone: a typo there must not take its clients' requests elsewhere.""" now = time.monotonic() + loaded = None with _PAIR_LOCK: if now - _PAIR["seen"] < 2: return _PAIR["conf"] @@ -3318,10 +3321,16 @@ def pair_conf(): tls = f", over TLS, this box's certificate sha256 {conf['tls']['mine'][:16]}..." if conf["peers"] else "" log(f"pair: {conf['name']} with {', '.join(p['name'] + ' (' + p['proxy'] + ')' for p in conf['peers']) or 'no peer'}" f"{tls} ({PAIR_FILE})") + loaded = conf except Exception as e: # whatever is wrong with it (a file, a certificate), the box stays alone _PAIR.update(conf=None, error=str(e)) log(f"pair: {PAIR_FILE} is not used: {str(e)[:200] or type(e).__name__}") - return _PAIR["conf"] + conf_now = _PAIR["conf"] + # each peer's list read at once, outside the lock _peer_models_soon takes: the first GET /v1/models after a + # start or a pairing listed this box's models alone (found on a pair simulated on the reference box, 2026-11-03) + for p in (loaded or {}).get("peers") or (): + _peer_models_soon(p) + return conf_now _PAIR_READING: dict = {} @@ -3358,25 +3367,45 @@ def _peer_models_soon(peer): threading.Thread(target=peer_models, args=(peer,), daemon=True).start() +def _json_finite(data): + """JSON as a browser reads it: Python's json takes NaN and Infinity (and 1e400 as inf) where JSON.parse + throws, and a value of the other box's written back into an answer of this one broke it for its client + (found in review, 2026-11-03).""" + def refuse(what): + raise ValueError(f"{what} is not JSON") + + def finite(text): + v = float(text) + if v != v or v in (float("inf"), float("-inf")): + raise ValueError(f"{text[:20]} is out of range") + return v + return json.loads(data, parse_constant=refuse, parse_float=finite) + + def _peer_models_read(peer): - models, rows, err = (), [], None + # answered: the peer's proxy gave an HTTP answer over the pair's TLS, which proves the pair both ways even + # when its engine does not answer (a 503 while a lane loads); pair.py's check reads it (found in review, + # 2026-11-03: add undid a working pair while either engine was stopped) + models, rows, err, answered = (), [], None, False try: # on the pair port, a hop: the peer answers with its own engine's list, never the union it shows its # clients, so two boxes that name each other do not ask each other in a loop, and a refusal says # what each box serves itself (found in review, 2026-11-02) req = urllib.request.Request(peer["proxy"] + "/v1/models") with peer["list_opener"].open(req, timeout=5) as r: - data = json.loads(r.read(1 << 20).decode()) + answered = True + data = _json_finite(r.read(1 << 20).decode()) if not isinstance(data, dict) or not isinstance(data.get("data"), list): raise ValueError("its /v1/models is not a list of models") rows = [m for m in data["data"] if isinstance(m, dict) and isinstance(m.get("id"), str) and _PAIR_SAFE_ID.fullmatch(m["id"])] models = tuple(m["id"] for m in rows) except urllib.error.HTTPError as e: - err = f"HTTP {e.code} on /v1/models" + answered, err = True, f"HTTP {e.code} on /v1/models" except Exception as e: # an address that is no HTTP server, a broken answer: the peer does not answer err = _pair_why(e) - _PAIR_MODELS[peer["name"]] = {"ts": time.monotonic(), "models": models, "rows": rows, "error": err} + _PAIR_MODELS[peer["name"]] = {"ts": time.monotonic(), "models": models, "rows": rows, "error": err, + "answered": answered} return models @@ -3476,7 +3505,14 @@ def _cockpit_get(path): def cockpit_summary(): """This box as the other box's tile shows it: what serves, the memory, the GPU, the job under way, the version; read from this box's cockpit, never relayed whole (its feed, its paths, its settings stay here).""" - st = _cockpit_get("/api/state") + try: + st, cockpit = _cockpit_get("/api/state"), None + except Exception as e: + # its cockpit stopped, restarting, or never installed (--no-cockpit): the tile still says what this box + # serves, and why the rest is missing (found in review, 2026-11-03: the whole tile read "HTTP 503") + cockpit = re.sub(r"[\x00-\x1f\x7f]", "?", str(getattr(e, "reason", None) or e))[:160] or type(e).__name__ + _say_once_a_minute("tile cockpit", f"pair: this box's cockpit does not answer for the other box's tile ({cockpit})") + st = None def d(name): v = st.get(name) if isinstance(st, dict) else None v = v.get("data") if isinstance(v, dict) else None @@ -3503,6 +3539,7 @@ def cockpit_summary(): "gpu_power_w": num(gpu.get("power_w")), "job": ({"action": word(cur.get("action")), "status": word(cur.get("status")), "elapsed": num(cur.get("elapsed"))} if cur else None), + "cockpit": cockpit, "ts": time.time()} @@ -3878,6 +3915,22 @@ class _NoUpstreamRedirect(urllib.request.HTTPRedirectHandler): _UPSTREAM_OPENER = urllib.request.build_opener(_UpstreamHTTP, _NoUpstreamRedirect) +def _pair_keepalive(sock): + """TCP keepalive on a connection between the boxes of a pair: a box that loses power or its cable sends no + FIN, and a request in flight to it waited up to pair_read_s (MAX_SILENCE_S, an hour in the unit) while its + client heard nothing; these boxes have had hard power-offs (found in review, 2026-11-03). Probes after 10 s + of silence, every 5 s, and a box that acknowledges nothing for 25 s is gone: the request gets the 503 a box + that does not answer gets. A box that is there acknowledges the probes however long its engine works.""" + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, 25000) + except (OSError, AttributeError): + pass # not Linux: the read timeout alone, as before + + class _PeerHTTPSConnection(http.client.HTTPSConnection): """A connection to a peer's pair port: connected, TCP and TLS, within PAIR_CONNECT_S; the peer's certificate the one pair.json pins, by the chain (its context trusts that one certificate alone) @@ -3891,6 +3944,7 @@ class _PeerHTTPSConnection(http.client.HTTPSConnection): def connect(self): super().connect() + _pair_keepalive(self.sock) der = self.sock.getpeercert(binary_form=True) if not der or hashlib.sha256(der).hexdigest() != self.pair_pin: try: self.sock.close() @@ -4547,6 +4601,7 @@ class PairServer(Server): if not tls: conn.close() raise OSError("no pair now: the pair port admits nobody") # serve_forever takes it and goes on + _pair_keepalive(conn) # an entry box gone: its request here is seen to have no caller left try: return tls["server"].wrap_socket(conn, server_side=True, do_handshake_on_connect=False), addr except Exception as e: @@ -4912,7 +4967,10 @@ class H(BaseHTTPRequestHandler): except Exception: pass # ---- relay ------------------------------------------------------------- - def _done(self, outcome): + def _done(self, outcome, quiet=False): + """The request's outcome, and its journal line unless quiet: the tile's reads every 5 s, written on both + boxes, pushed a paired box's real requests out of the 800 lines the cockpit reads in about 34 minutes + (found in review, 2026-11-03).""" self._ended = True _gen_discard(self) self._say_tool_targets(outcome) @@ -4922,7 +4980,8 @@ class H(BaseHTTPRequestHandler): f = f"{self._first:.1f}s" if self._first is not None else "never" l = f"{self._last:.1f}s" if getattr(self, "_last", None) is not None else "never" st = f" [{self._bytes}b relayed, first event at {f}, last at {l}]" - log(f"{getattr(self, '_peer', '?')} {self.command} {self.path.split('?')[0]} {outcome} in {time.time()-self._t0:.1f}s{st}") + if not quiet: + log(f"{getattr(self, '_peer', '?')} {self.command} {self.path.split('?')[0]} {outcome} in {time.time()-self._t0:.1f}s{st}") def _note_gave_up(self, outcome: str) -> None: """Role 9: a client that left a long prompt without an answer, kept for RESEND_WINDOW_S.""" @@ -5355,6 +5414,11 @@ class H(BaseHTTPRequestHandler): and waiting would only replay the failure. Once a hold began, an engine that answers again and still fails the request (a boot not quite done) gets it again, at most HOLD_ROUNDS_MAX times, each after a pause.""" + if self._pair_hop(): + # role 10: a request the other box sent on is answered now, never held: held, it waited through a + # whole boot and then got a 409 inside the stream the hold had opened, which its entry relayed as + # an answer (found in review, 2026-11-03). The 503 lets the entry read the lists again or say so. + return False if not engine_coming(): return False if self._hold_until is None: @@ -6026,7 +6090,7 @@ class H(BaseHTTPRequestHandler): self._done("503 pair cockpit unreachable") return self._plain(200, {"Content-Type": "application/json"}, json.dumps(summary).encode()) - self._done("ok pair cockpit") + self._done("ok pair cockpit", quiet=True) def _pair_peer_state(self, name): """GET /proxy/pair//state: the other box summed up by its own proxy, for this box's cockpit's tile @@ -6055,21 +6119,21 @@ class H(BaseHTTPRequestHandler): try: with peer["list_opener"].open(urllib.request.Request(peer["proxy"] + PAIR_COCKPIT_STATE), timeout=5) as r: data = r.read((1 << 20) + 1) - if len(data) > 1 << 20 or not isinstance(json.loads(data), dict): + if len(data) > 1 << 20 or not isinstance(_json_finite(data), dict): why = "its summary is no JSON object of 1 MiB at most" except urllib.error.HTTPError as e: why = f"HTTP {e.code}" except Exception as e: why = _pair_why(e) if why is not None: - log(f"{self._peer} pair: {name} does not say its state ({why})") + _say_once_a_minute(f"tile {name}", f"{self._peer} pair: {name} does not say its state ({why})") self._plain(503, {"Content-Type": "application/json", "Retry-After": "30"}, json.dumps({"error": {"type": "engine_unavailable", "message": f"keepalive-proxy: box {name} does not answer: {why}"}}).encode()) - self._done("503 pair peer unreachable") + self._done("503 pair peer unreachable", quiet=True) return self._plain(200, {"Content-Type": "application/json"}, data) - self._done("ok pair state") + self._done("ok pair state", quiet=True) def _pair_hop(self): """The box that sent this request on, or None: on the pair port, the box of the certificate that @@ -6228,7 +6292,9 @@ class H(BaseHTTPRequestHandler): resp = peer["opener"].open(req) except urllib.error.HTTPError as e: try: - data = _pair_read_whole(e.fp, (1 << 20) - 1) if e.fp is not None else b"" + # the cap of a 200: an error answer over 1 MiB went out cut to 1 MiB as if whole (a validation + # error echoing a long prompt, review of 2026-11-03) + data = _pair_read_whole(e.fp, PAIR_ANSWER_MAX) if e.fp is not None else b"" except (OSError, ValueError, http.client.HTTPException) as cut: # its error answer cut on the way (the box went, or this client left): it escaped this # function before (found in review, 2026-11-03) @@ -6244,6 +6310,11 @@ class H(BaseHTTPRequestHandler): self._pair_refuse(502, "upstream_cut", f"box {peer['name']} cut its answer short", pair_served_map(conf, local)) self._done("UPSTREAM CUT pair"); return None + if len(data) > PAIR_ANSWER_MAX: + log(f"{self._peer} pair: the answer of {peer['name']} is over {PAIR_ANSWER_MAX} bytes: refused") + self._pair_refuse(502, "upstream_too_large", f"the answer of box {peer['name']} is over " + f"{PAIR_ANSWER_MAX} bytes", pair_served_map(conf, local)) + self._done("502 pair answer too large"); return None if e.code == 409 and b'"model_not_served"' in data: log(f"{self._peer} pair: {peer['name']} serves another model now; the lists are read again") return "moved" diff --git a/pair.py b/pair.py index b9c61409..232c3b86 100755 --- a/pair.py +++ b/pair.py @@ -12,7 +12,7 @@ between two Sparks, and one command pairs both boxes (decisions 973-974): each b its own once, the two boxes swap their certificates over SSH, each pins the other's in its pair.json, and from then on the two proxies talk over TLS both ways on port 30002. The certificate is the pair's only credential (decision 978): no box ever holds the other's API key, which is also its cockpit's login, and -the pair port takes the generation routes and the model list only. Either box is then an entry: a request +the pair port takes the generation routes, the model list and the summary of the tile only. Either box is then an entry: a request that names a model of one of this repo's lanes goes to the box that serves it. Both proxies read pair.json again within seconds: nothing restarts. `add` then checks both ways, and keeps nothing on either box when one way fails (--no-check keeps the pair anyway). Nothing secret is ever on a command line, where ps shows @@ -234,11 +234,24 @@ def with_peer(mod, conf, name, proxy, pem, ssh=None): return new, gone, entry -def without_peer(conf, name): - gone = [q for q in conf["peers"] if isinstance(q, dict) and q.get("name") == name] +def without_peer(conf, name, sha=None): + """conf without the peer of that name, or of that certificate: a box renamed since the pair was made is + known on the other box by its certificate alone (found in review, 2026-11-03).""" + def norm(v): + return str(v or "").replace(":", "").lower() + gone = [q for q in conf["peers"] if isinstance(q, dict) and (q.get("name") == name + or (sha and norm(q.get("sha256")) == sha))] return dict(conf, peers=[q for q in conf["peers"] if q not in gone]), gone +def my_sha(mod): + """This box's certificate's fingerprint, or None before it has one.""" + try: + return fingerprint(mod, (IDENTITY / "cert.pem").read_text(), "this certificate") + except (OSError, SystemExit): + return None + + def reach(mod, name, within): """What the peer `name` of this box's pair serves, read as the proxy reads it (its pair port, over TLS both ways, with its key), tried for `within` seconds: its proxy opens that port within 2 s of @@ -254,11 +267,15 @@ def reach(mod, name, within): deadline = time.monotonic() + within while True: models = mod._peer_models_read(peer) - err = (mod._PAIR_MODELS.get(name) or {}).get("error") - if not err: + row = mod._PAIR_MODELS.get(name) or {} + if not row.get("error"): return list(models), None + if row.get("answered"): + # its proxy answered over TLS both ways, its engine did not (a lane loading, stopped, switching): the + # pair works, and that box serves nothing now (found in review, 2026-11-03: add undid a working pair) + return [], None if time.monotonic() >= deadline: - return None, err + return None, row.get("error") time.sleep(1) @@ -308,13 +325,9 @@ def do_check(req): def do_forget(req): mod = proxy_module() - with pair_lock(): - conf = read_conf() - new, gone = without_peer(conf, req["name"]) - if gone: - write_pair(mod, new) - drop_files(gone, keep=new["peers"]) - return {"forgot": bool(gone), "alone": not new["peers"]} + sha = str(req.get("sha256") or "").replace(":", "").lower() or None + gone = unpair_here(mod, req["name"], sha) + return {"forgot": bool(gone), "alone": not read_conf()["peers"]} def remote(req): @@ -371,10 +384,13 @@ def ssh_call(dest, do, req, timeout=120): return reply -def forget_there(dest, me): - """The other box forgets this one, or the reason it could not be told; never raises.""" +def forget_there(dest, me, sha=None, answer=None): + """The other box forgets this one (by its name or its certificate), or the reason it could not be told; + never raises. Its answer goes into `answer` when one is given.""" try: - ssh_call(dest, "forget", {"name": me}, timeout=60) + r = ssh_call(dest, "forget", {"name": me, "sha256": sha}, timeout=60) + if answer is not None: + answer.append(r) return None except SystemExit as e: return str(e.code if e.code is not None else "") @@ -394,10 +410,10 @@ def address(addr, what): return addr -def unpair_here(mod, name): +def unpair_here(mod, name, sha=None): with pair_lock(): conf = read_conf() - new, gone = without_peer(conf, name) + new, gone = without_peer(conf, name, sha) if gone: write_pair(mod, new) drop_files(gone, keep=new["peers"]) @@ -414,6 +430,7 @@ def cmd_add(args, mod): conf = read_conf() me = my_name(mod, conf) pem = ensure_identity(me) + mine = fingerprint(mod, pem, "this certificate") print(f"pairing {me} (this box) with the box at {host}, over SSH ({dest})...") # 1. the other box writes its side and says who it is: its name, certificate and pair port. A failure # once it may have written (an error after its write, SSH cut, a timeout, Ctrl-C) is undone there too: @@ -421,7 +438,7 @@ def cmd_add(args, mod): try: r = ssh_call(dest, "accept", {"name": me, "port": mod.PAIR_PORT, "back": back, "cert": pem}) except BaseException: - forget_there(dest, me) + forget_there(dest, me, mine) raise name, their_pem = r.get("name"), r.get("cert") try: @@ -434,7 +451,7 @@ def cmd_add(args, mod): their_back = address(r.get("back") or "", "the address it reaches this box at") replaced = [n for n in (r.get("replaced") or []) if isinstance(n, str) and mod.PAIR_NAME.fullmatch(n)] except (ValueError, TypeError, SystemExit) as e: - why = forget_there(dest, me) + why = forget_there(dest, me, mine) said = SAFE_TEXT.sub("?", str(getattr(e, "code", None) or e))[:200] raise SystemExit(f"pair.py: {dest} answered with something this box does not take ({said}): nothing was kept" + (f" here, and it could not be told ({why}): run pair.py remove {me} there" if why else "")) @@ -450,7 +467,7 @@ def cmd_add(args, mod): raise drop_files(gone, keep=new["peers"]) except BaseException: - forget_there(dest, me) + forget_there(dest, me, mine) raise # 3. both ways, as the proxies will: this box to its pair port, and that box to this one's if not args.no_check: @@ -471,7 +488,7 @@ def cmd_add(args, mod): undone = None except BaseException as e: undone = SAFE_TEXT.sub("?", str(getattr(e, "code", None) or e))[:200] - why = forget_there(dest, me) + why = forget_there(dest, me, mine) if why is None and undone is None: kept = "Nothing was kept on either box" else: @@ -509,9 +526,14 @@ def cmd_remove(args, mod): if not dest: print(f" on {args.name}, run: python3 ~/dgx-spark-qwen38/pair.py remove {me}") return - why = forget_there(dest, me) - if why is None: + said = [] + why = forget_there(dest, me, my_sha(mod), said) + if why is None and said and said[0].get("forgot"): print(f" {args.name} forgot this box too") + elif why is None: + # its answer was read: a remove there said nothing to forget when it knew this box under another name + # (found in review, 2026-11-03) + print(f" {args.name} had no pair with this box: nothing to forget there") else: print(f" {args.name} could not be told ({why}); this box refuses its requests now. On {args.name}, run: " f"python3 ~/dgx-spark-qwen38/pair.py remove {me}") diff --git a/tests/test_pair_tool.py b/tests/test_pair_tool.py index 0567544f..5cf73328 100644 --- a/tests/test_pair_tool.py +++ b/tests/test_pair_tool.py @@ -76,10 +76,19 @@ def fake_engine(name, model): class Handler(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" seen: list = [] + loading = False # SGLang while it loads: a 503 to everything def log_message(self, *a): pass + def loading_503(self): + if not Handler.loading: + return False + self.send_response(503) + self.send_header("Content-Length", "0") + self.end_headers() + return True + def reply(self, obj): out = json.dumps(obj).encode() self.send_response(200) @@ -89,6 +98,8 @@ def fake_engine(name, model): self.wfile.write(out) def do_GET(self): + if self.loading_503(): + return if self.path.startswith("/v1/models"): return self.reply({"object": "list", "data": [{"id": model, "object": "model"}]}) if self.path.startswith(("/server_info", "/get_server_info")): @@ -97,6 +108,8 @@ def fake_engine(name, model): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}") + if self.loading_503(): + return Handler.seen.append(body.get("model")) self.reply({"id": "c", "object": "chat.completion", "model": model, "choices": [{"index": 0, "message": {"role": "assistant", "content": f"from {name}"}, @@ -340,6 +353,26 @@ class PairTool(unittest.TestCase): self.assertNotEqual(rc, 0) self.assertIn("no peer named box2", out) + def test_a_box_renamed_since_it_was_paired_is_forgotten_by_its_certificate(self): + # remove asked the other box to forget a name it did not know, and said it had (review, 2026-11-03) + rc, out = self.add() + self.assertEqual(rc, 0, out) + conf = self.b1.pair() + (self.b1.cfg / "pair.json").write_text(json.dumps(dict(conf, name="box1-renamed"))) + rc, out = self.run_tool(self.b1, "remove", "box2") + self.assertEqual(rc, 0, out) + self.assertIn("box2 forgot this box too", out) + self.assertEqual(self.b2.pair()["peers"], [], "forgotten by its certificate") + + def test_remove_says_when_the_other_box_had_nothing_to_forget(self): + rc, out = self.add() + self.assertEqual(rc, 0, out) + (self.b2.cfg / "pair.json").write_text(json.dumps({"name": "box2", "peers": []})) + rc, out = self.run_tool(self.b1, "remove", "box2") + self.assertEqual(rc, 0, out) + self.assertIn("box2 had no pair with this box: nothing to forget there", out) + self.assertNotIn("forgot this box too", out) + def test_a_box_that_cannot_be_told_is_said_with_the_command_to_run_there(self): rc, out = self.add() self.assertEqual(rc, 0, out) @@ -385,6 +418,26 @@ class PairTool(unittest.TestCase): st, body = self.call(self.b1, "qwen3.8-flash-next-fp4") self.assertEqual(st, 200, body[:300]) + def test_a_box_whose_engine_does_not_answer_is_paired_all_the_same(self): + # a lane loading, stopped or switching on either box: its proxy answers 503 on its pair port, which proves + # the pair both ways; add undid the pair on both boxes, a working one too (found in review, 2026-11-03) + self.b2.engine_handler.loading = True + rc, out = self.add() + self.assertEqual(rc, 0, out) + self.assertIn("serves nothing now", out) + rc, out = self.add() + self.assertEqual(rc, 0, out) + self.assertEqual(([p["name"] for p in self.b1.pair()["peers"]], [p["name"] for p in self.b2.pair()["peers"]]), + (["box2"], ["box1"]), "kept on both boxes") + self.b2.engine_handler.loading = False + deadline, st, body = time.monotonic() + 15, None, b"" + while time.monotonic() < deadline: + st, body = self.call(self.b1, "qwen3.8-flash-next-fp4") + if st == 200: + break + time.sleep(0.5) + self.assertEqual(st, 200, body[:300]) + def test_status_says_what_each_box_serves_and_never_a_key(self): rc, out = self.run_tool(self.b1, "status") self.assertEqual(rc, 0, out) diff --git a/tests/test_proxy_pair.py b/tests/test_proxy_pair.py index 3a0bb9b3..53fb8613 100644 --- a/tests/test_proxy_pair.py +++ b/tests/test_proxy_pair.py @@ -30,6 +30,7 @@ import sys import tempfile import threading import time +import types import unittest import urllib.error @@ -531,6 +532,16 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase): self.assertEqual((path, model, auth), ("/v1/chat/completions", "qwen3.8-flash-next-fp4", f"Bearer {KEY_2}")) self.assertIsNone(hop, "the hop header stops at the peer's proxy, never reaches its engine") + def test_the_ollama_and_sagemaker_routes_go_to_the_box_that_serves_too(self): + # they stayed on this box, whose model answered under the other box's name (review, 2026-11-03) + for route in ("/api/chat", "/api/generate", "/invocations"): + with self.subTest(route=route): + st, out, _ = self.call(route, self.chat("qwen3.8-flash-next-fp4")) + self.assertEqual(st, 200, out[:300]) + self.assertIn(b"from spark2", out) + self.assertEqual(self.E2.seen[-1][:2], (route, "qwen3.8-flash-next-fp4")) + self.assertEqual(self.E1.seen, []) + def test_a_stream_from_the_peer_arrives_whole_and_in_order(self): st, out, hdrs = self.call("/v1/chat/completions", self.chat("qwen3.8-flash-next-fp4", stream=True)) self.assertEqual(st, 200, out[:300]) @@ -880,6 +891,35 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase): self.assertEqual(json.loads(out)["error"]["type"], "upstream_too_large") self.assert_said("huge", "502 pair answer too large") + def test_an_error_answer_is_relayed_whole_up_to_the_cap_and_refused_past_it(self): + # an error answer over 1 MiB went out cut to 1 MiB as if whole: a validation error that echoes a long + # prompt does that (review, 2026-11-03) + class BigError(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def reply(self, code, out): + self.send_response(code); self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(out))); self.end_headers(); self.wfile.write(out) + + def do_GET(self): + self.reply(200, json.dumps({"object": "list", "data": [{"id": "qwen3.8-flash-next-fp4"}]}).encode()) + + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length") or 0)) + self.reply(400, json.dumps({"error": {"message": "x" * 1_300_000}}).encode()) + port = self.spare_proxy("big-error", KEY_1, peers=[("spark2", tls_peer(self, BigError))]) + st, out, _ = self.call("/v1/chat/completions", self.chat("qwen3.8-flash-next-fp4"), port=port) + self.assertEqual(st, 400, out[:300]) + self.assertEqual(len(json.loads(out)["error"]["message"]), 1_300_000, "the whole answer") + port = self.spare_proxy("big-error-capped", KEY_1, peers=[("spark2", tls_peer(self, BigError))], + extra={"MAX_BODY_BYTES": "8192"}) + st, out, _ = self.call("/v1/chat/completions", self.chat("qwen3.8-flash-next-fp4"), port=port) + self.assertEqual(st, 502, out[:300]) + self.assertEqual(json.loads(out)["error"]["type"], "upstream_too_large") + def test_an_error_answer_the_other_box_cuts_is_said_cut(self): # its error answer cut on the way escaped the relay before (review, 2026-11-03) class CutError(http.server.BaseHTTPRequestHandler): @@ -962,9 +1002,15 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase): # decision 975: this box's cockpit asks its own proxy; the other box's proxy sums its own cockpit up, logged # in with its own key, never relayed whole FakeCockpit.logins.clear() + lines = (self.journal("spark1").count("pair/spark2/state"), self.journal("spark2").count("/pair/cockpit/state")) for _ in range(2): st, out, _ = self.call("/proxy/pair/spark2/state", method="GET") self.assertEqual(st, 200, out[:300]) + # a read comes every 5 s on both boxes: its lines pushed the real requests out of the 800 the cockpit reads + # in 34 minutes (review, 2026-11-03) + time.sleep(0.3) + self.assertEqual((self.journal("spark1").count("pair/spark2/state"), + self.journal("spark2").count("/pair/cockpit/state")), lines, "a read of the tile writes no line") s = json.loads(out) self.assertEqual(s["name"], "spark2") self.assertEqual(s["models"], ["qwen3.8-flash-next-fp4"]) @@ -1232,6 +1278,9 @@ class TwoBoxesBehindOneEndpointInProcess(TwoBoxesBehindOneEndpoint): def test_a_lane_the_peer_serves_goes_there_with_the_peers_key(self): super().test_a_lane_the_peer_serves_goes_there_with_the_peers_key() + def test_the_ollama_and_sagemaker_routes_go_to_the_box_that_serves_too(self): + super().test_the_ollama_and_sagemaker_routes_go_to_the_box_that_serves_too() + def test_a_stream_from_the_peer_arrives_whole_and_in_order(self): super().test_a_stream_from_the_peer_arrives_whole_and_in_order() @@ -1313,6 +1362,9 @@ class TwoBoxesBehindOneEndpointInProcess(TwoBoxesBehindOneEndpoint): def test_an_answer_past_the_cap_is_refused(self): super().test_an_answer_past_the_cap_is_refused() + def test_an_error_answer_is_relayed_whole_up_to_the_cap_and_refused_past_it(self): + super().test_an_error_answer_is_relayed_whole_up_to_the_cap_and_refused_past_it() + def test_an_error_answer_the_other_box_cuts_is_said_cut(self): super().test_an_error_answer_the_other_box_cuts_is_said_cut() @@ -1495,6 +1547,26 @@ class ThePairsPieces(unittest.TestCase): for body in (b"not json", b"[1]", b'{"model": 3}', b"{}"): self.assertIsNone(bm(body)) + def test_each_peers_list_is_read_as_soon_as_the_pair_is(self): + # the first GET /v1/models after a start or a pairing listed this box's models alone (a pair simulated on + # the reference box, 2026-11-03) + class One(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def do_GET(self): + out = json.dumps({"data": [{"id": "kolibri-1"}]}).encode() + self.send_response(200); self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(out))); self.end_headers(); self.wfile.write(out) + self.mod._PAIR_MODELS.clear() + self.conf_now({"name": "spark1", "peers": [peer_entry(self.cfg, "early", tls_peer(self, One), who="spark2")]}) + deadline = time.monotonic() + 8 + while (self.mod._PAIR_MODELS.get("early") or {}).get("models") != ("kolibri-1",) and time.monotonic() < deadline: + time.sleep(0.05) + self.assertEqual((self.mod._PAIR_MODELS.get("early") or {}).get("models"), ("kolibri-1",), "read with no request") + def test_a_peers_list_is_read_kept_and_read_again(self): class Lists(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" @@ -1634,6 +1706,58 @@ class ThePairsPieces(unittest.TestCase): f._pair_box = None self.assertEqual(self.mod._upstream_auth(f), "Bearer not-this-box", "a client of the client port: its own") + def test_a_summary_without_its_cockpit_still_says_what_this_box_serves(self): + # the other box's cockpit stopped or never installed (--no-cockpit): the whole tile read "HTTP 503" + # (review, 2026-11-03) + saved = os.environ.get("QWEN38_COCKPIT_URL") + os.environ["QWEN38_COCKPIT_URL"] = f"http://127.0.0.1:{localports.held(self)}" + self.addCleanup(lambda: os.environ.pop("QWEN38_COCKPIT_URL") if saved is None + else os.environ.__setitem__("QWEN38_COCKPIT_URL", saved)) + served = self.mod.served_models + self.mod.served_models = lambda: ("qwen3.8-27b",) + self.addCleanup(setattr, self.mod, "served_models", served) + s = self.mod.cockpit_summary() + self.assertEqual(s["models"], ["qwen3.8-27b"]) + self.assertTrue(isinstance(s["cockpit"], str) and s["cockpit"], s) + self.assertIsNone(s["job"]) + + def test_what_a_browser_cannot_parse_is_not_taken_from_the_other_box(self): + # NaN, Infinity and 1e400 parse in Python and not in a browser: written back into GET /v1/models or the tile, + # they broke the answer for its client (review, 2026-11-03) + for bad in ('{"data": [{"id": "x", "created": NaN}]}', '{"a": Infinity}', '{"a": -1e400}'): + with self.subTest(bad=bad), self.assertRaises(ValueError): + self.mod._json_finite(bad) + self.assertEqual(self.mod._json_finite('{"a": 1.5, "b": [1, 2e3]}'), {"a": 1.5, "b": [1, 2000.0]}) + + def test_a_request_the_other_box_sent_on_is_never_held(self): + # held through a whole boot, it got a 409 inside the held stream, relayed by its entry as an answer + # (review, 2026-11-03): answered at once, the entry reads the lists again or says 503 + saved = (self.mod.engine_coming, self.mod.engine_answers) + self.mod.engine_coming, self.mod.engine_answers = (lambda: True), (lambda: False) # a lane on its way back + self.addCleanup(lambda: (setattr(self.mod, "engine_coming", saved[0]), setattr(self.mod, "engine_answers", saved[1]))) + hop = types.SimpleNamespace(_pair_hop=lambda: "spark2", _hold_until=None) + self.assertFalse(self.mod.H._hold(hop, "the engine does not answer", True)) + self.assertIsNone(hop._hold_until, "no hold begun") + + def test_a_connection_between_the_boxes_probes_a_box_that_went(self): + # a box that loses power sends no FIN: a request in flight to it waited an hour (review, 2026-11-03) + lsn = socket.socket() + lsn.bind(("127.0.0.1", 0)); lsn.listen(1) + self.addCleanup(lsn.close) + c = socket.create_connection(lsn.getsockname()) + self.addCleanup(c.close) + s, _ = lsn.accept() + self.addCleanup(s.close) + self.mod._pair_keepalive(c) + got = (c.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE), c.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE), + c.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL), c.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT), + c.getsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT)) + self.assertEqual(got, (1, 10, 5, 3, 25000)) + # both ends of a pair: the connection a box opens to its peer, and the one its pair port accepts + src = (REPO / "keepalive-proxy.py").read_text() + self.assertIn(" super().connect()\n _pair_keepalive(self.sock)\n", src) + self.assertIn(" _pair_keepalive(conn)", src) + def test_a_line_said_once_a_minute_counts_the_others(self): lines = [] saved = self.mod.log @@ -1678,8 +1802,9 @@ class ThePairsPieces(unittest.TestCase): self.assertEqual(FakeCockpit.logins, [KEY_1, KEY_1], "logged in again, once") os.environ["QWEN38_COCKPIT_URL"] = f"http://127.0.0.1:{localports.held(self)}" self.mod._COCKPIT["cookie"] = None - with self.assertRaises(OSError): - self.mod.cockpit_summary() + gone = self.mod.cockpit_summary() # its cockpit gone: what this box serves, and why no more + self.assertEqual(gone["models"], ["qwen3.8-27b"]) + self.assertTrue(gone["cockpit"], gone) self.assertEqual(len(FakeCockpit.logins), 2) def test_the_cockpit_is_found_where_its_unit_binds_it(self):