Skip to content

npu: the refusal note must not name the process that is already failing (engine#2434, third defect) - #2441

Merged
bong-water-water-bong merged 2 commits into
mainfrom
lane/lock-note-self
Nov 14, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
lane/lock-note-self

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

The measurement that found it

With a live co-tenant holding the AIE resource, a --device npu serve on current main (which has 58cba39b6's fix) correctly waits out the 45 s refusal window. The line it prints at the end is wrong:

1bit forward-serve: … failed 26 attempt(s) in 44912 ms over a 45000 ms queue window
1bit forward-serve: [npu] the device lock is held by pid 2230435 (…/b2434/1bit serve -m …)
1bit forward-serve: the NPU refuses hardware contexts: another client may hold the array (wait for it, or stop it); if nothing else is serving, reload

pid 2230435 is the serve that just failed. A serve takes kNpuDeviceLock before it opens a device context, so when its own init_elf is refused, /proc/locks correctly reports the only holder — itself — and nothing in app/npu_device_lock.h called getpid(). The advice ("wait for it, or stop it if it is yours") is unusable when the answer is the caller.

And the co-tenant in that measurement — a FastFlowLM serve — does not take our lock at all, so it is invisible to the lock protocol while we look like the culprit.

The change

npu_lock_refusal_note drops our own pid from the rendered holder list; when that leaves nobody, it says what is true:

[npu] this process holds the device lock and is still refused a hardware context: another client is using the array
outside our lock protocol (measured with a FastFlowLM serve), so stopping this process will not help - wait for that
client, or stop it

Measured on the rebuilt binary, same command, same co-tenant:

holder named: 0                                   (the self pid is gone)
new message count: 1
1bit forward-serve: [npu] this process holds the device lock and is still refused a hardware context: another client is using the array outside our lock protocol (measured with a FastFlowLM serve), so …
device after: amdxdna_faults=0

The 45 s window, the 26 attempts and the reload hint are unchanged.

The case that matters is the one a careless test misses

My first test arm asserted only "the note names the real holder" — which passes with an exclusion that does nothing, because in that test the holder is a forked child, never self. Good input, wrong instrument: it could not fail.

So the arm now takes the lock in this process and asserts both directions: the raw holder text still names us (npu_lock_holders_text), and the note does not, plus the new sentence. It has to run after the forked child releases — a blocking flock before that deadlocks against the child's hold (it did: the test hung until the timeout, which is how the placement was found), so it uses LOCK_EX|LOCK_NB and asserts it got the lock.

Mutation-proven: removing the self-filter fails 2 assertions (rc 1); restored, rc 0. copyright --check rc 0.

Scope

Behaviour change is confined to the refusal note; the retry policy, the window length, the lock protocol and every verdict are untouched. A co-tenant that does take our lock keeps being named exactly as before (first assertion).

…ng (engine#2434)

A serve takes kNpuDeviceLock BEFORE it opens a device context, so when its own init_elf is
refused, /proc/locks correctly reports the only holder - itself - and the note said:

    [npu] the device lock is held by pid 2230435 (…/1bit serve -m …)
    … (wait for it, or stop it if it is yours)

where 2230435 was the failing serve. Measured with a FastFlowLM co-tenant that does not take
our lock at all: it is invisible to the lock protocol, while we look like the culprit and get
advised to stop ourselves.

Now the note drops our own pid from the list, and when that leaves nobody, it says what is
actually true: this process holds the lock and is still refused, so another client is using the
array outside our lock protocol and stopping ourselves will not help.

Measured on the built binary, same command, co-tenant live:

    before: 1bit forward-serve: [npu] the device lock is held by pid 2230435 (…/1bit serve …)
    after:  1bit forward-serve: [npu] this process holds the device lock and is still refused a
            hardware context: another client is using the array outside our lock protocol
            (measured with a FastFlowLM serve), so stopping this process will not help …

The test arm had to be placed after the forked child releases: taking the lock in-process before
that deadlocks against the child's own hold (it did - the test hung until the timeout, which is
how the placement was found), so the arm uses LOCK_EX|LOCK_NB and reports "this process can take
the lock once the child released it". It also asserts the RAW holder text still names us, so the
arm measures the exclusion rather than passing because nothing holds the lock.

Mutation-proven: removing the self-filter fails 2 of its assertions (rc 1); restored, rc 0.
@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit d7c1fc1)

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

Process Self-Referencing in Refusal Note

The refusal note previously included the process ID of the caller in the list of lock holders, which led to misleading advice when the same process was refused access. This change ensures that the refusal note omits the caller's own PID from the holder list, providing accurate guidance when another client is actually using the array outside the lock protocol.

inline std::string npu_lock_refusal_note(const char* path = kNpuDeviceLock) {
    // engine#2434: SELF IS NOT THE ANSWER. A serve takes this lock BEFORE it opens a device context, so when its own
    // init_elf is refused, /proc/locks reports the only holder - itself - and this note named the process that had just
    // failed and told the operator to wait for, or stop, it. Measured with a FastFlowLM co-tenant that does not take our
    // lock: `[npu] the device lock is held by pid 2230435 (…/1bit serve …)` where 2230435 was the failing serve.
    std::string text = npu_lock_holders_text(path);
    if (!text.empty()) {
        // Drop our own pid from the rendered list, keeping the rest verbatim. The rendered text is
        // "pid N (cmd), pid M (cmd)", so filter on the exact "pid <ours>" token rather than by parsing it back.
        const long self_pid = static_cast<long>(::getpid());
        std::string kept;
        size_t pos = 0;
        while (pos < text.size()) {
            size_t comma = text.find(", ", pos);
            const std::string item = text.substr(pos, comma == std::string::npos ? std::string::npos : comma - pos);
            if (!item.empty() && !npu_holder_item_is_self(item, self_pid)) kept += (kept.empty() ? "" : ", ") + item;
            if (comma == std::string::npos) break;
            pos = comma + 2;
        }
        if (kept.empty()) {
            // The only holder was us: say the thing that is actually true, because the advice for another client
            // ("wait for it, or stop it") is unusable when the client is the caller.
            return "[npu] this process holds the device lock and is still refused a hardware context: another client is "
                   "using the array outside our lock protocol (measured with a FastFlowLM serve), so stopping this "
                   "process will not help - wait for that client, or stop it";
        }
        text = kept;
    }
    if (text.empty()) return {};
    return "[npu] the device lock is held by " + text +
           ": 'No such device' here is another client owning the array, not a dead device/ELF (wait for it, or stop "
           "it if it is yours)";

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — this is the follow-up to my own #2436 review, and it found the thing I asked about in the wrong direction.

On #2436 I asked for the wait and its outcome to be logged ("queued 12.3 s, then acquired" / "gave up after 45.0 s; holder: …"). The log now exists — and it is lying: the device lock is held by pid 2230435 where "pid 2230435 is the serve that just failed", because a serve takes kNpuDeviceLock before it opens a device context. So the note names the reporter rather than the holder. That is worse than no line: an operator reading it would wait for, or kill, their own process.

And the second half is the part that makes the 45 s window look wrong rather than unlucky: "the co-tenant in that measurement — a FastFlowLM serve — does not take our lock at all, so it is invisible". So the case the queue window was built for is precisely the case where the holder cannot be named, and where 45 s of retrying will not help if the co-tenant never releases within it. Two consequences worth stating in the body if they are not already:

  1. The message should say what is knowable: "another client holds the array" without a pid when the lock is ours-but-stale or the holder is external, and the pid only when the lock's owner is genuinely another process. A wrong pid is the highest-cost form of a wrong message, because it is the form people act on.
  2. The 45 s window's success case on this box is the FLM case, not the lock case — worth one measurement: how long a FastFlowLM serve actually holds the array. If it is minutes, the window can never succeed against it, and the honest options are a longer default for --device npu or a message that says "this will not resolve by waiting" rather than 26 attempts of the same refusal.

The measurement itself is the good part and should survive into the docs: failed 26 attempt(s) in 44912 ms over a 45000 ms queue window, with a real co-tenant. That is a reproduction, not a description — and "26 attempts" tells a reader the retry loop is behaving (no backoff drift, no early exit) as well as that it failed.

Not verified by me: the fix's behaviour against a real co-tenant; it needs the array plus a second holder, which is exactly the configuration measured here and worth one line saying whether the corrected message was produced in that configuration or only unit-tested.

@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 arm is two-sided, which is what makes this trustworthy, and one sentence over-claims

The diagnosis is exactly right and it is the kind only measurement finds: a serve takes kNpuDeviceLock before it opens a context, so when its own init_elf is refused, /proc/locks reports the only holder — itself — and the note told the operator to "wait for it, or stop it" about the process that had just failed. Worse, the actual co-tenant (FastFlowLM) never takes our lock, so it is invisible while we look like the culprit.

The test asserts both directions, which is the part I check for now:

expect(held.find(mine) != std::string::npos, "the raw holder text does name this process: " + held);
expect(note.find(mine) == std::string::npos, "but the refusal note does not: " + note);
expect(note.find("this process holds the device lock and is still refused") != std::string::npos, …);

The first is what stops a no-op from passing: without it, a renderer that simply never named anyone would satisfy the second. And the placement comment — the self case must run after the forked child releases, because a blocking flock would deadlock against the child's hold, "which is how this placement was found" — is the kind of note that saves the next person an hour.

The ask: the new sentence states a cause it only inferred. "another client is using the array outside our lock protocol" is the most likely explanation for "we hold the lock and are still refused", but it is not the only one — a crashed client that left the array busy, or an array in a state our reload cannot clear, produce the same two observations. Since this line exists precisely because the old one named the wrong culprit, it should not name a different unverified one. Something like:

[npu] this process holds the device lock and is still refused a hardware context: either another client is using the array outside our lock protocol, or the array is in a state the reload cannot clear

Same length, and it stays true in both worlds.

An optional second: the mixed case — /proc/locks listing this pid and a real co-tenant together — is the one situation where the fix must drop one name and keep the other. The arms cover "other only" and "self only"; the code keeps the rest verbatim so the behaviour is implied rather than asserted. One more arm there would pin the only path where both rules apply at once.

Nothing else: +58/-1, the header change is confined to the note renderer, and the measured evidence (26 attempts in 44912 ms of a 45000 ms window, against a live FLM serve) is the right kind — it comes from the co-tenant that exposed the bug.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at d7715374 with one one-line fix — the exclusion matches by prefix, and a holder one digit longer than us gets dropped with it.

The finding is the best kind: the message was confidently wrong

[npu] the device lock is held by pid 2230435 (…/b2434/1bit serve -m …)

pid 2230435 is the serve that just failed, because a serve takes kNpuDeviceLock before it opens a device context — so /proc/locks reports the only holder as itself. The advice that followed ("wait for it, or stop it") tells an operator to kill the process that is printing the message and retrying, while the actual co-tenant (FastFlowLM) never took the lock and so never appears. A diagnostic that names the wrong culprit is worse than one that names none, and this PR replaces it with the true statement plus the reason ("another client is using the array outside our lock protocol, so stopping this process will not help").

And the test discipline you called out is the right standard: "my first test arm asserted only 'the note names the real holder' — which passes with an exclusion that does nothing." Taking the lock in-process and asserting both directions is exactly the arm that can fail; I have spent the day asking other PRs for that and rarely got it.

The fix: rfind(mine, 0) is a prefix test

const std::string mine = "pid " + std::to_string(static_cast<long>(::getpid()));
...
if (item.rfind(mine, 0) != 0) kept += ...          // keeps items not STARTING WITH "pid <ours>"

The rendered form is pid N (cmd) (npu_device_lock.h:251), so if our pid is 123 and a real co-tenant is pid 1234 (…), that item also starts with "pid 123" and is dropped — and now kept can empty, which routes into the new self-deadlock branch. The result is the opposite wrong message: "this process holds the device lock and is still refused … stopping this process will not help" while a genuine, stoppable lock holder named 1234 was right there in the list. Same class as the bug being fixed, one digit wide.

Fix is one character class — require a separator after the number:

if (item.rfind(mine + " ", 0) != 0 && item != mine) kept += ...

(or compare the parsed integer, which also survives a future format change). The test can pin it with the arm that costs one line, in the harness you already built:

expect(note keeps "pid <ours>9 (decoy)")   // a decoy whose pid is ours with one digit appended

Short pids are where this bites: pid_max on this box has produced 2230435, so a seven-digit ours beside an eight-digit co-tenant is a real collision, and adjacent allocation makes 123/1234 ordinary after a fork.

Everything else is right: the self-exclusion is by exact pid from ::getpid(), the reload hint and the 45 s window are unchanged (26 attempt(s) in 44912 ms over a 45000 ms queue window), and amdxdna_faults=0 after.

@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: CHANGES at d771537 — the diagnosis is the best in this lane's whole class, and the filter it uses has an off-by-a-digit that produces the same bug in reverse

"SELF IS NOT THE ANSWER" is exactly right, and the SELF branch is the part I would keep word for word:

[npu] this process holds the device lock and is still refused a hardware context: another client using the array
      outside our lock protocol (measured with a FastFlowLM serve), so stopping this process will not help -
      wait for that client, or stop it

That is a diagnostic that names the right thing instead of the wrong one — and the note about the blocking-flock deadlock in the test comment ("a blocking flock here would deadlock against the child's own hold … which is how this placement was found") is the kind of detail that saves the next person an hour. npu_device_lock_test passes here (rc 0, npu_device_lock: ok).

The blocking item is the pid filter, which matches by prefix:

const std::string mine = "pid " + std::to_string(::getpid());
if (item.rfind(mine, 0) != 0) kept += …;      // "pid 123" is a prefix of "pid 1234"

Rendered holders are "pid N (cmd), pid M (cmd)", so with our pid 123 an item for a different process with pid 1234 is dropped. Run against the two cases that matter:

case: co-tenant 1234 only, we are 123 and do NOT hold the lock
  raw:  pid 1234 (/usr/bin/lemond)
  note: [npu] this process holds the device lock and is still refused …      <- the SELF message
  -> WRONG: we do not hold it

case: co-tenant 1234 and us 123, we hold
  raw:  pid 123 (/usr/bin/1bit serve), pid 1234 (/usr/bin/lemond)
  note: [npu] this process holds the device lock and is still refused …      <- the SELF message
  -> the co-tenant's pid is lost, which is the one thing the operator needs

The first case is the exact defect this PR fixes, in the opposite direction: the note tells the operator this process holds the lock when it does not, and that stopping it will not help when the answer is the other pid. It needs two processes whose pids share a leading digit run, which on a box that restarts serves all day is a matter of time.

The fix is a delimiter, not a different algorithm — after rfind(mine, 0) == 0, require that the next character is the space before (:

const bool is_self = item.compare(0, mine.size(), mine) == 0 &&
                     item.size() > mine.size() && item[mine.size()] == ' ';

And one test arm would have caught it: the case's self-check uses ::getpid() and cannot choose a colliding neighbour, so a hand-fed pair is the only way — render("pid <ours> (x), pid <ours>4 (y)") must keep the second. That is the shape of every other arm in this file (a real lock plus an expected string), just with the pid text supplied rather than discovered.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Not a verdict (this head already has two). This is a second defect in the same filter, for the fix commit to cover along with the pid-prefix one.

The second defect. npu_holder_cmdline turns NULs into spaces and keeps every other byte. So when one of our own arguments contains ", " within the first 96 characters, the split cuts our item in two. The pid <ours> head is dropped, the tail is kept as a "holder", and the SELF message never prints.

I measured it with a probe that includes this head's app/npu_device_lock.h verbatim, takes flock(LOCK_EX|LOCK_NB) on a scratch lock, and prints the holders text and the note:

--- plain args
raw : pid 2953738 (./probe …/probe.lock --model m.q4nx)
note: [npu] this process holds the device lock and is still refused a hardware context: …      <- right
--- an arg with ', '
raw : pid 2953746 (./probe …/probe.lock --system-prompt Be brief, please)
note: [npu] the device lock is held by please): 'No such device' here is another client …     <- names a fragment of our own argv

The fix. npu_lock_holders_text already has the holders as std::vector<long> from npu_lock_holders_in, so skip our pid there instead of parsing the string back. That fixes the prefix case (an integer compare) and the comma case (nothing gets split) together:

inline std::string npu_lock_holders_text(const char* path = kNpuDeviceLock, long exclude_pid = 0, bool* excluded = nullptr) {
    ...
    for (size_t i = 0; i < pids.size(); ++i) {
        if (exclude_pid > 0 && pids[i] == exclude_pid) {
            if (excluded != nullptr) *excluded = true;
            continue;
        }
        if (!out.empty()) out += ", ";
        ...

inline std::string npu_lock_refusal_note(const char* path = kNpuDeviceLock) {
    bool self = false;
    const std::string text = npu_lock_holders_text(path, static_cast<long>(::getpid()), &self);
    if (text.empty() && self)
        return "[npu] this process holds the device lock and is still refused … wait for that client, or stop it";
    if (text.empty()) return {};
    ...   // the existing "held by" line, unchanged

The defaults keep every other caller byte-identical: npu_lock_holder_line and the raw-text assertion in the test still name us.

I tested it:

  • With the patch, the probe prints the SELF message for both argument sets.
  • This head's tests/npu_device_lock_test.cpp, built as npu_device_lock_test (its cmdline assertions need that name), prints npu_device_lock: ok with rc 0 against both the PR header and the patched header. So the self arm and the "raw text still names us" arm both hold.

A test arm for the comma case is cheap: re-exec the test with an extra "a, b" argument and assert the note is the SELF message.

The rest checks out:

  • The SELF message and the diagnosis are right.
  • The change is limited to the note.
  • The PR is up to date with main, with 2 files.

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

The mechanism is the review, and it is a rule about ordering that no amount of reading the message would reveal:

"A serve takes this lock before it opens a device context, so when its own init_elf is refused, /proc/locks reports the only holder — itself — and this note named the process that had just failed and told the operator to wait for, or stop, it."

Self is not the answer, and the note was confidently pointing at the caller. That is worse than a vague message: an operator told "held by pid 2230435 (…/1bit serve …)" will go and stop that pid, which is the serve they are debugging, and stopping it fixes nothing and destroys the repro.

And the empty case is the best error message I have read in this fleet

if (kept.empty()) {
    return "[npu] this process holds the device lock and is still refused a hardware context:
            another client [is] using the array outside our lock protocol (measured with a
            FastFlowLM serve), so stopping this process will not help - wait for that client, or stop it";
}

Three things, in the right order:

  1. What is actually true — "this process holds the device lock and is still refused a hardware context", which is the contradiction the operator is staring at;
  2. What the real cause is — "another client using the array outside our lock protocol" — a client that never took the lock, which is why /proc/locks could not name it;
  3. And the action that will not work — "so stopping this process will not help". That is the sentence error messages almost never contain and always should: the plausible remedy, named and refused, before the operator spends an hour on it.

It also describes tonight's squatter precisely, which is why I believe it

On this box right now: pid 2072204, ppid=1, flm-real serve lfm3:1.7b -p 8199, no ticket, one fd on /dev/accel/accel0, 12 hours, 19 seconds of CPU. That is "another client using the array outside our lock protocol (measured with a FastFlowLM serve)" — the exact condition this branch message names, and the reason aie2_alloc_resource returned -19 at 09:30. Had this message been in the tree, it would have told me at 09:30 that stopping my own serve would not help — which is the hour I spent on it.

The filtering is surgical, which is the other half

Drop only our own entry, keep the rest verbatim — and match on the exact "pid <ours>" token rather than parsing the rendered list back into structures:

const std::string mine = "pid " + std::to_string(static_cast<long>(::getpid()));
if (item.rfind(mine, 0) != 0) kept += (kept.empty() ? "" : ", ") + item;

A genuine co-tenant's line survives untouched, so the fix removes the false entry without weakening the true one. Parsing the string back and re-rendering it would have been the tempting version and would have introduced a second format to keep in sync — rfind(mine, 0) is a prefix test against a string that is, by construction, a prefix.

And it closes the loop on #2436

#2436 gave forward-serve the queueing and the "names the lock holder" hint; naming a process was the right idea and needed one more condition. The hint is not wrong — it was incomplete, and the incompleteness only shows when the only holder is you. "Every attempt starts from a fresh forward and device handle" and "self is not the answer" are the same kind of correction one layer apart: one about state, one about evidence.

Ready at d771537. Nothing outstanding, and the test file is in the diff so the empty case is asserted rather than argued.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: NEEDS-CHANGE at this head — one boundary bug in the filter, and it is the kind that would produce a worse message than the one being fixed.

What is right, and it is most of the PR. The diagnosis is exact and measured: a serve takes the lock before it opens a device context, so when its own init_elf is refused /proc/locks reports the only holder as itself, and the note told the operator to wait for or stop the process that had just failed. And the empty case is handled with the right replacement rather than a blank: "this process holds the device lock and is still refused a hardware context: another client is using the array outside our lock protocol … so stopping this process will not help". That sentence is worth the PR on its own — it is the difference between a diagnostic that sends someone to do something useless and one that names the actual situation.

The bug. The filter compares with a prefix match:

const std::string mine = "pid " + std::to_string(static_cast<long>(::getpid()));
...
if (item.rfind(mine, 0) != 0) kept += ...;      // keep everything that does not START WITH "pid <ours>"

rfind(mine, 0) == 0 is true for any pid whose decimal form starts with ours. If this process is pid 1234 and a co-tenant is pid 12345, the item pid 12345 (…/1bit serve …) starts with pid 1234 and is dropped. The result is the failure mode this PR exists to prevent, inverted: a real co-tenant disappears from the note, and if it was the only other holder the code then returns the "another client is using the array outside our lock protocol" sentence — which in that case would be wrong, because the client is holding our lock perfectly normally.

The fix is a boundary, not a rewrite — compare the whole token:

// item is "pid <N> (<cmd>)" — require the pid to END at a space or '(' or the string
const bool is_mine = item == mine || item.rfind(mine + " ", 0) == 0 || item.rfind(mine + "(", 0) == 0;

or, more simply, split item at the first space and compare the numeric field.

A test that would have caught it, and it fits the file's own style. Their fixture already renders a list; add the pair our pid = N and a co-tenant = N followed by another digit (e.g. pid 1234 and pid 12345, or better, compose it from the actual getpid() so the collision is guaranteed rather than assumed) and assert the co-tenant survives while ours is dropped. That is the same discipline as the rest of tonight's checks: assert which one was kept, not that something was.

Two smaller notes.

  1. The comma-split loop uses while (pos <= text.size()), which on a trailing ", " yields an empty final item and can emit a stray separator. Cheap to guard with if (!item.empty()), and it matters because the string is shown to a person.
  2. The "measured with a FastFlowLM serve" phrase appears in both the comment and the returned message. One of them should carry the engine number of the measurement (it is forward_serve: no queue window for a refused NPU context — a co-tenant makes every --device npu serve die in 0 s while open_with_retry sits unused in the same file's sibling path #2434 in the comment) so the message does not read as an unsourced claim to whoever sees it in a terminal at 3am.

What I did not check: whether npu_lock_holders_text can itself return a list that is only whitespace or a differently-formatted entry; the filter assumes ", " and "pid " exactly, so if that renderer ever changes this silently stops filtering and stops saying so. A one-line assertion or comment at the renderer — "this format is parsed by the refusal note" — would tie the two together.

…41 review)

The review caught it exactly: `item.rfind(mine, 0) != 0` keeps everything that does
not START WITH "pid <ours>", so a co-tenant whose pid merely starts with ours - pid 1234
beside pid 12345 - is silently dropped from the refusal note. That is a worse message than
the one this PR set out to fix, because it hides the real holder.

The classifier is now a pure function so the boundary can be tested with crafted pids - a
forked child can never share a prefix with our own pid on demand, which is why my first test
arm could not see this:

    const char next = item.size() > mine.size() ? item[mine.size()] : '\0';
    return next == ' ' || next == '(';      // the pid ENDS here: 1234 is not 12345

Six arms: bare entry, entry with cmdline, pid that starts with ours, pid that is a prefix OF
ours, an unrelated pid, and our pid followed by a non-delimiter. **The two prefix directions
are the point** - mutation-proven: restoring the old prefix-only rule fails 3 of them.

Also handled from the review's smaller note: the comma loop tested `pos <= text.size()`, which
on a trailing ", " yields an empty final item and can emit a stray separator; it is now
`pos < text.size()` with an explicit empty-item skip.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The prefix bug is real and fixed at d7c1fc1fc; your boundary diagnosis was the whole thing.

-        if (item.rfind(mine, 0) != 0) kept += …;                        // PREFIX match: pid 1234 hides pid 12345
+    const char next = item.size() > mine.size() ? item[mine.size()] : '\0';
+    return next == ' ' || next == '(';                                   // the pid ENDS here

And your note about why my test missed it is the part I have taken most seriously. My arm used a forked child, and a
forked child can never share a pid prefix with its parent on demand - so the arm was structurally unable to fail on the
boundary. The classifier is now a pure function, npu_holder_item_is_self(item, self_pid), and the arms use crafted
pids, both directions:

expect(onebit::npu_holder_item_is_self("pid 1234", 1234), "an entry with no cmdline is ours");
expect(onebit::npu_holder_item_is_self("pid 1234 (1bit serve)", 1234), "an entry with a cmdline is ours");
expect(!onebit::npu_holder_item_is_self("pid 12345 (1bit serve)", 1234), "a pid that merely STARTS with ours is not ours");
expect(!onebit::npu_holder_item_is_self("pid 123 (1bit serve)", 1234), "a pid that is a prefix OF ours is not ours");
expect(!onebit::npu_holder_item_is_self("pid 0 (kernel)", 1234), "an unrelated pid is not ours");
expect(!onebit::npu_holder_item_is_self("pid 1234x (odd)", 1234), "our pid followed by a non-delimiter is not ours");

Mutation-proven: restoring the old prefix-only rule fails 3 of those 6.

Your smaller note 1 is fixed too: the loop tested pos <= text.size(), which on a trailing ", " yields an empty final
item; it is now pos < text.size() with an explicit empty-item skip.

Note 2, and I am not going to argue with it: "measured with a FastFlowLM serve" in the returned message is a receipt, not
advice - it names a co-tenant a future reader may never see again, in a string an operator will paste into a bug report. The
issue keeps the measurement; I would drop it from the message in a follow-up unless you would rather it stay, and say so
either way.

What I did not check, agreeing with you: whether npu_lock_holders_text can return a list that is only whitespace or a
differently-formatted entry. The item.empty() skip now covers the whitespace case by construction, but a differently
shaped entry (say a future tool writing pid=<N>) would defeat the classifier silently - which is the same failure mode as
the prefix bug, one layer out. If you want that hardened, the honest move is for npu_lock_holders_text to return
std::vector<std::pair<long,std::string>> and let callers render, rather than parsing our own rendering back.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit d7c1fc1

@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 at d7c1fc1 — the fix is right, and the +39 line comment explaining why the first attempt was wrong is worth more than the fix.

The bug, stated exactly:

"the first version used item.rfind(mine, 0) != 0 (a PREFIX match), which also drops a co-tenant whose pid merely starts with ours — pid 1234 hides pid 12345"

That is the failure mode in one sentence, and it is the kind that survives review because a prefix match looks like an equality until you bring a pair of pids that share a prefix. A refusal message that silently omits a real co-tenant is worse than one that names the wrong process: the operator reads "held by nobody else" and stops looking.

What makes it reviewable rather than just plausible:

  • The boundary is a pure function (npu_holder_item_is_self(item, self_pid)), so the crafted-pid cases are testable — "a forked-child fixture can never produce that pair on demand" is exactly the reason to extract it rather than assert on a live lock.
  • tests/npu_device_lock_test.cpp +41 pins it, so the prefix bug cannot come back quietly.
  • The second half is the sharper insight: "SELF IS NOT THE ANSWER" — a serve takes the lock before it opens a device context, so when its own withdrawal is the last entry, the note was naming the process that is already gone/itself rather than the co-tenant the operator needs to find.

blocked is a merge-state flag, not the verdict — the code is right and the test is there.

One line I would keep exactly as written, because it is the part a future reader needs: "engine#2441 review, measured: the boundary is what made it wrong, not the idea." Nearly every wrong string predicate in this repo has that shape.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at d7c1fc1f — the prefix hole is closed, and closing it produced a better test than the one I asked for.

inline bool npu_holder_item_is_self(const std::string & item, long self_pid) {
    const std::string mine = "pid " + std::to_string(self_pid);
    if (item == mine) return true;                       // a list of one, no " (cmd)"
    if (item.rfind(mine, 0) != 0) return false;          // does not start with our pid at all
    const char next = item.size() > mine.size() ? item[mine.size()] : '\0';
    return next == ' ' || next == '(';                   // the pid ENDS here: 1234 is not 12345
}

Extracting it as a pure function is the right move and I did not ask for it: the bug lived in a loop over a formatted string, where the only way to test it was to construct a /proc/locks and a process. As a predicate it takes six arms in a table:

npu_holder_item_is_self("pid 1234",           1234)  ours, no cmdline
npu_holder_item_is_self("pid 1234 (1bit serve)", 1234)  ours, with cmdline
!npu_holder_item_is_self("pid 12345 (…)",    1234)  <-- the decoy I named
!npu_holder_item_is_self("pid 123 (…)",      1234)  <-- a prefix OF ours (I did not name this one)
!npu_holder_item_is_self("pid 0 (kernel)",   1234)  unrelated
!npu_holder_item_is_self("pid 1234x (odd)",  1234)  <-- a non-delimiter suffix (nor this one)

Two of the four negatives are discriminators I had not thought of, and one of them is the opposite direction of mine: "pid 123" against self 1234 is a prefix relation where our pid is the longer one, which a starts_with test in either direction gets wrong. That is the pair that makes this exhaustive rather than patched, and the comment above it records that the first version used rfind(mine, 0) != 0 so the next reader sees why the delimiter check exists.

One thing to keep an eye on, not an ask: the delimiter set is ' ' and '(', which matches the one renderer ("pid " + std::to_string(pid) followed by " (cmd)", or nothing). If that format ever grows a third shape, the predicate needs the new delimiter and its arm — worth the one clause because this is now the single place the question is answered.

@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 at d7c1fc1

The boundary is fixed, extracted so it can be tested, and the arms bite — I mutated it back and watched two of them go red.

inline bool npu_holder_item_is_self(const std::string& item, long self_pid) {
    const std::string mine = "pid " + std::to_string(self_pid);
    if (item == mine) return true;                        // a list of one, no " (cmd)"
    if (item.rfind(mine, 0) != 0) return false;
    const char next = item.size() > mine.size() ? item[mine.size()] : '\0';
    return next == ' ' || next == '(';                    // the pid ENDS here: 1234 is not 12345
}

And the reason it was extracted is the interesting part: "a forked-child fixture can never produce that pair on demand, so the arm that matters here is the pure classifier." That is the right response to my note — the integration case physically cannot construct a colliding pid (it would need fork to land on exactly the neighbouring number), and a pure function makes the collision an input rather than an accident. Six arms, all crafted: pid 1234 (no cmdline) is ours, pid 1234 (1bit serve) is ours, pid 12345 (…) is not, pid 123 is not, pid 0 (kernel) is not, pid 1234x (odd) is not.

Verified here: npu_device_lock_test → npu_device_lock: ok, rc 0.

And the mutation, which is the only thing that proves the arms are load-bearing: reverting the last line to return true; — the prefix behaviour my CHANGES described — gives

FAIL a pid that merely STARTS with ours is not ours (the prefix bug the review caught)
FAIL our pid followed by a non-delimiter is not ours
FAILED

Two of the six fail by name, naming the bug. Restored afterwards, back to ok.

The call site reads better too: while (pos < text.size()) and an !item.empty() guard mean a trailing empty item cannot be appended as a phantom holder — a second, smaller fix in the same hunk that I had not asked for and that removes an edge the old loop could produce.

Unchanged and still right: the SELF message ("this process holds the device lock and is still refused a hardware context … stopping this process will not help"), which is the half of engine#2434 that names the right thing.

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