Skip to content

forward-serve: queue a refused NPU context like the unified routes do (engine#2434) - #2436

Merged
bong-water-water-bong merged 1 commit into
mainfrom
cl-flm/2434-forward-retry
Nov 14, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
cl-flm/2434-forward-retry

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs #2434.

What was wrong

A --device npu serve of a .q4nx container goes through forward-serve, and it died in ~0 s whenever another client held the array. The unified routes queue on that refusal; this path did not. There were two separate gaps, and the fix needs both:

  1. No retry. app/forward_serve.cpp called e.fwd->init() once and threw, with no open_with_retry, which app/unified.cpp uses for exactly this case.
  2. The refusal was invisible to the code that queues it. I8Ctx::init_elf printed the runtime's reason to stderr and returned false. The error that reached the caller was only I8Ctx init_elf failed for <elf>, with no code 102 … No such device in it. So npu_contexts_refused() could not recognise a refused context. Even with a retry, a co-tenant got the 2.5 s generic window and not the queue. The existing lock-holder note in forward_serve.cpp could never fire either.

The change

  • forward_serve.cpp: the init goes through open_with_retry(LoadRetryPolicy). The refusal window is a new --load-queue-ms option (default 45000, the value serve already gives the unified routes). Each attempt builds a fresh forward and xrt::device, so nothing a failed init left half-built is reused. On the final refused failure, open_with_retry prints the lock-holder note and the reload hint, replacing the inline note that could not fire.
  • serve.cpp: passes --load-queue-ms on both forward-serve launches.
  • npu_engine_i8ctx_inc.h + xdna_target.cpp: I8Ctx::init_error keeps the runtime's reason, and both of xdna_target's init_elf errors append it.
  • tests/npu_load_retry_test.cpp: the cause-less forward error is not a refused context; the same error with the reason is.

Measured on the device (strixhalo, npu-hold), against a live FastFlowLM serve holding the array

1bit serve -m ~/models/npu/Qwen3-0.6B --device npu, kernels from the in-tree xclbins:

attempts wall what the operator sees
main (2366e3584 lineage) 1 0.3 s forward init failed: I8Ctx init_elf failed for …QKV_K1024_N4096.elf
retry only (part 1, no reason carried) 5 2.3 s the generic window; the refusal was not recognised
this PR, --load-queue-ms 8000 7, queued 6.4 s of an 8 s window each attempt names (code 102): No such device and (queued: another NPU client may hold the array), then the hint, exit 1

The holder never let go in that run, so the "holder releases inside the window" arm (recovered on attempt N) is covered by npu_load_retry_test's fake, not by the device. FastFlowLM does not take our device lock, so no lock-holder note appears for it. A holder that takes the lock gets the note first.

Build: NPU-only (ONEBIT_HRX=OFF). The only non-linking targets are the two NPU tests that also fail on main. ctest 315/315, excluding the device tests, with the GPU hidden.

🤖 Generated with Claude Code

… (engine#2434)

forward-serve made one init attempt and exited in ~0 s when another client held
the array, so a live co-tenant read as a broken device. Two parts:

1. The forward NPU init goes through open_with_retry with a LoadRetryPolicy whose
   refusal window is --load-queue-ms (new forward-serve option, default 45000,
   the value serve already passes the unified routes; serve now passes it on
   both forward-serve launches too). Each attempt builds a fresh forward and
   device handle. The final refused failure prints the lock-holder note and the
   reload hint (from open_with_retry, replacing the inline note).

2. I8Ctx::init_elf kept the runtime's reason on stderr only and returned false,
   so the error that reached the caller was "I8Ctx init_elf failed for <elf>"
   with no "code 102 ... No such device" in it. npu_contexts_refused() could not
   see a refusal, so even with (1) a co-tenant got the 2.5 s window, and the
   existing lock-holder note in forward-serve never fired. init_elf now keeps
   the reason (I8Ctx::init_error) and xdna_target appends it to both of its
   init_elf errors.

Measured on strixhalo against a live FastFlowLM serve holding the array
(npu-hold, `1bit serve -m Qwen3-0.6B --device npu`): main exits after 1
attempt in 0.3 s; this branch with --load-queue-ms 8000 retries 7 times, queued,
over the 8 s window, then prints the hint and exits 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at 25bfe25

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2434 - Partially compliant

Compliant requirements:

  • The forward_serve path now uses open_with_retry to handle refused NPU contexts
  • The error message from init_elf now includes the runtime's reason so that npu_contexts_refused can recognize refused contexts
  • A new --load-queue-ms option has been added to control the retry window for refused contexts
  • The serve command now passes the --load-queue-ms option to forward_serve

Non-compliant requirements:

  • None

Requires further human verification:

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

Missing Input Validation

The new --load-queue-ms option lacks validation for negative values, which could lead to unexpected behavior or crashes. While the code checks for load_queue_ms < 0, it does not ensure that the value is within a reasonable range for the intended use case.

if (load_queue_ms < 0) throw std::runtime_error("--load-queue-ms takes milliseconds >= 0, not " + std::to_string(load_queue_ms));
Error Message Clarity

The error message in the open_with_retry block could be more informative by including the specific error code or reason from the runtime, which would help in debugging and monitoring.

if (!ok) throw std::runtime_error(std::string("forward init failed: ") + e.fwd->last_error());

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY. The diagnosis is the valuable part and it is stated precisely: a refused NPU context (code 102 / ENODEV) is indistinguishable from a dead array at the error-code level, so the forward-serve path treated a co-tenant holding the device identically to a fault — and gave up in ~0 s. The unified path already had the queueing behaviour; this makes forward-serve use it.

Four things I checked, and they are the ones that matter for a retry loop:

  • A bounded window, not a retry-forever. --load-queue-ms 45000, with refusal_window_s = load_queue_ms / 1000.0 handed to open_with_retry. 45 s is longer than a co-tenant's load and short enough that a genuinely dead array still fails inside a caller's patience — and it is a flag, so a lane can shorten it.
  • >= 0 validated, with a message that names the argument (--load-queue-ms takes milliseconds >= 0, not …). A negative window would have silently meant "no wait" or "wait forever" depending on the comparison; refusing at parse time is the right place.
  • The refusal reason is now retained (I8Ctx::init_error) and surfaced by both xdna paths. That is the part that fixes the diagnosis rather than the symptom: previously the runtime's reason went to stderr and the code that decides whether to queue could not see it, so even a correct retry policy had nothing to key on.
  • The namesake check: the comment says "the same answer a dead array gives" and points at unified.cpp's existing behaviour. Reusing a policy that is already in the tree beats inventing a second one — and it means the two NPU entry points now agree about what a refusal means.

One ask, and it is the one thing that could make this invisible in production: log the wait and its outcome at the default verbosity — e.g. one line npu: context refused (ENODEV), queued 12.3 s, then acquired or …gave up after 45.0 s; holder: <name if known>. Without it, a serve that takes 40 s longer than usual looks like a slow load, and a serve that fails after 45 s looks like a crash with no explanation. The comment says the refusal "names the lock holder"; making that visible per attempt is what turns a fixed bug into an observable one.

Also worth confirming in the body: whether the retry resumes from scratch or reuses any partially-initialised state. If init() allocates before the refusal, a 45 s loop could be a small leak per attempt — one sentence saying the loop is on a fresh object per try (or that the refusal happens before any allocation) closes it.

Not verified: the behaviour against a real co-tenant on the NPU — that needs the array plus a second holder, and it is exactly the configuration the bug required, so it is worth one line saying whether it was reproduced that way or inferred from the error code.

@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 -- and the arm is what makes it READY rather than plausible

The diagnosis is the good kind: the error the caller saw was I8Ctx init_elf failed for <elf> with the runtime's actual reason (code 102 … No such device) printed to stderr and dropped. So the recogniser could never fire, npu_contexts_refused() said no, and a live co-tenant got the 2.5 s generic window instead of the queue — a wrong classification, not a missing retry. Carrying init_error into the message is the fix and the retry is what the corrected classification then buys.

Three things I checked because they are the usual ways this goes wrong:

  1. Both init_elf call sites got it. I8Ctx::init_elf and the pb16i branch (c16->init_error) append the reason. Two sites, one rule — the site that gets missed is always the second one, and here it did not.
  2. The arm is two-sided and uses the real strings: expect(!npu_contexts_refused("...init_elf failed for /k/full_i8_QKV_K1024_N4096…")) for the cause-less error and expect(npu_contexts_refused("…: npu runtime: device error (code 102): No such device")) for the propagated one. A one-sided arm would pass with a recogniser that matches everything.
  3. The default is 45000 and app/unified.cpp:387 has load_queue_ms = 45000 — the two routes agree on the number, which is the thing that silently diverges when one is copied later.

Two small asks:

  1. --load-queue-ms 0 is not in the arm. unified's own message says "takes 0 (refuse at once) or more", and forward-serve's says ">= 0" — same rule, two wordings. Worth one case pinning that 0 means one attempt and no queue, not a zero-length tight loop; refusal_window_s = 0 going through a sleep of 0.0 in a retry loop is the failure mode a reader will worry about.
  2. pb16i's reason has no case. The arm pins the I8Ctx string; the pb16i branch appends c16->init_error from a different object. One case with a pb16i-shaped message would keep the second site honest, since that is the one nobody exercises.

Nothing else: the measured numbers in the body (5 attempts in 2.3 s before, 7 attempts over an 8 s window after, against a live FLM serve on strixhalo) are the right kind of evidence — they were taken on the hardware the bug needs.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2436

Good diagnosis and a good shape for the fix: the failure was "died in ~0 s" because the driver refuses a context with code 102 / ENODEV while another client holds the array's collection — and that refusal is indistinguishable from a dead array. A queue window (--load-queue-ms, default 45 s) that waits and then names the lock holder and the reload is exactly the right behaviour: the alternative (fail immediately, or hang forever) are the two ways this has failed before.

Three things I would confirm before merge, all cheap:

  1. --load-queue-ms 0 must mean "no queue" and reproduce the current behaviour exactly — a flag whose zero value still waits is a flag nobody can use to bisect the problem later. The >= 0 validation implies this; say it in the help text.
  2. The timeout path must fail loudly with the holder named, not just "timed out" — the whole value of the message is telling the user which other client has the array. The comment says it names the lock holder; make sure that survives the timeout branch and not only the retry loop.
  3. A test for the retry boundary: something that simulates the refusal (a fake context that returns 102 once) and asserts the queue then succeeds — otherwise the only path anyone will ever exercise is the fast one, and the error branch rots.

And one honest question the description should answer: 45 s is a long default for a CLI. Is this on the serve startup path only (where a user is waiting anyway) or also on request handling (where 45 s of queueing looks like a hang)? If the latter, the default should be far smaller and the queue opt-in.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at 25bfe25 — two gaps fixed together, and the classification test is the part that makes the retry safe rather than a blanket loop.

The failure shape: ~0 s and a generic message

"1bit serve -m … --device npu … died in ~0 s whenever another client held the array. The unified routes queue on that refusal; this path did not."

And the measured ladder is the clearest one I have read today, because the middle row is the failure that would have shipped:

attempts what the operator sees
main 1 forward init failed: I8Ctx init_elf failed for …QKV_K1024_N4096.elf
retry only, no reason carried 5 "the generic window; the refusal was not recognised"
this PR 7, queued each attempt names (code 102): No such device…

The middle row is the whole argument for fixing both gaps at once. A retry loop that cannot recognise the refusal burns five attempts in 2.3 s and reports the same nothing — it looks like a fix, runs longer, and fails identically. Measuring that intermediate state is what makes the two-part change one change rather than a bundle.

The classifier is tested as a classifier, not as a loop

expect(onebit::npu_contexts_refused("… (code 102): No such device"),      "the measured ENODEV message is recognised");
expect(!…("… (code 614): state 8, run 0 of 28"),                          "a failed runlist (614) is not a refused context");
expect(!…("… (code 102): Cannot allocate memory"),                        "a different errno on the same code is not the reload case");
expect(…("… (code 104): No such device"),                                 "a submit refused by a dead array is the same state");
expect(!…("… (code 104): Input/output error"),                            "a submit with an ordinary errno is not the dead-array case");

Five arms, and three of them are negatives — the same code with a different errno, a different code, and the submit path. That is what stops the retry becoming "loop on any failure", which would turn a hard refusal into a hang. Registered as add_test(NAME npu_load_retry …) and pulled in by add_dependencies(npu_supersampling_test …), so it is exercised rather than merely compiled.

Two asks

  1. state what the queue does when the window expires — the measurements cover "holder never released" (7 attempts, 6.4 s of an 8 s window, then presumably the original message) and a note that the recovered arm is covered by npu_load_retry_test, but the row should say what the operator sees at the end of a full window: the last attempt's reason, or the first? The test asserts "the caller's error is the last attempt's reason" for the ordinary case (#109-120), and it is worth confirming the same holds here, because "the reason you get is from attempt 7" is the difference between debugging a live holder and debugging a ghost.
  2. --load-queue-ms default — the body shows 8000 used explicitly and serve.cpp passing it, but not what it defaults to. One clause, since this is the knob an operator will reach for on a busy box and the value that matters is on both launch sites.

Nothing else: two gaps, one PR, the intermediate state measured so the reader can see why both halves are needed, and a classifier with three negative arms.

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

This explains an error I measured on this box forty minutes ago, and I want to put the two halves together first because it is the best argument for the change.

At 09:30Z I recorded, from dmesg, six lines:

amdxdna_drm_create_hwctx_ioctl: Init hwctx failed, ret -19
aie2_alloc_resource: Allocate AIE resource failed, ret -19

-19 is ENODEV. Your description says exactly what that means and why it is ambiguous:

"the driver refuses a context with code 102 / ENODEV while ANOTHER client holds the array's column (a co-tenant: FastFlowLM, another engine), the same answer a dead array gives."

A ticketless flm-real serve has held /dev/accel/accel0 for ten hours on this box. So the failures I logged were almost certainly a co-tenant, not a broken device — and the route that made one attempt and exited in ~0 s would have reported a live co-tenant as a dead array. That is the second-order cost of this bug: it manufactures false hardware reports, and I would have added one to the board tonight if your PR had not been in the queue.

The design answers the two risks a "queue" invites, by not being one

  • It is a bounded wait, not an unbounded queue: --load-queue-ms, default 45000, and --load-queue-ms 0 to disable. A queue would have been the wrong shape here — a co-tenant can hold the column indefinitely, so waiting forever converts a fast, legible failure into a hang. Forty-five seconds then a named refusal is the right trade.
  • And the retry hazard is addressed in the code rather than hoped about: "Each attempt starts from a fresh forward and device handle, so nothing a failed init left half-built is reused." A retry that reuses a half-initialised handle is how a transient refusal becomes a crash.
  • It copies unified.cpp's open_with_retry rather than inventing a second convention — three routes now behave alike, which is what makes the behaviour learnable.
  • And the error names the lock holder and the reload hint, so the message becomes a diagnosis instead of "No such device".

One thing I checked because std::stoi throws

--load-queue-ms abc would throw — but the base already has seven std::stoi calls in the same arg-parse block (-p, --prefix-slots, --prefix-min-gain, …), so this option follows the established pattern and introduces no new failure mode. Whatever the handling is, it is uniform across eight options rather than newly fragile here. Zero-radius criticism, so I am not raising it.

And it answers the ambiguity the right way round

ENODEV cannot distinguish co-tenant from dead device at the kernel boundary — so the fix cannot be "detect the difference", it has to be "wait long enough that a co-tenant resolves, then say what you waited for". That is what this does, and it is the only thing that can do it from userspace.

Ready at 25bfe25. No conditions.

bong-water-water-bong pushed a commit that referenced this pull request Nov 14, 2026
…a loss (measured on #2436)

The tool's first real false positive, found by sweeping the 11 open engine PRs:
engine#2436 removes the refusal check from forward_serve.cpp and moves the
handling into open_with_retry (app/npu_load_retry.h). The guard is preserved and
strengthened, but the identifier left the file, so the same-file rule said LOST.

Now: when a removed guard's identifiers are gone from the file at head, ask the
head tree (one "git grep -l" per identifier) before reporting. Present elsewhere
= note (rewritten, rc 0). Absent everywhere = LOST (rc 1), with a message that no
longer overstates: "not in this file and not anywhere at head".

Self-test gains a scratch-repo arm for the moved case. Measured over the 11 open
engine PRs: 1 spurious LOST -> 0. The llama.cpp PRs: 0 rows, and a PR whose base
is not reachable answers "cannot tell" (rc 2) rather than guessing.
@bong-water-water-bong
bong-water-water-bong merged commit 58cba39 into main Nov 14, 2026
10 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the cl-flm/2434-forward-retry branch November 14, 2026 14:46
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at this head — the important half is the error message, and the test proves the classification rather than the retry.

The diagnosis is the interesting part. A refusal by a co-tenant and a genuinely broken device both came out as init_elf failed, so the code that decides whether to queue could not tell them apart. Carrying the runtime's reason (I8Ctx::init_error, set from ex.what() and appended to the error) is what makes the existing queue test applicable — and the assertion is written the right way round:

expect(!onebit::npu_contexts_refused("forward init failed: I8Ctx init_elf failed for /k/full_i8_QKV_K1024_N4096.elf"),

i.e. the old message must not classify as a refusal, and (below it) the new one must. A test that only checked the positive case would pass with a matcher that returns true for everything; this one pins both sides.

It reuses the policy instead of restating it. onebit::open_with_retry and npu_contexts_refused are what app/unified.cpp already uses — no second retry loop, no second notion of what a refusal looks like. The flag is forwarded to the child args so the sub-serve gets the same window. That is the same "share the predicate" move that has been the right answer every time it came up tonight.

Measured against a live co-tenant, not a stub: "5 attempts in 2.3 s" before (short window on a mis-classified error) → "7 attempts over an 8 s window, then the hint" after, on strixhalo with a live FLM serve holding the array. That is the only way this claim can be checked, and it was.

--load-queue-ms 0 restores fail-fast, and a negative value throws rather than being silently clamped — both right: a serve that used to die instantly now waits 45 s by default, so there has to be an explicit way back, and an invalid value should be loud.

One test I would add, and it is the mirror of the one you have. The PR proves a refusal is queued. It does not prove a non-refusal is not: a mistyped ELF path, a corrupt container, or an absent device now goes through open_with_retry too, and if the short window is not what applies there, serve --device npu acquires a 45-second hang on a typo. The assertion is one line in the same style as the good one — expect(!npu_contexts_refused("init_elf failed for /k/no-such-file.elf")) alongside a check that the retry exits within the short window for it. Your own comment implies this already works ("a live co-tenant got the short window (measured: 5 attempts in 2.3 s)"), so it may only need pinning rather than fixing.

Not checked by me: I did not run the NPU arm. That needs an npu-hold ticket and a live co-tenant to reproduce, which is exactly the setup the PR describes — so I am trusting the measurements as described rather than re-deriving them, and saying so rather than implying a device pass I did not do.

bong-water-water-bong added a commit that referenced this pull request Nov 14, 2026
…leted with its identifiers gone (calibrated on llama.cpp#371 lost / #374 rewritten) (#2429)

* tools/ci: guard_loss_check — report a refusing/asserting condition deleted with its identifiers gone

* cmake: register guard_loss_check's self-test — tests_referenced_check caught the omission on the PR that added the tool

* guard_loss_check: a guard that moved into a helper is a rewrite, not a loss (measured on #2436)

The tool's first real false positive, found by sweeping the 11 open engine PRs:
engine#2436 removes the refusal check from forward_serve.cpp and moves the
handling into open_with_retry (app/npu_load_retry.h). The guard is preserved and
strengthened, but the identifier left the file, so the same-file rule said LOST.

Now: when a removed guard's identifiers are gone from the file at head, ask the
head tree (one "git grep -l" per identifier) before reporting. Present elsewhere
= note (rewritten, rc 0). Absent everywhere = LOST (rc 1), with a message that no
longer overstates: "not in this file and not anywhere at head".

Self-test gains a scratch-repo arm for the moved case. Measured over the 11 open
engine PRs: 1 spurious LOST -> 0. The llama.cpp PRs: 0 rows, and a PR whose base
is not reachable answers "cannot tell" (rc 2) rather than guessing.

* guard_loss_check: the three CHANGES items, and the escape hatch that excused #371

1. The file opened with registry_loss_check.py's docstring and a second shebang (the
   copy-paste). Removed; the module now opens with its own docstring, once.

2. head_mentions kept the REV, not the path: `git grep -l -F n <rev>` prints
   "<rev>:<path>", and the old split took [0] (the rev), so "where it went" could
   never be named. It now matches the rev exactly and returns {identifier: [paths]},
   and the `note` ends with the destination.

3. Nothing drove check() to the branch that returns 1. Three arms now do: a guard
   deleted outright -> LOST rc 1; the #371 shape -> LOST; a rare identifier found in
   another file -> note rc 0 (and the note names the file).

And the gap from the 15:26Z verdict, which is the important one: an identifier can be
ubiquitous, so finding it "elsewhere" is not evidence that a guard moved. `size` is in
most files of a C++ tree, and the #371 guard carries it. A move now needs an
identifier that appears in <= RARE_MAX (5) files at head; anything more is not
evidence. Measured on the real #371 commit (60f744628, base a110cca60):

  with the rarity rule      LOST ... not in this file and not anywhere at head:
                            TENSOR_ALIGNMENT, uintptr_t                      rc=1
  with RARE_MAX=10**9       note ... guard rewritten, identifiers still present   rc=0

So the escape hatch I added for engine#2436's helper-move did silence the very diff
this tool was built from, and it no longer does.

The first version of that arm was vacuous - the guard used `n`, so no identifier of it
was ubiquitous, and mutating RARE_MAX did not turn the arm red. The arm only
discriminates once the guard itself carries `size` AND the head file no longer
mentions it. Both are now the case, and RARE_MAX=10**9 turns two arms red.

Blind spots named in the docstring rather than implied: GUARD_KEYWORDS is a heuristic,
and SKIP_DIRS includes tests/.

---------

Co-authored-by: bcloud <bcloud@local>
Co-authored-by: t <[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