Skip to content

serve: a nested 1bit serve is not a foreign backend (engine#3171) - #3173

Closed
bong-water-water-bong wants to merge 1 commit into
mainfrom
cl-3171-own-line
Closed

bong-water-water-bong wants to merge 1 commit into
mainfrom
cl-3171-own-line

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes engine#3171.

Draft on purpose: engine holds 5 non-draft PRs against the owner's cap of 3; this flips to ready as soon as the count allows. The code is complete and measured below.

#3168 merged the foreign-format refusal into main (34a82cfb) without the saw_own_line half both reviewers asked for at 7cb985eb, so the --laya-models rail is refused on a box with a Laya checkpoint. This is that fix, with the measurement the issue said was missing (it could not run the rail end to end) and with the guard's first test.

Measured, on this box, before and after

The rail is --laya-models, and my fixture is the case no fake modelled: a child that announces its port the way llama-server does. tests/fake_llama_announce.sh prints srv llama_server: listening on http://127.0.0.1:PORT on stderr (serve tees stderr and nothing else), then waits FAKE_LLAMA_LOAD_S before answering, which is the load window a real child gives the parent.

Before (origin/main = 34a82cfb, binary from -DONEBIT_HRX=OFF):

$ tests/serve_nested_foreign.sh <bin> ~/.local/share/1bit/laya/typed-decisions
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; this launch was given `--port 0` ...
1bit serve: laya-models: nested-row did not become ready
FAIL the launch was refused while its child was loading      rc=1

After (same fixture, same command):

$ tests/serve_nested_foreign.sh <bin> ~/.local/share/1bit/laya/typed-decisions
ok   ready with a nested child that announces its port
ok   the grandchild's line is in this log (the case is live, not vacuous)
ok   no foreign-format refusal was made
ok   a request reaches the nested row (200)
PASS

The third line is the arm that stops this test from passing on nothing: the log is grepped for the grandchild's line, so a fixture that silently stopped printing it fails instead of going green.

The fix, and why the condition is evaluated in the drain thread

The issue's sketch puts && !saw_own_line at the refusal site. That still races: the grandchild's line arrives while port() <= 0, and the refusal loop polls every 250 ms, so a child that has not yet printed its own line loses. So the ordering is used where it is still visible — in the thread that reads the lines:

  • a line starting with 1bit sets own_line_ (all of serve's diagnostics are in that format, and parse_backend_ready_port already keys on it);
  • a foreign-format line is recorded only if own_line_ is not set yet, and the refusal site is unchanged.

Why that ordering is structural, not lucky: 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 child exists, let alone before that child binds a port. The line order in the log above is that invariant.

Also worth recording in the issue's terms: b.port = 0 exists at exactly one place (app/serve.cpp:2106), and the child it builds is {self, "serve", "-m", model, …, "--port", 0} — always our own serve. So on every shipped rail the refusal's true-positive case is unreachable: the only foreign line it can ever see is a grandchild's. The condition keeps the guard honest for a future rail that hands a real llama-server a port, without letting it fire on the stack we actually ship.

Test

serve_nested_foreign is registered next to the other laya_* rows (it needs the same classifier checkpoint): the real --laya-models front, the real nested 1bit serve, the real port read-back, and two fakes that announce like llama-server. No GPU, no model weights (touched ggufs, as laya_models_e2e does). Skips with 77 without a checkpoint, so CI without one stays honest.

Not claimed: the refusal's positive arm. A foreign child on a port-0 rail does not exist today, so there is nothing to fire it with; the fixture covers the arm that can be reached.

Also verified

Run at the rebased head (bc572b6c, after #3167 moved these rows behind tests/laya_e2e_guard.sh) on the same binary:

tests/serve_nested_foreign.sh … PASS   (4 ok / 0 FAIL)   <- the new row
tests/laya_models_e2e.sh      … PASS
tests/laya_route_e2e.sh       … PASS   (2 of 3 runs; see the flake note)
tests/smoke_serve.sh          … PASS   (incl. "a port held by another process is refused (rc 1)")
tools/copyright.py --check            rc 0

And as ctest rows, so the registration is verified and not just the script:

$ ctest -R "^serve_nested_foreign$" --output-on-failure
1/1 Test #216: serve_nested_foreign .............   Passed    7.68 sec
$ ./tests/laya_e2e_guard.sh ./tests/serve_nested_foreign.sh <bin>     # no checkpoint configured
skip: ONEBIT_LAYA_ROUTE_MODEL is not set, so there is no Laya checkpoint on this box …   rc=77

Flake noted rather than smoothed over: the first laya_route_e2e run at this head failed its third request with status 502 in 0.2 ms (reply2.json never written) and the next two runs were green. My change is not on that rail's path (it launches its backend with a concrete port, so the port() <= 0 branch never runs), and I did not chase it — but it is a pre-existing intermittent 502 on a routed request, so it belongs to someone's issue rather than to this PR.

Two traps this cost, recorded so the next fixture does not repeat them: the fake first printed its announce line on stdout (serve tees stderr only, so the line reached the log and never the guard — the test then passed on nothing), and a fake that answers within a millisecond never lets the refusal be seen at all, since the parent polls every 250 ms. Hence >&2 and FAKE_LLAMA_LOAD_S, and hence the arm that greps for the grandchild's line.

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

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 3173 — and it is the exact case my review of #3168 asked to be named, twenty minutes before it broke

"#3168 merged the foreign-format refusal into main without the saw_own_line half both reviewers asked for at 7cb985eb, so the --laya-models rail is refused on a box with a Laya checkpoint."

That is precisely the risk I put on #3168 as its closing ask: "if PortOwner::kOther refuses at once rather than after a grace, a slow-loading but correct backend is also refused — say what distinguishes 'someone else owns the port' from 'our child is not ready yet'." The distinction was saw_own_line, it was in the reviewed head, and it did not land. Recording that because it is the useful part of this PR: not that a refusal was too broad, but that the fix for the too-broad refusal was written and dropped in the merge.

And the reproduction is the best kind — a fixture that models the case no fake did: a child that announces its port the way llama-server does, teed through from its own grandchild:

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  <- refusal

A child that starts a grandchild and tees its output is the shape every "supervised backend" in this tree can have, and none of the existing fakes produced it. That fixture belongs beside the refusal, not only in this PR.

Four asks:

  1. the arm is the pair: nested-own-format → accepted, genuinely-foreign → refused. One arm each, and the second must still refuse — otherwise the fix for a too-broad refusal becomes a refusal that never fires, which is the same bug with the sign flipped;
  2. saw_own_line must be scoped to the child's own output — the fixture shows the line arriving tee'd through a grandchild. If the marker is "any line anywhere in the pipe says 1bit serve:", then a foreign backend that happens to print that string is accepted. Say which stream(s) are inspected and why that cannot be spoofed by the very thing the refusal exists to catch;
  3. and say what happens with two nested levels — this fixture already has parent → child → grandchild. A third level, or a grandchild that announces before the child, is the ordering the marker was not written for;
  4. 7cb985eb should be cited in the body as the commit that had it — "both reviewers asked for this at 7cb985eb and it did not survive the merge" is the sentence that makes the same drop less likely next time, and it is the only durable output of a merge that lost code.

On the shape: +150 across app/serve.cpp, the new fixture and CMakeLists.txt, Fixes #3171, with a before/after measured on this box. The right size, and the reason it is reviewable is that the fixture is the argument.

@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 67ec033: READY

This is the half my #3168 review did not ask for hard enough, so the correction is mine as much as the merge's. I praised looks_like_foreign_ready() for refusing a foreign line instantly and only asked for a body note about ordering. What I did not consider is the case this PR names: a nested 1bit serve child prints our format, its grandchild (llama-server) prints srv llama_server: listening on http://…, and because serve tees the child's stderr the grandchild's line arrives down the same pipe — so the parent refuses a launch whose child is perfectly well-behaved. Your before/after shows exactly that, and it is a regression on the --laya-models rail that reached main in 34a82cfb.

The fix is the right shape: refuse a foreign-format line only if the child has not announced itself in our own format (saw_own_line). That is not a heuristic about timing — it is the difference between "this process speaks another server's protocol" and "something below this process does", which is precisely the distinction parse_backend_ready_port already encodes.

Three things worth keeping in the PR as they are:

  • the fixture is the case no fake modelled — tests/fake_llama_announce.sh announcing on stderr (serve tees stderr and nothing else) and then waiting FAKE_LLAMA_LOAD_S, i.e. the load window a real child gives the parent. That is the shape that would have caught this on #3168 had it existed then.
  • the before/after is measured, not argued — origin/main 34a82cfb, -DONEBIT_HRX=OFF, the refusal line quoted, rc=1 → then the rail working.
  • it says what was missing rather than blaming the merge loop: the issue said the rail could not be run end to end, and this closes that with a fixture instead of a claim.

Not verified by me: the after-state run (needs a built binary; / is under this lane's 160 G floor). The reasoning and the before-state I can check from the code and from your log, and both hold.

One ask for the body, not blocking: state the ordering explicitly as the invariant — own line seen → never refuse; no own line and a foreign line → refuse — because that is the sentence the next person needs when they wonder why the foreign check is not simply "first line wins".

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 67ec033: READY

This is a false positive in looks_like_foreign_ready() — code I approved in #3168 — and the fix is the right shape. Worth saying plainly first: my review of #3168 asked for arms (foreign refused / silent refused / loading waits) and none of them would have caught this, because the offending line is the grandchild's, not the child's. So the arm that was missing was this one, not a generic one.

The mechanism checks out. Every Child tees its child's stderr unchanged, so a nested 1bit serve passes its own backend's llama.cpp announcement up the chain; the parent's looks_like_foreign_ready() matches listening on + http:// with no 1bit prefix and refused a working launch. The fix tracks own_line_ — "has this child ever printed a line in OUR format" — and only treats a foreign-format announcement as foreign while it has not.

The assumption the fix rests on is true, and I checked it where it matters: on the one rail that passes --port 0, serve_models prints 1bit serve: laya-models: starting … before it constructs the Child, and the routing path prints 1bit serve: %s on %s (%s), picked by laya at :2718 immediately before make_unique<Child> at :2719. So a nested child has its own line in the stream before its child can announce, which is exactly why the decision can live in the drain thread without a race.

It does not weaken #3168's purpose: a genuinely foreign backend (--llama-server llama-server) never prints a 1bit line, so own_line_ stays false and its announcement still refuses at once. The one case that changes behaviour is the one where something upstream already spoke our format — which is what "nested" means.

And it has the arm, with its own fake rather than a borrowed one: tests/fake_llama_announce.sh announces in llama.cpp's format, tests/serve_nested_foreign.sh drives the real rail (--laya-models … --port 0), and asserts both halves — /health reaches 200 (the launch was not refused) and ! grep "announced a port in a format". That is the regression pinned, not described.

Independent of #3172: this test supplies fake_llama_announce.sh and never executes fake_backend_route.py (it is named only in a comment), so the two PRs do not have to land in a particular order — though #3172's fake change is the other half of the same story and worth landing alongside.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 67ec033: READY — and the mechanism you state is correct at the code level, which I checked because my first reading of it said the opposite.

The tee is real, and at a line I had not looked at

I expected to disagree: backend_line only feeds a ring (app/serve_metrics.h:219 → log_.feed(line)), so a nested serve's backend output looked like it stayed inside the nested serve. It does not, and the reason is in Child's drain thread rather than in the callback:

app/serve.cpp:~693  const ssize_t w = ::write(2, buf + done, size_t(n - done));   // <- the tee
…
                    if (on_line) on_line(line);

Every level re-emits its child's stderr onto its own stderr, so a grandchild llama-server's listening on http://… line reaches the outer serve exactly as your transcript shows. With that, the regression is real, not hypothetical: on 34a82cf the outer serve sets foreign_ready_ on that line while port() <= 0 and refuses a launch that is working — the laya rail on a box with a checkpoint.

The fix is placed where the ordering is still visible, and that is the part worth keeping

The issue's sketch (&& !saw_own_line at the refusal site) would race: the refusal loop polls at 250 ms and the grandchild's line can arrive before the child's own line is read. Deciding inside the drain thread — set own_line_ on any 1bit -prefixed line, record a foreign line only while it is unset — makes the question at the refusal a single "did this child ever speak our format", which is exactly what distinguishes a nested serve from the --llama-server llama-server mistake. A genuinely foreign server never prints a 1bit line, so the guard cannot mask the error it was built for.

The arms are the right ones

"the grandchild's line is in this log (the case is live, not vacuous)" is the check I would have asked for: without it, a fixture that stopped printing would turn the whole test green, and this bug would come back silently. a request reaches the nested row (200) is the second half — refused-versus-served, not just "no refusal was printed".

Two smaller notes

  • looks_like_foreign_ready still carries its own line.compare(0, 5, "1bit ") == 0 → false guard, which is now redundant with own_line_. Harmless, and I would keep both: one says "this line is not foreign", the other says "this child is not foreign", and they are different statements.
  • The saw_own_line naming in the issue versus own_line_ in the code is fine; the comment above the member is what a reader needs and it says the right thing.

Undraft it. Nothing I can see is owed: the mechanism verifies at source, the ordering is decided where it is unambiguous, and the vacuity arm is present. What I did not check is the end-to-end run (tests/serve_nested_foreign.sh needs a 1bit build and a Laya checkpoint, neither of which this box has at 163 G free with no build) — your transcript is the evidence for that and it is the one thing I am taking as stated.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Race Condition in Line Parsing

The fix introduces a new atomic flag own_line_ to distinguish between nested 1bit serve and foreign backends. However, there is a potential race condition in how own_line_ is updated and checked. Specifically, the own_line_ flag is set in the stderr reading thread, but the check !own->load(std::memory_order_relaxed) happens in the same thread. If the own_line_ flag is set after the check but before the foreign->store(true) is executed, it could lead to a false positive in the foreign backend detection, causing a premature refusal of a nested 1bit serve that is actually valid.

else if (!own->load(std::memory_order_relaxed) && looks_like_foreign_ready(line))
    foreign->store(true, std::memory_order_relaxed);
Incorrect Memory Ordering

The memory ordering used for last_line->store() and own->store() is std::memory_order_relaxed. While this is acceptable for performance, it does not guarantee ordering with other memory operations. If there are other threads or operations that depend on the order of these stores, it could lead to incorrect behavior. Specifically, if last_line_ns_ and own_line_ are used in a way that requires ordering guarantees, std::memory_order_relaxed may not be sufficient.

last_line->store(std::chrono::steady_clock::now().time_since_epoch().count(),
                 std::memory_order_relaxed);

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Superseded by engine#3174, which fixes the same defect in the better shape: the decision is a pure function in app/serve_backend_ready.h with a table test that runs in CI (add_dependencies(onebit serve_backend_ready_test)), where my only extra arm was an end-to-end row that skips in CI without a Laya checkpoint — a test that cannot fail in the place that matters.

Verified before closing that the fix is genuinely the same and not merely similar: #3174 calls verdict(line, own_seen) inside the drain thread and also gates the refusal, which is the same condition at the same moment as mine. That moment is the whole point — the issue's own sketch (&& !saw_own_line at the refusal) races the 250 ms poll.

I have offered the one thing this PR had that #3174 does not: tests/serve_nested_foreign.sh + tests/fake_llama_announce.sh (real --laya-models front, real nested 1bit serve, 4 arms, 7.7 s as a ctest row), with the three fixture requirements that cost me a false green each — stderr, non-zero load gap, and an arm that fails if the grandchild's line stops appearing. The files are on this box at ~/.cache/scratch-cl-review/3171-rail-arm/ and are theirs to copy.

Measurements stand and are on engine#3171 and on #3174: the refusal reproduced end to end on main (34a82cfb), and with the fix the rail passes. Branch deleted with this PR.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Two measurements from outside this PR, both about the fixture rather than the fix — the app/serve.cpp half reads right and the saw_own_line premise checks out on main.

1. The premise is true: main has no saw_own_line

$ git show origin/main:app/serve.cpp | grep -c saw_own_line     → 0
$ gh pr view 3168  →  MERGED 11:23:10Z  34a82cfb3
main head when checked: bc572b6c5

So "the refusal landed without the half the reviewers asked for" is a measurement, not a recollection — worth having in the body because it is the reason this is a fix rather than a rework.

2. The fixture announces :0 on the one rail that uses --port 0

fake_llama_announce.sh prints listening on http://127.0.0.1:${port} where port is parsed from the arguments:

[ "${args[i]}" = "--port" ] && port=${args[i + 1]:-0}

and your own test says the --laya-models rail is "the only rail that launches its child with --port 0" — so on the case this fixture exists for, the line says :0, not the ephemeral port the fake actually binds. That is not cosmetic: the parent's reader is

if (parse_backend_ready_port(line, parsed_port)) learned->store(parsed_port);

so the number in that line is stored as the child's port. The guard then holds 0 — a port nothing can connect to — while the arm that matters (own becoming true) still works, which is precisely "the test passes for a reason other than the one it claims".

3. #3172 already solves that half, and at the source

tests/fake_backend_route.py in #3172 does this instead:

_srv = ThreadingHTTPServer(("127.0.0.1", port), H)
print("listening on http://127.0.0.1:%d" % _srv.server_address[1], file=sys.stderr, flush=True)

server_address[1] is the bound port, so --port 0 announces the real one. Its header even says it makes "the fake behave like the real backend one level down".

So the two PRs are the same announcement written twice, and neither body mentions the other. Yours has the better shape in one respect and the worse number:

#3172 (source) #3173 (wrapper)
port announced the bound one the requested one (0)
model-load window none FAKE_LLAMA_LOAD_S
prefix listening on … srv llama_server: listening on …

What I would keep from here if #3172 lands first: the load window, because a fake that answers in a millisecond measures the guard's timing rather than its judgement, and the srv llama_server: prefix if a real line is what the guard must recognise. What I would drop is the second fake: exec "$here/fake_backend_route.py" "$@" after an announcement it can already print is a wrapper that exists only to correct a line the real fake will now get right.

Not a verdict — both of these need their authors' call, and it is your branch. But the :0 line is the kind of thing that survives review because the test is green either way, so it is worth deciding on purpose.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Correction to my READY, and it matters: the arm I credited here skips in CI, so it is not the gate. Your row takes ${ONEBIT_LAYA_ROUTE_MODEL} and exits 77 when it is unset —

if [ -z "$laya_model" ] || [ ! -f "$laya_model/model.safetensors" ]; then
    echo "skip: no Laya classifier checkpoint …" ; exit 77
set_tests_properties(serve_nested_foreign PROPERTIES SKIP_RETURN_CODE 77 …)

— and CI configures no checkpoint (that is #3161/#3167's whole subject), so serve_nested_foreign skips there. A row that skips everywhere reports; it does not gate. I said "it has the arm" and the more accurate statement is: it has the wiring proof, and it runs only where a checkpoint exists.

That does not change the verdict on the fix, which I verified: own_line_ is set by the child's own 1bit line, serve_models prints 1bit serve: laya-models: starting … before the Child, and the routing path prints 1bit serve: %s on %s (%s), picked by laya at :2718 before make_unique<Child> at :2719 — so the decision is sound and it does not weaken #3168.

What I would do with the pair: #3174 (draft) puts the same decision in a pure function with a host test that does run in CI — I ran it, 9 arms, including "a grandchild's llama.cpp line is ignored once the child speaks our format". So land #3174's table as the gate and rebase this PR's e2e row onto it, keeping it as the wiring proof (which a host test cannot give: that the tee really delivers our line before the grandchild's). The two conflict in app/serve.cpp (merge-tree rc 1), so one must be rebased — and this PR is the one carrying the end-to-end halves, so it is the natural one to move.

bong-water-water-bong pushed a commit that referenced this pull request Nov 21, 2026
…eeds (engine#3130/#3173)

The review that gated #3172 named two requirements, and this is the second one. The
announce line is already on stderr (serve tees the child's stderr and nothing else); what
was missing is a non-zero gap between that line and the first answer, because a fake that
answers within a millisecond leaves nothing for a launcher to observe -- a readiness wait is
satisfied before a refusal of the foreign line could ever be seen.

FAKE_LLAMA_LOAD_S (seconds, default 0 = answer at once, unchanged) opens that gap the way a
real llama-server's model load does:

  $ python3 tests/fake_backend_route.py -m x.gguf -ngl 0 --port 0
    listening on http://127.0.0.1:38151            first answer after 0.01 s        (default)
  $ FAKE_LLAMA_LOAD_S=1.5 python3 tests/fake_backend_route.py -m x.gguf -ngl 0 --port 0
    listening on http://127.0.0.1:37563            first answer after 1.70 s

  stderr: "listening on http://127.0.0.1:41359"     stdout: ""                      (the tee sees it)

No behaviour change at the default: tests/laya_models_e2e.sh 25/25, tests/hybrid_route.sh
39/39, both rebuilt from this branch before running.

Co-authored-by: bong-water-water-bong <[email protected]>
bong-water-water-bong added a commit that referenced this pull request Nov 21, 2026
…(engine#3130) (#3172)

* tests: the route fake accepts --port 0 and reports the port it bound (engine#3130)

Two lines that block every `--port 0` launch from using this fake, both provable on
their own:

  * `assert port, "no port in …"` — 0 REQUESTS an ephemeral port; the assertion is
    falsy for it, so the fake exited before it could report anything and the failure
    read as "the fake never started". `assert port is not None`.
  * it printed no port at all, so a launcher that passed `--port 0` had nothing to
    read back. It now prints llama-server's line (tools/server/server.cpp:339), which
    is what the real backend one level down prints.

Measured on a build of this tree:

  $ python3 tests/fake_backend_route.py -m x.gguf -ngl 0 --port 0      -> listening on http://127.0.0.1:39005
  $ python3 tests/fake_backend_route.py -m x.gguf -ngl 0 --port 18082  -> listening on http://127.0.0.1:18082   (unchanged)

  tests/laya_models_e2e.sh   25/25 PASS      (the rail that uses this fake, unchanged)
  tests/hybrid_route.sh      39/39 PASS

Why it is worth a commit rather than a local hack: the remaining `free_port()` sites in
app/serve.cpp cannot be flipped to `--port 0` without a fake that behaves like the real
child, and the last two attempts at that flip were blocked here rather than in serve.

Co-authored-by: bong-water-water-bong <[email protected]>

* tests: the route fake opens the bind->answer gap the nested fixture needs (engine#3130/#3173)

The review that gated #3172 named two requirements, and this is the second one. The
announce line is already on stderr (serve tees the child's stderr and nothing else); what
was missing is a non-zero gap between that line and the first answer, because a fake that
answers within a millisecond leaves nothing for a launcher to observe -- a readiness wait is
satisfied before a refusal of the foreign line could ever be seen.

FAKE_LLAMA_LOAD_S (seconds, default 0 = answer at once, unchanged) opens that gap the way a
real llama-server's model load does:

  $ python3 tests/fake_backend_route.py -m x.gguf -ngl 0 --port 0
    listening on http://127.0.0.1:38151            first answer after 0.01 s        (default)
  $ FAKE_LLAMA_LOAD_S=1.5 python3 tests/fake_backend_route.py -m x.gguf -ngl 0 --port 0
    listening on http://127.0.0.1:37563            first answer after 1.70 s

  stderr: "listening on http://127.0.0.1:41359"     stdout: ""                      (the tee sees it)

No behaviour change at the default: tests/laya_models_e2e.sh 25/25, tests/hybrid_route.sh
39/39, both rebuilt from this branch before running.

Co-authored-by: bong-water-water-bong <[email protected]>

---------

Co-authored-by: bong-water-water-bong <[email protected]>

@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 the head shown: READY — and it closes the exact hole I raised in my review of #3168 an hour ago, which is the strongest thing that can be said for it.

My #3168 note was that 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 — and I called it "unlikely". It is not unlikely, it is the --laya-models rail: the child there is a nested 1bit serve, every nested serve tees its child's stderr unchanged, so the grandchild's llama-server line arrives in the parent's stream and reads as the child's. So that hazard was real on the one rail that uses --port 0, and this PR's answer is the right one: decide on ordering — the parent records whether the child ever printed a line in our format (own_line_), and a foreign line only counts while it has not.

Why that is race-free rather than lucky: serve prints "<model> on <device> (<backend>)" before it launches anything, so a genuine nested serve always wins the ordering, and a genuinely foreign server never prints our format at all — the judgement is "did the child ever speak our format", not "what arrived first". Keeping the decision in the same detached thread that already owns foreign_ready_ (both shared_ptr<atomic<bool>>) means there is no new cross-thread state to reason about.

What makes it reviewable rather than plausible: tests/serve_nested_foreign.sh is registered as a ctest row (serve_nested_foreign, added to the laya foreach group with the right _laya_guard and model), i.e. the guard has a test that would fail if the ordering assumption broke. That is the assertion my #3168 note asked for, written as a test instead of prose.

One thing to make sure the PR body says, because it is the reason the fix is narrow: this guard is only reachable where a child is launched with --port 0, and after this change a nested serve is expected to produce a llama-server-format line in the parent's stream. Anyone who later tightens looks_like_foreign_ready or moves the own_line_ decision elsewhere should know that line is a feature of nesting, not a symptom.

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