Repository navigation
serve: keep driver calls away from the process exit's teardown - #747
Conversation
There was a problem hiding this comment.
Verdict: MUST_FIX: the embeddings thread retains the driver-teardown race this fix addresses.
Must fix
1. Keep a panicked side model alive through process exit
crates/gpu-gates/src/side_seat.rs:201 sends the panic error before returning and dropping the GPU model. If SIGTERM reaches the server before the HTTP thread reports that error, shutdown starts waiting. The chat loop can finish and the HTTP thread can write its 500 while the side thread is still dropping the model. crates/serve/src/worker.rs:270 waits only for the chat loop and HTTP answers, so it can return Waited::Done. crates/serve/src/api.rs:1020 then runs normal exit, racing library teardown against the side thread's device frees.
Fixing this sibling path with its existing panic test avoids another hardware-dependent heap-corruption investigation.
Replace the side thread's panic arm:
Err(p) => {
std::mem::forget(model);
let _ = answer.send(Err(EmbedError(format!(
"the embedding model panicked: {p}"
))));
return;
}At crates/gpu-gates/src/side_seat.rs:390, replace the assertion after drop(engine); keep the later idle-engine Drop assertion:
assert!(
!dropped.load(Ordering::SeqCst),
"a panicked side model is left to the process exit"
);Restoring the model's Drop must turn this assertion red.
Non-blocking
⚠ Seed the close test's pending payload: crates/gpu/src/host/node.rs:2058 starts with an empty req. Removing production line 1237, self.req.clear(), still passes its empty-payload assertion. Insert node.req.u8(1); before the first close so the test catches this mutant.
⚠ Retain a reproducible crash probe: crates/serve/src/worker.rs:450 changes teardown ownership, but the reported stop-cycle and exitshim probes are absent. Which retained tool or state record supplies the fix's debuggability layer? Include the exact model path, both tested hashes and full invocation/output so another contributor can reproduce the failure.
Checked
Duplicates: diagnostics report 0 qualifying dryer pairs in gpu and serve; gpu-gates was excluded from that scan.
Complexity: diagnostics report SeatEngine::spawn 40 → 41.
Silent failure: explicit close and stdout-flush failures print; a closed node rejects later requests.
Tests: the close test misses removal of node.rs:1237; the proposed panic-test assertion detects restoration of model Drop. The PR body reports seven failing mutants followed by passing fixes.
Gates: the unsafe-count increase has a dated PIN and reason. The stop-loop test's replaced Drop expectation also has a dated PIN and reason.
Escape catalog: no C1–C4 pattern matches these findings; no ledger lessons are in force.
Notes
Static review only; no tests executed here. The body reports no head run of just gate-serve or the two-process tier shutdown, and carries no complete card gate evidence.
Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/shared/serve_seats/ds41.rs, crates/gpu-gates/src/bin/shared/serve_seats/glm.rs, crates/gpu-gates/src/bin/shared/serve_seats/hybrid.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
| control_round_trips: 0, | ||
| lost: None, | ||
| }; | ||
| node.close().expect("the close"); |
There was a problem hiding this comment.
Seed a pending payload so removing close()'s req.clear() makes the existing empty-payload assertion fail.
| node.close().expect("the close"); | |
| node.req.u8(1); | |
| node.close().expect("the close"); |
An orderly stop called exit(0) as soon as the engine thread left its loop, while that thread was still dropping the engine: freeing device memory, destroying streams and graphs, releasing the context. exit() runs the loaded libraries' destructors, the device driver's and any injected profiler's among them, so those driver calls ran beside the teardown. Under Nsight Compute the stop of the Qwen3.8 NVFP4 server aborted with "double free or corruption (fasttop)". The engine thread now leaves the engine and the slots' saved states to the process exit on every way its loop ends (stop, engine failure, panic): it closes the channels it holds and never drops the engine. When the stop's wait runs out, the engine thread or an answer can still be inside a driver call, so the process ends with _exit after flushing stdout instead of tearing the libraries down beside it. The threads beside the engine thread that own a model follow the same rule. The embedding side seat's thread answered a pass that panicked and then dropped its model, and the decide seat's worker dropped a panicking decision's reply before its backbone. Either answer can be the last one an orderly stop waits for, so the exit could start while that Drop still freed device memory. The side seat now leaves a panicked model to the process exit, and the decide worker never drops its head and backbone: its loop ends only when its server goes away. Dropping the engine was also how a host tier told its tier nodes that the load ended (TierNode's Drop sends Close). With the engine left to the exit, the node would see its channel end with no close and report node 0 lost at every stop. The engine thread now asks the engine to close its nodes (Engine::close_nodes, through the seat's thread to GpuModel and the host tier) before it publishes the loop's end, so the stop's wait covers the close; nothing is freed.
f883e84 to
2c7a4ce
Compare
There was a problem hiding this comment.
Since the last review:
- Fixed: the panicked side model is retained before its error is sent at crates/gpu-gates/src/side_seat.rs:206.
- Fixed: the close test seeds a pending payload at crates/gpu/src/host/node.rs:2059.
- Still open: the reproducible shutdown probe, detailed below.
Verdict: CLEAN: the earlier teardown race is fixed, and no new must-fix defect survives the interdiff review.
Non-blocking
⚠ Retain a reproducible shutdown probe: crates/serve/src/worker.rs:450 changes teardown ownership, but the stop-cycle and exitshim probes remain absent from the tree. Retain the probe in existing tooling and supply the exact model path, both tested hashes, and full invocation/output. This makes a recurrence reproducible without another hardware investigation.
Checked
Duplicates: 4 new definitions checked; no duplicate warrants another owner. Dryer reports 0 qualifying pairs; gpu-gates was excluded and checked with Grep.
Complexity: SeatEngine::spawn 40 → 41 adds one close-command match arm; harmless even growth, unchanged by the interdiff.
Silent failure: 3 reply-send sites followed. Startup cancellation has no receiver; abandoned requests have no waiting caller; worker loss becomes a named engine error.
Tests: plain ownership instead of ManuallyDrop at decide.rs:653 fails its Drop assertion; removing side_seat.rs:206 fails the panic-retention assertion; removing node.rs:1237 fails the seeded payload assertion. The body reports failing mutants H–J and passing fixes.
Gates: the changed side-model Drop expectation has a dated PIN and reason; no tolerance or band moved.
Escape catalog: no C1–C4 pattern matches; no ledger lessons are in force.
Adversarial checks: panic, job-channel closure after bind failure, startup failure, and an abandoned reply leave model teardown protected or joined before the caller proceeds.
Notes
Static review only; no tests executed here. The body reports no head run of just gate-serve or the two-process tier shutdown and carries no complete card gate evidence.
Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/shared/serve_seats/decide.rs, crates/gpu-gates/src/bin/shared/serve_seats/ds41.rs, crates/gpu-gates/src/bin/shared/serve_seats/glm.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
|
The review is done and the contribution check passed, so I'm merging this. |
SIGTERM으로 서버를 멈출 때 엔진을 해제하는 호출과 프로세스 종료가 겹쳐 힙이 깨지던 결함을 고치고, 그 수정으로 빠지게 되는 tier node 종료 신호를 함께 지킵니다.
Part of #565. Tracked in #699.
What and why
bloomery-serveaborts at SIGTERM when Nsight Compute is injected, with a heap error from the C library. The stop path returns fromShared::wait_stopas soon as the engine thread publishes the end of its loop, andexit(0)runs while that thread is still dropping the engine: freeing device memory, destroying streams and graphs, releasing the context.exit()runs the loaded libraries' destructors, among them the device driver's and an injected profiler's, so driver calls ran beside the driver's teardown. A stop whose wait ran out had the same problem, becauseexit(0)could race an engine call still inside the driver. The race was introduced byb3a73bfd3, which stopped waiting for the engine's Drop, and0082b7bd1, which added the bounded wait followed byexit(0). Both were pushed to main without a PR.Two threads beside the engine thread had the same defect. The embedding side seat's thread answered a pass that panicked and then dropped its model. The decide seat's worker dropped a panicking decision's reply before its backbone, and when the server failed to bind it dropped its model while
mainreturned. Either answer can be the last one an orderly stop waits for, so the exit could start while that Drop still freed device memory.The fix has four parts.
exit_shutdowncallsexit(0)only after a wait that ended. When the wait ran out, it flushes stdout and ends with_exit(0), so no library teardown runs beside a driver call that may still be in flight.std::mem::forget, and the decide worker holds its head and backbone inManuallyDrop(answer_jobs), so it drops them on no path. A normal end of the side seat stays a joined Drop, which the embedding gate uses to free one encoder before it opens the next.TierNode's Drop sentClose. With the engine left to the process exit, a node would see its channel end without a close and report node 0 lost at every stop. The engine thread now asks the engine to close its nodes (Engine::close_nodes, forwarded bySwapEngineandSeatEngine, then through the seat's thread,GpuModel,HostServedandHostTiertoTierNode::close) before it publishes the end of the loop, so the stop's wait covers the close.TierNode::closesendsCloseonce and marks the node closed; the Drop calls it, so a second close sends nothing. The close is one control round trip per node and frees nothing. A failure is one stderr line.The tier nodes' close test also seeds a payload byte before the first close, so it fails if
close()stops clearing its request buffer.Release notes: Fixed:
bloomery-serveno longer aborts at SIGTERM when a profiler is injected, and still tells its tier nodes that the load ended.Code shape
TierNode::close, and each layer forwards it once. The seats' four three-line forwards follow the existingresidency_resetpattern. No new protocol tag;Tag::Closealready existed.Seat::close_nodeswith a forward. No model file gained a branch or flag.pubitem (Engine::close_nodes,Seat::close_nodes,HostServed::close_nodes,GpuModel::close_nodes) has a production caller in this change._exit(1)is unchanged.tools/unsafe-ratchet.txtmoves the serve count from 12 to 14 blocks for the_exitcall and the test'satexit, each with a dated PIN line.tools/spawn-allow.txtgains two thread rows for new tests. The side seat's test asserts that a panicked model is not dropped, where it used to assert that it was; that line carries aPIN(2026-10-23):comment.cargo fmt --all -- --checkis clean.cargo clippyhas not been run on this head, so the lint count is unchecked.Duplication found or removed (
path:line): none. The duplicate scan flaggedcrates/gpu/src/host/tier.rs:1722(close_node) against:1668(work_mut), andcrates/gpu/src/model.rs:1296(close_nodes) against:1269(keep_rows). They share a dispatch shape but do different work: one closes a node-side tier, the other returns local work or books kept rows.What I ran
Seven mutants, each removing the line one test protects, then the fix. The serve tests are
api::tests::stop_wait::(ten tests); the node test ishost::node::tests::a_node_gets_one_close.With the fix, on the same head:
The node test runs on loopback and needs no card. Each mutant left the tree clean afterwards.
Three more mutants cover the side seat, the decide worker and the close test's payload. They ran on the commit before its last comment and allow-list edits; the code is the same.
These are host tests and use no card; the build ran for
sm_121on a DGX Spark.Compile check of the workspace with the feature set of the upstream check recipe, on an RTX 5090 machine:
I stopped the fixed build under Nsight Compute with the Qwen3.8 NVFP4 model on a DGX Spark. The profiler was injected with
ncu --target-processes all -k regex:^never_matches_anything$, so no kernel was profiled. Each cycle loads the server, sends requests, sends SIGTERM and counts heap messages in the server's output (double free,corruption,free(),malloc(), munmap_chunk,Segmentationand the profiler'serror code (lines).n1andn2stop an idle server without and with the MTP draft,m1stops a request in the middle of a long decode, andt1stops while a very long prompt is one engine call, so the stop's wait runs out:In
m1the halted request was answered with the stop's 503. Int1the client's connection closed with no answer and the process ended through_exit; its stop-to-exit time includes the profiler's own end after its target exited.The same cycles on upstream main, from an earlier run, before this change (three stops: idle, idle with the draft, mid-decode):
I did not rerun main for this PR.
A fifth cycle,
p1, ran the server with anexit()wrapper that lists the live threads whenexitis entered:Both engine threads were asleep at that point, and the stop ended with no heap message.
Not run: a two-process stop of
bloomery-servewithtier_server.tier_serverreads GGUF only and the GGUF Qwen3.8 tier model is not on the test machines, sogate_qwen38_nodescould not run either. The tier-node side is covered by the loopback node test above, and the node's handling of Close and of a closed channel is existing code.cargo test -p bloomery-serve --libin full,just gate-serveandcargo clippywere not run on this head.GPU Evidence
The change adds no kernel, launch or memory move, and touches no decode or prefill path, so there is no PTX comparison or speed measurement. The stop-path runs used these cards:
The GB10 runs: NVIDIA GB10, 595.84; CUDA 13.3.1 in the project's container.
just gate-serve, not run on this head: the server stop cycles above ran the real server under the profiler.What I ran into
This does not block the PR.
With the engine left to the process exit, a stop whose tier node does not answer the close holds the wait for up to
DRAIN_DEADLINE + REPLY. Past the stop's wait bound the process ends through_exitand the node reports node 0 lost, which is then true.api::tests::gone_client::a_whole_answer_whose_client_closed_ends_at_the_next_eventfailed once on CI. This change does not touch the path that test runs. I ran the serve lib tests alternately on main and on this change, pinned to two cores of a 12-thread x86 machine, 15 rounds each: main failed that test in rounds 7 and 10 ("the slot still runs the request of a closed client"), this change did not fail it. The test gives the engine one permit at a time and waits only for the engine's next call, so a scheduler stall of the HTTP thread lets the engine run past the test's limit.Hardware
A DGX Spark (GB10, driver 595.84, CUDA 13.3.1) for the server stops under Nsight Compute, and an RTX 5090 machine (driver 595.99.02) for the mutant tests and the workspace compile check.
AI help
AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.