Skip to content

embed_serve: a free port, and the lock the census requires (#2826 follow-up) - #2833

Merged
bong-water-water-bong merged 1 commit into
mainfrom
os3-embed-serve-port
Nov 17, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
os3-embed-serve-port

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes the hole I found while reviewing #2826: a route test the port-lock census cannot see.

#2826's safety argument is that "every test that binds a port holds RESOURCE_LOCK route_ports … enforced by the route_port_lock row, which fails when a new server test is added without the lock". tests/embed_serve.sh is a counter-example:

CMakeLists.txt:233   add_test(NAME embed_serve COMMAND …/tests/embed_serve.sh $<TARGET_FILE:onebit>)   # no lock
tests/embed_serve.sh:24    PORT=${EMBED_SERVE_PORT:-8247}
tests/embed_serve.sh:33    "$BIN" serve --embedding -m "$FIX" --device cpu --port "$PORT"

tests/route_port_lock_test.py:46
BIND_RE = re.compile(r'freeport|free_port|bind\(\s*\("127\.0\.0\.1",\s*0\)\s*\)|--port\s+43\d{3}\b')

--port "$PORT" with an 8247 default matches none of those shapes, so the census stayed green over a port-binding test with no lock. Nothing else uses 8247 today, which is why this is a hole and not a bug — and ctest -j 4 (#2826) is what turns "cannot collide" into "collides whenever the numbers line up".

The change

  • tests/embed_serve.sh picks a free port with the same freeport() helper pm_route.sh and pm_laya_route.sh use; EMBED_SERVE_PORT still overrides it for a debugger run.
  • CMakeLists.txt gives the test RESOURCE_LOCK route_ports — the census now sees it and would fail loudly without the lock.
  • tests/route_port_lock_test.py names embed_serve among the tests it must find, so a revert to a fixed port fails by name rather than reporting a smaller census that still clears the floor.

Verified with the census's own predicates, imported rather than copied:

binds_a_port('tests/embed_serve.sh')   -> True     it is seen now
binds_a_port('tests/pm_route.sh')      -> True     nothing else lost
pre-change text of embed_serve.sh      -> False    the change is what makes it visible

and the property lands: cmake add_test + set_tests_properties report RESOURCE_LOCK: route_ports (checked in a stub project, since a full configure stops at the HRX SDK here).

bash -n on the script and tools/copyright.py --check are clean. The real test needs the CI build (embed_serve.sh <path-to-1bit>), which is what will run it.

Independent of #2826 — it applies whether or not -j 4 lands, and it is the census gap rather than that PR's change.

…low-up)

`tests/embed_serve.sh` bound a fixed loopback port (`${EMBED_SERVE_PORT:-8247}`)
and carried no `RESOURCE_LOCK route_ports`, while `tests/route_port_lock_test.py`
exists to require that lock on every script that binds a port. It could not:
`BIND_RE` recognises `freeport`, `free_port`, `bind(("127.0.0.1", 0))` and a
fixed `--port 43xxx`, and `--port "$PORT"` with an 8247 default is none of them.

So a route test was invisible to the census written to catch exactly that, and
nothing else uses 8247 today -- which is why main is green rather than why it is
safe. It becomes reachable with `ctest -j 4` (#2826), where two rows can race
for a number nobody reserved.

- the script picks a free port with the same `freeport()` helper `pm_route.sh`
  and `pm_laya_route.sh` use; `EMBED_SERVE_PORT` still overrides for a debugger.
- `CMakeLists.txt` gives the test `RESOURCE_LOCK route_ports`, which the census
  now requires of it.
- the census names `embed_serve` among the tests it must find, so a revert to a
  fixed port fails by name instead of shrinking the census under its floor.

Verified with the census's own predicates (not a copy of them):

  binds_a_port('tests/embed_serve.sh')          -> True     (it is seen now)
  binds_a_port('tests/pm_route.sh')             -> True     (nothing else lost)
  the pre-change text of embed_serve.sh         -> False    (the change is what makes it visible)
  cmake add_test + set_tests_properties         -> RESOURCE_LOCK: route_ports
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2833

"A route test the port-lock census cannot see" found while reviewing #2826 — that is the best provenance a test can have: a safety argument was made, a reviewer asked what it does not cover, and the answer became a test.

#2826's argument was that -j4 is safe because device rows serialise through gpu-hold — so a route test that takes a port without the lock is exactly the thing that argument would miss, and a parallel ctest run is what turns the miss into a flake rather than a wrong result. Naming it that way is worth more than the +15 lines.

Three asks:

  1. the arm must fail on the pre-change tree — with -j4 on, run the suite and require the collision to be detected. A test that only asserts "this test now takes the lock" passes even if the lock is a no-op;
  2. say why the census cannot see it — the census reads a specific pattern (a port literal? a bind(? a service name?); one line naming the shape it greps is what lets the next new route test be written so the census does see it, which is better than one exemption at a time;
  3. CMakeLists.txt is touched: confirm this registers a new row rather than re-registering an existing one — a dropped row is route_port_lock_test: see a C++ route test, and fail by name when it has no lock (#2504 follow-up) #2508's blind spot, and test-only PRs are where it happens.

And a note on the chain this belongs to: #2826 (the -j4 lever), this (the hole it opened), and the port-lock census are now three artefacts about the same invariant. That is the right way for a safety argument to mature — each step names what the previous one could not see.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — and this one corrects my review of #2826.

I endorsed #2826's hazard table as "a conclusion I believe because the four questions were asked". The fixed ports row said "every configured test that starts a server already holds RESOURCE_LOCK route_ports", and I did not check it. It is false:

CMakeLists.txt:233  add_test(NAME embed_serve COMMAND …/tests/embed_serve.sh $<TARGET_FILE:onebit>)   # no lock
tests/embed_serve.sh:24   PORT=${EMBED_SERVE_PORT:-8247}

embed_serve binds 8247 with no RESOURCE_LOCK, so -j 4 puts it in parallel with every other row — including http_guard, whose lock protects its own port, not this one. My "believed because the questions were asked" was therefore worth exactly as much as the row was, and the row was wrong. Verified on main just now: 7 RESOURCE_LOCK route_ports properties, and embed_serve is not among them.

The fix is the right shape: give the test a free port and the lock the census requires, rather than pinning it to 8247 and hoping. A free-port allocation makes the row safe even without the lock; taking the lock as well makes it visible to the census that guards every other row. Doing both is correct, and one without the other would have left half the argument standing.

Three things I would pin:

  1. Assert the census itself, not just this row. The lesson is that a hand-written list of "every row that starts a server" drifts. If route_port_lock_test.py can be made to fail when a test whose script contains --port lacks the lock, then the next embed_serve is caught at PR time rather than by a reviewer's grep. The body says the census "cannot see" it — say whether that is now fixed or only this instance.
  2. EMBED_SERVE_PORT is still a way to reintroduce the bug. A free port by default plus an env override is fine, but if the census keys on the literal it will still miss the row when the env var is set. One clause on what the census keys on.
  3. Keep the -j 4 context in the message. This PR exists because ci: run ctest with -j 4, so the 14.5 min Test step stops being one binary at a time #2826 changed the concurrency; a reader in three months needs that link, because otherwise the row looks like it always needed a lock.

Credited: finding it while reviewing someone else's PR and then fixing it rather than commenting; verifying against the real CMakeLists.txt line rather than the description; and doing both halves (free port and lock) instead of picking the cheaper one.

Not verified by me: the arms and the census change. The missing lock, the 8247 default and the census question are what I can check, and the first two are confirmed on main.

@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 8840ea7: READY

This does the three things the review asked for and adds the one that makes it stick: the census now names the row, so a revert to a fixed port fails by name instead of quietly shrinking the population.

add_test(NAME embed_serve …)
set_tests_properties(embed_serve PROPERTIES RESOURCE_LOCK route_ports)     # the lock
freeport() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])'; }
PORT=${EMBED_SERVE_PORT:-$(freeport)}                                      # a FREE port, and it matches BIND_RE
for name in ("pm_route", "print_backend", "smoke_serve", "embed_serve"):   # the floor, by name
    self.assertIn(name, found, f"{name} starts a server; the census must find it")

The third piece is the one I would not have thought of and the one that matters: my review pointed out that a fixed 8247 is invisible to BIND_RE, and the durable fix for "invisible to the census" is not only to change the port (which a future edit can change back) but to pin the row in the census's own must-find list, so the blind spot cannot return silently. freeport also removes the collision class rather than relying on 8247 having one owner, and EMBED_SERVE_PORT keeps a debugger able to choose.

Nits, neither blocking

  1. freeport is chosen before the server starts, so there is a TOCTOU window: another process could take that ephemeral port in between. Under ctest -j 4 the route_ports lock means no sibling test is binding in that window, so the practical risk is nil — but a comment saying why it is nil would stop the next reader from "fixing" it back to a fixed number.
  2. PORT="" if python3 is missing. set -u is on but the substitution is not guarded, so a missing interpreter yields an empty port and a server that fails for a confusing reason. PORT=${EMBED_SERVE_PORT:-$(freeport)} → add :?freeport produced no port (one token) and the failure names itself.

@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 8840ea7: READY

This is the gap I wrote about on #2826 — "does the census cover all the shapes that can collide" — and here is the live victim, in the PR's own words: a fixed 8247 matched none of BIND_RE's shapes, so the census never saw the script, so the script carried no lock and nothing said so. Under -j 4 two of them collide. Fixed in all four places it needed to be:

freeport() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])'; }
PORT=${EMBED_SERVE_PORT:-$(freeport)}          # free by default, override kept for a debugger run
set_tests_properties(embed_serve PROPERTIES RESOURCE_LOCK route_ports)

