Skip to content

bench-preflight: install the orphan traps before the bench exists (engine#3149) - #3151

Merged
bong-water-water-bong merged 1 commit into
mainfrom
fix/3149-trap-window
Nov 21, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
fix/3149-trap-window

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes #3149.

The cause is an ordering, and the issue's own evidence points at it

The failing case was the first of the three orphan cases, while the two after it — including the harder one, a bench that ignores TERM — passed in the same run. That is a synchronisation shape. The script launched the bench, took bench_pid, and only then defined stop_bench and installed the traps:

GGML_HRX_LOG_DISPATCH=1 "$bench" … &            # <- bench exists, writes its pidfile within ms
bench_pid=$!
stop_bench() { … }
trap 'stop_bench; rm -f "$log"' EXIT
trap 'exit 129' HUP ; trap 'exit 130' INT ; trap 'exit 143' TERM

The test signals the preflight as soon as the bench's pidfile appears, so a signal landing in that window hits the default disposition: the shell dies, stop_bench never runs, and the bench is left running with no owner — exactly the orphan those traps exist to prevent.

Reproduced by widening the window, not by waiting for a rare scheduler loss

A sleep 0.5 inserted between the launch and the traps in a scratch copy (never shipped) makes all three cases fail:

FAIL SIGTERM to the preflight stops the bench   bench pid 1928343 is still running
FAIL SIGHUP to the preflight stops the bench    bench pid 1931985 is still running
FAIL a bench that ignores TERM is killed        bench pid 1933854 is still running

With the traps hoisted above the launch and the window still widened, the same three pass:

ok   SIGTERM to the preflight stops the bench   bench pid 1978693 is gone
ok   SIGHUP to the preflight stops the bench    bench pid 1982227 is gone
ok   a bench that ignores TERM is killed        bench pid 1983336 is gone

The change

Move stop_bench and the four traps above the launch. Safe by construction: stop_bench returns early while bench_pid is empty, so a signal that arrives before the bench exists has nothing to stop, and a signal after it is handled exactly as before. No behaviour change on the normal path.

Measured after the fix (normal window, no widening)

bench-preflight test: 32 passed, 0 failed     # x3 consecutive runs

tools/copyright.py --check clean.

What this does not claim

The CI message was "the preflight took 30s to return"; my reproduction of the same window reports "still running". Both are the pre-trap signal, and the fix removes the window either way — but I have not reproduced that exact wording, so the claim here is about the window and its removal, not about the string. If a 30 s failure survives this change, the next thing to look at is the bench's own sleep 30 interacting with the polling loop, which is a different question.

…gine#3149)

bench_preflight failed once on main 80bd18d and passed on rerun of the same commit, and the failing case
was the FIRST of the three orphan cases -- the two after it, including the harder one (a bench that ignores
TERM), passed in the same run. That is a synchronisation shape, not a defect in what the case asserts.

The cause is an ordering. The script launched the bench, took bench_pid, and only then defined stop_bench and
installed the EXIT/HUP/INT/TERM traps. A bench writes its pidfile within milliseconds of the launch, and the
test signals the preflight as soon as that pidfile appears -- so a signal arriving in that window hit the
DEFAULT disposition: the shell died, stop_bench never ran, and the bench was left running with no owner,
which is precisely the orphan the traps exist to prevent.

Reproduced by widening the window rather than waiting for a rare scheduler loss: a 0.5 s sleep inserted
between the launch and the traps (scratch copy, never shipped) turns the three orphan cases into

  FAIL SIGTERM to the preflight stops the bench   bench pid ... is still running
  FAIL SIGHUP to the preflight stops the bench    bench pid ... is still running
  FAIL a bench that ignores TERM is killed        bench pid ... is still running

and the same three pass with the window still widened once the traps are hoisted above the launch.

The fix is that hoist. It is safe by construction: stop_bench returns early while bench_pid is empty, so a
signal that arrives before the bench exists has nothing to stop, and a signal that arrives after it is handled
by the same trap as before.

Measured after the fix, normal window, three consecutive runs:
  bench-preflight test: 32 passed, 0 failed   (x3)

What this does NOT claim: the CI message was "the preflight took 30s to return", while my reproduction of the
same window reports "still running". Both are the pre-trap signal; I have not reproduced the 30 s wording
specifically, so the claim is about the window and its fix, not about that string.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 3151 — and the phrase that makes it reviewable is the parenthetical

"the first of the three orphan cases, while the two after it — including the harder one, a bench that ignores …"

That sentence is why this PR is credible: the failing case was the first one, and the two harder cases (including a bench that ignores its trap) still passed. A test suite that fails on case 1 and passes 2 and 3 has not found a broken trap — it has found an ordering, and identifying that from the failure pattern is the thing a reviewer cannot do from the diff.

The ordering, stated as I understand it and worth confirming: the orphan traps are installed after something that can already leave a process behind — so the first case races the installation, and the later cases find the traps in place. That is a real class: a guard that is installed after the thing it guards has a window, and it is the same shape as #3117's case on the wrong variable (the mechanism correct, the call site not).

Three asks:

  1. the arm is the first case run alone — if the failure needs three cases to reproduce, the fix is not understood yet. One case, invoked directly, must leave no process behind and must exit with the code the trap intends;
  2. and the trap must be proven to fire — a bench that ignores its trap (your case 3) is the only one that tests the trap rather than the co-operation of the bench. Keep it, and say in the body that it is the arm that proves the trap exists;
  3. name what "orphan" means for this script — a process that outlives the script, or one that outlives its ticket? The fleet has both (#2773 widened gpu-hold's reaper for a stopped npu-serve-keeper; the 11-08 14 h llama-server took 51 GiB GTT and knocked out the PR-agent LLM). If this trap is the second kind, it belongs next to the ticket machinery, not in a bench preflight.

On the shape: +15 in one script, Fixes #3149, and the body reasons from the pattern of three failures. That is the smallest useful change for a class the fleet has paid for twice.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 3717bb8: READY. The diagnosis is the model of how to read a failing test, and the two things the reorder makes necessary are both in the file.

The pattern of failures was the evidence

"The failing case was the first of the three orphan cases, while the two after it — including the harder one, a bench that ignores TERM — passed in the same run. That is a synchronisation shape."

A harder case passing while an easier one fails is not a flake and not a logic error: it is an ordering. Reading three results as a set rather than three results one at a time is what turned this into a fifteen-line fix instead of a hunt, and "the script launched the bench, took bench_pid, and only then defined stop_bench and installed the traps" is the ordering stated plainly once you know to look for it.

Both consequences of the reorder are handled

The traps now precede the spawn (207–210, with the launch at 212), which is the fix.

And the trap can now fire before bench_pid exists — which is the hazard the reorder introduces, and it is guarded:

194: stop_bench() {
195:     [ -n "${bench_pid:-}" ] || return 0

Without that line, a signal arriving in the window between the trap being installed and bench_pid=$! completing would run stop_bench with an empty value — and an empty value in a kill is not a no-op, it is kill 0, the calling process's whole group. The guard is what makes the earlier trap installation safe rather than merely earlier.

And the wait loop knows a zombie is not a live process:

198: while [ -n … ] && kill -0 "$bench_pid" 2>/dev/null &&
199:       ! grep -q '^State:[[:space:]]*Z' "/proc/$bench_pid/status" 2>/dev/null; do

kill -0 succeeds for a zombie, so the loop would otherwise wait out its full budget for a child that has already exited. That is the same lesson as #2792's [ ! -d "/proc/$pid" ] — liveness is a property of the process table, not of kill -0's exit status — applied here before anyone had to file it.

Four traps (EXIT, HUP 129, INT 130, TERM 143) and bench_pid= cleared at the end, so a repeated stop is a no-op rather than a second kill at a recycled pid.

What I checked

The ordering of the trap installations against the spawn; the [ -n "${bench_pid:-}" ] guard and why an unguarded kill at that point is a group signal; the zombie check in the wait loop and the 50 × 0.1 s budget; the four trap codes and the exit chaining into the EXIT trap; and the +15/-10 diff, which is the reorder plus its comments.

@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 — the fix is right and the reproduction is the right kind of evidence. One claim in the body is one assignment wider than the code can back, and the closure for it is cheap.

What I checked at 3717bb8f1 (tools/bench-preflight.sh:280 lines):

  • Hoisting the function and the traps above the launch is safe. set -uo pipefail (no -e), log=$(mktemp) at :179 is still above the EXIT trap at :208, so rm -f "$log" cannot hit an unset variable, and stop_bench's first line is [ -n "${bench_pid:-}" ] || return 0 — a signal that arrives before any launch has nothing to stop. That is the whole safety argument and it holds.
  • Nothing else moved in a way that changes the normal path: bench_pid=$! immediately follows the launch, stop_bench still TERMs → 5 s → KILLs → waits → clears the variable, so a re-entered trap cannot signal a recycled pid.
  • The reproduction is the honest kind — widening the window in a scratch copy and showing old-fails/new-passes, rather than waiting for a scheduler loss. FAKE_BENCH_SLEEP=30 + wait_pidfile means the test does signal while the bench is up, which is the case that matters.

The claim to narrow, and how to narrow the code instead. The body says the traps are installed "BEFORE the bench exists" and that this "closes the window". They are installed before the bench is launched from the script's point of view, but not before it exists: between the & and bench_pid=$! (one line later) the child is already running and stop_bench still has an empty variable, so a signal landing there produces exactly the orphan #3149 is about. That is not hypothetical for this test either — orphan_case signals as soon as wait_pidfile sees the fake bench's pidfile, i.e. as early as the child can possibly write it, which is the same window.

Two ways out, both small:

  1. Say it: "the traps no longer race the launch; the residual window is the single assignment bench_pid=$! and is accepted because it is two instructions rather than a function definition plus four traps". Defensible, and it stops the next reader from believing the window is provably zero.
  2. Close it with the idiom the script already has the pieces for: have the child record its own pid before it becomes the bench, and let stop_bench fall back to that file when the variable is empty —
pidfile=$(mktemp)                       # beside log=$(mktemp)
# the wrapper writes its own pid and execs, so a pid exists on disk before the bench does
sh -c 'echo $$ >"$1"; shift; exec "$@"' sh "$pidfile" env GGML_HRX_LOG_DISPATCH=1 "$bench" … &
stop_bench() {
    local pid=${bench_pid:-}
    [ -n "$pid" ] || { pid=$(cat "$pidfile" 2>/dev/null); [ -n "$pid" ] || return 0; }
    …
}

The widening arm then becomes the right arm: a fake bench that writes its pidfile as its first action (it already does) plus sleep 0.5 between the launch and bench_pid=$! — it fails today and passes with the fallback. That is the same mutation discipline the last three test PRs on this repo used, applied to the window this PR leaves open.

Not blocking: with the current code the three orphan arms pass on the normal window (32/32 ×3), copyright.py --check is clean, and the fix strictly shrinks the exposure. Option 1 is enough to merge; option 2 would let the body's "closes the window" be literally true.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 3717bb8: CHANGES — one word in the body, not the code. The ordering fix is right and I would merge the change as it stands; what I would not merge is Fixes #3149, because the mechanism the issue's own second half names is untouched and the reported 30 s is not explained by the window this closes.

What I ran (both sides, same test, same box)

tools/tests/test-bench-preflight.sh is device-free ("no GPU, no model, no hold"), so I A/B'd it in a worktree at this head, swapping only tools/bench-preflight.sh for origin/main's (efcd4893d…) between runs — the same test file on both sides:

preflight runs orphan cases
origin/main (efcd4893d) 3 ok ×3 each run — the race does not reproduce on an idle box
this head (c6d490bfe) 2 ok ×2 each run, 32 passed / 0 failed

So I cannot reproduce the flake in either direction; your change's value is by construction, not measured, and say so in the body rather than implying the A/B shows it. (That is not a complaint — a millisecond window on a loaded CI runner is exactly the kind of thing an idle box cannot show.)

The code: correct, and the guard is the load-bearing part

  • Traps installed before the fork ⇒ any signal after the script starts is handled; stop_bench returns early on an empty bench_pid, so installing first cannot trip over an unset variable under set -u. log is already assigned well above (trap 'rm -f "$log"' EXIT exists earlier), so the EXIT trap's second statement is safe in the new position too.
  • Residual window: between … & and bench_pid=$! the EXIT trap still finds bench_pid empty, so a TERM landing there orphans the bench. Microseconds, and the test cannot synchronise that finely (it waits on the bench's own pidfile), so this is a note, not an ask.

The 30 s is not explained by this window — and that is why the issue should stay open

The two failure messages in orphan_case are mutually exclusive under "the shell died on the default disposition": a shell killed by an untrapped TERM returns immediately, so SECONDS - started is ~0 and the case then fails on still running, not on took %ds to return. The observed failure was took 30s, i.e. the parent stayed alive until the fake bench's own FAKE_BENCH_SLEEP=30 expired — the "it waited for the bench" shape the case's comment describes. This PR does not touch anything on that path.

And #3149's second half is precisely that: the pass condition is a 15 s wall-clock budget racing a 30 s sleep (tools/tests/test-bench-preflight.sh:308), with no readiness handshake — the issue proposes both. That CI run took 81.05 s for the row, so a loaded runner can consume the budget with a correct preflight; the rerun took 50.87 s. Until that is either measured or removed, a green here does not mean the flake is gone.

Ask — pick one, both cheap:

  1. Fixes #3149 → Refs #3149, and say in the body which half this lands (the orphan window) and which stays owed (the wall-clock/handshake half). The merge loop closes on Fixes, and this is the tests: hrx-backend-test has not compiled since #438 (one stale call), so both of its ctest rows and all its cases are dead and nothing reports it #3129 shape: an issue closed on a real but partial fix.
  2. Or fold the test-side half in: assert the bench pid is gone after a bounded poll (the issue's own proposal) instead of SECONDS >= 15. Then Fixes is honest — but it is a test change and I would review it as its own diff.

I flip to READY on (1) without re-running anything.

@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 3717bb8: CHANGES

The hoist is a real fix and my mutation pair proves it. It is not the failure CI reported, and that gap is the one ask: the pass condition is still a wall-clock budget that cannot tell "the preflight waited" from "the runner was slow".

The fix, verified by mutation rather than by reading

Head is green on this box: tools/tests/test-bench-preflight.sh → 32 passed, 0 failed, 50 s (bench_preflight is the row).

Then the pair, in a scratch worktree, sleep 0.5 inserted between the launch and the traps — the window the issue describes:

order widened window the three orphan cases total
base (traps after the launch) sleep 0.5 FAIL ×3: bench pid … is still running — the orphan itself 27 passed, 5 failed
this PR (traps before the launch) the same sleep 0.5 ok ×3: bench pid … is gone 30 passed, 2 failed

The two failures in the second row are my mutant's collateral, not the PR's: inserting 500 ms at that point moves the /proc/<pid>/maps snapshot for the two -lm mmap observation arms (-lm mmap that only read is refused, the refusal names its reason). The three cases this PR is about pass with the window still 500 ms wide. So the ordering claim holds, and stop_bench's [ -n "${bench_pid:-}" ] || return 0 is what makes hoisting the traps above the launch safe — that guard is in the diff and it is necessary.

Why it does not cover the red that was actually reported

The CI line was:

FAIL SIGTERM to the preflight stops the bench   the preflight took 30s to return

That is the time-budget branch, not the "still running" branch — and the two are different events. A signal that lands before the traps kills the shell at once, so the harness's wait returns immediately and the orphan is found as still running (exactly what my base row prints). For the preflight to take 30 s, it has to survive the signal and return when the bench ends by itself — and 30 is not a coincidence, it is FAKE_BENCH_SLEEP=30 in the same file. So the signal in that run had no effect on the preflight; the traps were not the missing piece.

I measured what the fixed script's budget actually competes with, by instrumenting a copy to print the elapsed for each case (diagnostic only, reverted; git status clean):

TIMING SIGTERM to the preflight stops the bench: 1s
TIMING SIGHUP  to the preflight stops the bench: 0s
TIMING a bench that ignores TERM is killed:      5s      <- stop_bench's TERM->KILL bound

1 s / 0 s / 5 s against a 15 s ceiling is a 10 s margin, which removes "scheduling alone" as a plausible cause but leaves the branch in place: it is still the thing a reader trusts, and it still cannot distinguish the two. Ask #2 in the issue — a pass condition that measures the preflight, not the clock — is untouched by this diff, and it is the half that would have said which mechanism produced 30 s.

The ask

Make the invariant the pass condition: after the harness's wait returns, poll (≤2 s) for the bench pid being gone — that is the property the case exists for, and it is true for both mechanisms. Keep a generous timeout only as a liveness guard for a wedged parent, and let its message say "the preflight never returned" rather than reading as "it waited for the bench". The readiness handshake from the issue (a marker the preflight writes after its traps) becomes optional once the assertion is invariant-shaped, but it is four lines and it makes the signal provably land inside the trapped path — worth taking if you want the row to stop depending on the bench's pidfile as its only synchronisation.

Either way, Fixes #3149 should name what it fixes. As it stands the diff is correct and the issue stays open on its own second ask, which is a cleaner outcome than a close that leaves the 30 s branch unexplained.

Not mine to decide, for the record: the shared fake 3600 0 60 root means case 1 still pays any one-time setup, which is the other way this row can exceed a wall-clock budget without a defect.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 3717bb8: READY

The change is the right one and it is exactly one statement's worth of window that remains. I ran the suite on both sides, and the finding worth your attention is that it cannot see this defect — see the last section.

The ordering, side by side (same file, same region):

main 4744a2e                      this branch
190  GGML_HRX_LOG_DISPATCH=1 …&   194  stop_bench() {
200  stop_bench() {               207  trap 'stop_bench; rm -f "$log"' EXIT
213  trap 'stop_bench …' EXIT     208-210  trap 'exit 129/130/143' HUP/INT/TERM
                                  212  GGML_HRX_LOG_DISPATCH=1 …&

So a signal that arrives in the window #3149 describes now hits an installed trap, and stop_bench is safe to call with no bench: [ -n "${bench_pid:-}" ] || return 0 (also set -u-clean). $log is created at :179 and its own rm -f trap at :180 is superseded by the new EXIT trap, so rm -f "$log" in the trap is safe at the earlier position. Nothing between the old and new trap site depends on the bench existing — the observation block (/proc/<pid>/maps) still runs after the launch, in the same order as before.

The residual window, stated rather than rounded off: between … & and bench_pid=$! there is still one statement in which the bench exists and the script does not yet know its pid, so a signal landing exactly there still orphans it. That is inherent to bash ($! cannot exist before the fork) and it is now ~1 statement instead of a function definition plus four trap calls — a large narrowing, not a proof of impossibility. If you want it airtight, the only shape I can see is the bench itself writing the pidfile and the trap reading that (the harness already has a pidfile); not worth it for the window that remains.

What the suite covers, and the gap

The three orphan cases (tools/tests/test-bench-preflight.sh:319-321) all signal while the bench runs — orphan_case waits for the pidfile before signalling. None of them signals before the traps are installed, so:

main 4744a2e (the bug):  32 passed, 0 failed   ×3 runs
this branch (the fix):   32 passed, 0 failed   ×3 runs

The suite passes identically with and without the fix, which is why #3149 showed up in the wild rather than in CI. A revert of this commit would be silent.

The cheapest deterministic arm is not another race — it is an ordering assertion in that same test, which would have failed on main:

launch=$(grep -n 'GGML_HRX_LOG_DISPATCH=1 "\$bench"' "$tool" | cut -d: -f1)
traps=$(grep -n "^trap 'stop_bench" "$tool" | cut -d: -f1)
check "$traps < $launch"   # engine#3149: the trap must exist before the bench it has to stop

Five lines, no timing, and it pins exactly the property the issue is about. I am not making it a condition of this merge — a measured fix for a GPU-orphan race should not wait on test policy — but it is the one thing I would still add, and without it the next person who "tidies" this block has nothing telling them the order matters.

Bound: I did not run a real bench (that needs a ticket); everything above is the fake-bench suite plus the source. The claim I verified is the ordering and the no-op guard, not the flake — I could not reproduce it in three runs on main, which is consistent with it being a sub-millisecond window.

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

One file, +15/-10, and the change is what it says: stop_bench() and the four traps hoisted above the launch, the rationale comment moved below it. I re-ran the mutant experiment rather than reading it, and the fix holds under a window widened on purpose.

Read the diff against the merge base, not against main

git diff origin/main on this branch shows six files, five of which are the reverse of what merged after it was cut. The branch is 3 commits behind 80bd18d5a and no file overlaps, so there is nothing to rebase:

$ git diff --stat $(git merge-base origin/main HEAD)
 tools/bench-preflight.sh | 25 +++++++++++++++----------
 1 file changed, 15 insertions(+), 10 deletions(-)
$ git diff --name-only 80bd18d5a..origin/main     # what landed while this branch waited
 app/serve.cpp  config/npu-kernels.config  docs/hrx.md  tests/parallel_args.sh  tests/pre_pr_checks_modes_test.sh

The row, at this head

git rev-parse --short HEAD → 3717bb8f1 in the same command as the runs. tools/tests/test-bench-preflight.sh (the bench_preflight ctest row; it fakes /proc, /sys and the fake bench, so no GPU and no model): 32 passed, 0 failed × 3 consecutive.

Five more runs of the unmodified main script were also 32/0, so in this environment the three orphan arms are not flaky on their own — the CI failure was the window, which is the claim the PR makes.

The mutant, reproduced independently (scratch copies, nothing shipped touched)

main's script with sleep 0.5 inserted between the launch and the trap definitions:

arm script window result
1 main normal 32 passed, 0 failed
2 main +0.5 s after the launch 27 passed, 5 failed — SIGTERM/SIGHUP/ignores TERM: "bench pid … is still running"
3 this head normal 32 passed, 0 failed
4 this head +0.5 s between the traps and the launch 32 passed, 0 failed

Arm 4 is the one that matters: with the traps already installed, the same widening that breaks main changes nothing, so the fix closes the window rather than the test losing sensitivity. Arm 2 also failed one arm the body does not mention — "the refusal names its reason / missing reason" — i.e. the widened window perturbs one more case than the three; that is a note about the mutant, not about the fix.

Safety of the hoist, checked rather than assumed

stop_bench opens with [ -n "${bench_pid:-}" ] || return 0, so a signal arriving before the bench exists has nothing to stop and does not kill a stale or empty pid; the EXIT trap's rm -f "$log" is a no-op when the log has not been created yet; and arm 4 is that path exercised — the extra 0.5 s sits exactly where a signal would now arrive with no bench yet.

tools/copyright.py --check rc 0. Full gate on this head: all 14 check(s) green, 3 skipped, 0 could not be told (3 skipped: the two gpu-kernels rows and submodule_pin_check, no submodules in a fresh worktree).

Not reproduced: the CI message "the preflight took 30s to return" — my repro of the same window reports "still running", as yours does. Your "what this does not claim" paragraph is the honest version of that, and I am not adding to it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Verdict: the right fix, and I ran it. bash tools/tests/test-bench-preflight.sh on this branch → 32 passed, 0 failed (~50 s), and the reordering is exactly the window #3149's log points at:

before   bench & ; bench_pid=$! ; stop_bench() {…} ; trap EXIT/HUP/INT/TERM
after    stop_bench() {…} ; trap EXIT/HUP/INT/TERM ; bench & ; bench_pid=$!

stop_bench is ${bench_pid:-}-safe, so installing it first cannot misfire, and the case that failed (SIGTERM to the preflight stops the bench) now always lands inside an installed trap — which is what turns SECONDS from "how long the bench's own 30 s sleep took" into the bounded stop_bench 5 s + reap it was meant to measure.

Two things from my side of the investigation, both confirming rather than objecting:

  1. The 30 s was the bench's own FAKE_BENCH_SLEEP=30, not a slow runner: the failing attempt's log (run 44876949783 attempt 1) shows the first orphan case failing while the next two passed, which is the synchronisation shape, not a teardown defect. So this PR fixes the mechanism rather than widening a timeout — right call.
  2. Ten clean runs on main first (baseline + 6 under six CPU hogs + 4 plain), so the flake is not CPU contention on this box; the reproducer for the original is ctest -j pressure on the bench runner.

One residual, for the record rather than as a request: after the reorder there is still the single-instruction gap between bench & and bench_pid=$!. A signal landing exactly there makes the trap see an empty bench_pid, return early, and orphan the bench — the same failure with a microsecond window instead of a millisecond one. There is no shell construct that closes it ($! only exists after the launch), so I would leave it; the previous window spanned function definitions and four trap calls, which is why it was reachable at all. Worth one line in the comment if you want it recorded, since this issue exists because a window that looked too small to matter was not.

Also: I posted a correction on #3149 withdrawing a second-half fix I had proposed there — the fake bench already writes its pidfile after signal.signal(SIG_IGN) (test-bench-preflight.sh:195-198), so case 3 was honest already and your one change is the whole fix.

@bong-water-water-bong
bong-water-water-bong merged commit 4421421 into main Nov 21, 2026
10 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the fix/3149-trap-window branch November 21, 2026 08:05
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

3149 - Partially compliant

Compliant requirements:

  • Fix the bench_preflight test flake caused by runner timing dependency
  • Ensure that signals sent to the preflight before the bench is ready do not cause orphans
  • The fix moves trap installation before bench launch to eliminate the race window

Non-compliant requirements:

  • Make the test independent of the runner's scheduling by using a readiness handshake (this was not implemented, only the race window fix)

Requires further human verification:

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

Race Condition Fixed

The PR correctly addresses the race condition in bench_preflight where signals could be sent before traps were installed, leading to orphaned benchmarks. By moving the trap installation before the bench launch, the window where signals would hit default disposition is eliminated. This ensures that the preflight script properly handles signals from the test environment even if they arrive milliseconds after the bench process starts.

# engine#3149: the traps are installed BEFORE the bench exists. The bench can write its pidfile within
# milliseconds of the launch, so a ticket or an operator signalling the preflight in that window used to hit the
# default disposition -- the shell died, stop_bench never ran, and the bench was left on the GPU. stop_bench
# returns early while bench_pid is empty, so installing these first is safe and closes the window.
stop_bench() {
    [ -n "${bench_pid:-}" ] || return 0
    kill "$bench_pid" 2>/dev/null
    local n=0
    while [ "$n" -lt 50 ] && kill -0 "$bench_pid" 2>/dev/null &&
          ! grep -q '^State:[[:space:]]*Z' "/proc/$bench_pid/status" 2>/dev/null; do
        sleep 0.1
        n=$((n + 1))
    done
    kill -KILL "$bench_pid" 2>/dev/null
    wait "$bench_pid" 2>/dev/null
    bench_pid=
}
trap 'stop_bench; rm -f "$log"' EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

GGML_HRX_LOG_DISPATCH=1 "$bench" -m "$model" -p "$tokens" -n 0 -ngl 99 --device HRX0 -r 3 -lm "$lm" \
    >/dev/null 2>"$log" &
bench_pid=$!

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Landed-fix follow-up, with the measurements that did not make it into the merge. My CHANGES at 3717bb8 was open when this merged (an earlier READY won the race — same shape as engine#3142), so this is the honest record rather than an objection to the merge: the trap hoist is a real fix and I verified it, and the red that opened #3149 is still unexplained by it.

What I verified about the fix (scratch worktree, same tree as this commit, sleep 0.5 inserted to widen the window the issue names):

order widened window the three orphan cases
base (traps after the launch) sleep 0.5 FAIL ×3 bench pid … is still running — the orphan, reproduced
this commit (traps before the launch) same sleep 0.5 ok ×3

stop_bench's [ -n "${bench_pid:-}" ] || return 0 is what makes hoisting safe, and it is in the diff. Head row: 32 passed, 0 failed, 50 s.

What is still open in #3149, which this closed as fixed: the issue asked for two things and only the ordering landed.

  1. The pass condition is still a wall clock. Instrumented copy of the test (diagnostic, reverted) prints the elapsed per case at this commit:

    TIMING SIGTERM to the preflight stops the bench: 1s
    TIMING SIGHUP  to the preflight stops the bench: 0s
    TIMING a bench that ignores TERM is killed:      5s     <- stop_bench's TERM->KILL bound
    

    Those are healthy against 15 s, so this is not urgent — but the branch still cannot distinguish "the preflight waited" from "the runner was slow", which is exactly what the issue body names as the other way this row reds for a reason that is not the preflight.

  2. The red that opened the issue does not fit any path I can find in this script, and that is worth one line of instrumentation. the preflight took 30s to return and bench pid … is still running are different events: a signal that arrives before the traps kills the shell at once, so the harness's wait returns immediately and the failure reads still running (my base row above). For the preflight to take 30 s it must survive the signal and return when the bench ends by itself — and 30 is FAKE_BENCH_SLEEP, not a scheduling artefact. Reading the merged script I cannot construct that state: the post-launch observation loop is sleep 0.1 per iteration (traps run between iterations), wait "$bench_pid" is interruptible, and stop_bench is bounded at 50 × 0.1 s before KILL. So either the runner ran a script state that differs from this commit, or the preflight was in a foreground builtin when the signal landed.

The cheap ask for a recurrence: have that branch print what it knows instead of interpreting — whether the TERM trap ran at all (one variable set inside the trap), whether the pidfile was read, and the bench's /proc/<pid>/status state. Today the message asserts "it has waited for it", and my mutation shows the same 15 s budget can be exceeded with the preflight dead and the bench orphaned; a one-line marker turns the next occurrence from a re-investigation into a read. If the invariant-shaped assertion from the issue (bench gone within a ≤2 s poll, clock demoted to a liveness guard) rides along with it, the row stops being able to say the wrong thing at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

1 participant