pair: an answer the other box cuts is said cut; the tile as its captures read

What the first run of the pair's tests and the tile's captures found (2026-11-03):

- A non-streamed answer of the other box, an error or a 200, whose body ended before its
  Content-Length went to the client as a whole one: http.client's read(n) hands a body cut
  short over as if it were complete and leaves the bytes still owed in .length (read() alone
  raises IncompleteRead), which the engine's relay already reads since 2026-09-24. Both reads
  of the pair now go through _pair_read_whole(): the client gets a 502 upstream_cut.
- The tile said "does not answer: box spark9 does not answer: ..." (the proxy's own words
  already name the box), and the other box's memory as "of 122 GiB" where this box says its
  own "of 121.6 GiB".
- pair.py dropped the key files of a format no release ever wrote; an entry of pair.json
  edited by hand into something else is passed over instead of stopping the cleanup.
- Tests: two still read the key file the pair no longer has; the journal's outcome lines are
  written after the answer's last byte, and six checks read them at once (one failed in a
  run): they wait for their line now. New: the cut 200, and the tile in the page (a box
  alone, the figures, a box that does not answer said once, its words as text only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Hasan BasbunarandClaude Opus 5.5 committed 2026-11-03 04:44:04 +01:00
1 parent 38e9a86eb3
commit eda19f84bb
6 files changed
+121 -22

No files matched your search

+8 -2
View File
@@ -361,10 +361,16 @@ function renderPair(){
const rows = [];
for (const n of names){
const b = boxes[n] || {}, s = b.state || {};
if (b.error){ rows.push([n, `does not answer: ${b.error}`]); continue; }
if (b.error){
// the proxy's own words already name the box: "box spark2 does not answer: <why>"
const said = `box ${n} does not answer: `, why = String(b.error);
rows.push([n, `does not answer: ${why.startsWith(said) ? why.slice(said.length) : why}`]);
continue;
}
const models = (Array.isArray(s.models) ? s.models : []).join(', ');
rows.push([n, models ? `serves ${models}` : 'serves nothing now']);
if (s.mem_total) rows.push(['memory', `${fmtGiB(s.mem_total - (s.mem_available || 0))} of ${fmtGiB(s.mem_total, 0)} in use`]);
// 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)
rows.push(['GPU', [s.gpu_temp_c != null ? `${Number(s.gpu_temp_c).toFixed(0)} °C` : '', s.gpu_power_w != null ? `${Number(s.gpu_power_w).toFixed(0)} W` : ''].filter(Boolean).join(', ')]);
if (s.job && s.job.action) rows.push(['job', `${s.job.action}${s.job.status ? ', ' + s.job.status : ''}${s.job.elapsed != null ? ', ' + fmtDur(s.job.elapsed) : ''}`]);
+45
View File
@@ -2543,5 +2543,50 @@ class TheBoxItIs(unittest.TestCase):
self.assertTrue(all("Download" in row for row in r["library"]), r["library"])
class TheOtherBoxOfAPairIsShownInNow(unittest.TestCase):
"""The tile of the other box of a pair (docs/pair.md, decision 975), as the captures of 2026-11-03 read
it: hidden on a box alone, the other box's figures as this box says its own, its words as text only."""
BODY = r"""
feed({config: CONFIG, units: UNITS, lifecycle: life({'qwen38-sglang.service': eng('ready')}), pair: %s});
report({hidden: $('now-pair').hidden, title: txt('pair-title'),
rows: [...document.querySelectorAll('#pair-facts dt')].map(dt => dt.textContent + ': ' + dt.nextElementSibling.textContent),
elements: document.querySelectorAll('#pair-facts *').length});
"""
GIB = 2 ** 30
def test_a_box_alone_shows_no_tile(self):
r = run(self, self.BODY % json.dumps({"node_id": "local", "boxes": {}}))
self.assertTrue(r["hidden"], r)
def test_the_other_box_is_said_with_the_figures_this_box_gives_its_own(self):
state = {"name": "spark2", "version": "1.42.0", "models": ["qwen3.8-27b"], "mem_total": 121.6 * self.GIB,
"mem_available": 18.2 * self.GIB, "gpu_temp_c": 61, "gpu_power_w": 42,
"job": {"action": "switch to qwen3.8-flash-next-fp4", "status": "running", "elapsed": 95}}
r = run(self, self.BODY % json.dumps({"node_id": "local", "boxes": {"spark2": {"state": state}}}))
self.assertFalse(r["hidden"], r)
self.assertEqual(r["title"], "The other box: spark2")
self.assertEqual(r["rows"][:3], ["spark2: serves qwen3.8-27b", "memory: 103.4 GiB of 121.6 GiB in use",
"GPU: 61 °C, 42 W"], r)
self.assertIn("Alzeo: v1.42.0", r["rows"])
self.assertTrue(any(x.startswith("job: switch to qwen3.8-flash-next-fp4, running, ") for x in r["rows"]), r)
def test_a_box_that_does_not_answer_is_said_once(self):
# the row read "does not answer: box spark9 does not answer: ..." (captures, 2026-11-03)
why = "nothing listens on its pair port: its proxy is stopped, or older than this pair"
r = run(self, self.BODY % json.dumps({"node_id": "local", "boxes": {
"spark9": {"error": f"box spark9 does not answer: {why}"}}}))
self.assertEqual(r["rows"], [f"spark9: does not answer: {why}"], r)
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_what_the_other_box_says_is_text_never_markup(self):
hostile = '<img src=x onerror="alert(1)">'
r = run(self, self.BODY % json.dumps({"node_id": "local", "boxes": {"spark2": {"state": {
"models": [hostile], "version": hostile, "job": {"action": hostile}}}}}))
self.assertIn(f"spark2: serves {hostile}", r["rows"])
self.assertEqual(r["elements"], 2 * len(r["rows"]), "a dt and a dd per row, nothing else")
if __name__ == "__main__":
unittest.main()
+14 -2
View File
@@ -3398,6 +3398,18 @@ def _pair_why(e):
return re.sub(r"[\x00-\x1f\x7f]", "?", s)[:160] or type(r).__name__
def _pair_read_whole(r, cap):
"""An answer of the other box that is not streamed, at most cap + 1 bytes, or the cut it is: http.client's
read(n) hands over a body its sender ended early as if it were whole and leaves the bytes still owed in
.length (read() alone raises IncompleteRead), as the engine's relay already knows (2026-09-24); an error
answer cut on the way was relayed as complete (found by the tests, 2026-11-03)."""
data = r.read(cap + 1)
owed = getattr(r, "length", None)
if isinstance(owed, int) and owed > 0 and len(data) <= cap:
raise http.client.IncompleteRead(data, owed)
return data
def _cockpit_base():
"""Where this box's cockpit answers: its unit's COCKPIT_BIND and COCKPIT_PORT, 127.0.0.1 for a bind on every
interface (QWEN38_COCKPIT_URL names it outright, the tests)."""
@@ -6181,7 +6193,7 @@ class H(BaseHTTPRequestHandler):
resp = peer["opener"].open(req)
except urllib.error.HTTPError as e:
try:
data = e.read(1 << 20)
data = _pair_read_whole(e.fp, (1 << 20) - 1) 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)
@@ -6218,7 +6230,7 @@ class H(BaseHTTPRequestHandler):
try:
if "text/event-stream" not in (resp.headers.get("Content-Type") or ""):
try:
data = resp.read(PAIR_ANSWER_MAX + 1)
data = _pair_read_whole(resp, PAIR_ANSWER_MAX)
except (OSError, http.client.HTTPException) as e:
if left.is_set():
self._done("CLIENT GONE during pair"); return None
+9 -9
View File
@@ -200,15 +200,15 @@ def write_peer_cert(name, pem):
def drop_files(entries, keep=()):
"""The certificate files of these pair.json entries (and a key file of an earlier version), those under
pair/ and in no entry kept."""
kept = {(CONFIG / os.path.expanduser(q.get(k, ""))).resolve() for q in keep for k in ("key_file", "cert_file")
if isinstance(q, dict) and q.get(k)}
for p in entries:
for k in ("key_file", "cert_file"):
f = (CONFIG / os.path.expanduser(p.get(k) or "")).resolve()
if p.get(k) and f.parent == PAIR_DIR.resolve() and f not in kept:
f.unlink(missing_ok=True)
"""The certificate files of these pair.json entries, those under pair/ and in no entry kept (an entry
edited by hand into something else is passed over)."""
def cert(q):
rel = q.get("cert_file") if isinstance(q, dict) else None
return (CONFIG / os.path.expanduser(rel)).resolve() if isinstance(rel, str) and rel else None
kept = {cert(q) for q in keep} - {None}
for f in map(cert, entries):
if f is not None and f.parent == PAIR_DIR.resolve() and f not in kept:
f.unlink(missing_ok=True)
def url_host(addr):
+2 -1
View File
@@ -378,7 +378,8 @@ class PairTool(unittest.TestCase):
self.assertIn("box2 had a pair with box1 under that name or certificate: replaced", out)
again = self.b1.pair()["peers"]
self.assertEqual(len(again), 1)
self.assertNotEqual((again[0]["key_file"], again[0]["cert_file"]), (first["key_file"], first["cert_file"]))
self.assertNotEqual(again[0]["cert_file"], first["cert_file"])
self.assertNotIn("key_file", again[0], "a pair holds no key of the other box")
self.assertEqual(self.b1.peer_files(), [pathlib.Path(again[0]["cert_file"]).name], "the earlier one dropped")
self.assertEqual(len(self.b2.peer_files()), 1, "box2 too: one certificate, no key")
st, body = self.call(self.b1, "qwen3.8-flash-next-fp4")
+43 -8
View File
@@ -469,6 +469,12 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase):
time.sleep(0.1)
return text in self.journal_of(label)
def assert_said(self, label, text):
"""An outcome line of the journal, waited for: it is written after the answer's last byte, and read at
once it was not there yet now and then (a run of 2026-11-03)."""
if not self.until_in_journal(label, text):
self.fail(f"{text!r} not in the journal of {label}: ...{self.journal_of(label)[-1200:]}")
def spare_proxy(self, label, key, peers=(), name="spark1", pair=None, who="spark1", upstream=None, extra=None,
keyfile=True):
"""A proxy of its own for one test: its pair.json names `peers` ((name, port, key), each with its own
@@ -738,14 +744,14 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase):
self.assertIn(b"from spark1", out)
st, out, _ = self.tls_call(self.pport1, "/v1/models", method="GET")
self.assertEqual([r["id"] for r in json.loads(out)["data"]], ["qwen3.8-27b"], "its own list, not the union")
self.assertIn("sent on by spark2", self.journal("spark1"))
self.assert_said("spark1", "sent on by spark2")
def test_the_cockpits_stop_is_never_taken_from_the_pair_port(self):
# the other box's connection may come from loopback (a tunnel's end, these tests): POST /proxy/stop is
# this machine's operator's, never a pair's
st, out, _ = self.tls_call(self.pport1, "/proxy/stop", {"why": "a pair's stop", "kind": "operator"})
self.assertEqual(st, 403, out[:300])
self.assertIn("403 pair route refused", self.journal("spark1"))
self.assert_said("spark1", "403 pair route refused")
def test_the_pair_port_refuses_a_box_without_a_pinned_certificate(self):
for me in (None, "rogue"):
@@ -872,7 +878,7 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase):
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")
self.assertIn("502 pair answer too large", self.journal("huge"))
self.assert_said("huge", "502 pair answer 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)
@@ -898,7 +904,34 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase):
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_cut")
self.assertIn("UPSTREAM CUT pair", self.journal("cut-error"))
self.assert_said("cut-error", "UPSTREAM CUT pair")
def test_an_answer_the_other_box_cuts_is_said_cut(self):
# a 200 whose body ended before its Content-Length went to the client whole, half a document as a
# complete one: http.client's read(n) says nothing of a body cut short (found by the tests, 2026-11-03)
class CutAnswer(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a):
pass
def do_GET(self):
out = json.dumps({"object": "list", "data": [{"id": "qwen3.8-flash-next-fp4"}]}).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)
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length") or 0))
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", "400"); self.end_headers()
self.wfile.write(b'{"choices": [{"message": {"content": "half'); self.wfile.flush()
self.close_connection = True
self.connection.shutdown(socket.SHUT_RDWR)
port = self.spare_proxy("cut-answer", KEY_1, peers=[("spark2", tls_peer(self, CutAnswer))])
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_cut")
self.assert_said("cut-answer", "UPSTREAM CUT pair")
def test_a_certificate_whose_dates_this_clock_does_not_hold_still_pairs(self):
# a new certificate is valid from the second it is made: two boxes whose clocks disagree could not pair
@@ -977,7 +1010,7 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase):
r.read()
finally:
c.close()
self.assertIn("UPSTREAM CUT pair", self.journal("spark1"))
self.assert_said("spark1", "UPSTREAM CUT pair")
def test_a_request_sent_on_to_a_box_whose_engine_restarts_is_told_to_try_again_not_held(self):
# a box whose engine does not answer while its unit starts again (a switch): its own clients are held for
@@ -1283,6 +1316,9 @@ class TwoBoxesBehindOneEndpointInProcess(TwoBoxesBehindOneEndpoint):
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()
def test_an_answer_the_other_box_cuts_is_said_cut(self):
super().test_an_answer_the_other_box_cuts_is_said_cut()
def test_a_certificate_whose_dates_this_clock_does_not_hold_still_pairs(self):
super().test_a_certificate_whose_dates_this_clock_does_not_hold_still_pairs()
@@ -1368,8 +1404,7 @@ class ThePairsPieces(unittest.TestCase):
return self.mod._pair_parse(json.dumps(conf))
def peer(self, name="spark2", proxy="https://127.0.0.1:30002", who="spark2"):
return {"name": name, "proxy": proxy, "key_file": f"pair/{name}.key", "cert_file": f"pair/{name}.crt",
"sha256": ident(who)[1]}
return {"name": name, "proxy": proxy, "cert_file": f"pair/{name}.crt", "sha256": ident(who)[1]}
def conf_now(self, conf):
"""conf written as pair.json and read by the proxy at once."""
@@ -1385,8 +1420,8 @@ class ThePairsPieces(unittest.TestCase):
self.assertEqual([p["proxy"] for p in ok["peers"]],
["https://127.0.0.1:30002", "https://[fe80::1]:30002", "https://spark2.local:30002"])
self.assertEqual(ok["peers"][2]["sha256"], ident("spark3")[1], "openssl's form, with colons, is taken")
self.assertTrue(ok["peers"][0]["key_file"].endswith("/.config/qwen38/pair/spark2.key"))
self.assertTrue(ok["peers"][0]["cert_file"].endswith("/.config/qwen38/pair/spark2.crt"))
self.assertNotIn("key_file", ok["peers"][0], "the certificate is the pair's only credential")
self.assertTrue(self.mod.PAIR_NAME.fullmatch(self.parse({"peers": []})["name"]), "the host's name, made safe")
def test_what_pair_json_may_not_say(self):