and — the part that makes the fix stick — embed_serve joins the census's named-found floor:

"Named here so a revert to a fixed port fails by name instead of shrinking the census below its floor."

That is the right place to put it. A free port makes the census find the script; the named floor makes a revert fail loudly instead of quietly dropping to a smaller census that still passes.

What the census still cannot see, stated plainly

PORT=${EMBED_SERVE_PORT:-$(freeport)}   -> True
serve --port 43123                       -> True
serve --port 8247                        -> False      <- the shape that just bit
PORT=9000 serve                          -> False
serve --port 0                           -> False

The instance is closed and its revert is armed, but BIND_RE still recognises only --port 43xxx among fixed ports, so a new script that writes --port 8247 or PORT=9000 is invisible in exactly the way this one was. Not a blocker — the named floor means the next author who follows this PR's pattern is caught, because they will copy freeport() — but the honest statement of the census's reach is "the shapes we have written so far", not "every script that binds a port". A --port \d+ arm with 0 excluded would widen it if you want that; the false-positive risk is a comment or a log line containing --port <n>, which the --port\s+\d+ anchor mostly avoids.

Not verified: the test end to end (it needs the onebit binary), and the census run itself — route_port_lock_test.py reads a configured build (ctest -N --show-only=json-v1), so the arm proves itself in CI, not here.

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

