Skip to content

serve: keep driver calls away from the process exit's teardown - #747

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:fix-serve-exit-double-free
Oct 23, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:fix-serve-exit-double-free

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

SIGTERM으로 서버를 멈출 때 엔진을 해제하는 호출과 프로세스 종료가 겹쳐 힙이 깨지던 결함을 고치고, 그 수정으로 빠지게 되는 tier node 종료 신호를 함께 지킵니다.

Part of #565. Tracked in #699.

What and why

bloomery-serve aborts at SIGTERM when Nsight Compute is injected, with a heap error from the C library. The stop path returns from Shared::wait_stop as soon as the engine thread publishes the end of its loop, and exit(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, because exit(0) could race an engine call still inside the driver. The race was introduced by b3a73bfd3, which stopped waiting for the engine's Drop, and 0082b7bd1, which added the bounded wait followed by exit(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 main returned. 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.

  1. The engine thread never drops the engine or the slots' saved states. On every way its loop ends (stop, engine failure, panic) it answers the requests it holds, closes its channels, publishes the end of the loop and leaves the rest to the process exit.
  2. exit_shutdown calls exit(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.
  3. The side seat leaves a panicked model to the process exit with std::mem::forget, and the decide worker holds its head and backbone in ManuallyDrop (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.
  4. Dropping the engine was also how a host tier told its tier nodes that the load ended: TierNode's Drop sent Close. 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 by SwapEngine and SeatEngine, then through the seat's thread, GpuModel, HostServed and HostTier to TierNode::close) before it publishes the end of the loop, so the stop's wait covers the close. TierNode::close sends Close once 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-serve no longer aborts at SIGTERM when a profiler is injected, and still tells its tier nodes that the load ended.

Code shape

  • No second copy. The close has one owner, TierNode::close, and each layer forwards it once. The seats' four three-line forwards follow the existing residency_reset pattern. No new protocol tag; Tag::Close already existed.
  • Model code holds only architecture facts. The four seats that can open a tier override the default Seat::close_nodes with a forward. No model file gained a branch or flag.
  • Dead code is gone. Every new pub item (Engine::close_nodes, Seat::close_nodes, HostServed::close_nodes, GpuModel::close_nodes) has a production caller in this change.
  • No silent failure. A close failure is printed on stderr. The second-signal _exit(1) is unchanged.
  • Comments state what is true now.
  • No relaxed gate. No band, tolerance or lint level moved. tools/unsafe-ratchet.txt moves the serve count from 12 to 14 blocks for the _exit call and the test's atexit, each with a dated PIN line. tools/spawn-allow.txt gains 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 a PIN(2026-10-23): comment.
  • cargo fmt --all -- --check is clean. cargo clippy has not been run on this head, so the lint count is unchecked.

Duplication found or removed (path:line): none. The duplicate scan flagged crates/gpu/src/host/tier.rs:1722 (close_node) against :1668 (work_mut), and crates/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 is host::node::tests::a_node_gets_one_close.

== mutant-A rc=101   (the engine thread drops its engine after the loop)
the engine thread dropped its engine after its loop ended by ["stop", "failure", "panic", "stop of turns"]
test result: FAILED. 7 passed; 3 failed; 0 ignored; 0 measured; 346 filtered out; finished in 2.01s
== mutant-B rc=101   (exit(0) on every stop)
test result: FAILED. 9 passed; 1 failed; 0 ignored; 0 measured; 346 filtered out; finished in 2.01s
== mutant-C rc=101   (the nodes are never closed)
the engine's nodes are closed once before the loop's end is published; (loop ended by, closes at its end, closes after) [("stop", 0, 0), ("failure", 0, 0), ("panic", 0, 0), ("stop of turns", 0, 0)]
== mutant-D rc=101   (the close runs after the loop's end is published)
the engine's nodes are closed once before the loop's end is published; (loop ended by, closes at its end, closes after) [("stop", 0, 1), ("failure", 0, 1), ("panic", 0, 1), ("stop of turns", 0, 1)]
== mutant-E rc=101   (SwapEngine does not pass the close on)
the engine's nodes are closed once before the loop's end is published; (loop ended by, closes at its end, closes after) [("stop", 1, 1), ("failure", 1, 1), ("panic", 1, 1), ("stop of turns", 0, 0)]
== mutant-F rc=101   (a closed node is not marked closed)
a closed node is lost
== mutant-G rc=101   (the node is sent no Close)
assertion `left == right` failed: the frames the node got
  left: []
 right: [(Close, 0)]
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 386 filtered out; finished in 0.00s

With the fix, on the same head:

== fix rc=0
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 346 filtered out; finished in 2.01s
== fix rc=0
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 386 filtered out; finished in 0.00s

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.

== side_seat mutant-H rc=101   (the panicked model is no longer forgotten)
a panicked side model is left to the process exit
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 221 filtered out; finished in 0.00s
== decide mutant-I rc=101   (the worker's model is a plain Box)
panic: the worker dropped its model
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
== node mutant-J rc=101   (the close no longer clears the request buffer)
  left: [(Close, 1)]
 right: [(Close, 0)]
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 396 filtered out; finished in 0.00s
== side_seat fix rc=0
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 221 filtered out; finished in 0.00s
== decide fix rc=0
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
== node fix rc=0
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 396 filtered out; finished in 0.00s

These are host tests and use no card; the build ran for sm_121 on a DGX Spark.

Compile check of the workspace with the feature set of the upstream check recipe, on an RTX 5090 machine:

check rc=0

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, Segmentation and the profiler's error code ( lines). n1 and n2 stop an idle server without and with the MTP draft, m1 stops a request in the middle of a long decode, and t1 stops while a very long prompt is one engine call, so the stop's wait runs out:

CYCLE n1 how=ncu draft=off when=idle rc=0 load_s=240 http=200,200,200 stop_to_exit_s=2.22 heap_lines=0
CYCLE n2 how=ncu draft=on when=idle rc=0 load_s=231 http=200,200,200 stop_to_exit_s=2.17 heap_lines=0
CYCLE m1 how=ncu draft=off when=mid rc=0 load_s=225 http=-,503,- stop_to_exit_s=2.07 heap_lines=0
CYCLE t1 how=ncu draft=off when=long rc=0 load_s=226 http=-,000,- stop_to_exit_s=8.41 heap_lines=0

In m1 the halted request was answered with the stop's 503. In t1 the 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):

CYCLE n2 how=ncu draft=off when=idle rc=6 load_s=235 http=200,200,200 stop_to_exit_s=2.52 heap_lines=2
    double free or corruption (fasttop)
CYCLE n3 how=ncu draft=on when=idle rc=6 load_s=220 http=200,200,200 stop_to_exit_s=2.55 heap_lines=2
    double free or corruption (fasttop)
CYCLE m1 how=ncu draft=off when=mid rc=6 load_s=220 http=-,200,- stop_to_exit_s=2.50 heap_lines=2
    double free or corruption (out)

I did not rerun main for this PR.

A fifth cycle, p1, ran the server with an exit() wrapper that lists the live threads when exit is entered:

CYCLE p1 how=shim draft=on when=idle rc=0 load_s=230 http=200,200,200 stop_to_exit_s=2.01 heap_lines=0
    exitshim engine-threads-at-exit=2

Both engine threads were asleep at that point, and the stop ended with no heap message.

Not run: a two-process stop of bloomery-serve with tier_server. tier_server reads GGUF only and the GGUF Qwen3.8 tier model is not on the test machines, so gate_qwen38_nodes could 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 --lib in full, just gate-serve and cargo clippy were 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:

nvidia-smi --query-gpu=name,driver_version,clocks.sm,temperature.gpu --format=csv,noheader
NVIDIA GB10, 595.84, 208 MHz, 50
nvidia-smi --query-gpu=name,driver_version --format=csv,noheader
NVIDIA GeForce RTX 5090, 595.99.02

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 _exit and the node reports node 0 lost, which is then true.

  • api::tests::gone_client::a_whole_answer_whose_client_closed_ends_at_the_next_event failed 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.

round 7 main cpus=0-1 rc=101 gone_client_failed=1 (still runs the request of a closed client) finished in 24.87s other_failed=[]
round 10 main cpus=0-1 rc=101 gone_client_failed=1 (still runs the request of a closed client) finished in 24.50s other_failed=[]

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 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve labels Oct 23, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seed a pending payload so removing close()'s req.clear() makes the existing empty-payload assertion fail.

Suggested change
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.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review:

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)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit f14661b into midagedev:main Oct 23, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant