Skip to content

serve: /health follows the backend; progress watchdog for a hung backend (P3) - #394

Merged
bong-water-water-bong merged 3 commits into
mainfrom
1bit/serve-wedge-watchdog
Oct 16, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
1bit/serve-wedge-watchdog

Conversation

@bong-water-water-bong

@bong-water-water-bong bong-water-water-bong commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Goal P3 of the 2026-10-12 architecture review (gap G3): a hung GPU dispatch turns into a backend reload instead of a silent stall.

Problem: a hung dispatch stops llama-server's main loop, but its HTTP thread keeps answering /health with 200. serve's own /health was a flag set once at load. So Lemonade's BackendWatchdog never saw a wedged backend.

Scope: owner rule "What ever we are missing, lemonade provides". serve mirrors the child's health and exits on a stalled child. The restart and reload policy stays with Lemonade's BackendWatchdog, and serve has no restart logic.

Changes:

  • /health (and /v1/health): after load, serve asks each child backend's own health route (0.5 s connect, 1 s read, so it answers inside Lemonade's 2 s probe). It answers 503 with the reason when a backend has exited, does not answer, or the watchdog has fired.
  • Progress watchdog (app/serve_watchdog.h). Every forwarded chat, completion and Responses request is tracked. Progress is either a byte from the backend on that request, or the backend's main loop answering GET /slots; serve probes /slots while requests are in flight, and llama-server only answers it between decode steps. A request with no progress for --watchdog SECS triggers the watchdog. The default is 120 s; $ONEBIT_WATCHDOG_SECS changes the default, and 0 turns it off. Before a request's first byte, it gets extra time: prompt tokens / --watchdog-prompt-tps (default 50). When the watchdog fires, serve SIGKILLs the backend and exits 1, and Lemonade reloads it.
  • The kill is logged: the request, how long it waited, the limit, the bytes received, Tctl (k10temp), and the backend's last 12 stderr lines.
  • On Linux the backend's stderr now passes through serve, byte for byte, so serve can keep its tail.
  • app/sysinfo.h: Tctl, /proc/meminfo, amdgpu mem_info_gtt_*. P5 and P1 reuse it; the file is identical in those PRs.
  • Backends without /slots (ds4, onnx, mlx, --no-slots): only streamed requests are judged there, because from outside a long non-streamed answer looks the same as a hang.
  • The in-process NPU route is not covered.

Tests:

  • New tests/watchdog_serve.sh (ctest watchdog_serve, no GPU, runs in CI). tests/fake_backend.py gains a /slots route and a "fake_hang" request, which stops the stream and /slots while /health stays 200.
  • The script checks:
    • /health returns 503 while the backend is SIGSTOPped, and 200 again after SIGCONT;
    • a 5 s answer with --watchdog 2 is not killed;
    • a hung stream takes serve down in 2 s with rc 1, the reason logged, and the backend gone;
    • a long prompt gets its prompt-scaled grace;
    • --watchdog 0 disables the watchdog.
  • Local run (ryzen, g++-15): all 26 ctest tests pass, including smoke_serve, pm_route, bench_selftest and device_route.

Docs: docs/serve.md (new section "When a backend hangs", endpoint table, synopsis) and docs/lemonade.md.

Lemonade compatibility. Checked against our fork's wrapped_server.cpp at the pin 4812a683, then run with that lemond on strixhalo; the backend was tests/fake_backend.py, so no GPU was used.

  • What Lemonade's BackendWatchdog does:
    • every 5 s (LEMONADE_BACKEND_WATCHDOG_POLL_SECONDS) it checks that the process is alive;
    • only during an active request with 90 s of no activity does it probe /health, with a 2 s timeout, needing a 200, and giving up after 3 failures.
  • A wedged llama-server keeps answering /health 200, so that probe never fires. serve's exit is the signal Lemonade acts on.
  • Real run (onebit_args "--llama-server tests/fake_backend.py --watchdog 5", a fake_hang stream through Lemonade):
    • 05:31:00.169: serve's watchdog fires: POST /v1/chat/completions (streamed) on the cpu backend ... made no progress for 5 s ... killing it and exiting so Lemonade reloads it, Tctl 76.0 C.
    • 05:31:00.810: Lemonade logs BackendWatchdog llama-server backend marked unavailable: backend process exited while watchdog was active; reaped ... (exit_code=1).
    • Lemonade ends the client's stream with [DONE].
    • 05:31:02.18: the next chat request makes Lemonade log Pruning unavailable backend for model: user.wd (state=watchdog_reset), reload the model, and answer "The capital of France is Paris."
  • Follow-up commit 8550eed tightens the health probe to fit Lemonade's 2 s window, and documents this interplay in docs/serve.md.

