mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-06 04:44:19 +01:00
pair: what two more reviewers found in the changes since the code review
Two independent reviewers (correctness, security; effort max) read eda19f8..87ae395 and reproduced what follows; each fix was checked in the code and has a test that fails on901862b: - Decision 986 held a lane up forever while the other box stayed off once this box had restarted (a power cut): a box never read held every lane it does not load. A box that may serve a lane now holds it up (503, why) for PAIR_FIRST_READ_S (30 s) from the pair's load if it was never read, for PAIR_KNOWN_WAIT_S (15 min) from its last good read if it served it; then this box's lane answers it, as on a box alone. - A box off without a reset made every such request wait the read's 5 s: a box whose last read failed slowly is read again in the background (one read at a time, its own function: a first try handed the read back to the background from the background). - A box listing a model and refusing it twice fell through to this box's lane: a 503. - TCP_USER_TIMEOUT cut a live stream whose client stopped reading for 25 s: dropped, keepalive alone sees a box that lost power. - pair.py add: a Ctrl-C during the checks lost a working pair (both boxes put back now); an undo that came before the other box's write let that write land (a cancelled run is refused there); its record is dropped once the run succeeds (done); a restored entry's name is checked before it names a file; the messages say what was undone. - The other box could end every generation of this one: SGLang aborts every request whose rid starts with one it aborts, and a request it sends on kept its own rid, in the body or the x-override-rid header. It never names one now. - The piped27240agave each request in flight doubled its descriptors, which the other box could exhaust (EMFILE at 256 hops), and select() refused any past 1024 (read as a caller gone by _client_left): the keepers poll() every 50 ms, no descriptor of their own (51 ms through the proxy for an answer of 35 ms at the engine, 502 on v1.41.0). - Nested JSON from the other box (9,990 deep) broke GET /v1/models here and froze the cockpit once written back: its rows and its summary are rebuilt field by field. - Its summary is kept 2 s: its reads were quiet and each one read this cockpit. - Ollama's NDJSON streams reached the client whole at the end: relayed as they come. - Docs and comments said holds, 404 and "within the hour" where the code does not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
901862b3aa
commit
526d5993a5
8 files changed
+603
-128
No files matched your search
+12
-3
@@ -29,10 +29,11 @@ sends that summary alone, over the pair's TLS. To switch the other box's lane, u
|
||||
|
||||
**Non-streamed answers half a second sooner, on every box.** The proxy watched the caller of a request in a
|
||||
select() of 0.5 s, and relayed the answer once that watch had ended, at its next tick: a one-token answer the
|
||||
engine gave in 35 ms took 503 ms through the proxy, eight times in eight (measured on the reference box,
|
||||
engine gave in 35 ms took 502 ms through the proxy, eight times in eight (measured on the reference box,
|
||||
v1.41.0). Every non-streamed request paid it (Claude Code's token counts, the SDKs' default calls), and a
|
||||
stream whose engine took more than a second lost up to 0.45 s more before its first byte. The watch now ends
|
||||
the moment the answer comes. Found by the code review of the pair.
|
||||
stream whose engine took more than a second lost up to 0.45 s more before its first byte. The watch now looks
|
||||
every 50 ms with poll(), which holds no descriptor of its own and has no limit at 1,024 descriptors as select()
|
||||
had: the same answer takes 51 ms through this release's proxy. Found by the code review of the pair.
|
||||
|
||||
**Reviews and tests.** Two independent reviewers, then a code review at max effort, read the pair before this
|
||||
release, and every finding was checked in the code. What they found and this release fixes: an API key swapped
|
||||
@@ -41,6 +42,14 @@ credential now), a client that left a TLS connection was never seen, an answer c
|
||||
as a whole one, a box that lost power held the requests in flight to it for up to an hour (TCP keepalive
|
||||
between the boxes now sees it within 25 s), `pair.py add` undid a working pair while an engine was loading,
|
||||
and the tile's reads every 5 s pushed a paired box's real requests out of the cockpit's view in half an hour.
|
||||
Two more reviewers then read what had changed since, and found: a box restarted while the other one stayed off
|
||||
held every lane it does not load for as long (a box that may serve a lane now holds it up for 30 s if it was
|
||||
never read, 15 min if it served it), a box off without a reset made each such request wait 5 s (it is read
|
||||
again in the background), a Ctrl-C during the checks of `pair.py add` lost a working pair (both boxes are put
|
||||
back), the other box could end every generation of this one by naming request ids, which SGLang aborts by
|
||||
prefix (a request it sends on never names one), nested JSON from it broke this box's model list and froze its
|
||||
cockpit (what comes from it is rebuilt field by field), and the Ollama routes reached the client whole at the
|
||||
end.
|
||||
tests/test_proxy_pair.py runs two proxies over real TLS, as processes and in this one, tests/test_pair_tool.py
|
||||
pairs two proxies through a fake ssh, and the tile and its collector have tests of their own. Each fix has a
|
||||
test that fails on the code before it.
|
||||
|
||||
+9
-3
@@ -159,9 +159,15 @@ 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, 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.
|
||||
a summary of this box (its name in the pair, what serves, its lanes' units, memory, CPU,
|
||||
GPU, the job under way, the version, why its cockpit does not answer when it does not,
|
||||
the time), which the proxy reads from its own cockpit with its own key, never relayed
|
||||
whole, and keeps 2 s, so the other box's reads cost this one a cockpit read every 2 s
|
||||
at most. What a box takes from the other (its list of models, its summary) is rebuilt
|
||||
field by field, each of its type: nothing nested, no NaN, comes through. A request the
|
||||
other box sends on never names the engine's request id, in its body or in a header:
|
||||
SGLang aborts every request whose id starts with one it aborts, and a box naming the
|
||||
ids "0" to "f" could end every generation of the other.
|
||||
This box's cockpit reads the other's through `/proxy/pair/<box>/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
|
||||
|
||||
+5
-2
@@ -42,7 +42,8 @@ one its SSH server sees, give that one: `--back 192.168.100.1`.
|
||||
|
||||
- A request that names a model of one of this repo's lanes (`qwen3.8-27b`, `qwen3.8-flash-next`,
|
||||
`qwen3.8-flash-next-fp4`, `ornith-1.5-122b`, `nemotron-3.5-bolt`, `nemotron-3.5-super-vl`,
|
||||
`kolibri-1`) goes to the box that serves it, streamed or not, OpenAI or Anthropic dialect.
|
||||
`kolibri-1`) goes to the box that serves it, streamed or not, in the OpenAI and Anthropic dialects and on
|
||||
the Ollama (`/api/chat`, `/api/generate`) and SageMaker (`/invocations`) routes.
|
||||
- Any other name (`claude-*` from Claude Code's background tasks, `gpt-*`, none) stays on the box it was
|
||||
sent to, as on a box alone.
|
||||
- `GET /v1/models` lists the models of both boxes, each with a `box` field. It never waits for the other
|
||||
@@ -91,7 +92,9 @@ cockpit for now.
|
||||
- Every request a box sends on comes from one address, so the other box's limit of 64 connections per
|
||||
address is shared by all its clients together.
|
||||
- Both boxes should keep the default `KEEPALIVE_S`: a stream from the other box that stays silent for
|
||||
four of its keepalives (60 s at least) is cut, as a box that went sends nothing more.
|
||||
four of its keepalives (60 s at least) is cut, as a box that went sends nothing more. A box that loses
|
||||
power or its cable while a request waits on it is seen within about 25 s (TCP keepalive between the
|
||||
boxes), and that request gets a 503.
|
||||
- When both boxes serve the same model, its requests stay on the box they were sent to for now.
|
||||
- `GET /v1/models/<id>` answers for the box's own models only.
|
||||
- To switch the other box's lane, use its own cockpit for now: the tile only shows it.
|
||||
|
||||
+190
-81
@@ -3087,6 +3087,25 @@ VLLM_MODEL_ROUTES = ("/v1/chat/completions", "/v1/completions", "/v1/messages",
|
||||
"/invocations")
|
||||
|
||||
|
||||
def strip_rid(body):
|
||||
"""The body without a rid of its own (top level): (body, True) when one was dropped. SGLang takes a rid from
|
||||
the body of a generation, and aborts every request whose rid starts with one it aborts (when its client
|
||||
leaves, too)."""
|
||||
if not body or b'"rid"' not in body:
|
||||
return body, False
|
||||
try:
|
||||
j = json.loads(body)
|
||||
except Exception:
|
||||
return body, False
|
||||
if not isinstance(j, dict) or "rid" not in j:
|
||||
return body, False
|
||||
j.pop("rid")
|
||||
try:
|
||||
return rewritten(j), True
|
||||
except Exception:
|
||||
return body, False
|
||||
|
||||
|
||||
def route_model_name(body, path):
|
||||
"""(the body to forward, the name it replaced or None). On vLLM only, which answers 404
|
||||
to a model it does not serve where SGLang answers any name: a body naming another model
|
||||
@@ -3129,7 +3148,7 @@ def route_model_name(body, path):
|
||||
# name no box serves, and any other name (claude-*, gpt-*, none), stays on this box, as on a box alone
|
||||
# ("any name reaches the lane that serves", claude-local.py; decision 986). A request a peer sends on comes in on
|
||||
# the pair port: it is served here or refused (409), never sent on again, so two boxes that name each
|
||||
# other cannot bounce it. The peer runs every guard of its own on it (sizes, tools, efforts, holds),
|
||||
# other cannot bounce it. The peer runs every guard of its own on it (sizes, tools, efforts; never a hold),
|
||||
# so it goes there as the client wrote it. pair.json is read again when it changes: no restart.
|
||||
# The boxes talk over TLS both ways (decisions 971-978, the model of NVIDIA PAIR's nodes: a
|
||||
# certificate of its own per box, pinned by the other, a client certificate demanded). pair.py makes
|
||||
@@ -3178,7 +3197,17 @@ PAIR_CONNECT_S = PAIR_CONNECT_S if PAIR_CONNECT_S > 0 else 10.0 # 0 made the
|
||||
# MAX_SILENCE_S with nothing (found in review, 2026-11-02)
|
||||
PAIR_STREAM_SILENCE_S = float(os.environ.get("PAIR_STREAM_SILENCE_S") or 0) or max(4 * KEEPALIVE_S, 60.0)
|
||||
PAIR_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,39}")
|
||||
_PAIR = {"stamp": None, "conf": None, "error": None, "seen": 0.0}
|
||||
_PAIR = {"stamp": None, "conf": None, "error": None, "seen": 0.0, "loaded": 0.0}
|
||||
# decision 986 and what a review of it found (2026-11-03): a lane name no box lists waits (503) only for a box
|
||||
# that may serve it and does not answer, and for a while: one that served it at its last good read, for
|
||||
# PAIR_KNOWN_WAIT_S from that read (a lane switch, a reboot), and one never read, for PAIR_FIRST_READ_S from the
|
||||
# pair's load (its first read). Past that, this box's lane answers it, as on a box alone: a box restarted while
|
||||
# the other one stays off held every lane it does not load for as long as that one was off.
|
||||
PAIR_KNOWN_WAIT_S = float(os.environ.get("PAIR_KNOWN_WAIT_S") or 900)
|
||||
PAIR_FIRST_READ_S = float(os.environ.get("PAIR_FIRST_READ_S") or 30)
|
||||
PAIR_SLOW_READ_S = 1.0
|
||||
PAIR_SUMMARY_KEEP_S = 2.0
|
||||
_PAIR_SUMMARY = {"ts": 0.0, "data": None}
|
||||
_PAIR_MODELS: dict = {}
|
||||
_PAIR_LOCK = threading.Lock()
|
||||
|
||||
@@ -3314,7 +3343,7 @@ def pair_conf():
|
||||
conf = _pair_parse(f.read())
|
||||
if conf["peers"]:
|
||||
_pair_tls(conf)
|
||||
_PAIR.update(conf=conf, error=None)
|
||||
_PAIR.update(conf=conf, error=None, loaded=time.monotonic())
|
||||
_PAIR_MODELS.clear()
|
||||
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'}"
|
||||
@@ -3342,6 +3371,15 @@ def peer_models(peer, fresh=False, since=None):
|
||||
asked = time.monotonic()
|
||||
with _PAIR_LOCK:
|
||||
lock = _PAIR_READING.setdefault(peer["name"], threading.Lock())
|
||||
row = _PAIR_MODELS.get(peer["name"])
|
||||
if row and row.get("error") and row.get("read_s", 0) > PAIR_SLOW_READ_S:
|
||||
# a box whose last read failed slowly is read again in the background, never waited for by a request, nor
|
||||
# the read under way: one off without a reset (power, a cable) took the read's whole timeout, and every
|
||||
# request for a lane loaded nowhere waited 5 s for it (found in review, 2026-11-03). One that refused at
|
||||
# once (a proxy restarting, its engine's 503) is read again in the request, as before: the request after
|
||||
# it came back reaches it.
|
||||
_peer_models_soon(peer)
|
||||
return row["models"]
|
||||
with lock:
|
||||
row = _PAIR_MODELS.get(peer["name"])
|
||||
if row and since is not None and row["ts"] >= since:
|
||||
@@ -3362,7 +3400,46 @@ def _peer_models_soon(peer):
|
||||
lock = _PAIR_READING.setdefault(peer["name"], threading.Lock())
|
||||
if lock.locked():
|
||||
return # a read is under way
|
||||
threading.Thread(target=peer_models, args=(peer,), daemon=True).start()
|
||||
threading.Thread(target=_peer_models_refresh, args=(peer,), daemon=True, name=f"pair-list-{peer['name']}").start()
|
||||
|
||||
|
||||
def _peer_models_refresh(peer):
|
||||
"""The background read of a peer's list: one at a time per peer, and only while it is still stale. Not
|
||||
peer_models, which hands a box that did not answer back to the background without reading it."""
|
||||
with _PAIR_LOCK:
|
||||
lock = _PAIR_READING.setdefault(peer["name"], threading.Lock())
|
||||
with lock:
|
||||
row = _PAIR_MODELS.get(peer["name"])
|
||||
if row and time.monotonic() - row["ts"] < PAIR_TTL_S:
|
||||
return
|
||||
_peer_models_read(peer)
|
||||
|
||||
|
||||
def _pair_row(m):
|
||||
"""A row of the other box's list as this box gives it on: its id and its scalar fields, nothing nested (a
|
||||
row nested 9,990 deep parsed, then made every GET /v1/models here drop when written back: found in review,
|
||||
2026-11-03)."""
|
||||
return {k: v for k, v in m.items() if k in ("id", "object", "created", "owned_by", "root", "max_model_len")
|
||||
and (v is None or isinstance(v, (str, int, float, bool)))}
|
||||
|
||||
|
||||
def _pair_summary_clean(s):
|
||||
"""The other box's summary as the tile reads it: the fields cockpit_summary writes, each of its type, nothing
|
||||
else (one nested 9,988 deep froze every view of this cockpit once written back: found in review, 2026-11-03)."""
|
||||
num = lambda v: v if isinstance(v, (int, float)) and not isinstance(v, bool) else None
|
||||
word = lambda v: v[:200] if isinstance(v, str) else None
|
||||
job = s.get("job") if isinstance(s.get("job"), dict) else None
|
||||
lanes = s.get("lanes") if isinstance(s.get("lanes"), dict) else {}
|
||||
models = s.get("models") if isinstance(s.get("models"), list) else []
|
||||
return {"name": word(s.get("name")), "version": word(s.get("version")),
|
||||
"models": [m for m in models if isinstance(m, str) and _PAIR_SAFE_ID.fullmatch(m)][:16],
|
||||
"lanes": {k[:80]: v[:40] for k, v in list(lanes.items())[:16] if isinstance(k, str) and isinstance(v, str)},
|
||||
"mem_total": num(s.get("mem_total")), "mem_available": num(s.get("mem_available")),
|
||||
"cpu_pct": num(s.get("cpu_pct")), "gpu_temp_c": num(s.get("gpu_temp_c")),
|
||||
"gpu_power_w": num(s.get("gpu_power_w")),
|
||||
"job": ({"action": word(job.get("action")), "status": word(job.get("status")),
|
||||
"elapsed": num(job.get("elapsed"))} if job else None),
|
||||
"cockpit": word(s.get("cockpit")), "ts": num(s.get("ts"))}
|
||||
|
||||
|
||||
def _json_finite(data):
|
||||
@@ -3385,6 +3462,7 @@ def _peer_models_read(peer):
|
||||
# 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
|
||||
t0 = time.monotonic()
|
||||
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
|
||||
@@ -3395,7 +3473,7 @@ def _peer_models_read(peer):
|
||||
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)
|
||||
rows = [_pair_row(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:
|
||||
@@ -3406,9 +3484,11 @@ def _peer_models_read(peer):
|
||||
# not answer now may still serve those, and a request for one of them waits for it (503); a box never read
|
||||
# may serve any (another certificate at its address, a box not reached yet: the 503 says why); any other
|
||||
# name is this box's own (decision 986), even while that box is off
|
||||
known = models if err is None else (_PAIR_MODELS.get(peer["name"]) or {}).get("known")
|
||||
_PAIR_MODELS[peer["name"]] = {"ts": time.monotonic(), "models": models, "rows": rows, "error": err,
|
||||
"answered": answered, "known": known}
|
||||
prev = _PAIR_MODELS.get(peer["name"]) or {}
|
||||
now = time.monotonic()
|
||||
known, known_ts = (models, now) if err is None else (prev.get("known"), prev.get("known_ts"))
|
||||
_PAIR_MODELS[peer["name"]] = {"ts": now, "models": models, "rows": rows, "error": err,
|
||||
"answered": answered, "known": known, "known_ts": known_ts, "read_s": now - t0}
|
||||
return models
|
||||
|
||||
|
||||
@@ -3922,14 +4002,15 @@ 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."""
|
||||
of silence, every 5 s, and a box that answers 3 of them with nothing is gone, about 25 s on: the request gets
|
||||
the 503 a box that does not answer gets. A box that is there answers the probes however long its engine works.
|
||||
No TCP_USER_TIMEOUT: it also cut a live stream whose client stopped reading for 25 s (a full window, a review
|
||||
of 2026-11-03 measured it), where a box alone waits CLIENT_IO_S for such a client."""
|
||||
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
|
||||
|
||||
@@ -4402,34 +4483,13 @@ def _peek(sock):
|
||||
return sock.recv(1, socket.MSG_PEEK | socket.MSG_DONTWAIT)
|
||||
|
||||
|
||||
class _Wake(threading.Event):
|
||||
"""The end of a request's wait, as an Event a select() also waits on: set() makes its pipe readable. The
|
||||
keepers watched the caller in a select() of 0.5 s and _forward joins them before relaying, so every
|
||||
non-streamed answer, and every stream whose engine took more than a second, waited for the keeper's next
|
||||
tick: 503 ms through the proxy for an answer the engine gave in 35 ms (measured on the reference box,
|
||||
v1.41.0, 2026-11-03)."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._r, self._w = os.pipe()
|
||||
os.set_blocking(self._w, False)
|
||||
|
||||
def fileno(self):
|
||||
return self._r
|
||||
|
||||
def set(self):
|
||||
super().set()
|
||||
try:
|
||||
os.write(self._w, b"x")
|
||||
except OSError:
|
||||
pass # already written, or closed: the Event says it
|
||||
|
||||
def close(self):
|
||||
for fd in (self._r, self._w):
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
# The keepers watch their caller in poll() ticks of KEEPER_TICK_S, and see the end of their request's wait at the next
|
||||
# tick. With a select() of 0.5 s, and _forward joining them before it relays, every non-streamed answer, and every
|
||||
# stream whose engine took more than a second, waited for that tick: 503 ms through the proxy for an answer the engine
|
||||
# gave in 35 ms (measured on the reference box, v1.41.0, 2026-11-03). A pipe per request ended the wait at once and
|
||||
# doubled the descriptors of a request in flight, which the other box of a pair could then exhaust, and select()
|
||||
# refuses any past 1024 (found in review, 2026-11-03): poll() takes no descriptor and has no such limit.
|
||||
KEEPER_TICK_S = 0.05
|
||||
|
||||
|
||||
def _counted_peer(addr):
|
||||
@@ -4785,7 +4845,10 @@ class H(BaseHTTPRequestHandler):
|
||||
if getattr(self, "_frid", "unset") != "unset":
|
||||
return self._frid
|
||||
if self.path.split("?")[0] in RID_OVERRIDE_ROUTES:
|
||||
self._frid = self.headers.get("x-override-rid") or uuid.uuid4().hex
|
||||
# a request the other box of a pair sent on never names the rid: it could name "0" to "f" and end
|
||||
# every generation here (SGLang aborts by prefix; found in review, 2026-11-03)
|
||||
mine = None if self._pair_hop() else self.headers.get("x-override-rid")
|
||||
self._frid = mine or uuid.uuid4().hex
|
||||
else:
|
||||
self._frid = None
|
||||
return self._frid
|
||||
@@ -4798,8 +4861,11 @@ class H(BaseHTTPRequestHandler):
|
||||
# conversation_id): fields of its scheduler no client of this port has to set. By the
|
||||
# prefix, so that one a later release adds stays here too (found in a cloud review,
|
||||
# 2026-10-18).
|
||||
# A request the other box of a pair sent on keeps no rid of its own either, on any route: SGLang aborts by
|
||||
# prefix, and its rids "0" to "f" ended every generation here (found in review, 2026-11-03)
|
||||
hop = self._pair_hop()
|
||||
h = {k: v for k, v in self.headers.items() if k.lower() not in HOP and k.lower() != PAIR_HOP.lower()
|
||||
and not (k.lower().startswith("x-override-") and k.lower() != "x-override-rid")}
|
||||
and not (k.lower().startswith("x-override-") and (k.lower() != "x-override-rid" or hop))}
|
||||
auth = _upstream_auth(self)
|
||||
if auth:
|
||||
h["Authorization"] = auth
|
||||
@@ -5400,8 +5466,11 @@ class H(BaseHTTPRequestHandler):
|
||||
makes, for a non-streamed request that waits in silence while the engine is away."""
|
||||
sock = self.connection
|
||||
try:
|
||||
readable, _, _ = select.select([sock], [], [], 0)
|
||||
if not readable:
|
||||
# poll(), not select(): select() refuses a descriptor past 1024, and that ValueError read as the
|
||||
# caller gone, a request aborted for a busy proxy (found in review, 2026-11-03)
|
||||
poller = select.poll()
|
||||
poller.register(sock, select.POLLIN)
|
||||
if not poller.poll(0):
|
||||
return False
|
||||
return not _peek(sock)
|
||||
except BlockingIOError:
|
||||
@@ -5489,15 +5558,20 @@ class H(BaseHTTPRequestHandler):
|
||||
sock = self.connection
|
||||
# Under TLS too (_peek): this keeper returned at once on TLS before the pair, and a stop of the
|
||||
# cockpit went unseen while a request waited
|
||||
poller = select.poll()
|
||||
try:
|
||||
poller.register(sock, select.POLLIN)
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
while not done.is_set():
|
||||
if self._stopped_while_routed(done):
|
||||
return
|
||||
try:
|
||||
readable, _, _ = select.select([sock, done] if isinstance(done, _Wake) else [sock], [], [], 0.5)
|
||||
except (OSError, ValueError):
|
||||
readable = poller.poll(KEEPER_TICK_S * 1000)
|
||||
except OSError:
|
||||
return
|
||||
if done.is_set():
|
||||
return # the answer came: woken at once (_Wake), not at the next tick
|
||||
return # the answer came: seen within a tick (KEEPER_TICK_S)
|
||||
if not readable:
|
||||
continue
|
||||
try:
|
||||
@@ -5573,6 +5647,11 @@ class H(BaseHTTPRequestHandler):
|
||||
return
|
||||
sock = self.connection
|
||||
peek = True # through TLS too (_peek; a streamed request of the pair, 2026-11-03)
|
||||
poller = select.poll()
|
||||
try:
|
||||
poller.register(sock, select.POLLIN)
|
||||
except (OSError, ValueError):
|
||||
peek = False # its keepalives still go, on done.wait() ticks
|
||||
anthropic = self.path.startswith("/v1/messages")
|
||||
next_ka = start + KEEPALIVE_S
|
||||
while not done.is_set():
|
||||
@@ -5602,15 +5681,14 @@ class H(BaseHTTPRequestHandler):
|
||||
return
|
||||
next_ka = now + KEEPALIVE_S
|
||||
if not peek:
|
||||
done.wait(min(0.5, max(0.0, next_ka - time.time())))
|
||||
done.wait(min(KEEPER_TICK_S, max(0.0, next_ka - time.time())))
|
||||
continue
|
||||
try:
|
||||
readable, _, _ = select.select([sock, done] if isinstance(done, _Wake) else [sock], [], [],
|
||||
min(0.5, max(0.0, next_ka - time.time())))
|
||||
except (OSError, ValueError):
|
||||
readable = poller.poll(min(KEEPER_TICK_S, max(0.0, next_ka - time.time())) * 1000)
|
||||
except OSError:
|
||||
return
|
||||
if done.is_set():
|
||||
return # the engine answered: woken at once (_Wake)
|
||||
return # the engine answered: seen within a tick (KEEPER_TICK_S)
|
||||
if not readable:
|
||||
continue
|
||||
try:
|
||||
@@ -6081,7 +6159,15 @@ class H(BaseHTTPRequestHandler):
|
||||
return True
|
||||
|
||||
def _pair_cockpit_state(self):
|
||||
"""GET PAIR_COCKPIT_STATE on the pair port: this box summed up for the other box's tile (decision 975)."""
|
||||
"""GET PAIR_COCKPIT_STATE on the pair port: this box summed up for the other box's tile (decision 975). Kept
|
||||
PAIR_SUMMARY_KEEP_S: each summary reads this box's cockpit, and the other box could ask for it as fast as
|
||||
it liked, unseen, its reads being quiet in the journal (found in review, 2026-11-03)."""
|
||||
with _PAIR_LOCK:
|
||||
kept = _PAIR_SUMMARY["data"] if time.monotonic() - _PAIR_SUMMARY["ts"] < PAIR_SUMMARY_KEEP_S else None
|
||||
if kept is not None:
|
||||
self._plain(200, {"Content-Type": "application/json"}, kept)
|
||||
self._done("ok pair cockpit", quiet=True)
|
||||
return
|
||||
try:
|
||||
summary = cockpit_summary()
|
||||
except Exception as e:
|
||||
@@ -6092,7 +6178,10 @@ class H(BaseHTTPRequestHandler):
|
||||
f"keepalive-proxy: the cockpit of this box does not answer ({why})"}}).encode())
|
||||
self._done("503 pair cockpit unreachable")
|
||||
return
|
||||
self._plain(200, {"Content-Type": "application/json"}, json.dumps(summary).encode())
|
||||
data = json.dumps(summary).encode()
|
||||
with _PAIR_LOCK:
|
||||
_PAIR_SUMMARY.update(ts=time.monotonic(), data=data)
|
||||
self._plain(200, {"Content-Type": "application/json"}, data)
|
||||
self._done("ok pair cockpit", quiet=True)
|
||||
|
||||
def _pair_peer_state(self, name):
|
||||
@@ -6122,8 +6211,11 @@ 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_finite(data), dict):
|
||||
summary = _json_finite(data) if len(data) <= 1 << 20 else None
|
||||
if not isinstance(summary, dict):
|
||||
why = "its summary is no JSON object of 1 MiB at most"
|
||||
else:
|
||||
data = json.dumps(_pair_summary_clean(summary)).encode() # its fields alone, rebuilt
|
||||
except urllib.error.HTTPError as e:
|
||||
why = f"HTTP {e.code}"
|
||||
except Exception as e:
|
||||
@@ -6200,9 +6292,15 @@ class H(BaseHTTPRequestHandler):
|
||||
"(~/.config/qwen38/api-key), so it sends no request on to another box", {})
|
||||
self._done("503 pair own key unreadable")
|
||||
return True
|
||||
if attempt == 2 or self._forward_peer(body, peer, name, conf, local) != "moved":
|
||||
if attempt == 2:
|
||||
return False if local is None else self._pair_served_nowhere(name, conf, local)
|
||||
if attempt == 2:
|
||||
# a box lists it and refused it twice (its list lags a switch): never answered here with this box's
|
||||
# own model, which docs/pair.md promises; the client tries again (found in review, 2026-11-03)
|
||||
log(f"{self._peer} pair: {peer['name']} lists {name} and refused it twice: try again")
|
||||
self._pair_refuse(503, "engine_unavailable", f"box {peer['name']} lists {name} and refused it "
|
||||
f"twice (it is switching lanes): try again", pair_served_map(conf, local))
|
||||
self._done("503 pair peer unreachable")
|
||||
return True
|
||||
if self._forward_peer(body, peer, name, conf, local) != "moved":
|
||||
return True
|
||||
since = time.monotonic() # the peer serves another model since its list was read
|
||||
if local is None:
|
||||
@@ -6220,7 +6318,11 @@ class H(BaseHTTPRequestHandler):
|
||||
said = "; ".join(f"{b}: {v if isinstance(v, str) else (', '.join(v) or 'nothing')}" for b, v in served.items())
|
||||
def waited_for(p):
|
||||
row = _PAIR_MODELS.get(p["name"]) or {}
|
||||
return bool(row.get("error")) and (row.get("known") is None or name in row["known"])
|
||||
if not row.get("error"):
|
||||
return False
|
||||
if row.get("known") is None:
|
||||
return time.monotonic() - _PAIR["loaded"] < PAIR_FIRST_READ_S
|
||||
return name in row["known"] and time.monotonic() - (row.get("known_ts") or 0) < PAIR_KNOWN_WAIT_S
|
||||
unread = [p["name"] for p in conf["peers"] if waited_for(p)]
|
||||
if unread:
|
||||
# a peer whose list cannot be read may be the box that serves it (unreachable, or its engine
|
||||
@@ -6237,12 +6339,12 @@ class H(BaseHTTPRequestHandler):
|
||||
|
||||
def _pair_held_refused(self, body, route):
|
||||
"""Role 10, after a hold: the lane that came back may serve another model than the one this request
|
||||
names. On a box of a pair, or for a request an entry sent on, it is refused then (409 sent on, 404
|
||||
otherwise), never answered by that other lane (found in review, 2026-11-02: a peer in the middle of
|
||||
a switch held a request for Flash, and Ornith answered it)."""
|
||||
names. On a box of a pair it is refused then, with a 503 the client tries again, never answered by that
|
||||
other lane on the spot (found in review, 2026-11-02: a peer in the middle of a switch held a request for
|
||||
Flash, and Ornith answered it); sent again, it goes to the box that serves it, or, served by no box, to
|
||||
this box's lane (decision 986). A request the other box sent on is never held (_hold)."""
|
||||
conf = pair_conf()
|
||||
hop = self._pair_hop()
|
||||
if (not (conf and conf["peers"]) and not hop) or route not in PAIR_ROUTES or not body:
|
||||
if not (conf and conf["peers"]) or route not in PAIR_ROUTES or not body:
|
||||
return False
|
||||
name = body_model(body)
|
||||
if name not in LANE_NAMES:
|
||||
@@ -6252,20 +6354,14 @@ class H(BaseHTTPRequestHandler):
|
||||
local = served_models() or None
|
||||
except EngineUnreachable:
|
||||
local = None
|
||||
if name in (local or ()) or (local is None and not hop):
|
||||
if local is None or name in local:
|
||||
return False
|
||||
me = (conf or {}).get("name") or "this box"
|
||||
now = ", ".join(local) if local else "a lane whose name it does not give yet"
|
||||
me = conf.get("name") or "this box"
|
||||
now = ", ".join(local)
|
||||
log(f"{self._peer} REFUSED {name} after a hold: the lane that came back serves {now}")
|
||||
if hop and local:
|
||||
self._pair_refuse(409, "model_not_served", f"this box ({me}) serves {now}, not {name}", {me: list(local)})
|
||||
self._done("409 pair another model here")
|
||||
else:
|
||||
# a 503 the client tries again (a 404 it would take as final): sent again, it goes to the box that
|
||||
# serves it, or is told that none does (found in review, 2026-11-02)
|
||||
self._pair_refuse(503, "engine_unavailable", f"this box ({me}) came back serving {now}, not {name}: "
|
||||
f"try again", {me: list(local) if local else "does not answer"})
|
||||
self._done("503 engine unreachable")
|
||||
self._pair_refuse(503, "engine_unavailable", f"this box ({me}) came back serving {now}, not {name}: "
|
||||
f"try again", {me: list(local)})
|
||||
self._done("503 engine unreachable")
|
||||
return True
|
||||
|
||||
def _forward_peer(self, body, peer, name, conf, local):
|
||||
@@ -6344,7 +6440,10 @@ class H(BaseHTTPRequestHandler):
|
||||
self._done("CLIENT GONE during pair"); return None
|
||||
headers = {k: v for k, v in resp.headers.items() if k.lower() not in PAIR_DROP_IN}
|
||||
try:
|
||||
if "text/event-stream" not in (resp.headers.get("Content-Type") or ""):
|
||||
# a stream is relayed as it comes: SSE, and the NDJSON of the Ollama routes, which reached the
|
||||
# client whole at its end (found in review, 2026-11-03)
|
||||
ctype = resp.headers.get("Content-Type") or ""
|
||||
if "text/event-stream" not in ctype and "application/x-ndjson" not in ctype:
|
||||
try:
|
||||
data = _pair_read_whole(resp, PAIR_ANSWER_MAX)
|
||||
except (OSError, http.client.HTTPException) as e:
|
||||
@@ -6444,6 +6543,13 @@ class H(BaseHTTPRequestHandler):
|
||||
def _served_name(self, body):
|
||||
"""The body as the engine that serves now takes it (route_model_name, qwen_effort_none, nemotron_effort,
|
||||
ornith_effort), each change said once."""
|
||||
if self._pair_hop():
|
||||
# role 10: the rid is this box's to give. The other box naming rids "0" to "f" in its bodies and leaving
|
||||
# ended every generation here, SGLang aborting by prefix (found in review, 2026-11-03)
|
||||
body, dropped = strip_rid(body)
|
||||
if dropped:
|
||||
_say_once_a_minute("hop rid", f"{self._peer} pair: a rid in the body of a request the other box "
|
||||
f"sent on is dropped: this box names its engine's requests")
|
||||
body, renamed = route_model_name(body, self.path)
|
||||
if renamed and _model_rename_logged.first(renamed): # once per name, not per request
|
||||
shown = repr(renamed[:60]) + ("..." if len(renamed) > 60 else "")
|
||||
@@ -6567,7 +6673,7 @@ class H(BaseHTTPRequestHandler):
|
||||
if not self._floor_refused():
|
||||
self._cut_stopped()
|
||||
return None
|
||||
done = _Wake()
|
||||
done = threading.Event()
|
||||
self._wlock = threading.Lock() # the keeper writes into the stream until _open returns
|
||||
whole = bool(body) and answered_whole(body)
|
||||
keeper = None
|
||||
@@ -6581,8 +6687,6 @@ class H(BaseHTTPRequestHandler):
|
||||
done.set() # headers, or an error: the generation is over
|
||||
if keeper is not None:
|
||||
keeper.join(timeout=CLIENT_IO_S)
|
||||
if keeper is None or not keeper.is_alive():
|
||||
done.close() # a keeper still in select() keeps its pipe: never a reused fd there
|
||||
with self._wlock: # and nothing is half-written into the stream
|
||||
pass
|
||||
if getattr(self, "_caller_left", False):
|
||||
@@ -6663,10 +6767,15 @@ class H(BaseHTTPRequestHandler):
|
||||
sock = self.connection
|
||||
if isinstance(sock, ssl.SSLSocket):
|
||||
return # a peek through TLS is not this simple; drain instead
|
||||
poller = select.poll() # not select(): it refuses a descriptor past 1024 (review, 2026-11-03)
|
||||
try:
|
||||
poller.register(sock, select.POLLIN)
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
while not cancel.is_set():
|
||||
try:
|
||||
readable, _, _ = select.select([sock], [], [], 0.5)
|
||||
except (OSError, ValueError):
|
||||
readable = poller.poll(500)
|
||||
except OSError:
|
||||
return
|
||||
if not readable:
|
||||
continue
|
||||
|
||||
@@ -218,6 +218,15 @@ def undo_file(token):
|
||||
return PAIR_DIR / f"undo-{token}.json"
|
||||
|
||||
|
||||
def cancelled(token):
|
||||
"""True when the run of that token was undone here before it wrote (a Ctrl-C or a timeout in its step 1, whose
|
||||
command went on there without its terminal): its write would leave this box paired one way (review, 2026-11-03)."""
|
||||
try:
|
||||
return json.loads(undo_file(token).read_text()).get("cancelled") is True
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
def save_undo(token, name, gone):
|
||||
"""What a run of add is about to replace on this box (the entries, each with its certificate), kept under
|
||||
the run's token, so that the run puts it back if it fails further on (decision 988): run again on a pair
|
||||
@@ -250,13 +259,18 @@ def undo(mod, token):
|
||||
try:
|
||||
rec = json.loads(f.read_text())
|
||||
except (OSError, ValueError):
|
||||
rec = None
|
||||
if not isinstance(rec, dict) or rec.get("cancelled"):
|
||||
# nothing written here by that run, yet: a write of it that comes later is refused (cancelled())
|
||||
write_atomic(f, json.dumps({"cancelled": True}), 0o600)
|
||||
return False
|
||||
conf = read_conf()
|
||||
new, gone = without_peer(conf, rec.get("name"))
|
||||
back = []
|
||||
for item in rec.get("replaced") or []:
|
||||
q = dict(item.get("entry") or {})
|
||||
if not item.get("pem") or not isinstance(q.get("name"), str):
|
||||
# the name becomes a file name: one of a box's names only, never a path (review, 2026-11-03)
|
||||
if not item.get("pem") or not isinstance(q.get("name"), str) or not mod.PAIR_NAME.fullmatch(q["name"]):
|
||||
continue
|
||||
q["cert_file"] = write_peer_cert(q["name"], item["pem"])
|
||||
back.append(q)
|
||||
@@ -267,6 +281,22 @@ def undo(mod, token):
|
||||
return True
|
||||
|
||||
|
||||
def roll_back(mod, dest, token, name, me):
|
||||
"""Both boxes as they were before the run of token, said in words for the message."""
|
||||
try:
|
||||
undone = None if undo(mod, token) else "no record of what this run replaced here"
|
||||
except BaseException as e:
|
||||
undone = SAFE_TEXT.sub("?", str(getattr(e, "code", None) or e))[:200]
|
||||
why = undo_there(dest, token)
|
||||
if why is None and undone is None:
|
||||
return "Both boxes are as they were before this run"
|
||||
kept = ("This box is as it was" if undone is None else
|
||||
f"This box keeps the new pair ({undone}): run pair.py remove {name} here")
|
||||
if why is not None:
|
||||
kept += f", and {name} could not be told ({why}): run pair.py remove {me} there"
|
||||
return kept
|
||||
|
||||
|
||||
def undo_there(dest, token):
|
||||
"""The other box as it was before this run, or the reason it could not be told; never raises."""
|
||||
try:
|
||||
@@ -370,6 +400,8 @@ def do_accept(req):
|
||||
f"(python3 ~/dgx-spark-qwen38/pair.py name <another name>)")
|
||||
back = address(req["back"], "--back") if req.get("back") else ssh_client_address()
|
||||
pem = ensure_identity(me)
|
||||
if cancelled(token_of(req)):
|
||||
raise SystemExit("pair.py: this run of add was already undone here: nothing written")
|
||||
new, gone, _ = with_peer(mod, conf, req["name"], f"https://{url_host(back)}:{int(req['port'])}",
|
||||
req["cert"], ssh=back)
|
||||
save_undo(token_of(req), req["name"], gone)
|
||||
@@ -395,6 +427,12 @@ def do_undo(req):
|
||||
return {"undone": undo(mod, token_of(req))}
|
||||
|
||||
|
||||
def do_done(req):
|
||||
"""The run of that token succeeded: its record goes."""
|
||||
undo_file(token_of(req)).unlink(missing_ok=True)
|
||||
return {"done": True}
|
||||
|
||||
|
||||
def do_check(req):
|
||||
mod = proxy_module()
|
||||
models, why = reach(mod, req["name"], min(float(req.get("within", 10)), 60.0))
|
||||
@@ -411,7 +449,8 @@ def do_forget(req):
|
||||
def remote(req):
|
||||
"""The other box's half (run there over SSH by ssh_call): one JSON line on standard output."""
|
||||
try:
|
||||
out = {"accept": do_accept, "check": do_check, "forget": do_forget, "undo": do_undo}[req["do"]](req)
|
||||
out = {"accept": do_accept, "check": do_check, "forget": do_forget, "undo": do_undo,
|
||||
"done": do_done}[req["do"]](req)
|
||||
except SystemExit as e:
|
||||
out = {"error": str(e.code if e.code is not None else "").removeprefix("pair.py: ")[:800]}
|
||||
except Exception as e:
|
||||
@@ -516,7 +555,10 @@ def cmd_add(args, mod):
|
||||
try:
|
||||
r = ssh_call(dest, "accept", {"name": me, "port": mod.PAIR_PORT, "back": back, "cert": pem, "undo": token})
|
||||
except BaseException:
|
||||
undo_there(dest, token)
|
||||
why = undo_there(dest, token)
|
||||
if why is not None:
|
||||
sys.stderr.write(f"pair.py: {dest} could not be told to undo this run ({why}): if pair.py status there "
|
||||
f"lists {me}, run pair.py remove {me} there\n")
|
||||
raise
|
||||
name, their_pem = r.get("name"), r.get("cert")
|
||||
try:
|
||||
@@ -553,31 +595,25 @@ def cmd_add(args, mod):
|
||||
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:
|
||||
there, why_there = reach(mod, name, 10)
|
||||
back_said = f"https://{url_host(their_back)}:{mod.PAIR_PORT}"
|
||||
here, why_here = None, None
|
||||
if why_there is None:
|
||||
try:
|
||||
got = ssh_call(dest, "check", {"name": me, "within": 10}).get("models") or []
|
||||
here = [m for m in got if isinstance(m, str) and mod._PAIR_SAFE_ID.fullmatch(m)]
|
||||
except SystemExit as e:
|
||||
why_here = str(e.code if e.code is not None else "").removeprefix(f"pair.py: on {dest}: ")
|
||||
try:
|
||||
there, why_there = reach(mod, name, 10)
|
||||
back_said = f"https://{url_host(their_back)}:{mod.PAIR_PORT}"
|
||||
here, why_here = None, None
|
||||
if why_there is None:
|
||||
try:
|
||||
got = ssh_call(dest, "check", {"name": me, "within": 10}).get("models") or []
|
||||
here = [m for m in got if isinstance(m, str) and mod._PAIR_SAFE_ID.fullmatch(m)]
|
||||
except SystemExit as e:
|
||||
why_here = str(e.code if e.code is not None else "").removeprefix(f"pair.py: on {dest}: ")
|
||||
except BaseException:
|
||||
# a Ctrl-C during the checks left the new pair on both boxes, and a pair they had lost (found in
|
||||
# review, 2026-11-03): put back as it was, then the interruption goes on
|
||||
sys.stderr.write(f"pair.py: interrupted during the checks. {roll_back(mod, dest, token, name, me)}.\n")
|
||||
raise
|
||||
if why_there is not None or why_here is not None:
|
||||
# undone on both boxes whatever fails on the way, and never in place of why the pair failed
|
||||
# (found in review, 2026-11-03)
|
||||
try:
|
||||
undo(mod, token)
|
||||
undone = None
|
||||
except BaseException as e:
|
||||
undone = SAFE_TEXT.sub("?", str(getattr(e, "code", None) or e))[:200]
|
||||
why = undo_there(dest, token)
|
||||
if why is None and undone is None:
|
||||
kept = "Both boxes are as they were before this run"
|
||||
else:
|
||||
kept = ("This box is as it was" if undone is None else
|
||||
f"This box keeps the new pair ({undone}): run pair.py remove {name} here")
|
||||
if why is not None:
|
||||
kept += f", and {name} could not be told ({why}): run pair.py remove {me} there"
|
||||
kept = roll_back(mod, dest, token, name, me)
|
||||
if why_there is not None:
|
||||
raise SystemExit(f"pair.py: this box cannot reach the pair port of {name} at https://{url_host(host)}:{port}: "
|
||||
f"{why_there}. {kept}. Check that both boxes run this version of Alzeo, that no "
|
||||
@@ -586,7 +622,13 @@ def cmd_add(args, mod):
|
||||
raise SystemExit(f"pair.py: {name} cannot reach the pair port of this box at {back_said}: {why_here}. "
|
||||
f"{kept}. Check that no firewall stops {mod.PAIR_PORT}/tcp toward this box, and give "
|
||||
f"this box's address as {name} reaches it with --back (--no-check keeps a pair anyway).")
|
||||
undo_file(token).unlink(missing_ok=True) # kept: the other box drops its record within the hour
|
||||
# the run's records go on both boxes (certificates and addresses only; a record left there by a cut goes at
|
||||
# that box's next add, an hour on)
|
||||
undo_file(token).unlink(missing_ok=True)
|
||||
try:
|
||||
ssh_call(dest, "done", {"undo": token}, timeout=60)
|
||||
except SystemExit:
|
||||
pass
|
||||
print(f"{me} and {name} are a pair: each box now sends a request for a model the other serves to that box.")
|
||||
if not args.no_check:
|
||||
print(f" {me} -> {name} (https://{url_host(host)}:{port}): answers over TLS, serves {', '.join(there) or 'nothing now'}")
|
||||
|
||||
+79
-9
@@ -9,6 +9,7 @@ no box ever holds the other's API key, and nothing secret is on a command line o
|
||||
box writes is what its proxy takes, and a request then goes from one box to the other over TLS; a check that
|
||||
fails, or an SSH cut once the other box wrote, keeps nothing on either box; `remove` unpairs both; an SSH
|
||||
that does not reach the other box, two boxes of one name and an older proxy are said with what to do."""
|
||||
import base64
|
||||
import hashlib
|
||||
import http.client
|
||||
import http.server
|
||||
@@ -17,6 +18,7 @@ import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import signal
|
||||
import socketserver
|
||||
import ssl
|
||||
import stat
|
||||
@@ -220,15 +222,19 @@ class PairTool(unittest.TestCase):
|
||||
def add(self, *extra):
|
||||
return self.run_tool(self.b1, "add", "127.0.0.1", "--ssh", "box2", *extra)
|
||||
|
||||
def call_until_200(self, box, model, within=15.0):
|
||||
"""A call made again until it answers 200: a proxy reads pair.json again within 2 s of a change."""
|
||||
def call_until_from(self, box, model, there, within=15.0):
|
||||
"""A call made again until the box `there` answers it: a proxy reads pair.json again within 2 s of a change."""
|
||||
deadline = time.monotonic() + within
|
||||
while True:
|
||||
st, body = self.call(box, model)
|
||||
if st == 200 or time.monotonic() > deadline:
|
||||
if (st == 200 and f"from {there}".encode() in body) or time.monotonic() > deadline:
|
||||
return st, body
|
||||
time.sleep(0.5)
|
||||
|
||||
def tool_env(self, box):
|
||||
return {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(box.home), "PAIR_PORT": str(box.pair_port),
|
||||
"FAKE_SSH_BOXES": str(self.boxes_file), "FAKE_SSH_LOG": str(self.ssh_log)}
|
||||
|
||||
def call(self, box, model):
|
||||
c = http.client.HTTPConnection("127.0.0.1", box.port, timeout=60)
|
||||
try:
|
||||
@@ -341,9 +347,11 @@ class PairTool(unittest.TestCase):
|
||||
self.assertEqual(([p["name"] for p in self.b1.pair()["peers"]], [p["name"] for p in self.b2.pair()["peers"]]),
|
||||
(["box2"], ["box1"]), "the pair as it was, on both boxes")
|
||||
self.assertEqual((len(self.b1.peer_files()), len(self.b2.peer_files())), (1, 1), "each certificate back")
|
||||
for here, model in ((self.b1, "qwen3.8-flash-next-fp4"), (self.b2, "qwen3.8-27b")):
|
||||
st, body = self.call_until_200(here, model)
|
||||
self.assertEqual(st, 200, body[:300])
|
||||
# each box's request for the other box's model is answered by that box: since decision 986 a box alone
|
||||
# answers 200 too, from its own lane (review, 2026-11-03: these calls could not fail)
|
||||
for here, model, there in ((self.b1, "qwen3.8-flash-next-fp4", "box2"), (self.b2, "qwen3.8-27b", "box1")):
|
||||
st, body = self.call_until_from(here, model, there)
|
||||
self.assertIn(f"from {there}".encode(), body, body[:300])
|
||||
|
||||
def test_a_check_that_fails_on_a_working_pair_puts_both_boxes_back(self):
|
||||
rc, out = self.add()
|
||||
@@ -354,9 +362,71 @@ class PairTool(unittest.TestCase):
|
||||
self.assertNotEqual(rc, 0)
|
||||
self.assertIn("Both boxes are as they were before this run", out)
|
||||
self.ssh_boxes({})
|
||||
for here, model in ((self.b1, "qwen3.8-flash-next-fp4"), (self.b2, "qwen3.8-27b")):
|
||||
st, body = self.call_until_200(here, model)
|
||||
self.assertEqual(st, 200, body[:300])
|
||||
# each box's request for the other box's model is answered by that box: since decision 986 a box alone
|
||||
# answers 200 too, from its own lane (review, 2026-11-03: these calls could not fail)
|
||||
for here, model, there in ((self.b1, "qwen3.8-flash-next-fp4", "box2"), (self.b2, "qwen3.8-27b", "box1")):
|
||||
st, body = self.call_until_from(here, model, there)
|
||||
self.assertIn(f"from {there}".encode(), body, body[:300])
|
||||
|
||||
def test_a_ctrl_c_during_the_checks_puts_both_boxes_back(self):
|
||||
# step 3 had no handler of its own: a Ctrl-C left the new pair on both boxes, and lost the one they had
|
||||
# (review, 2026-11-03)
|
||||
rc, out = self.add()
|
||||
self.assertEqual(rc, 0, out)
|
||||
held = localports.held(self) # box2 now says a pair port nothing listens on: the check waits 10 s
|
||||
self.ssh_boxes({"box2": {"home": str(self.b2.home), "pair_port": held, "from": "127.0.0.1"}})
|
||||
proc = subprocess.Popen([sys.executable, str(REPO / "pair.py"), "add", "127.0.0.1", "--ssh", "box2"],
|
||||
env=self.tool_env(self.b1), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
peers = (self.b1.pair() or {}).get("peers") or []
|
||||
if peers and peers[0].get("proxy", "").endswith(f":{held}"):
|
||||
break # step 2 wrote: the run is in its checks now
|
||||
time.sleep(0.1)
|
||||
time.sleep(1)
|
||||
proc.send_signal(signal.SIGINT)
|
||||
out, _ = proc.communicate(timeout=60)
|
||||
self.assertNotEqual(proc.returncode, 0, out)
|
||||
self.assertIn("interrupted during the checks. Both boxes are as they were before this run", out)
|
||||
self.ssh_boxes({})
|
||||
for here, model, there in ((self.b1, "qwen3.8-flash-next-fp4", "box2"), (self.b2, "qwen3.8-27b", "box1")):
|
||||
st, body = self.call_until_from(here, model, there)
|
||||
self.assertIn(f"from {there}".encode(), body, body[:300])
|
||||
|
||||
def remote(self, box, req):
|
||||
"""The other box's half of pair.py, run on `box` as ssh_call runs it there: its answer."""
|
||||
spec = importlib.util.spec_from_file_location(f"pair_boot_{time.time_ns()}", REPO / "pair.py")
|
||||
tool = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(tool) # its main() runs only as a script
|
||||
code = tool.REMOTE_BOOT
|
||||
stdin = base64.b64encode((REPO / "pair.py").read_bytes()).decode() + "\n" + json.dumps(req) + "\n"
|
||||
r = subprocess.run([sys.executable, "-I", "-c", code], input=stdin, env=self.tool_env(box),
|
||||
capture_output=True, text=True, timeout=60)
|
||||
return json.loads(r.stdout.strip().splitlines()[-1])
|
||||
|
||||
def test_a_run_undone_there_before_it_wrote_writes_nothing_after(self):
|
||||
# a Ctrl-C or a timeout in step 1 ends the local ssh, not the command there: its undo could come first,
|
||||
# find nothing, and its write land after it, a pair one way (review, 2026-11-03)
|
||||
token = "ab" * 16
|
||||
self.assertEqual(self.run_tool(self.b1, "identity")[0], 0) # box1's certificate, made once
|
||||
self.assertEqual(self.remote(self.b2, {"do": "undo", "undo": token}), {"undone": False})
|
||||
out = self.remote(self.b2, {"do": "accept", "undo": token, "name": "box1", "port": self.b1.pair_port,
|
||||
"back": "127.0.0.1", "cert": (self.b1.cfg / "pair/identity/cert.pem").read_text()})
|
||||
self.assertIn("already undone", out.get("error", ""), out)
|
||||
self.assertEqual((self.b2.pair() or {"peers": []})["peers"], [], "nothing written there")
|
||||
|
||||
def test_an_undo_never_writes_outside_its_folder(self):
|
||||
# the name of an entry put back becomes a file name: one with a path in it wrote outside pair/ (review,
|
||||
# 2026-11-03); it is passed over
|
||||
self.assertEqual(self.run_tool(self.b1, "identity")[0], 0)
|
||||
pem = (self.b1.cfg / "pair/identity/cert.pem").read_text()
|
||||
token = "cd" * 16
|
||||
(self.b2.cfg / "pair").mkdir(mode=0o700, exist_ok=True)
|
||||
(self.b2.cfg / f"pair/undo-{token}.json").write_text(json.dumps({"name": "box1", "replaced": [
|
||||
{"entry": {"name": "../../evil", "proxy": "https://127.0.0.1:1", "cert_file": "x", "sha256": "00" * 32},
|
||||
"pem": pem}]}))
|
||||
self.assertEqual(self.remote(self.b2, {"do": "undo", "undo": token}), {"undone": True})
|
||||
self.assertEqual(sorted(str(f) for f in self.b2.home.rglob("evil@*")), [], "no file outside pair/")
|
||||
|
||||
def test_a_check_the_other_way_that_fails_keeps_nothing_either(self):
|
||||
# box2 reaches box1 at an address where box1 does not listen
|
||||
|
||||
@@ -340,6 +340,27 @@ class AnAnswerIsRelayedTheMomentItComes(unittest.TestCase):
|
||||
self.assertLess(min(took), 0.25, took)
|
||||
|
||||
|
||||
class ARequestInFlightHoldsItsSocketsAlone(unittest.TestCase):
|
||||
"""A first fix of the relay's wait gave each request in flight a pipe of its own, two descriptors more: the other
|
||||
box of a pair could then exhaust the proxy's 1024, and select() refused any past 1024 (review, 2026-11-03). Its
|
||||
keepers now poll(): a request in flight holds its client's socket and its engine's, nothing else."""
|
||||
INPROC = False
|
||||
|
||||
def test_eight_requests_in_flight_hold_no_more_than_their_sockets(self):
|
||||
box = Box(self, inproc=self.INPROC)
|
||||
box.start_engine(delay=2.0)
|
||||
where = f"/proc/{os.getpid() if self.INPROC else box.proc.pid}/fd"
|
||||
before = len(os.listdir(where))
|
||||
replies = [box.send(stream=False) for _ in range(8)]
|
||||
time.sleep(1.0) # all of them in flight, their engine still working
|
||||
during = len(os.listdir(where))
|
||||
for r in replies:
|
||||
self.assertTrue(r.done.wait(15))
|
||||
self.assertEqual(r.status, 200)
|
||||
# in this process: the test's client socket and the fake engine's too, two per request more
|
||||
self.assertLessEqual((during - before) / 8, 4.5 if self.INPROC else 2.5, (before, during))
|
||||
|
||||
|
||||
class WhatIsNotWaitedFor(unittest.TestCase):
|
||||
INPROC = False
|
||||
|
||||
@@ -666,6 +687,13 @@ class AnAnswerIsRelayedTheMomentItComesInProcess(AnAnswerIsRelayedTheMomentItCom
|
||||
super().test_a_stream_whose_engine_took_over_a_second_is_relayed_at_once()
|
||||
|
||||
|
||||
class ARequestInFlightHoldsItsSocketsAloneInProcess(ARequestInFlightHoldsItsSocketsAlone):
|
||||
INPROC = True
|
||||
|
||||
def test_eight_requests_in_flight_hold_no_more_than_their_sockets(self):
|
||||
super().test_eight_requests_in_flight_hold_no_more_than_their_sockets()
|
||||
|
||||
|
||||
class WhatIsNotWaitedForInProcess(WhatIsNotWaitedFor):
|
||||
INPROC = True
|
||||
|
||||
@@ -725,7 +753,8 @@ class AHoldEndsInProcess(AHoldEnds):
|
||||
class EveryCaseHasItsInProcessTwin(unittest.TestCase):
|
||||
def test_each_twin_declares_every_case_of_its_class(self):
|
||||
for twin in (AStreamedRequestWaitsForItsEngineInProcess, ANonStreamedRequestWaitsInSilenceInProcess,
|
||||
AnAnswerIsRelayedTheMomentItComesInProcess, WhatIsNotWaitedForInProcess, AHoldEndsInProcess):
|
||||
AnAnswerIsRelayedTheMomentItComesInProcess, ARequestInFlightHoldsItsSocketsAloneInProcess,
|
||||
WhatIsNotWaitedForInProcess, AHoldEndsInProcess):
|
||||
base = twin.__bases__[0]
|
||||
cases = {n for n in vars(base) if n.startswith("test_")}
|
||||
self.assertTrue(cases, base.__name__)
|
||||
|
||||
+210
-3
@@ -159,6 +159,7 @@ def fake_engine(name, model):
|
||||
protocol_version = "HTTP/1.1"
|
||||
served = [model]
|
||||
seen: list = []
|
||||
rids: list = [] # (the body's rid, the x-override-rid header) of every POST
|
||||
delay = 0.0
|
||||
mode = "ok" # "down": /v1/models answers 503 (a boot) ; "cut": a stream dies mid-way
|
||||
|
||||
@@ -187,6 +188,7 @@ def fake_engine(name, model):
|
||||
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
|
||||
Handler.seen.append((self.path, body.get("model"), self.headers.get("Authorization"),
|
||||
self.headers.get("X-Alzeo-Pair-Hop")))
|
||||
Handler.rids.append((body.get("rid"), self.headers.get("x-override-rid")))
|
||||
time.sleep(Handler.delay)
|
||||
if self.path.startswith("/v1/messages"):
|
||||
return self.reply({"id": "m", "type": "message", "role": "assistant", "model": Handler.served[0],
|
||||
@@ -237,6 +239,7 @@ class FakeCockpit(http.server.BaseHTTPRequestHandler):
|
||||
keys = {KEY_1, KEY_2}
|
||||
logins: list = []
|
||||
sessions: set = set()
|
||||
states: list = [] # one per /api/state read
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
@@ -263,7 +266,10 @@ class FakeCockpit(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if (self.headers.get("Cookie") or "").removeprefix("cockpit=") not in FakeCockpit.sessions:
|
||||
return self.reply(401, {"error": "auth"})
|
||||
self.reply(200, COCKPIT_STATE) if self.path == "/api/state" else self.reply(404, {"error": "not found"})
|
||||
if self.path == "/api/state":
|
||||
FakeCockpit.states.append(1)
|
||||
return self.reply(200, COCKPIT_STATE)
|
||||
self.reply(404, {"error": "not found"})
|
||||
|
||||
|
||||
def tls_peer(test, handler, me="spark2", trusts=("spark1",)):
|
||||
@@ -430,7 +436,7 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def setUp(self):
|
||||
self.E1.seen.clear(); self.E2.seen.clear()
|
||||
self.E1.seen.clear(); self.E2.seen.clear(); self.E1.rids.clear(); self.E2.rids.clear()
|
||||
self.E1.served[:] = ["qwen3.8-27b"]; self.E2.served[:] = ["qwen3.8-flash-next-fp4"]
|
||||
self.E1.delay = self.E2.delay = 0.0
|
||||
self.E1.mode = self.E2.mode = "ok"
|
||||
@@ -760,6 +766,85 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase):
|
||||
self.assertEqual([r["id"] for r in json.loads(out)["data"]], ["qwen3.8-27b"], "its own list, not the union")
|
||||
self.assert_said("spark1", "sent on by spark2")
|
||||
|
||||
def test_the_other_boxs_rows_and_summary_are_rebuilt_from_their_fields(self):
|
||||
# nested 9,990 deep, a row parsed and then made every GET /v1/models here drop when written back, and a
|
||||
# summary froze every view of the cockpit (review, 2026-11-03)
|
||||
deep = "[" * 9990 + "]" * 9990
|
||||
|
||||
class Deep(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/pair/cockpit/state"):
|
||||
out = ('{"name": "spark2", "models": ["qwen3.8-flash-next-fp4"], "job": {"action": ' + deep
|
||||
+ '}, "extra": 1}').encode()
|
||||
else:
|
||||
out = ('{"object": "list", "data": [{"id": "qwen3.8-flash-next-fp4", "owned_by": "sglang", '
|
||||
'"nested": ' + deep + '}]}').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)
|
||||
port = self.spare_proxy("deep", KEY_1, peers=[("spark2", tls_peer(self, Deep))])
|
||||
st, rows = self.models_once_known(port=port)
|
||||
self.assertEqual((st, rows.get("qwen3.8-flash-next-fp4")), (200, "spark2"))
|
||||
st, out, _ = self.call("/v1/models", port=port, method="GET")
|
||||
row = [r for r in json.loads(out)["data"] if r["id"] == "qwen3.8-flash-next-fp4"][0]
|
||||
self.assertEqual(set(row), {"id", "owned_by", "box"}, "its scalar fields alone")
|
||||
st, out, _ = self.call("/proxy/pair/spark2/state", port=port, method="GET")
|
||||
self.assertEqual(st, 200, out[:200])
|
||||
s = json.loads(out)
|
||||
self.assertEqual((s["models"], s["job"]["action"], "extra" in s), (["qwen3.8-flash-next-fp4"], None, False))
|
||||
|
||||
def test_an_ndjson_stream_from_the_other_box_arrives_as_it_comes(self):
|
||||
# the Ollama routes stream NDJSON, and the entry read every answer but SSE whole (review, 2026-11-03)
|
||||
class Ollama(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/x-ndjson")
|
||||
self.send_header("Transfer-Encoding", "chunked"); self.end_headers()
|
||||
for line, pause in ((b'{"message": {"content": "one"}, "done": false}\n', 2.0),
|
||||
(b'{"message": {"content": "two"}, "done": true}\n', 0.0)):
|
||||
self.wfile.write(b"%x\r\n%s\r\n" % (len(line), line)); self.wfile.flush()
|
||||
time.sleep(pause)
|
||||
self.wfile.write(b"0\r\n\r\n"); self.wfile.flush()
|
||||
port = self.spare_proxy("ndjson", KEY_1, peers=[("spark2", tls_peer(self, Ollama))])
|
||||
c = http.client.HTTPConnection("127.0.0.1", port, timeout=30)
|
||||
self.addCleanup(c.close)
|
||||
t0 = time.monotonic()
|
||||
c.request("POST", "/api/chat", json.dumps(self.chat("qwen3.8-flash-next-fp4", stream=True)).encode(),
|
||||
{"Content-Type": "application/json", "Authorization": f"Bearer {KEY_1}"})
|
||||
r = c.getresponse()
|
||||
first = r.readline()
|
||||
self.assertIn(b'"one"', first)
|
||||
self.assertLess(time.monotonic() - t0, 1.5, "its first line before its end")
|
||||
self.assertIn(b'"two"', r.read())
|
||||
|
||||
def test_the_other_box_never_names_the_engines_requests_here(self):
|
||||
# SGLang aborts every request whose rid starts with one it aborts: the other box naming rids "0" to "f",
|
||||
# in a body or in the header, and leaving, ended every generation here (review, 2026-11-03)
|
||||
for path in ("/v1/completions", "/v1/chat/completions", "/invocations"):
|
||||
with self.subTest(path=path):
|
||||
st, out, _ = self.tls_call(self.pport1, path, dict(self.chat("qwen3.8-27b"), rid="0"),
|
||||
headers={"X-Override-Rid": "0"})
|
||||
self.assertEqual(st, 200, out[:300])
|
||||
rid, header = self.E1.rids[-1]
|
||||
self.assertIsNone(rid, "no rid of the other box's in the body")
|
||||
self.assertNotEqual(header, "0", "nor in the header")
|
||||
if path == "/v1/chat/completions":
|
||||
self.assertRegex(header or "", r"^[0-9a-f]{32}$", "this box names it")
|
||||
|
||||
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
|
||||
@@ -1005,6 +1090,8 @@ 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()
|
||||
time.sleep(2.2) # past the summary another test may have had kept (PAIR_SUMMARY_KEEP_S)
|
||||
FakeCockpit.states.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")
|
||||
@@ -1023,6 +1110,8 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase):
|
||||
for kept_home in ("feed", "repo_dir", "argv", "secret log", "10.0.0.9", "disks"):
|
||||
self.assertNotIn(kept_home, out.decode(), "its feed, paths and logs stay on the other box")
|
||||
self.assertEqual(FakeCockpit.logins, [KEY_2], "logged in once, with that box's own key, its session kept")
|
||||
# the other box could ask for it as fast as it liked, each time a read of this cockpit (review, 2026-11-03)
|
||||
self.assertEqual(len(FakeCockpit.states), 1, "two reads within PAIR_SUMMARY_KEEP_S: one read of the cockpit")
|
||||
|
||||
def test_the_tiles_route_is_this_machines_alone(self):
|
||||
st, out, _ = self.tls_call(self.pport1, "/proxy/pair/spark2/state", method="GET")
|
||||
@@ -1047,6 +1136,79 @@ class TwoBoxesBehindOneEndpoint(unittest.TestCase):
|
||||
self.E2.mode = "ok"
|
||||
time.sleep(PAIR_TTL + 0.5)
|
||||
|
||||
def test_a_box_never_read_holds_no_lane_past_its_first_read(self):
|
||||
# the entry restarted while the other box stays off (a power cut): every lane it does not load got a 503
|
||||
# for as long as that box was off (review, 2026-11-03); past its first read, it holds nothing up (986)
|
||||
port = self.spare_proxy("first-read", KEY_1, peers=[("spark2", localports.held(self))],
|
||||
extra={"PAIR_FIRST_READ_S": "1"})
|
||||
time.sleep(1.5)
|
||||
st, out, _ = self.call("/v1/chat/completions", self.chat("qwen3.8-flash-next-fp4"), port=port)
|
||||
self.assertEqual(st, 200, out[:300])
|
||||
self.assertIn(b"from spark1", out)
|
||||
|
||||
def test_a_box_that_went_off_holds_its_lanes_for_a_while_then_none(self):
|
||||
class Going(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
up = True
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def reply(self, code, obj):
|
||||
out = json.dumps(obj).encode()
|
||||
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):
|
||||
if not Going.up:
|
||||
return self.reply(503, {"error": "its lane is loading"})
|
||||
self.reply(200, {"object": "list", "data": [{"id": "qwen3.8-flash-next-fp4"}]})
|
||||
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
||||
self.reply(200, {"id": "c", "choices": [{"message": {"content": "from going"}}]})
|
||||
port = self.spare_proxy("known-wait", KEY_1, peers=[("spark2", tls_peer(self, Going))],
|
||||
extra={"PAIR_KNOWN_WAIT_S": "3", "PAIR_TTL_S": "0.5"})
|
||||
st, out, _ = self.call("/v1/chat/completions", self.chat("qwen3.8-flash-next-fp4"), port=port)
|
||||
self.assertIn(b"from going", out)
|
||||
Going.up = False
|
||||
time.sleep(1)
|
||||
st, out, _ = self.call("/v1/chat/completions", self.chat("qwen3.8-flash-next-fp4"), port=port)
|
||||
self.assertEqual(st, 503, out[:300]) # it served it at its last good read: try again
|
||||
time.sleep(3.5)
|
||||
st, out, _ = self.call("/v1/chat/completions", self.chat("qwen3.8-flash-next-fp4"), port=port)
|
||||
self.assertEqual(st, 200, out[:300]) # off for longer than a switch: this box's lane answers it
|
||||
self.assertIn(b"from spark1", out)
|
||||
|
||||
def test_a_box_that_lists_a_model_and_refuses_it_twice_gets_a_503_never_this_boxs_answer(self):
|
||||
# docs/pair.md promises that a box never answers the other box's model with its own: a 409 twice from a
|
||||
# box whose list says it serves it fell through to this box's lane (review, 2026-11-03)
|
||||
class Lagging(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
posts: list = []
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def reply(self, code, obj):
|
||||
out = json.dumps(obj).encode()
|
||||
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, {"object": "list", "data": [{"id": "qwen3.8-flash-next-fp4"}]})
|
||||
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
||||
Lagging.posts.append(1)
|
||||
self.reply(409, {"error": {"type": "model_not_served", "message": "another model here now"}})
|
||||
port = self.spare_proxy("twice-409", KEY_1, peers=[("spark2", tls_peer(self, Lagging))])
|
||||
st, out, _ = self.call("/v1/chat/completions", self.chat("qwen3.8-flash-next-fp4"), port=port)
|
||||
self.assertEqual(st, 503, out[:300])
|
||||
self.assertIn("refused it twice", json.loads(out)["error"]["message"])
|
||||
self.assertNotIn(b"from spark1", out)
|
||||
self.assertEqual(len(Lagging.posts), 2)
|
||||
|
||||
def test_a_lane_the_box_that_does_not_answer_never_served_is_answered_here(self):
|
||||
# decision 986 holds while the other box is off: only a model it served at its last good read waits
|
||||
# for it (503 above); a client set up for a lane loaded nowhere is answered here, as on a box alone
|
||||
@@ -1361,6 +1523,15 @@ class TwoBoxesBehindOneEndpointInProcess(TwoBoxesBehindOneEndpoint):
|
||||
def test_a_request_on_the_pair_port_is_a_hop_from_the_box_of_its_certificate(self):
|
||||
super().test_a_request_on_the_pair_port_is_a_hop_from_the_box_of_its_certificate()
|
||||
|
||||
def test_the_other_boxs_rows_and_summary_are_rebuilt_from_their_fields(self):
|
||||
super().test_the_other_boxs_rows_and_summary_are_rebuilt_from_their_fields()
|
||||
|
||||
def test_an_ndjson_stream_from_the_other_box_arrives_as_it_comes(self):
|
||||
super().test_an_ndjson_stream_from_the_other_box_arrives_as_it_comes()
|
||||
|
||||
def test_the_other_box_never_names_the_engines_requests_here(self):
|
||||
super().test_the_other_box_never_names_the_engines_requests_here()
|
||||
|
||||
def test_the_cockpits_stop_is_never_taken_from_the_pair_port(self):
|
||||
super().test_the_cockpits_stop_is_never_taken_from_the_pair_port()
|
||||
|
||||
@@ -1409,6 +1580,15 @@ class TwoBoxesBehindOneEndpointInProcess(TwoBoxesBehindOneEndpoint):
|
||||
def test_a_peer_whose_engine_restarts_gets_a_503_to_try_again_not_a_404(self):
|
||||
super().test_a_peer_whose_engine_restarts_gets_a_503_to_try_again_not_a_404()
|
||||
|
||||
def test_a_box_never_read_holds_no_lane_past_its_first_read(self):
|
||||
super().test_a_box_never_read_holds_no_lane_past_its_first_read()
|
||||
|
||||
def test_a_box_that_went_off_holds_its_lanes_for_a_while_then_none(self):
|
||||
super().test_a_box_that_went_off_holds_its_lanes_for_a_while_then_none()
|
||||
|
||||
def test_a_box_that_lists_a_model_and_refuses_it_twice_gets_a_503_never_this_boxs_answer(self):
|
||||
super().test_a_box_that_lists_a_model_and_refuses_it_twice_gets_a_503_never_this_boxs_answer()
|
||||
|
||||
def test_a_lane_the_box_that_does_not_answer_never_served_is_answered_here(self):
|
||||
super().test_a_lane_the_box_that_does_not_answer_never_served_is_answered_here()
|
||||
|
||||
@@ -1596,6 +1776,32 @@ class ThePairsPieces(unittest.TestCase):
|
||||
time.sleep(0.05)
|
||||
self.assertEqual((self.mod._PAIR_MODELS.get("early") or {}).get("models"), ("kolibri-1",), "read with no request")
|
||||
|
||||
def test_a_box_that_did_not_answer_is_read_again_in_the_background_once(self):
|
||||
# a box off without a reset took each read's whole timeout, and every request for a lane loaded nowhere
|
||||
# waited 5 s for it (review, 2026-11-03); the first fix of it handed the read back to the background from
|
||||
# the background, a thread after a thread: one read at a time, never waited for
|
||||
class Frozen(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
time.sleep(30)
|
||||
conf = self.mod._pair_parse(json.dumps({"name": "spark1", "peers": [
|
||||
peer_entry(self.cfg, "frozen", tls_peer(self, Frozen), who="spark2")]}))
|
||||
self.mod._pair_tls(conf)
|
||||
peer = conf["peers"][0]
|
||||
self.mod._PAIR_MODELS.pop("frozen", None)
|
||||
self.assertEqual(self.mod.peer_models(peer), ()) # its first read: its whole timeout, once
|
||||
self.assertTrue(self.mod._PAIR_MODELS["frozen"]["error"])
|
||||
self.mod._PAIR_MODELS["frozen"]["ts"] -= 60 # stale: read again, in the background
|
||||
t0 = time.monotonic()
|
||||
for _ in range(20):
|
||||
self.assertEqual(self.mod.peer_models(peer, fresh=True, since=time.monotonic()), ())
|
||||
self.assertLess(time.monotonic() - t0, 1.0, "no request waits for a box that did not answer")
|
||||
time.sleep(0.3)
|
||||
self.assertLessEqual(sum(t.name == "pair-list-frozen" for t in threading.enumerate()), 1,
|
||||
"one read of it in the background at a time")
|
||||
|
||||
def test_a_peers_list_is_read_kept_and_read_again(self):
|
||||
class Lists(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
@@ -1781,7 +1987,8 @@ class ThePairsPieces(unittest.TestCase):
|
||||
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))
|
||||
# no TCP_USER_TIMEOUT: it also cut a live stream whose client stopped reading for 25 s (review, 2026-11-03)
|
||||
self.assertEqual(got, (1, 10, 5, 3, 0))
|
||||
# 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)
|
||||
|
||||
Reference in new issue
Block a user