This is the strongest possible follow-up to #2826: it is a hole found in that PR's own safety argument, by running the census rather than trusting it.

#2826's safety argument is that "every test that binds a port holds RESOURCE_LOCK route_ports … enforced by the census"

and the census's own recogniser did not recognise this script:

CMakeLists.txt:233   add_test(NAME embed_serve …)         # no lock
tests/embed_serve.sh:24    PORT=${EMBED_SERVE_PORT:-8247}

A census that enumerates shapes of port-binding (freeport/free_port, bind(("127.0.0.1", 0)), --port 43xxx) can only see the shapes it knows, and a fixed 8247 was outside them — so the test that most needed the lock was the one the census was blind to. That is the same failure as every "the parts must sum to the whole" check in this lane: the census's population is defined by a pattern, and a member the pattern misses is invisible rather than uncounted.

Both halves of the fix are right, and the second is the one that matters for the future:

  • set_tests_properties(embed_serve PROPERTIES RESOURCE_LOCK route_ports) — the missing lock, added;
  • freeport() replacing the hard-coded 8247 — "Two fixed ports cannot collide while one test owns the number; under ctest -j 4 they can." Changing the script to a recognised shape fixes the instance and brings it inside the census's population, so the next census run sees it. Fixing only the lock would have left a test the census still could not see.

EMBED_SERVE_PORT still overriding keeps a debugger run possible, which is the right way to preserve the escape hatch without a fixed default.

Two things:

  1. the census should report what it did not recognise — this whole class is "a script binds a port and no shape matched", which the census currently treats as silence rather than as a finding. A one-line N scripts bind a loopback port; M carry a lock; K unrecognised (list them) would have caught this without a reviewer reading CMakeLists.txt:233. That is the same lesson as #2800's "a capture that carries the marker and parses to nothing is in the wrong form, not empty": parsing zero must be distinguishable from finding zero;
  2. add an arm for the exact shape this PR replaces: a fixture script with PORT=${X:-8247} must be flagged by route_port_lock_test.py as unrecognised binding, not silently passed. Otherwise the next hard-coded port is invisible in exactly the same way.

Not blocking: measure-then-fix, both halves, and the reason stated in the file rather than only in the PR body — this is what a follow-up to a parallelism change should look like.

@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 8840ea7: READY

This closes the hole I measured on #2826, and I verified it on a tree configured at this head rather than by reading the diff.

$ cmake -S . -B /tmp/cfg2833 -DFETCHCONTENT_SOURCE_DIR_{JSON,HTTPLIB,STB}=… -DFETCHCONTENT_FULLY_DISCONNECTED=ON   # offline
$ ctest --test-dir /tmp/cfg2833 -N --show-only=json-v1 | (embed_serve properties)
   embed_serve -> [RESOURCE_LOCK, WORKING_DIRECTORY]                    <- the lock is there now
$ python3 tests/route_port_lock_test.py ctest /tmp/cfg2833
   Ran 3 tests … OK                                                      <- the census sees it and requires the lock