Not merged: the release is held until #389/#390/#315 are fixed.

🤖 Generated with Claude Code

…ung one down

A hung GPU dispatch stops llama-server's main loop while its HTTP thread keeps
answering /health 200, and serve's own /health was a flag set once at load, so
Lemonade's BackendWatchdog never saw a wedged backend (ARCH-GAPS G3, goal P3).

- /health: once loaded, serve asks each backend's own health route (3 s) and
  answers 503 with the reason when one has exited, does not answer, or the
  watchdog fired.
- Progress watchdog (app/serve_watchdog.h): every forwarded chat, completion
  and Responses request is tracked; progress is a byte from the backend, or the
  backend's main loop answering GET /slots (probed while requests are in
  flight). No progress for --watchdog SECS (default 120, $ONEBIT_WATCHDOG_SECS,
  0 = off), plus prompt tokens / --watchdog-prompt-tps (default 50) before the
  first byte, kills the backend and exits 1, so Lemonade reloads it. The log
  names the request, the wait, Tctl and the backend's last stderr lines.
- The backend's stderr now passes through serve (Linux), unchanged, so serve
  keeps its tail. app/sysinfo.h reads Tctl, /proc/meminfo and amdgpu GTT.
- tests/watchdog_serve.sh (ctest watchdog_serve, no GPU): fake_backend.py
  gains /slots and a "fake_hang" request that stops its stream and its /slots
  while /health stays 200.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 19b09b7)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

389 - Partially compliant

Compliant requirements:

  • The PR introduces a progress watchdog that monitors backend activity and kills hung backends, which helps prevent the silent stall that could lead to the 512-token cap issue
  • The watchdog mechanism addresses the root cause of backend hangs that could manifest as token cap issues

Non-compliant requirements:

  • The PR does not directly address the specific 512-token ubatch cap issue mentioned in the ticket
  • The PR does not include specific fixes for the HRX memory management or batch processing limitations

Requires further human verification:

  • The actual performance and memory behavior with large ubatches needs to be verified on the hardware
  • The specific 512-token limitation needs to be confirmed as resolved by the watchdog mechanism

390 - Partially compliant

Compliant requirements:

  • The PR introduces a watchdog mechanism that can detect and kill hung backends, which helps identify when operations are not running on the intended hardware
  • The watchdog logs detailed information about backend behavior including Tctl and last stderr lines, which can help identify when operations are running on CPU

Non-compliant requirements:

  • The PR does not implement the strict mode (GGML_HRX_STRICT=1) as requested
  • The PR does not provide the detailed op listing functionality mentioned in the ticket
  • The PR does not directly address the performance gap issue with Flash-Next models

Requires further human verification:

  • The strict mode functionality needs to be implemented to fully comply with the requirements
  • The detailed op reporting functionality needs to be added to meet the requirements
  • The performance comparison with Flash-Next models needs to be verified

315 - Partially compliant

Compliant requirements:

  • The PR introduces a watchdog mechanism that can detect and kill hung backends, which helps prevent the silent stall that could contribute to memory faults
  • The watchdog mechanism provides better error reporting and logging which can help identify memory-related issues

Non-compliant requirements:

  • The PR does not directly address the specific memory fault or NaN logits issue mentioned in the ticket
  • The PR does not implement the specific fixes for the GLM varied-length fault

Requires further human verification:

  • The specific memory fault and NaN logits issues need to be verified as resolved
  • The fix for the runtime-overhead work needs to be confirmed to address the underlying issues
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Race Condition in Progress Tracking

