Skip to content

npu: the device-lock wait names its holder, and ONEBIT_NPU_LOCK_WAIT_MAX bounds it (closes #1241) - #1244

Merged
bong-water-water-bong merged 2 commits into
mainfrom
1bit/npu-lock-holder-diagnostic
Nov 6, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
1bit/npu-lock-holder-diagnostic

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Closes #1241. Six files, +529/-11: app/npu_device_lock.h, app/npu_load_retry.h, app/forward_serve.cpp, tests/npu_device_lock_test.cpp, CMakeLists.txt (comment), docs/npu.md.

What the issue measured

A live orphan 1bit serve --device npu (ppid 1) held /tmp/1bit-npu-device.lock for ~32 min. Two npu-hold tickets were granted the NPU in that window and could not use it: 1bit forward-serve printed waiting for the exclusive device lock ... and then said nothing for the whole 1375 s ticket, and a retry produced 72 aie2_alloc_resource errors surfaced as npu runtime: device error (code 102): No such device — which reads as a broken device/ELF/container, not as "another process owns the array". flock(2) dies with its holder, so there is no stale lock to reap: the fix is a diagnostic, not a reaper.

What lands (the issue's cures 1-3)

  • The wait names the holder. After ~2 s of a blocking wait, the header reads /proc/locks for the FLOCK on this file's st_dev/st_ino (hex major:minor as the kernel prints it, decimal fallback) and prints one line: [npu] device lock held by pid <pid> (<truncated cmdline>) for <n> s; it repeats at most once a minute. Unreadable /proc degrades to one "cannot name the holder" line — never a lock failure.
  • The same line on the refusal path. npu_lock_refusal_note() is printed by the NPU load-retry path (code 102/104 + "No such device") and by forward_serve's init failure, so a held array is named instead of misreported as a dead device or ELF.
  • ONEBIT_NPU_LOCK_WAIT_MAX=<seconds> bounds the wait (unset/0/junk = unlimited, the behaviour since showcase: one measured heterogeneous demo (2-stream NPU, batched HRX, hybrid) at the current pin #612). On timeout it names the holder and throws, so a gate/harness can fail in seconds instead of spending a device ticket. The holder is never signalled or reaped.

The wait now polls flock(LOCK_NB) every 100 ms instead of a bare blocking flock: same file, same lock, same exclusivity — up to 100 ms extra acquisition latency on release, in exchange for being able to talk and to honour the bound.

Tests (device-free, in the existing CI target)

tests/npu_device_lock_test.cpp is extended (the target is already in ci.yml's Build list, so no workflow change): synthetic /proc/locks parse cases (FLOCK only, a blocked waiter excluded, decimal dev form), a forked child that takes the flock and is named by the parent's wait (pid + command line), ONEBIT_NPU_LOCK_WAIT_MAX=1 failing in ~1 s with the holder and the variable named, and the plain wait printing the holder after ~2 s then acquiring once the holder exits.

Local: ctest -R '^(npu_device_lock|npu_load_retry)$' → 2/2 passed (npu_device_lock 4.02 s); tools/copyright.py --check clean. Live demo with flock(1) holding a temp lock and MAX=2: [npu] device lock held by pid 2635458 (flock -x /tmp/... sleep 5) for 2 s, then a timeout naming the pid and the env var.

Not verified here

No NPU/GPU was touched (the real orphan path is simulated with flock(1)), unified.cpp/forward_serve.cpp compile only with ONEBIT_NPU=ON (syntax-checked with in-tree headers, not linked/run), and the multi-holder formatting was unit-tested rather than exercised live. The real code-102 message path still needs an NPU.

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 5bc7c5e)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1241 - Partially compliant

Compliant requirements:

  • The wait now names the holder after ~2s and repeats at most once a minute
  • The refusal path now includes a note indicating another process holds the lock
  • ONEBIT_NPU_LOCK_WAIT_MAX is implemented to bound the wait
  • The fix is purely diagnostic as intended

Non-compliant requirements:

  • None

Requires further human verification:

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

Potential race condition in holder detection

The code reads /proc/locks and then attempts to read /proc/<pid>/cmdline to get the process name. There is a potential race condition where the process identified as the holder may have already exited between the time /proc/locks is read and /proc/<pid>/cmdline is accessed, which could lead to incorrect diagnostics or failed reads.

// "pid 2689658 (1bit serve --device npu ...)" for every FLOCK holder of `path`, comma separated;
// "" when nobody holds it, the file does not exist, or /proc/locks is unreadable.
inline std::string npu_lock_holders_text(const char* path = kNpuDeviceLock) {
    struct stat st;
    if (::stat(path, &st) != 0 || !S_ISREG(st.st_mode)) return {};
    const std::string locks = npu_read_small_file("/proc/locks");
    if (locks.empty()) return {};
    const std::vector<long> pids = npu_lock_holders_in(
        locks, static_cast<unsigned>(major(st.st_dev)), static_cast<unsigned>(minor(st.st_dev)),
        static_cast<unsigned long long>(st.st_ino));
    std::string out;
    for (size_t i = 0; i < pids.size(); ++i) {
        if (i) out += ", ";
        out += "pid " + std::to_string(pids[i]);
        const std::string cmd = npu_holder_cmdline(pids[i]);
        if (!cmd.empty()) out += " (" + cmd + ")";
    }
    return out;
}
Error message clarity

The error message generated when ONEBIT_NPU_LOCK_WAIT_MAX is exceeded could be more precise in indicating that the lock is held by another process, as it currently includes a generic timeout message without clearly linking it to the lock holder.

std::string why = "[npu] device lock wait ended after " + std::to_string(static_cast<long>(waited)) +
                  " s (ONEBIT_NPU_LOCK_WAIT_MAX=" + (raw ? raw : "") + ")";
if (!text.empty()) why += ": the lock is held by " + text;
why += "; unset or raise ONEBIT_NPU_LOCK_WAIT_MAX to keep waiting (the holder is another process, "
       "do not kill it unless it is yours)";
::close(fd);
throw std::runtime_error(why);
Lock holder naming logic

The logic for parsing /proc/locks to identify the holder of an flock on a specific device and inode is complex and could be prone to errors if the kernel's /proc/locks format changes. The code attempts to handle both hexadecimal and decimal device formats, but this adds complexity and potential for misinterpretation.

// Whether one /proc/locks line is the FLOCK on (dev_major, dev_minor, inode), and if so the pid
// holding it. The format (fs/locks.c) is:
//   <id>: FLOCK  ADVISORY  WRITE <pid> <major>:<minor>:<inode> <start> <end>
// The kernel prints major/minor in hex; kernels before that printed them decimal, so both readings
// are accepted. The inode is decimal. A blocked waiter's line is "<id>: -> FLOCK ..." -- it is
// waiting for the holder, not holding, so it is not a holder.
inline bool npu_proc_lock_holder(const std::string& line, unsigned dev_major, unsigned dev_minor,
                                 unsigned long long inode, long* pid) {
    if (pid == nullptr) return false;
    const std::vector<std::string> tok = npu_split_spaces(line);
    size_t t = 1;  // tok[0] is "<id>:"
    if (t < tok.size() && tok[t] == "->") return false;
    if (t >= tok.size() || tok[t] != "FLOCK") return false;
    // The "<major>:<minor>:<inode>" token has exactly two colons; the pid is the token before it.
    for (size_t d = t + 1; d < tok.size(); ++d) {
        if (std::count(tok[d].begin(), tok[d].end(), ':') != 2) continue;
        long holder = 0;
        if (!npu_parse_pid(tok[d - 1], &holder)) continue;
        const size_t c1 = tok[d].find(':');
        const size_t c2 = tok[d].find(':', c1 + 1);
        const std::string maj_s = tok[d].substr(0, c1);
        const std::string min_s = tok[d].substr(c1 + 1, c2 - c1 - 1);
        const std::string ino_s = tok[d].substr(c2 + 1);
        unsigned long long ino = 0;
        if (!npu_parse_uint(ino_s, 10, &ino) || ino != inode) continue;
        unsigned long long maj = 0, min = 0;
        bool match = npu_parse_uint(maj_s, 16, &maj) && npu_parse_uint(min_s, 16, &min) &&
                     maj == dev_major && min == dev_minor;
        if (!match)  // a kernel that printed the device in decimal
            match = npu_parse_uint(maj_s, 10, &maj) && npu_parse_uint(min_s, 10, &min) &&
                    maj == dev_major && min == dev_minor;
        if (!match) continue;
        *pid = holder;
        return true;
    }
    return false;
}
✅ Resolved findings

app/npu_device_lock.h:227-245

Potential for race condition in holder detection

The code reads /proc/locks and then attempts to read /proc/<pid>/cmdline to get the process name. There is a potential race condition where the process identified as the holder may have already exited between the time /proc/locks is read and /proc/<pid>/cmdline is accessed.

app/npu_load_retry.h:318-324

Error message clarity

The error message generated when ONEBIT_NPU_LOCK_WAIT_MAX is exceeded could be more precise in indicating that the lock is held by another process, as it currently includes a generic timeout message without clearly linking it to the lock holder.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 5bc7c5e

@bong-water-water-bong
bong-water-water-bong merged commit 84122fb into main Nov 6, 2026
9 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/npu-lock-holder-diagnostic branch November 6, 2026 05:55
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.

npu: a live orphan serve holds the device lock indefinitely, and the wait says nothing — name the holder

1 participant