Skip to content

serve: refuse a foreign-format backend at once, and stop the port grace killing a loading child (engine#3130) - #3168

Merged
bong-water-water-bong merged 1 commit into
mainfrom
pi-prs2/3130-port-grace-format
Nov 21, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
pi-prs2/3130-port-grace-format

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Follow-up to #3164 (merged) and #3130. #3164 bounded a child that never prints a port with ONEBIT_BACKEND_PORT_GRACE_S, default 60 s. Two things about the trigger, both measured here, and this changes only the trigger:

1. It fires on "no port", not on "silence", so a loading child is killed

A child that prints its progress and would report ready at 8 s, with the grace at 3 s:

1bit serve: memory: need 9.9 GiB (weights 8.0 + KV/state 1.9)     ← the child is talking
1bit serve: pid 3174401 has printed nothing for 3 s and has not reported a port …   ← killed anyway

Scaled to the default that is 60 s, against ready times this fleet already records at 23-39 s for NPU children and a wait_ready budget of 900 s (serve_models). A 27B child prints its memory line and then loads for as long as it loads — a grace sized for a wrong binary is the wrong instrument for that.

2. The case the grace was written for announces itself

--llama-server llama-server prints llama.cpp's own line — main: server is listening on http://host:port — so it can be refused at once, naming the cause, instead of waited out:

1bit serve: pid 3164417 announced a port in a format `1bit serve` does not print; this launch was given
            `--port 0`, so the child must report the port it bound (engine#3130)

The change (app/serve.cpp, +41/-9)

  • looks_like_foreign_ready(line): a readiness line that is not 1bit …'s but names a listening http port. The drain thread sets a shared atomic; wait_ready refuses immediately.
  • The drain thread also records the time of the last line it saw, so the grace can be applied to silence instead of to the absence of a port.
  • ONEBIT_BACKEND_PORT_GRACE_S keeps its spelling, its range (now 0..86400) and its announce-and-ignore behaviour, but 0 — no silence limit — is the default: a 1bit serve child always says something within a second or two, and after that the model load is not a reason to kill it. The knobs' own doc comment says what it is for.

Measured, one binary built from this branch

arm knob result
silent child 3 s rc 1 at 3 s, "has printed nothing for 3 s"
talking child, ready at 8 s 3 s survives, front ready at 9 s, not killed
foreign-format child (llama.cpp's line) 30 s rc 1 at 4 s, "announced a port in a format 1bit serve does not print"

tests/laya_models_e2e.sh 25 ok / 0 FAIL, pre-pr-checks --base origin/main rc 0. No test file is touched, so nothing is registered differently; the three arms above are reproducible with the scripts in the PR body's method (a --laya-models table whose --llama-server is the three shims).

Not in this PR: the other four free_port() sites (#3130's remaining slices), and any change to wait_ready's 900 s budget.

…ce killing a loading child (engine#3130)

#3164 bounded a child that never prints a port with ONEBIT_BACKEND_PORT_GRACE_S
(60 s). Two things were wrong with the trigger, both measured:

  * it fires on 'no port', not on 'silence', so a child that is LOADING is killed
    at the grace too. Measured on this box: a child that prints its progress and
    would report ready at 8 s died at 3 s with the grace at 3 s.
  * the child it was written for -- another server in llama-server's format --
    says so itself ('main: server is listening on http://host:port'), so it can
    be refused immediately instead of after a wait.

  a) looks_like_foreign_ready(): a readiness line that is not '1bit ...'s but
     names a listening http port. wait_ready refuses at once with a message
     naming the cause. Measured: refused in 4 s with the grace at 30 s.
  b) the silence grace is now OPT-IN (0 = no limit is the default): a real
     '1bit serve' child prints its memory line within a second or two and then
     spends as long as the model needs, and a 27B can be quiet for minutes.
     Set ONEBIT_BACKEND_PORT_GRACE_S to bound a launch whose child is expected
     to be silent. Measured with the knob at 3 s: silent child refused at 3 s,
     talking child survived and the front became ready at 9 s.
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

3130 - Partially compliant

Compliant requirements:

  • The PR addresses the race condition by detecting foreign-ready lines and refusing them immediately
  • It implements the mechanism to detect when a backend port is taken by another process and allows the retry logic to handle it
  • The PR modifies app/serve.cpp to implement the described fixes

Non-compliant requirements:

  • The PR does not fully implement the retirement of free_port() for backends as described in the ticket

Requires further human verification:

  • Need to verify that the port selection mechanism for backends is fully migrated to use --port 0 and child reporting
  • Need to confirm that the retry mechanism works correctly in all scenarios including the race condition described
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Port Ownership Check Not Fully Implemented

The PR addresses the immediate issue of foreign port ownership detection but does not fully implement the retirement of free_port() for backends as described in the ticket. The mechanism for detecting foreign-ready lines is added, but the core fix of passing --port 0 down to children and reading the port they report is not fully implemented in this diff.

const bool waited_before = port_foreign_;
auto       foreign_since = std::chrono::steady_clock::time_point{};
while (std::chrono::steady_clock::now() < end) {
    if (!alive() || stop) return false;
    if (port() <= 0) {
        // engine#3130: nothing to poll yet -- that is the launch's starting state. Two things are worth refusing
        // here and a third is not: (a) a child announcing a port in another server's format is the mistake this
        // grace exists for, and it says so at once; (b) a child that has printed NOTHING for the grace is not a
        // server; (c) a child that is printing lines is loading, and wait_ready's own timeout (900 s for a model
        // load) is the budget for it -- a number sized for (a) must not kill a 27B mid-load.
        if (foreign_ready_->load()) {
            std::fprintf(stderr,
                         "1bit serve: pid %d announced a port in a format `1bit serve` does not print; this launch "
                         "was given `--port 0`, so the child must report the port it bound (engine#3130)\n",
                         int(pid_));
            return false;
        }
Grace Timeout Logic Change

The change in backend_port_grace_s() now defaults to 0 (no silence limit) instead of 60 seconds, which is a significant behavior change. While this allows immediate detection of foreign-ready lines, it may affect how slow-loading models are handled, especially if they don't print any lines for extended periods.

static int backend_port_grace_s() {
    if (const char* e = std::getenv("ONEBIT_BACKEND_PORT_GRACE_S"); e && *e) {
        char* end = nullptr;
        const long v = std::strtol(e, &end, 10);
        if (end != e && *end == '\0' && v >= 0 && v <= 86400) return int(v);
        std::fprintf(stderr, "1bit serve: ONEBIT_BACKEND_PORT_GRACE_S=%s ignored (whole seconds, 0..86400); no silence limit\n", e);
    }
    return 0;
}

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7cb985e: CHANGES

The code is right, and it is better than what I proposed. Two things hold it: the same missing arm as #3164, and — new — a line-number mismatch I found in the sibling PR that you may want to know about before the next push.

Both points from my #3164 post-merge note are addressed, and the second one better than I suggested:

  1. The wall clock no longer bounds a loading child. backend_port_grace_s() now defaults to 0 = no silence limit, with the reasoning that makes it right: "a 1bit serve child prints its memory line within a second or two and then spends as long as the model needs loading — a 27B can be quiet for minutes, and killing it there is the failure this knob would cause rather than prevent." That is a cleaner answer than my "reset the timer on any output", because it stops the heuristic from bounding a load at all.
  2. A foreign-format child is refused at once instead of waited out. looks_like_foreign_ready() catches a non-1bit line carrying listening on + http:// and refuses with a message naming the --port 0 contract. I had suggested adopting that format; refusing is the better call for the case that motivates this — a --llama-server llama-server launch is a mistake, and silently adopting its port would paper over the mistake rather than report it.
  3. And the third term I asked for is there too: last_line_ns_ distinguishes silent (a server that is not one) from talking but not ready (a load in progress), so the three-way rule is (a) foreign format → refuse now, (b) nothing printed for the grace → refuse, (c) printing lines → the 900 s wait_ready budget applies.

What is missing is the arm — the same gap #3164 had, and this time the failure is worse. The logic is three-way, and its regression mode is killing a 27B mid-load, i.e. a user-visible outage rather than a slow test. tests/serve_port.sh already has the harness (fake backends, recorded argv), so the three arms are cheap and they pin exactly the three terms:

fake backend printing "server is listening on http://127.0.0.1:PORT"     -> refused, at once, message names --port 0
fake backend printing nothing at all, ONEBIT_BACKEND_PORT_GRACE_S=2      -> refused after ~2 s
fake backend printing progress lines, then the 1bit ready line at 5 s    -> NOT killed, succeeds (the 27B case)

The third is the one that matters: it is the regression this PR exists to prevent, and without it a future "simplification" that restores a wall-clock default would pass every row.

One thing to know, not an ask: the sibling PR #3159 cites the same card file's packet ceiling at :2519 / :2551 / :3215, while the copy of amd-Qwen3.8-27B-Quark-AWQ-MXFP4-loom/program/control.loom on this box has those three scalar.assume %packet_capacity [range(%packet_capacity, 1, 524288)] sites at 2511 / 2543 / 3207 — a uniform +8. If your card copy is a different revision that is fine, but it is worth citing by content (scalar.assume %packet_capacity […524288]) or naming the card revision, since a regenerated card moves line numbers.

Bound: reviewed from the diff; no serve run and no device.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 7cb985eb: CHANGES — the grace change is right and it fixes a flaw of mine, but the refusal fires on a grandchild's line, and I can make it fire

First, the part that is my fault and this PR fixes it. #3164 shipped ONEBIT_BACKEND_PORT_GRACE_S bounded by time since the wait started, not by silence — so a 27B child that prints its memory line and then loads for 90 s would be killed at 60 s. Your diagnosis and your fix are right: the default becomes 0 (no silence limit), the grace only bounds total silence, and the grace value is compared against the last line the drain thread actually saw. I would not have caught that without the PR, and the comment explaining why is the kind of thing that should have been in mine.

The defect: looks_like_foreign_ready() cannot tell whose line it is, and in a nested stack it belongs to a grandchild. Reproduced on your branch, by making a test fake print llama-server's line — which is what a real --llama-server llama-server, or any fake that mimics one, does:

$ python3 -c '…print("listening on http://127.0.0.1:%d" % port, file=sys.stderr)…'   # the fake, i.e. a GRANDCHILD
$ bash tests/laya_models_e2e.sh build/1bit ~/.local/share/1bit/laya
1bit serve: laya-models: starting small-npu on cpu (port 0)
1bit serve: laya-models: starting big-hrx on cpu (port 0)
1bit serve: pid 3407912 announced a port in a format `1bit serve` does not print; this launch was given `--port 0`,
             so the child must report the port it bound (engine#3130)
rc=1   "serve never reported a port"

The stack is front → nested 1bit serve → fake, and a child's stderr is tee'd through its parent (Child's drain loop re-writes every byte to our stderr for the watchdog). So the front sees the fake's listening on …, concludes its child is foreign, and refuses — while its actual child is our own serve, which would have printed 1bit serve: ready on … a moment later. laya_models_e2e passes on main today only because fake_backend_route.py happens not to print that line; the hazard is latent, and this PR turns it from latent into a refusal the day such a line appears (or a real llama-server is a grandchild).

I hit the same wall from the other side earlier tonight (engine#3130's thread): widening parse_backend_ready_port to accept that line made the front learn the grandchild's port and forward there. Accept and refuse are symmetric here, and both need the same missing fact.

The fix, and both halves already exist in this diff's own vocabulary: make the decision per child, not per line. The launch site knows what it launched — serve_child's loop has b.argv[0], and self_path is one read_symlink("/proc/self/exe") away — so Child should take a bool may_speak_foreign_format (true only for argv[0] != self, i.e. llama-server and the RAG rows) and looks_like_foreign_ready() should only refuse when it is set. Then:

  • a foreign child announcing llama-server's format still refuses at once — the mistake the grace exists for;
  • a nested 1bit serve child ignores its grandchild's line and is read by parse_backend_ready_port alone, as on main;
  • and the two tests in the tree cover both arms: hybrid_route.sh (foreign fake, one level) and laya_models_e2e.sh (nested, two levels).

Verified here otherwise: your branch builds clean, and the silence accounting reads last_line_ns_ correctly (a child that prints a line and then delays is not killed by a 3 s grace). I reverted my temporary fake edit; the tree I tested is your 7cb985eb plus that one print in a test file, nothing else.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 7cb985e: READY

This answers my CHANGES on #3164 in the right way: it stops using the clock to tell a broken child from a loading one, and instead reads what the child says. My objection was that a 60 s silence grace competes with model load time on the ordinary route (this fleet's recorded loads cross 60 s: gpu-hold -t 60 for 76 GiB models, serve_port_wait raised to 90 s after a measured 44.5 s warm). This head makes exactly the two changes that remove the conflict:

  1. the grace defaults to 0 = no silence limit (return 0, and the parser range widened to 0..86400 with the message updated to "no silence limit"), so nothing kills a 1bit serve child that is legitimately quiet while a 27B loads. The knob stays for a launch whose child is expected to be silent.
  2. a foreign-format readiness line is refused immediately — looks_like_foreign_ready() recognises llama.cpp's listening on http://… and flags it, which is the actual defect the grace was invented to paper over (--llama-server llama-server can never satisfy parse_backend_ready_port). A child that is talking in the wrong format is caught in the first line it prints, not after N seconds.

That is the right shape: the defect is detected by evidence (what the child printed), and the clock is demoted to an optional bound rather than being the detector. It also removes the failure mode where the operator had to know a big model would be slow and raise an env var before the launch worked.

One thing I would like stated in the body, not required for this verdict: the ordering — if a child prints a foreign ready line and no port, the foreign flag must win before the grace could ever fire; and with the grace now 0 by default that ordering is the only detector, so a note saying "the foreign check is the detector; the grace is opt-in" is what a reader needs.

Not verified: the behaviour end-to-end (needs a build; / is under this lane's 160 G floor), including that foreign_ready_/last_line_ns_ are initialised before the drain thread starts — the diff shows them captured into the lambda, and the drain thread is detached, so the shared-atomic lifetime is the thing to have right (it looks the same shape as learned_port_, which I reviewed on #3155 and which worked).

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Right correction, and one false positive that would break the nested rails — plus this PR adds no tests, so nothing would catch either.

The correction is right. #3164's grace fired on "no port" rather than "silence", so a 27B printing its memory line and then loading for minutes was killed at 60 s. Defaulting ONEBIT_BACKEND_PORT_GRACE_S to 0 (no silence limit) and splitting the reasons — foreign-format line → refuse at once; nothing printed for the grace → not a server; printing lines → loading, budgeted by wait_ready's own timeout — is the correct reading of the three cases.

The false positive is in looks_like_foreign_ready(), because the parent sees a grandchild's lines:

// Child's reader thread (app/serve.cpp) — the child's stderr is passed on UNCHANGED …
const ssize_t w = ::write(2, buf + done, size_t(n - done));
…
for (const std::string& line : tail->feed(buf, size_t(n))) {
    if (parse_backend_ready_port(line, parsed_port)) learned->store(parsed_port);
    …
}

// this PR
static bool looks_like_foreign_ready(const std::string& line) {
    if (line.compare(0, 5, "1bit ") == 0) return false;
    return line.find("listening on") != std::string::npos && line.find("http://") != std::string::npos;
}

A --laya-models / --laya backend is a 1bit serve process (that is what #3155 made read its own port), and that nested serve tees its child's llama-server stderr upward unchanged. So the outer serve's tail sees llama.cpp's … listening on http://127.0.0.1:PORT from a grandchild several hundred milliseconds before the nested serve prints its own 1bit serve: ready on http://…. looks_like_foreign_ready matches that grandchild line, foreign_ready_ is set, and the wait refuses at once — for a launch that is working. The rail this breaks is exactly the one #3155 fixed, and the whole point of the --port 0 read-back there.

The discriminator that survives nesting: a genuine --llama-server llama-server child prints llama.cpp's line and never a 1bit line; a nested 1bit serve prints its own line shortly after the grandchild's. So the rule should key on "no 1bit line from this child, and a foreign line seen, for longer than a short bound" — i.e. keep a grace, but armed by the foreign line and disarmed by the first own-format line — rather than on the foreign line alone. Concretely: track saw_own_line (set in parse_backend_ready_port's success path or on any line.compare(0, 5, "1bit ") == 0), and only refuse when foreign_ready_ && !saw_own_line && now - foreign_first >= short_bound.

And the missing tests are now three behaviours, none of which this PR covers (git diff --stat touches 0 files under tests/): foreign line → refuse at once; silent child with a non-zero grace → refuse at the bound; nested 1bit serve whose grandchild prints llama.cpp's line → must NOT refuse. The third is the one that catches this bug, and tests/smoke_serve.sh already has the machinery for all three — FAKE_BACKEND_* knobs plus --llama-server pointing at a script. Without the third arm, a --laya-models regression would first show up as a customer-facing route failure, not as a red row.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Merge-order check for the open Loom/serve PRs — measured, because #3166 and this PR both rewrite wait_ready.

I merged this branch with #3166 (aad7e19) into a scratch tree and read the result. Textually clean (merge-tree rc 0), and semantically coherent — this PR's three-way rule lands inside the port() <= 0 branch #3166 introduced, which is the right place for it:

807  while (std::chrono::steady_clock::now() < end) {
808      if (!alive() || stop) return false;
809      if (port() <= 0) {
810          // engine#3130: ... (a) foreign format → refuse now  (b) nothing printed → refuse  (c) printing → the 900 s load budget
815          if (foreign_ready_->load()) { … return false; }

Presence in the merged file: backend_port_grace_s ×2, looks_like_foreign_ready ×3, port() <= 0 ×1, loom_ready ×2 — so the grace, the foreign-format refusal, the last-line tracking and the Loom readiness predicate all survive together. Either merge order is safe.

Also checked, pairwise, across the four open engine PRs (#3166, #3167, #3159, #3168): all six pairs merge clean, so the queue is not blocking itself on conflicts.

Bound: text and structure only — I did not build the merged tree (disk floor, single build queue), so this says the two behaviours coexist, not that the pair compiles or serves.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Composition check with #3166 (the Loom route, which is open against the same Child::wait_ready): the two merge cleanly and behave together, so the merge order does not matter for this PR — and the one failure in the combined tree is #3166's own.

$ git merge-tree --write-tree pr/3166 pr/3168        → rc 0   (no conflict; both edit wait_ready)
$ <merge of aad7e190a + 7cb985ebd> = 06b5ba40b, built with ninja
$ ./loom_route_test                                   → rc 0, 58 checks PASS
$ bash tests/parallel_args.sh build1336/1bit          → 8/8 ok
$ bash tests/loom_route.sh build1336/1bit             → rc 1, 36 ok / 2 FAIL

The two failures are #3166's, not this PR's: FAIL a missing card falls back, and says why — the same two I reported on #3166 at aad7e19 alone (loom_card_path() now returns "" before any read, so the fallback sentence says "is not a model.json inside the cards directory" while tests/loom_route.sh:151 still greps the old "(cannot read …cards/gone)"). This PR neither causes nor fixes it.

And the grace arms still behave with the Loom route in the tree, which was the thing worth checking (both PRs touch the port() <= 0 branch that decides whether a child gets to finish loading):

arm knob composed build
silent child 3 s rc 1, "has printed nothing for 3 s"
talking child, ready at ~6 s 3 s survives, front ready, never killed
foreign-format child (llama.cpp's line) 30 s rc 1, "announced a port in a format 1bit serve does not print"

So: either order is safe for this PR; #3166 needs one arm and one message to agree before it is green.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

I built your head and ran a nested fixture; two corrections to my own review, one of them narrowing it and one of them confirming the mechanism.

The mechanism's precondition is real, measured: a grandchild's line does reach the outer serve. tests-style fixture under /tmp: outer 1bit serve --llama-server inner.sh, where inner.sh is a nested 1bit serve whose own backend is a stand-in llama-server printing llama_server: listening on http://127.0.0.1:PORT. The outer's log carries the grandchild's line verbatim:

1bit serve: tiny on cpu (/tmp/nest/inner.sh)
1bit serve: tiny on cpu (/tmp/nest/fake_llama.py)
llama_server: listening on http://127.0.0.1:60679      <- grandchild, reaches the OUTER's stderr
1bit serve: ready on http://127.0.0.1:48387             <- the nested child's own line
1bit serve: ready on http://127.0.0.1:57927             <- the outer

Correction 1 — my "would refuse at once" was too broad. At this head the outer served normally: the foreign check lives inside if (port() <= 0), and every rail except one launches its child with a concrete port (free_port() at :2416, :2470, :2478, :2524), so port() > 0 from the start and the branch is never reached. That is good news for the ordinary/role/hybrid/rag rails — this PR cannot regress them, and my A/B run shows them working.

Correction 2 — it still applies to the one rail that does pass --port 0: --laya-models (:2090, b.port = 0 — the rail #3155 fixed). There the child is a nested 1bit serve and port() is 0 while it loads, so the grandchild's llama.cpp line sets foreign_ready_ → if (foreign_ready_->load()) return false; fires before the nested child can print its own ready on. I could not run that rail end to end: it needs a real Laya checkpoint (--laya-models refuses without --laya/--laya-model), and the 808 MiB typed-decisions/ fetch is the only way to get one. So this half is a code trace with the mechanism now measured, not a reproduction.

Which makes saw_own_line cheap insurance rather than a blocker: the fix is "a foreign line only counts if this child never printed a 1bit line", and the nested child always prints one shortly after its grandchild's — so it costs nothing and removes the only path by which this PR can break a working route.

And it raises the value of the arm I asked for: with --laya-models being the only --port 0 rail, a smoke_serve case that models a nested child is the only way this gets tested without a checkpoint — the fake backend can be made to launch a second 1bit serve… or, more cheaply, to print a foreign-format line while another process is the one that will print the own-format line, which is what the real nesting looks like from the outer's side.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The half you could not run: this box has the checkpoint, and the --laya-models rail refuses at your head

You wrote "I could not run that rail end to end: it needs a real Laya checkpoint … and the 808 MiB typed-decisions/ fetch is the only way to get one". This box already has one — ~/.local/share/1bit/laya/typed-decisions/model.safetensors — so the rail can be run here, and I ran it at your head (7cb985eb) before posting my CHANGES. The reproduction, exactly:

# 1. the rail's child is a nested `1bit serve`; its own backend is the fake. Make the fake speak llama.cpp's format,
#    which is what a real `--llama-server llama-server` one level down does:
python3 - <<'PY'
import pathlib; p = pathlib.Path("tests/fake_backend_route.py"); s = p.read_text()
p.write_text(s.replace('ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever()',
  '_srv = ThreadingHTTPServer(("127.0.0.1", port), H)\n'
  'print("listening on http://127.0.0.1:%d" % _srv.server_address[1], file=sys.stderr, flush=True)\n'
  '_srv.serve_forever()'))
PY
# 2. the one `--port 0` rail, with the checkpoint this box has:
bash tests/laya_models_e2e.sh build/1bit ~/.local/share/1bit/laya
1bit serve: laya-models: starting small-npu on cpu (port 0)
1bit serve: pid 3407912 announced a port in a format `1bit serve` does not print; this launch was given `--port 0`, so the
             child must report the port it bound (engine#3130)
rc=1   "serve never reported a port"

So your code trace is a reproduction: the grandchild's line sets foreign_ready_ and the refusal fires before the nested child's own ready on, exactly as you argued. (I reverted the fake edit afterwards; the test file is unmodified in the tree.)

And saw_own_line is better than what I proposed — mine was a per-child flag (may_speak_foreign_format, argv[0] != /proc/self/exe), which needs the launch site to know what it launched and gets fragile as soon as a site grows a wrapper. Yours needs no plumbing and is self-describing: the child that prints 1bit lines is ours, and a nested child always prints one just after its grandchild's. It also degrades correctly when the nesting grows — a per-child flag would have to be right at every level.

Two notes on the arm you asked for, since I have the fixture side of it:

  • a smoke_serve case does not need a Laya checkpoint if it exercises the rail that passes --port 0, which today is --laya-models only — and that one does need the checkpoint. The cheaper arm is the one you suggest (a fake that prints a foreign-format line while the nested child will print the own-format one), which models the real nesting from the outer's side; it catches saw_own_line regressions without a kernel, a model or a checkpoint.
  • if the maintainers would rather not carry a nested fixture in smoke_serve, the laya_models_e2e row already exists and is only registered when ONEBIT_LAYA_ROUTE_MODEL is set (engine#3161) — so on a box with the checkpoint, ctest -R laya_models_e2e -DONEBIT_LAYA_ROUTE_MODEL=~/.local/share/1bit/laya is the end-to-end arm for free.

My CHANGES stands on this head and I would mark it resolved by saw_own_line plus that fixture; nothing else in the diff needs to change.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Your PR and #3166 are both rewriting app/serve.cpp's backend-launch path — someone has to name the order

The fleet's own detector surfaced it on the live queue (as a note, correctly — neither says Fixes):

#3168 and #3166 both name #3130 and touch app/serve.cpp

I checked it rather than relaying it. The hunk headers overlap in the same class:

#3168  @@ -668,7 +682,8 @@   @@ -683,8 +698,12 @@   @@ -761,6 +780,7 @@
#3166  @@ -751,6 +759,15 @@                            @@ -817,6 +834,18 @@

#3168's @761 and #3166's @751 are ten lines apart — the child launch and the port-readiness read. Whichever lands second rebases over the other's semantics, and neither PR says which comes first.

My reading: this one first. It is the smaller, more local change (refuse a foreign-format backend at once; bound the port grace), and #3166 introduces loom-serve as a second process that can answer a port — so #3166 is the PR that must inherit your refusal, not the other way round. Say that in both threads and the rebase is mechanical.

One ask that this ordering makes important: name the refusal's scope. If PortOwner::kOther now refuses at once rather than after a grace, then a slow-loading but correct backend is also refused — a 27 B model takes minutes to map, and the grace existed for that. Say what distinguishes "someone else owns the port" from "our child is not ready yet", because the second is legitimate and the first is the bug.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

One more data point for saw_own_line, and it is a harsher one than the refusal: the extra line breaks the nested rail even when nothing refuses it

Trying to make the fixture side of this easier, I patched tests/fake_backend_route.py on main (no serve change at all) to do the two things a --port 0 fake needs — assert port is not None instead of assert port, and printing llama-server's listening on http://127.0.0.1:PORT after binding. Both are provable in isolation:

$ python3 tests/fake_backend_route.py -m x.gguf -ngl 0 --port 0     →  listening on http://127.0.0.1:34295   (before: AssertionError "no port in …")
$ python3 tests/fake_backend_route.py -m x.gguf -ngl 0 --port 18081 →  listening on http://127.0.0.1:18081   (unchanged)

On main that breaks the --laya-models rail, with no port 0 anywhere in the serve path and no refusal involved:

main + that fake change:   bash tests/laya_models_e2e.sh build/1bit ~/.local/share/1bit/laya
                           rc=1, "serve never reported a port"   (3 ok, 1 fail; 25/25 before)
reverted:                  rc=0, 25/25

So the nested stack is sensitive to the child's output existing at all, not only to what the foreign check does with it. That matters for this PR in two ways:

  1. saw_own_line is the right shape and this strengthens the case. A predicate keyed on "has this child ever printed a 1bit line" is robust to a grandchild's line and to extra chatter; anything keyed on a specific line's absence is not.
  2. The fixture you asked for must not be this fake. Whatever we add for a nested arm should print the foreign line from a dedicated stand-in (as your /tmp fixture does with inner.sh), not by changing fake_backend_route.py, or it will be measuring the fake's chattiness rather than the rail. I reverted the change; tests/fake_backend_route.py is untouched on main, and the branch is deleted.

I did not chase the cause — the rail's 25 checks passing again after the revert is the only claim I am making, and the interesting question ("why does one extra stderr line from a grandchild stop the outer serve becoming ready on main, where nothing refuses it?") is a second defect that this PR neither causes nor needs to fix. It belongs in engine#3130's thread as the next thing to measure, and I would rather report it than smear a fix across two PRs.

@bong-water-water-bong
bong-water-water-bong merged commit 34a82cf into main Nov 21, 2026
12 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the pi-prs2/3130-port-grace-format branch November 21, 2026 11:23

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 7cb985e: READY — the three-way split is the right shape, and it is the first version of this wait that does not use the clock to answer a question the child's output already answers: (a) a readiness line in another server's format is refused at once (looks_like_foreign_ready, with the 1bit prefix excluded so our own line is untouched), (b) a child that has printed nothing for the grace is not a server, (c) a child that is talking is loading and gets wait_ready's 900 s. Moving the grace default to 0 follows from (c) rather than being a loosening: a number sized for (a) must not bound a 27B mid-load, and the parser range widening to 0..86400 keeps the old behaviour available for anyone who wants it.

One question I would want answered in the commit message, not in code: with the grace at 0, what catches a child that exits without ever printing a line? If an exit check (a waitpid/EOF on the pipe) ends the wait immediately, then the trade is clean. If the only bound left is the 900 s timeout, then a mistyped --llama-server path now costs 15 minutes instead of 60 seconds, and that is a real regression for the human in front of it even though it is the right call for the model load.

Secondary and non-blocking: looks_like_foreign_ready is a substring pair (listening on + http://), so a loading child that prints an unrelated line containing both would be refused. The prefix exclusion makes that unlikely, and I would take the behaviour as-is — just worth one line so the next reader knows it was considered rather than missed.

Nothing else from me; the reasoning in the body is the part that makes this reviewable, and it holds.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Retracting the finding I posted above: it was a stale binary, and the rail is fine on main

I wrote, an hour ago, that the same fake change "breaks laya_models_e2e on main — no port 0 in the serve path, nothing refusing anything — 25/25 → 3 ok + 'serve never reported a port'", and concluded the nested stack was sensitive to a child's output existing at all.

That was wrong, and the log said so where I should have looked first:

1bit serve: pid 1040423 announced a port in a format `1bit serve` does not print; this launch was given `--port 0` …

That is your message. My build/1bit was still the binary I had built from your head (7cb985eb) for the earlier reproduction — I checked the tree back out to main but did not rebuild, so I measured your refusal and attributed it to main. Rebuilt from 7436ecbc and re-run with the identical fake change:

tests/laya_models_e2e.sh  →  rc=0, 25/25 PASS        (string "does not print": 0 occurrences)
tests/hybrid_route.sh     →  rc=0, 39/39 PASS

So: the fake change is harmless on main, and my "sensitive to output existing at all" conclusion is withdrawn. What stands from that comment is only the part I had measured on your head with the real checkpoint — the refusal does fire in the nested --laya-models rail — and the recommendation that the nested fixture use a dedicated stand-in rather than the shared fake, which is now weaker than I made it: the shared fake is fine, it just isn't the thing that should demonstrate a foreign line, because a test that changes a shared fixture to prove a point measures the fixture.

The fake support itself went out as its own PR (#3172, fda29160, 25/25 + 39/39) rather than living in a comment: --port 0 now binds and reports listening on http://127.0.0.1:PORT instead of asserting, which is what any future flip of the remaining free_port() sites needs from a fake.

Apologies for the noise on your PR — a stale binary is indistinguishable from a tree unless the build is rebuilt after the checkout, and I quoted a result that belonged to your head.

bong-water-water-bong pushed a commit that referenced this pull request Nov 21, 2026
PR #3168 merged the foreign-format refusal into main without the own-line half both reviewers asked
for at 7cb985e, and that half is not optional on the rail the refusal can reach. Measured on this
box, on main (34a82cf), with a child that announces its port the way llama-server does:

  1bit serve: laya-models: starting nested-row on cpu (port 0)
  1bit serve: nested-row on cpu (tests/fake_llama_announce.sh)    <- the child, in our format
  srv  llama_server: listening on http://127.0.0.1:34797          <- its GRANDCHILD, teed through
  1bit serve: pid 1263999 announced a port in a format `1bit serve` does not print ...
  1bit serve: laya-models: nested-row did not become ready         rc=1

`--laya-models` launches its child with `--port 0` (app/serve.cpp:2106, the only such site) and
that child is ALWAYS a nested `1bit serve`, so the refusal's true-positive case is unreachable on
every shipped rail: the only foreign line it can see is a grandchild's, arriving across the child's
stderr tee. Fix: a line in our format is recorded as it is read, and a foreign-format line only
counts while the child has not spoken ours yet.

The condition is evaluated in the drain thread, not at the refusal, because the refusal polls every
250 ms and would still race a child that has not printed yet. The ordering it relies on is
structural: serve prints "1bit serve: <model> on <device> (<backend>)" (app/serve.cpp:3015) BEFORE
it constructs the Child, so a nested child has spoken our format before its own child exists.

Test: tests/serve_nested_foreign.sh drives the real --laya-models front, the real nested serve and
the real port read-back against tests/fake_llama_announce.sh (a fake llama-server that announces its
port on stderr and models the load gap). Four arms, including one that greps the log for the
grandchild's line so the case cannot pass vacuously. Registered through tests/laya_e2e_guard.sh with
the other laya_* rows (77 with a reason when there is no checkpoint). This is also the merged
guard's first test at all.

laya_models_e2e, laya_route_e2e and smoke_serve are green at this head.
bong-water-water-bong added a commit that referenced this pull request Nov 21, 2026
…ever fire (engine#3130) (#3206)

launch_for fills argv[0] with llama-server on every branch that returns and
gguf_devices() is hrx/cpu only, so launched.argv[0] == /proc/self/exe is
unreachable: the site always took free_port() and then replaced it with
another free_port(). Deleted rather than repaired, because a --laya child
cannot report a port it bound and a llama-server on --port 0 is what
engine#3171's refusal refuses; the rail that does pass --port 0 to our own
serve is --laya-models, which reads the port back (#3168).

No behaviour change. kPortTakenRetries stays for foreign children
(tests/hybrid_route.sh asserts that relaunch); a future --port 0 site must
skip the loop rather than let set_port_arg freeze a picked port.

Co-authored-by: bong-water-water-bong <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant