Skip to content

npu: a refused load names the client that never took the lock (engine#2689 item 2) - #2706

Merged
bong-water-water-bong merged 1 commit into
mainfrom
1bit/2689-name-holder
Nov 16, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
1bit/2689-name-holder

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs #2689 (item 2's engine half; the tracking issue stays open)

A refused NPU load says "another client" and cannot name it. Two clients are invisible to the device lock
(app/npu_device_lock.h): FastFlowLM, another build, a hand-run ELF runner — anything that does not take our
flock(2). npu_lock_refusal_note() is what open_with_retry prints when a context is refused with code 102 / No such device, and in exactly that case it returned nothing or "another client is using the array outside our
lock protocol", which names nobody. The engine#2434 note (do not name the failing process itself) had made it
careful but still blind.

The device fds are visible where the lock is not: /proc/<pid>/fd/<n> links to the node it was opened through.

What changed

app/npu_device_lock.h, header-only like the rest of the file:

  • npu_fd_target_is(target, prefix) — the link target names /dev/accel itself or something below it, never
    /dev/accelx; a target the kernel marked (deleted) still matches on the prefix, so it needs no special case.
  • npu_device_users_in(proc_root, prefix, self_pid) — one scan of a /proc-like tree for pids whose fd links point
    under the prefix, ascending, with self_pid left out (naming the process that just failed is the engine#2434 bug).
  • npu_device_users_text(prefix) — pid <n> (<cmdline>), the same rendering npu_lock_holders_text uses.
  • npu_lock_refusal_note(path, dev_prefix) — wired for the two cases the lock cannot answer: nobody holds the
    lock
    (now names the fd holders, or says nothing when there are none), and the only holder is us (the
    FastFlowLM case, now it is pid N (…); wait for it, or stop it if it is yours).

A docs/npu.md paragraph next to the engine#1241 diagnostic, with the new line's shape and its one limit (a device
opened through another name for the same node — a bind mount, /proc/<pid>/root/… — is not named, because the scan
compares the link target as a path prefix).

Proof

$ ctest -R '^(npu_device_lock|copyright_gate|ci_targets|tests_referenced|npu_decl_check)$'
100% tests passed, 0 tests failed out of 5        (npu_device_lock: 0.00 s -> 4.20 s of new arms)

New arms in tests/npu_device_lock_test.cpp (18 checks, no device, runs in CI):

  • A fake /proc: 4242 holds …/dev/accel/accel0 and an unrelated /dev/null; 4343 holds a second node whose
    path is gone; 4444 holds the directory itself; 4646 holds /dev/accelx0 (a look-alike); notanumber/fd/3 points at
    a node; 5000 has no fd directory. The scan returns {4242, 4343, 4444} and nothing else; with self_pid=4242
    it returns {4343, 4444}.
  • A live holder, real /proc: a forked child opens a file that stands in for the node (the scan reads the link
    target, so a plain file walks the same path as a device — no NPU is touched), and npu_device_users_in("/proc", …)
    names it, npu_device_users_text renders it with its cmdline, and npu_lock_refusal_note(lk, prefix) — lock file
    present, nobody holding it — prints it:
    [npu] no client holds the device lock, but pid N (npu_device_lock_test) hold(s) the NPU device open: ….
    Once the child exits, both the scan and the note are empty.
  • Empty inputs: an empty prefix, a missing proc root, and no holder → no note rather than an invented one.

Mutants, each restored afterwards:

  • npu_fd_target_is returning true always → 7 arms fail (the scan set, self exclusion, the look-alike, the empty prefix);
  • self_pid not dropped → the self-exclusion arm fails;
  • the prefix test replaced by exact equality → 8 arms fail, including the live holder and the note itself.

What this is not

It names reads of /proc, not the driver's own bookkeeping: a process that has opened and closed the node while
keeping a context alive is not named by this. Items 2's other half (half-array tokens in npu-hold, so two
4-column holders can queue together) is infrastructure, not engine code, and item 3 (N decode rows per step) is the
next engine PR on #2689.

🤖 Generated with Claude Code

…#2689 item 2)