The ProgressWatch class uses a mutex to protect access to the live_ vector, but there's a potential race condition in how entries are added and removed. When a request is tracked, it's added to live_ in begin(), but the entry is deleted in end() which is called via a custom deleter. If a request is completed and its entry is deleted while another thread is checking for stalled requests, it could lead to accessing freed memory or inconsistent state.

    std::shared_ptr<Entry> begin(int port, std::string what, size_t prompt_bytes, bool needs_probe) {
        auto e = std::shared_ptr<Entry>(new Entry, [this](Entry* p) { end(p); delete p; });
        e->port = port;
        e->what = std::move(what);
        e->grace = cfg_.prompt_tps > 0 ? double(prompt_bytes) / 4.0 / cfg_.prompt_tps : 0;  // ~4 bytes a token
        e->needs_probe = needs_probe;
        e->start = clock::now();
        e->last_ns = ns(e->start);
        std::lock_guard<std::mutex> lock(mu_);
        live_.push_back(e.get());
        return e;
    }

    // bytes arrived from the backend on this request
    static void progress(Entry& e, size_t n) {
        e.bytes += n;
        e.first = true;
        e.last_ns = ns(clock::now());
    }

    // the backend on `port` answered its liveness probe: its main loop is turning
    void alive(int port) {
        const int64_t now = ns(clock::now());
        std::lock_guard<std::mutex> lock(mu_);
        for (Entry* e : live_)
            if (e->port == port) e->last_ns = now;
    }

    // the ports with requests in flight
    std::vector<int> busy_ports() const {
        std::lock_guard<std::mutex> lock(mu_);
        std::vector<int> out;
        for (const Entry* e : live_)
            if (std::find(out.begin(), out.end(), e->port) == out.end()) out.push_back(e->port);
        return out;
    }

    struct Stall {
        int port = 0;
        std::string what;
        double idle = 0, limit = 0, age = 0;
        uint64_t bytes = 0;
    };

    // The first request past its limit, if any. probe_ok(port) says whether that backend answers a
    // liveness probe; a non-streamed request on a backend without one is not judged (a long answer
    // and a hang look the same from outside).
    template <class ProbeOk>
    std::optional<Stall> stalled(ProbeOk probe_ok, clock::time_point now = clock::now()) const {
        if (!enabled()) return std::nullopt;
        std::lock_guard<std::mutex> lock(mu_);
        for (const Entry* e : live_) {
            if (e->needs_probe && !probe_ok(e->port)) continue;
            const double idle = double(ns(now) - e->last_ns.load()) / 1e9;
            const double limit = cfg_.secs + (e->first ? 0.0 : e->grace);
            if (idle > limit)
                return Stall{e->port, e->what, idle, limit,
                             std::chrono::duration<double>(now - e->start).count(), e->bytes.load()};
        }
        return std::nullopt;
    }

private:
    static int64_t ns(clock::time_point t) {
        return std::chrono::duration_cast<std::chrono::nanoseconds>(t.time_since_epoch()).count();
    }
    void end(Entry* p) {
        std::lock_guard<std::mutex> lock(mu_);
        live_.erase(std::remove(live_.begin(), live_.end(), p), live_.end());
    }

    WatchdogConfig cfg_;
    mutable std::mutex mu_;
    std::vector<Entry*> live_;
};
Potential Memory Leak in Child Process Management

The Child class manages child processes and uses a LineTail to capture stderr output. However, there's a potential memory leak in the Linux implementation where the stderr pipe is not properly closed in all code paths, particularly in the case where the thread fails to start or encounters an error during setup.

        // The backend's stderr comes through serve (passed on unchanged), so serve keeps its last
        // lines for a watchdog report and can read what it says (docs/serve.md).
        int err[2] = {-1, -1};
        const bool tee = ::pipe2(err, O_CLOEXEC) == 0;
        const pid_t parent = ::getpid();
        pid_ = ::fork();
        if (pid_ < 0) throw std::runtime_error("cannot fork for " + argv[0] + ": " + std::strerror(errno));
        if (pid_ == 0) {
            // The kernel ends the child when `1bit serve` dies for any reason,
            // SIGKILL included, so a backend is never left running on its own.
            ::prctl(PR_SET_PDEATHSIG, SIGTERM);
            if (::getppid() != parent) ::_exit(127);  // parent already gone
            if (tee) ::dup2(err[1], 2);
            ::execvpe(args[0], args.data(), envp.data());
            ::_exit(127);
        }
        if (tee) {
            ::close(err[1]);
            // detached: a backend stuck in the kernel keeps the pipe open, and serve must still exit
            std::thread([fd = err[0], tail = tail_, on_line = std::move(on_line)] {
                char buf[4096];
                for (;;) {
                    const ssize_t n = ::read(fd, buf, sizeof buf);
                    if (n < 0 && errno == EINTR) continue;
                    if (n <= 0) break;
                    for (ssize_t done = 0; done < n;) {
                        const ssize_t w = ::write(2, buf + done, size_t(n - done));
                        if (w < 0 && errno == EINTR) continue;
                        if (w <= 0) break;
                        done += w;
                    }
                    for (const std::string& line : tail->feed(buf, size_t(n)))
                        if (on_line) on_line(line);
                }
                ::close(fd);
            }).detach();
        }
