Repository navigation
serve: bound response and decoder waits and preserve half-closed clients - #742
Conversation
There was a problem hiding this comment.
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)
| &Default::default(), | ||
| |req, w| { | ||
| assert!( | ||
| w.write_timeout()?.is_some(), |
There was a problem hiding this comment.
This accepts any timeout and then overwrites it, so a 600-second production deadline still passes.
| w.write_timeout()?.is_some(), | |
| w.write_timeout()? == Some(Duration::from_secs(10)), |
550165e to
bd13656
Compare
There was a problem hiding this comment.
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)
|
The review is done and the contribution check passed, so I'm merging this. |
serve가 닫힌 연결, 멈춘 연결, 멈춘 영상 디코더 때문에 요청 슬롯을 잡고 있던 다섯 가지 경우를 고치고, 쓰기 방향만 닫은 정상 클라이언트의 응답은 그대로 돌려주도록 했습니다.
Part of #565. Tracked in #699.
What and why
Five defects in
bloomery-servelet 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 incrates/serve. It does not touch generation math, token choice, samplers, GPU paths or public API signatures.Startedmessage with no receiver left returns the slot before prefill.keep_aliveentry point now sets a ten second no-progress limit on every response write, so plain responses, SSE, auth errors,100 Continueand the generative, decide and embed servers inherit it. If the socket option cannot be set, the connection is closed.frames_fromstill 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 existingwait_withinowner 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
Clientstate, the response write limit,admitandrefuse,Board::canceland the reset fixture are the only owners for their jobs.probe_client,keep_alive,frames_from,wait_withinandGatedare reused, and the streaming callers inapi.rs,anthropic.rs,oaicompl.rsandresponses.rsall take the new argument.serveblock count intools/unsafe-ratchet.txtgoes from 11 to 12 under a datedPINcomment, for oneSO_LINGERcall in test code that makes a peer reset without timing assumptions.cargo fmtran clean. I did not runcargo clippyfor this head.Duplication found or removed (
path:line): none.What I ran
On this head, the targeted tests:
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 inBoard::cancel, the depth test fails withcancellation passed the waiting request's ticket: Busy, and with a 600 second response write limit,lifecycle_stalled_writers_release_their_connectionfails withresponse writes must time out after ten seconds.Both exit 0.
Not run: the whole
bloomery-servesuite on this head,gate-serve-videoagainst a realffmpeg(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_genstill 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 초안 리뷰는 제가 직접 했습니다.