Skip to content

serve: bound response and decoder waits and preserve half-closed clients - #742

Merged
juliankang4 merged 4 commits into
midagedev:mainfrom
juliankang4:fix-serve-client-lifecycle
Oct 23, 2026
Merged

juliankang4 merged 4 commits into
midagedev:mainfrom
juliankang4:fix-serve-client-lifecycle

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

serve가 닫힌 연결, 멈춘 연결, 멈춘 영상 디코더 때문에 요청 슬롯을 잡고 있던 다섯 가지 경우를 고치고, 쓰기 방향만 닫은 정상 클라이언트의 응답은 그대로 돌려주도록 했습니다.

Part of #565. Tracked in #699.

What and why

Five defects in bloomery-serve let a request or a connection hold a slot, a connection permit or a decoder process longer than it should, and one of them dropped a valid response. This PR fixes all five in crates/serve. It does not touch generation math, token choice, samplers, GPU paths or public API signatures.

  1. A client that half-closes loses its answer. A client that sends its request and then shuts down only its write side is a normal HTTP client, but the non-stream path read the resulting EOF as "client gone" and cancelled the request. The EOF is no longer treated as a cancellation. The socket's transport error is read once and remembered in the request's shared state, so only a real reset or transport failure cancels. The check does not change the socket's blocking mode and does not read bytes that belong to the next request.
  2. A request whose connection reset while queued still reached prefill. The HTTP wait now checks the transport every tenth of a second. A cancelled request leaves the waiting queue at once and returns its serving ticket, so the next request can queue before the engine call in progress finishes. The worker checks an admitted request before it starts and before each turn change of a sequential engine, and a Started message with no receiver left returns the slot before prefill.
  3. A stalled response reader kept its connection permit. Response writes had no timeout. The shared keep_alive entry point now sets a ten second no-progress limit on every response write, so plain responses, SSE, auth errors, 100 Continue and the generative, decide and embed servers inherit it. If the socket option cannot be set, the connection is closed.
  4. Refusing an over-limit connection delayed healthy ones. The refusal write and the input drain ran on the accept thread. They now run on one refusal thread per listener, which handles one over-limit connection at a time. An over-limit connection that arrives while that thread is busy is closed at once, so the accept thread never waits.
  5. A decoder stalled inside a partial video frame held the request forever. frames_from still reads the frames, but it now hands each one over a zero-capacity channel, and the request thread waits at most the existing 60 second read limit per frame. When a frame stalls, or the callback stops or panics, the existing wait_within owner kills and reaps the decoder and joins the reader. The callback runs on the request thread, and the only extra frame held is the one being read.

Limit of what a socket can show

A graceful close from the client with no response written yet looks the same on the wire as a half-close, so a bare FIN cannot be told from a client that still wants its answer. Those connections end when the next response write errors or when the request completes. A reset or transport error cancels before prefill. Probing the peer with extra bytes would change the response contract, so I did not do that.

Code shape

  • No second copy. The new Client state, the response write limit, admit and refuse, Board::cancel and the reset fixture are the only owners for their jobs. probe_client, keep_alive, frames_from, wait_within and Gated are reused, and the streaming callers in api.rs, anthropic.rs, oaicompl.rs and responses.rs all take the new argument.
  • Model code holds only architecture facts. Nothing under a model's files changed.
  • Dead code is gone. The EOF-based cancellation is removed, not kept beside the new check.
  • No silent failure. A failure to set the write limit closes the connection, and a frame read error reaches the caller as a named error, not a short read.
  • Comments state what is true now.
  • No relaxed gate. One existing assertion changed with its contract: it expected EOF to cancel a request. The serve block count in tools/unsafe-ratchet.txt goes from 11 to 12 under a dated PIN comment, for one SO_LINGER call in test code that makes a peer reset without timing assumptions.
  • cargo fmt ran clean. I did not run cargo clippy for this head.

Duplication found or removed (path:line): none.

What I ran

On this head, the targeted tests:

cargo test -p bloomery-serve --lib lifecycle_ -- --nocapture
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 353 filtered out; finished in 1.20s
cargo test -p bloomery-serve --lib sched::tests::a_request_past_the_depth_is_refused -- --nocapture
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 360 filtered out; finished in 0.00s

The reset test fails without the fix, with only the test in place. It failed with the reset connection still occupies the queue (left: 1, right: 0), because the reset request stayed in the waiting queue. Two mutants on this head fail where they should: without the ticket return in Board::cancel, the depth test fails with cancellation passed the waiting request's ticket: Busy, and with a 600 second response write limit, lifecycle_stalled_writers_release_their_connection fails with response writes must time out after ten seconds.

cargo fmt --all
git diff --check upstream/main...HEAD

Both exit 0.

Not run: the whole bloomery-serve suite on this head, gate-serve-video against a real ffmpeg (the stalled-frame deadline, the kill and reap, the normal frame loop and the callback stop and panic cases run against a fake decoder process and the existing unit gate), cargo clippy, and any GPU gate. None of the changes is on a GPU path.

Hardware

CPU only. The reset test's failing run was on an x86-64 Linux machine. This head's targeted tests and mutants ran on an Apple silicon Mac.

What I ran into

This does not block the PR. run_gen still sends events through an unbounded channel, so a slow reader can let already generated events pile up during the ten second write limit. I did not measure the memory this costs, and this PR does not claim a gain there.