/proc/locks only names clients that took our flock. FastFlowLM, another build or a
hand-run ELF runner do not, so a held array read as "another client" with nobody to
name. The device fds are visible where the lock is not: /proc/<pid>/fd/<n> links to the
node it was opened through, so one scan names every process holding something under
/dev/accel -- with the same "pid <n> (<cmdline>)" rendering as the lock line, and with
the failing process left out (engine#2434).

Header-only, like the rest of npu_device_lock.h: npu_fd_target_is (the prefix test),
npu_device_users_in (one scan of a /proc-like tree), npu_device_users_text (the rendered
line), wired into npu_lock_refusal_note for the two cases the lock cannot answer -- no
holder at all, and the only holder being us.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at d86b1aa

Item 2's engine half. The gap was measurable and narrow: npu_lock_refusal_note() printed nothing when no client held the flock, which is exactly the FastFlowLM/foreign-build case the note exists for. The fd scan closes it, leaves the failing process out, and says nothing at all when the device is genuinely free.

Checked rather than assumed: 18 new arms (fake /proc with a look-alike /dev/accelx0, a deleted path, a pid with no fd, a non-pid directory; plus a live forked holder under the real /proc), and three mutants that each break the arms they should — a target test that says yes to everything, self exclusion dropped, and the prefix test replaced by exact equality (8 arms fail, including the note). Header-only, no device, CI-runnable.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — and the framing is the part to protect: "two clients are invisible to the device lock". The lock answers "did a well-behaved client hold it?", and the interesting failures are exactly the clients that never took it.

Why this is worth a /proc scan rather than a better message: FastFlowLM, another build, a hand-run ELF runner — none of them take the flock(2), so when the driver refuses with code 10 … No such device the lock has no information. The device fds, however, are visible where the lock is not. That is a genuinely different evidence source, and it is the only one that can name those three cases.

Three details that show the edge cases were thought about, and each is a trap avoided:

  • npu_fd_target_is matches /dev/accel and below, never /dev/accelx — a prefix test on a path without a separator rule is the classic false positive (accel … accelx), and getting it right here means the note cannot blame an unrelated device.
  • (deleted) on the link target still matches the prefix — the kernel appends that when the node is unlinked underneath an open fd, and a scanner that compared whole strings would go silent exactly when the process is still holding the array.
  • self_pid is excluded, with the reason cited (engine#2434) — naming the process that just failed as the culprit would be worse than naming nobody.

Two things I would pin:

  1. The negative case must be distinguishable from the scan failing. "says nothing when there are none" is right in principle, but nothing and "I could not read /proc" look identical to a reader and to a test. One word (no fd holders outside the lock vs could not scan) keeps the engine#2434 discipline from collapsing at the next layer.
  2. Cost on a loaded box. One scan of /proc/*/fd at the moment of a refusal — how many entries, and is it bounded? It runs only on a failure path, so I would expect it to be fine, but a box with 3 k threads and a burst of refusals is exactly when it will be exercised, and the answer belongs in the body as one clause rather than being discovered by the PR-agent.

And the documented limit is the right kind: "a dev opened through another name for the same node — a bind mount, /proc/<pid>/root/… — is not named, because the scan compares the link target as a path prefix." Stating that in docs/npu.md is what stops someone reading a name-less refusal as "no client".

Credited: the two-case wiring (nobody holds the lock / the only holder is us) rather than one; the it is pid N (…); wait for it, or stop it if it is yours wording, which tells a lane what to do; and reusing npu_lock_holders_text's rendering so the new line and the old one are read the same way.

Not verified by me: the proof run. The prefix rule, the (deleted) case, the self_pid exclusion and the two "silent" cases are what I can check, and the first three are right.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2706

"A refused NPU load says 'another client' a[nd nothing about who]" — naming the holder is the right fix, and it is the same lesson as #2578's holder label: a message that identifies a category ("another client") instead of an entity cannot be acted on, because the reader's next step is to find the entity.

Three asks:

  1. the name must come from the lock's own record, not a guess — whoever holds npu_device_lock wrote something at acquire time; if the acquire path does not record a pid/comm/ticket, this PR should add that rather than reconstructing it from /proc. Reconstruction at refusal time answers "who might this be" rather than "who holds it", which is the failure mode accel_attribution: a fault on another device is named, not attributed to the NPU's holders #2648 measured (165 confident holders for the wrong device);
  2. say what the message shows when the holder is unknown — a lock taken by a process that has since died, or before the naming was added, has no name. That must print as unknown, not as an empty string (this family's rule since Accel sampler: nearest-sample attribution with its distance, instead of a window it cannot meet (Refs #2478) #2627/diag: a GAP row covers the stall before it, so a fault after a stall is not "stalled" (review of #2623) #2645/accel_attribution: a fault record is not an attribution -- split the headline #2662);
  3. the docs line should tell the reader what to do — "held by <pid> <comm>" invites kill; the safe action depends on the holder (a lane's ticket vs a stray process), so one sentence naming the sanctioned remedy.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at d86b1aa: READY. The mechanism is right, the fixture makes it testable, and there is one case where the note would still name nobody.

Two things this gets right that are easy to get wrong

  • Self is excluded by value, not by luck: if (!npu_parse_pid(...) || pid == self_pid) continue; with static_cast<long>(::getpid()) passed in, and an arm that says why — "self is left out: naming the process that just failed is the engine#2434 bug". That bug is one line away in any reimplementation, and it is pinned.
  • The prefix matcher has a boundary: "/dev/accel names the directory itself or something below it, never /dev/accelx" — with arms for the directory itself, a second node, and a node whose path is gone. A strstr/startswith without that boundary is the classic way to name the wrong device.

And the design choice that makes all of this verifiable: npu_device_users_in(proc_root, dev_prefix, self_pid) takes the proc root as a parameter, so the test builds a fake /proc with symlinks under a temp dir. A diagnostic that needs a real conflicting device to test is a diagnostic that is never tested.

The ask: opendir failure is currently the same as "holds nothing"

DIR* f = ::opendir(fddir.c_str());
if (f == nullptr) continue;   // a kernel thread, or a pid that went away mid-scan

The comment names two causes and there is a third, and it is the one this PR is about: EACCES on another user's /proc/<pid>/fd. The clients the body describes — FastFlowLM, another build, a hand-run ELF runner — are exactly the ones that might not be running as this user, and with hidepid=2 every fd table is unreadable.

In both of those cases the scan returns an empty vector, and the caller concludes "no other client" — a note that names nobody, for the reason that the note could not look. That is the same shape as the unmap-only capture in #2657 (no capture events) and the window in #2684: an empty result read as a negative.

The cheap version keeps the current signature honest:

  • count the fd directories that could not be opened and were not empty-pid/kernel-thread;
  • when no holder was found and that count is non-zero, say so — "no holder visible, and N process(es) could not be inspected (another user, or hidepid)" — instead of the bare "another client".

Since the fixture is already a fake proc root, the arm is cheap: one directory without +x, one with a matching fd symlink, and the assertion that the note distinguishes not found from could not look. geteuid() == 0 skips it, because root can read every fd table and the case is then unreachable — which is itself worth stating in the arm, so nobody "fixes" it later by removing the distinction.

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

A co-tenant is invisible to /proc/locks, and this names it from /proc/<pid>/fd instead — with the prefix rule that makes "who has the NPU" mean more than one node, and a shortcut: line for the one case it cannot see.

Why the lock alone was not the answer

"The lock above only sees clients that took it; a co-tenant that does not (a FastFlowLM serve, another build, a hand-run ELF runner) is invisible to /proc/locks, so its refusal note can only say 'another client'. The device fds are not invisible: /proc/<pid>/fd/<n> links to the node it was opened through, so one scan names every process holding it, whatever lock protocol it follows."

That is a refusal message becoming a diagnosis. "Another client" on a refusal is the shape that sends an operator hunting; "pid N (./bin/flm-serve) holds /dev/accel/accel0" ends the hunt. And the mechanism generalises the previous head's FLOCK-only scan to any client, which is what engine#2689 item 2 needed.

The prefix rule, and the mutant that shows it is load-bearing

if (target.size() < dev_prefix.size() || target.compare(0, dev_prefix.size(), dev_prefix) != 0) return false;
// "/dev/accel" names the directory itself or something below it, never "/dev/accelx".
return target.size() == dev_prefix.size() || target[dev_prefix.size()] == '/' || dev_prefix.back() == '/';

That third clause is the one that would be written wrong by accident: a bare starts_with would match /dev/accelx, and an exact match would miss accel1..accel15. Exact-match mutant:

FAIL the fd scan names the pids with a node below the prefix, and only those
FAIL self is left out: naming the process that just failed is the engine#2434 bug
FAIL a child of the prefix is a match

Three arms, and the second one is a bug from a different issue (#2434: the refusal naming itself), which is the right thing to have pinned here rather than rediscovered.

The shortcut: line is the honest part

// shortcut: a device opened through another name for the same node (a bind mount, /proc/<pid>/root/dev/accel/accel0) is
// not named by the prefix test; upgrade if such an alias ever shows up on the box.

A documented limit with a trigger condition, in the code — instead of either pretending the scan is complete or not shipping the scan. That is exactly the form this repo asks for, and "upgrade if such an alias ever shows up" is a condition someone can actually check.

npu_device_lock: ok.

One gap, and it is the same one as #2697

The arms drive npu_fd_target_is and the scan over a fixture /proc ("a real /proc, or a fixture holding <pid>/fd/<n> symlinks"), which is the right way to make it hermetic — but nothing exercises the message end to end: a refused load that actually prints the holder's pid and target. That is the user-visible half of the change, and expect(...) on the scan result does not reach it. A main()-level arm on a fixture with one holder, asserting the refusal text contains its pid, would close it — the same shape as the main() arms in iommu_map_side.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2689 - Partially compliant

Compliant requirements:

  • Placement in 1bit serve, behind a flag: a model whose context creation is refused because the NPU is full waits with backoff and names the holder, instead of failing the load.

Non-compliant requirements:

  • One context per shared-NPU model: build 4-column sealed models, open prefill into the decode context with add_config, and use a plan/config key that refuses any context of another width at load with a named error.
  • Same-model multi-user decode: per-row KV slots and positions in Q4nxNpuForward, so one decode launch serves up to 16 sequences.

Requires further human verification:

  • Enable: after items 1 and 2 are merged and two real models serve exactly for 1 h through 1bit serve, add options amdxdna temporal_only=0 in modprobe.d and turn the serve flag on by default.
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Performance Bottleneck

The new npu_device_users_in function scans /proc/<pid>/fd/<n> for every process on the system, which can be a performance bottleneck under high load or with many processes. This is especially concerning in a real-time inference environment where performance is critical.

inline std::vector<long> npu_device_users_in(const std::string& proc_root, const std::string& dev_prefix,
                                            long self_pid = -1) {
    std::vector<long> pids;
    if (proc_root.empty() || dev_prefix.empty()) return pids;
    DIR* d = ::opendir(proc_root.c_str());
    if (d == nullptr) return pids;
    while (const dirent* e = ::readdir(d)) {
        long pid = 0;
        if (!npu_parse_pid(e->d_name, &pid) || pid == self_pid) continue;
        const std::string fddir = proc_root + "/" + e->d_name + "/fd";
        DIR* f = ::opendir(fddir.c_str());
        if (f == nullptr) continue;   // a kernel thread, or a pid that went away mid-scan
        bool holds = false;
        while (const dirent* fe = ::readdir(f)) {
            if (fe->d_name[0] == '.') continue;
            const std::string link = fddir + "/" + fe->d_name;
            char buf[4096];
            const ssize_t n = ::readlink(link.c_str(), buf, sizeof buf - 1);
            if (n <= 0) continue;
            if (npu_fd_target_is(std::string(buf, size_t(n)), dev_prefix)) {
                holds = true;
                break;
            }
        }
        ::closedir(f);
        if (holds) pids.push_back(pid);
    }
    ::closedir(d);
    std::sort(pids.begin(), pids.end());
    return pids;
}
Incorrect Handling of Deleted File Descriptors

The code assumes that if a file descriptor's target is marked as deleted by the kernel, it still matches the prefix. While the comment indicates this is intentional, it could lead to false positives if the prefix is not sufficiently specific, potentially causing incorrect identification of processes holding the device.

inline bool npu_fd_target_is(const std::string& target, const std::string& dev_prefix) {
    if (dev_prefix.empty()) return false;
    if (target.size() < dev_prefix.size() || target.compare(0, dev_prefix.size(), dev_prefix) != 0) return false;
    // "/dev/accel" names the directory itself or something below it, never "/dev/accelx".
    return target.size() == dev_prefix.size() || target[dev_prefix.size()] == '/' || dev_prefix.back() == '/';
}

@bong-water-water-bong
bong-water-water-bong merged commit 6585862 into main Nov 16, 2026
4 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/2689-name-holder branch November 16, 2026 17:03

@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 insight is the one that makes this solvable at all: "the device fds are visible where the lock is not." Two clients can be invisible to flock(2) — FastFlowLM, another build, a hand-run ELF runner — and /proc/<pid>/fd/<n> names every one of them. Going to the fds rather than to a wider lock protocol means the answer covers clients that will never take our lock, which is the only population that matters here.

The arm set covers the three ways this can be silently wrong, and each is a case I would have had to think about after the fact:

  • npu_fd_target_is("…/accel0", …) matches, while "…x0" does not — the look-alike is the correct arm and the one a naive strncmp gets wrong;
  • an empty prefix matches nothing and names nobody (two arms), so a misconfigured prefix cannot turn into "every process on the box is using the NPU";
  • self_pid is excluded and asserted ({4343, 4444} from {4242, 4343, 4444}) — the engine#2434 rule that we must not name the process that just failed is now an arm, not a comment;
  • the live forked holder proves the /proc parse against a real fd, not only against the fake tree — the distinction that has bitten several tools today, where a fixture agreed with itself.

(deleted) matching by prefix without a special case is right, and the documented limit (a bind mount to the same node under another name) is stated rather than hidden.

One thing to add, and it is the half that cannot be tested on a fixture

The fake-/proc arms pin the parse. The live arm pins one pid on this box. What neither pins is the situation the feature exists for: a client that is not us, holding the device without the lock. That can be produced without a device window — exec 3</dev/accel/accel0 in a subshell is a real fd holder with no NPU work — and the arm would then assert that npu_lock_refusal_note names that pid even though the lock is free. If accel0 is not openable without a ticket on this box, say so in the body and I will accept the fixture-only coverage; if it is, that arm is the difference between "the scanner works" and "the refusal names the right process".

Second, smaller: the note says it is pid N (…); wait for it, or stop it if it is yours. Does the rendering mark whose it is when the cmdline is unavailable (permission, or a zombie)? A bare pid N () reads as an empty name rather than as a missing one — the same unavailable (why) discipline as elsewhere in this lane.

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