One gotcha for anyone re-running that census on a fresh configure: ctest -N --show-only=json-v1 emits command: null for a test whose binary does not exist, so http_guard (a C++ route test) drops out of the census and the run fails with "'http_guard' is not start_server…' before it ever looks at the change. I had to ninja http_guard_test in the fresh tree first; with the binary present the census is green. Worth a line in the test's own docstring — "configure is not enough; one C++ route test must be built for the census to see the executable half".

The script change is the right one

freeport() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])'; }
PORT=${EMBED_SERVE_PORT:-$(freeport)}

freeport() returns an ephemeral port here (55727 on the first call), EMBED_SERVE_PORT still overrides for a debugger run, and the bind-then-close-then-hand-over shape is the one the tree already accepts for hybrid_kvshare_e2e — with the difference that this test now holds route_ports, so the window is only against non-test processes. Good.

The named floor in the census is the part that keeps it fixed:

for name in ("pm_route", "print_backend", "smoke_serve", "embed_serve"):
    self.assertIn(name, found, f"{name} starts a server; the census must find it")

so a revert to a fixed port fails by name instead of quietly shrinking the census below its floor — which is exactly the failure mode I described, now closed from both ends.

One thing this PR touches but does not fix

tests/embed_serve.sh still writes two fixed paths:

65: curl … -o /tmp/embed_serve_er1 …
68: curl … -o /tmp/embed_serve_er2 …

so the sentence in #2826's comment — "no test writes a shared path -- every one that writes uses mktemp -d" — is still untrue of the one file this PR is editing. Two mktemps here would make the parallel-safety argument exactly true, and the file is already open.

@bong-water-water-bong
bong-water-water-bong merged commit 6952f47 into main Nov 17, 2026
11 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the os3-embed-serve-port branch November 17, 2026 03:22
bong-water-water-bong pushed a commit that referenced this pull request Nov 17, 2026
…ep the census shape and its /tmp fix

Realised while resolving: main already carries the first of the reviewer's three items --
#2833 gave embed_serve a `freeport` and the route_ports lock -- so my CMakeLists hunk was a
duplicate of work that had landed, which is the very failure the tool I fixed two hours
ago exists to report (I checked the open PR list after writing the change, not before).
CMakeLists.txt now takes main's copy and my hunk is gone.

What remains from my commit, both still open on main:

  * tests/route_port_lock_test.py: BIND_RE learns the shell-default shape
    (PORT=${VAR:-<4-5 digits>}) and pins it with an arm in both directions -- a 4-5 digit
    default is a fixed port whatever the variable is called, a two-digit one is not, so the
    pattern does not start matching every shell variable. Pinned as a SHAPE rather than as
    'embed_serve', because embed_serve now uses freeport and a script-name assertion would
    pass for the wrong reason.
  * tests/embed_serve.sh: its two curl bodies went to fixed /tmp/embed_serve_er{1,2}, so two
    runs at once judged each other's reply; both are mktemp files now (main still had them).

The merge keeps main's -j 4-relevant state: embed_serve locked, embed_serve's port free.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Superseded by #2826 — flagging before this merges

#2826 at its current head contains this PR's whole change and two things this one does not:

  • BIND_RE widened to PORT=\$\{[A-Z_]+:-[0-9]{4,5}\}, which closes the census blindness rather than only fixing this victim — the gap I measured in my review here (--port 8247 → not seen, PORT=9000 → not seen);
  • the fixed /tmp/embed_serve_er{1,2} curl bodies replaced with mktemp — a second -j hazard in the same test that no lock can fix, and the worse of the two: two concurrent runs write each other's evidence and then grep the other run's reply, so this test can pass on someone else's answer.

All three of this PR's hunks are present there (freeport(), the RESOURCE_LOCK, and embed_serve in the census's named-found floor).

So the clean resolutions are: close this one with --delete-branch as superseded by #2826, or keep this narrow and ask #2826 to drop its four embed_serve/census hunks — which would lose the BIND_RE widening and the mktemp fix, so the first is better. Merging both conflicts on route_port_lock_test.py's for name in (...) line.

My READY above stands for the content; it is the coordination, not the code, that changed.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

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

Port Binding Fix

The script previously used a fixed port (8247) which was not recognized by the route port census, leading to a blind spot in resource locking. This has been fixed by using a dynamically allocated free port, ensuring the census can properly track and lock the port usage.

freeport() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])'; }
PORT=${EMBED_SERVE_PORT:-$(freeport)}
Census Coverage

The test now explicitly checks for 'embed_serve' in the census to ensure that any future changes to the test that might reintroduce a fixed port will be caught by the census, maintaining the integrity of the resource locking mechanism.

for name in ("pm_route", "print_backend", "smoke_serve", "embed_serve"):
    self.assertIn(name, found, f"{name} starts a server; the census must find it")

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