#else
        // No parent-death signal outside Linux: the SIGTERM/SIGINT handler
        // below still takes the child down with a normal stop.
        if (::posix_spawnp(&pid_, args[0], nullptr, nullptr, args.data(), envp.data()) != 0)
Incomplete Error Handling in Watchdog Thread

The watchdog thread in serve_child() has limited error handling. If the watchdog thread itself encounters an error or crashes, it's not properly handled, which could leave the system in an inconsistent state. The thread should have better error recovery mechanisms.

    watchdog_thread = std::thread([&] {
        using clock = std::chrono::steady_clock;
        const double secs = o.watchdog.secs;
        const auto every = std::chrono::duration<double>(std::clamp(secs / 4, 0.25, 5.0));
        const auto timeout = std::chrono::milliseconds(int64_t(std::clamp(secs / 2, 0.5, 10.0) * 1000));
        std::unordered_map<int, int> probe;   // port -> 1 answers /slots, -1 has none, 0 not known yet
        std::unordered_map<int, clock::time_point> last;
        while (!watchdog_quit && !g_stop) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            for (const int port : watch.busy_ports()) {
                if (probe[port] < 0 || clock::now() - last[port] < every) continue;
                last[port] = clock::now();
                httplib::Client c("127.0.0.1", port);
                c.set_connection_timeout(timeout);
                c.set_read_timeout(timeout);
                if (auto r = c.Get("/slots")) {
                    if (r->status == 200) {
                        probe[port] = 1;
                        watch.alive(port);
                    } else if (probe[port] == 0) {
                        probe[port] = -1;   // DwarfStar, ONNX, MLX, or llama-server --no-slots
                    }
                }
            }
            if (auto st = watch.stalled([&](int port) { return probe[port] >= 0; })) {
                std::lock_guard<std::mutex> lock(wedged_mu);
                stall = *st;
                char why[256];
                std::snprintf(why, sizeof why, "%s made no progress for %.0f s", st->what.c_str(), st->idle);
                wedged = why;
                return;
            }
        }
    });
}

…tchdog interplay

Lemonade's BackendWatchdog (our fork, wrapped_server.cpp) probes /health with a
2 s curl timeout and needs a 200. serve asked the backend for up to 3 s, so a
slow backend made serve's own answer arrive after Lemonade gave up. It now asks
for 1.5 s at most (0.5 s connect, 1 s read) and answers first with a 503 and the
reason. docs/serve.md says how serve's exit meets Lemonade's 5 s process poll and
reload-on-retry, which stay Lemonade's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 8550eed

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Hardware evidence for this PR's code, run as part of the #395 build (which contains it): strixhalo, HRX0, Qwen3-0.6B, pinned llama-server, under flock ~/npu.lock. Per-request cost: no measurable change. Interleaved, 150 requests per arm, serve minus direct: non-stream main +1.12 ms vs this +1.22 ms; stream +0.45 vs +0.30 ms. kat through serve against main's golden: all 9 cases have identical text and logprobs (max_dlp=0.0000). Details are in #395.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 19b09b7

@bong-water-water-bong
bong-water-water-bong merged commit 03f9b03 into main Oct 16, 2026
7 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/serve-wedge-watchdog branch October 16, 2026 09:42
bong-water-water-bong pushed a commit that referenced this pull request Oct 16, 2026
#394 (squash 03f9b03) is byte-identical, in the four conflicting files, to the
1bit/serve-wedge-watchdog tip this branch already merged (8550eed); keep this
branch's side, which builds on it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bong-water-water-bong pushed a commit that referenced this pull request Oct 16, 2026
All conflicts were additive: #398's --mem-check/--no-mem-check options, help text and
'Will it fit?' section sit next to #394's --watchdog options and the 'When a backend
hangs' / 'Metrics' sections; both sides kept.

Co-Authored-By: Claude Opus 5.5 <[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