Release notes: Fixed: serve no longer cancels a request from a client that only half-closed, and a reset connection, a stalled response reader, an over-limit refusal and a stalled video decoder no longer hold their slot, permit or process.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@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: cancelled requests retain queue capacity and cause false overload responses.

Must fix

1. Remove cancelled requests from the waiting queue (kind A)

crates/serve/src/api.rs:3205 returns without removing Submit from Board::waiting. While an engine call blocks, queue and reset requests until the configured depth is reached. A healthy request then receives 503 from crates/serve/src/sched.rs:237, even after every cancelled HTTP thread has exited. The default depth is 63 with one slot [derived]. Cleanup in Worker::start runs only after that engine call returns.

Fixing reclamation at cancellation now avoids client retry workarounds for false overloads. Add this method to impl<R, A> Board<R, A> in sched.rs; retire the removed request's ticket as admission does:

pub(crate) fn cancel(&mut self, matches: impl Fn(&R) -> bool) -> bool {
    let Some(at) = self.waiting.iter().position(|w| matches(&w.payload)) else {
        return false;
    };
    self.waiting.remove(at).expect("the matched waiter is still queued");
    self.tickets.pass(self.tickets.serving());
    true
}

Replace the cancellation branch in run_gen with:

if (slot.is_none() || !p.stream)
    && let Err(e) = client.check()
{
    let cancelled = relock(&state.shared.board)
        .cancel(|sub| Arc::ptr_eq(&sub.client, &client));
    if cancelled {
        relock(&state.shared.stats).n_cancelled_before_prompt_total += 1;
    }
    return Ok((Err(GenError::Client(e)), at));
}

Extend lifecycle_reset_while_queued_never_prefills with queue depth 1. Submit the next live request after the reset connection exits and before releasing the first engine call. Assert it queues successfully. The current test releases the engine before submitting that request and misses the retained capacity.

Non-blocking

⚠ Pin the write deadline: crates/serve/src/api.rs:6698 accepts any timeout, then replaces it with 100 ms. Changing RESPONSE_WRITE to 600 seconds still passes. Pinning the value here prevents that relaxation. Replace the condition with:

w.write_timeout()? == Some(Duration::from_secs(10)),

Checked

Duplicates: dryer reported zero pairs. The cancellation fix uses the existing board and ticket mechanism.
Complexity: read_frames +12 adds reader lifetime/error handling; run_gen +7 adds polling branches; decode +2 adds error arms. Diagnostics flag six other functions at +1.
Silent failure: transport errors are remembered; failed starts release slots; frame-read errors propagate.
Tests (static): the queued-reset test releases the engine before submitting the next live request. The writer test catches a missing timeout but accepts an incorrect value. Neither checks the respective finding.
Gates: EOF expectation and unsafe-count increase have dated PIN reasons; probe deadline stays 60 seconds.
Escape catalog: C1–C4 have no matching changed code.

Notes

Static review; tests were not rerun. The PR reports no real-ffmpeg gate or clippy run. Its text describes six lifecycle tests; the head adds eight.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

Comment thread crates/serve/src/api.rs Outdated
&Default::default(),
|req, w| {
assert!(
w.write_timeout()?.is_some(),

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.

This accepts any timeout and then overwrites it, so a 600-second production deadline still passes.

Suggested change
w.write_timeout()?.is_some(),
w.write_timeout()? == Some(Duration::from_secs(10)),

@juliankang4
juliankang4 force-pushed the fix-serve-client-lifecycle branch from 550165e to bd13656 Compare October 23, 2026 15:57

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

Must-fix 1: fixed. crates/serve/src/api.rs:3205 removes a cancelled waiter before returning. The depth-one test queues a healthy request before the blocked engine returns.

Write-deadline question: fixed. crates/serve/src/api.rs:6717 asserts the ten-second timeout.

Verdict: CLEAN: both earlier findings are resolved, and no new must-fix defect survives the interdiff review.

Checked

Duplicates: 1 new item checked, Board::cancel; no existing cancellation owner. Dryer reported zero pairs.
Complexity: run_gen 14→22 adds polling and cancellation branches. Previously reviewed: read_frames 1→13 adds reader cleanup; decode 17→19 adds error arms; anthropic::stream, chat, completion, keep_alive, oaicompl::completions and responses::stream each add one error path.
Silent failure: 2 cancellation paths followed. A removed waiter frees capacity immediately; an already admitted request reaches the worker's shared transport check. Board locking serializes removal and admission, preventing double cancellation counts.
Tests (static mutation check): dropping the cancellation at api.rs:3206 fails the empty-queue assertion; dropping the ticket advance at sched.rs:253 fails the reservation assertion; setting RESPONSE_WRITE to 600 seconds fails the writer assertion.
Gates: the rebased unsafe count is 11→12 with a dated PIN and the reset fixture's invariant. The write-timeout assertion strengthens the existing check.
Escape catalog: C1–C4 have no matching changed code.

Notes

Static review; tests were not rerun. The author reports passing targeted lifecycle tests and ticket/deadline mutants. The full serve suite, real-ffmpeg gate and clippy were not run on this head.

🔨 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 e4204cc 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

serve The HTTP server: crates/serve

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant