Skip to content

serve: n on /v1/chat/completions and /v1/completions answers that many choices of the prompt, queued together, choice i seeded with the request's seed plus i - #959

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-usab-n-choices
Oct 29, 2026

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

/v1/chat/completions와 /v1/completions가 n을 받아 한 prompt에 대한 choice를 n개 돌려줍니다.

Part of #565.

What and why

bloomery-serve answered n with a 400 ("n is not supported by this server"). Clients that ask for several candidates of one prompt had to send n requests. Now n on /v1/chat/completions and /v1/completions returns n choices with index 0 to n-1, for whole and streamed replies.

  • The choices of one request enter the queue together, so they run one after another on one slot and side by side with --parallel N. If the board cannot take all of them, the request gets a 503 and none of them start.
  • Choice i is seeded with the request's seed plus i, so a request with a seed is reproducible, and choice i equals the n=1 reply with seed seed + i. With n=1 nothing changes.
  • usage counts the prompt once and sums the completion tokens of all choices. timings come from the first choice.
  • n must be between 1 and slots plus queue depth (64 by default); anything else is a 400 that names the range. /completion, /v1/responses and /v1/messages still refuse n > 1 by name.
  • In a stream, text deltas carry their index as they are produced, and the finish chunks follow in choice order once every choice has ended.

Release notes: Added: n on /v1/chat/completions and /v1/completions returns that many choices of the prompt (choice i is seeded with seed + i).

Code shape

  • No second copy. run_gen and run_whole are one-choice wrappers over the new run_choices and run_whole_choices, so the single-choice and multi-choice paths share one owner. The chat parser and its state types gained Clone so each choice starts from the same parser.
  • Model code holds only architecture facts. The change is in crates/serve and docs/serving.md; no model file changed.
  • Dead code is gone. run_gen no longer returns a slot that no caller used.
  • No silent failure. An n outside the range, and n > 1 on the routes that do not support it, are named 400 errors.
  • Comments state what is true now. The comments describe the code as it is.
  • No relaxed gate. No band, tolerance or lint level moved.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

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

What I ran

Card: NVIDIA GB10, driver 595.84. Model: Qwen3.8 FP4-Local. The binary is the real bloomery-serve, built with

cargo oxide build --arch sm_121a -- -p bloomery-gpu-gates --features glm5next,clef,vision,mimo2,solar2,minimaxm3,flint,gemma-embedding2,hf,checkpoint --release --bin bloomery-serve

and started as bloomery-serve -m <Qwen3.8-Flash-Next-FP4-Local folder> --host 127.0.0.1 --port 18733 --parallel {1,2} --ctx-size 16896. A client then posts to both routes with temperature 0.8, max_tokens 40 and stream_options.include_usage: chat with the prompt Write one short sentence about the sea. and reasoning_effort: none, completions with The sea at night is. Each route gets n=1 with seeds 42, 43 and 44, n=1 greedy, and n=3 seed 42 whole and streamed. The same requests ran against a binary of the base commit.

The run was on commit 50daca1a32b90e6c1726ba1b2d150754df598f88, base 5e743ada812e7377054e4d8a8756b7c466c833ae. The base binary refuses n=3:

base /v1/chat/completions n=3 seed 42 stream False 400 "{\"error\":{\"code\":400,\"message\":\"n is not supported by this server\",\"type\":\"invalid_request_error\"}}" usage null

The branch answers it with three choices, and the choice for seed 42 is the base's n=1 reply:

head1 /v1/chat/completions n=3 seed 42 stream False 200 ["The endless blue horizon stretched toward the setting sun, whispering secrets of the deep.", "The vast sea whispers secrets to the shore.", "The sea whispered its ancient secrets to the shore."] usage {"completion_tokens": 39, "prompt_tokens": 20, "total_tokens": 59, "prompt_tokens_details": {"cached_tokens": 19}}
base /v1/chat/completions n=1 seed 42 200 ["The endless blue horizon stretched toward the setting sun, whispering secrets of the deep."]
base /v1/chat/completions n=1 seed 43 200 ["The vast sea whispers secrets to the shore."]
base /v1/chat/completions n=1 seed 44 200 ["The sea whispered its ancient secrets to the shore."]

Summary lines of the client's checks (34 CHECK PASS, none failed). The checks are the same for chat and completions, and they ran with one slot (--parallel 1, MTP draft) and two slots (--parallel 2, draft off):

CHECK PASS chat n=1 s42 head == base   (also s43, s44, greedy; same for compl)
CHECK PASS chat base refuses n=3       (same for compl)
CHECK PASS chat p1 n=3 stream=True: 3 choices, choice i == n=1 seed 42+i
CHECK PASS chat p1 n=3 stream=True: choices differ and are non-empty
CHECK PASS chat p1 n=3 stream=True: usage completion 39 == sum 39
CHECK PASS compl p2 n=3 stream=True: usage completion 120 == sum 120
INFO chat p2 singles == p1 singles: True
INFO compl p2 singles == p1 singles: True
ALL PASS

The same n=3 request on the PR head d779b63a7a6c404298d16ff2d12bbdb428e764f0 (base e85f0c8cbdb884bec5144705902422166123ac55), with one slot and with two slots, on the same card:

n=3 choices [0, 1, 2] {'completion_tokens': 39, 'prompt_tokens': 20, 'total_tokens': 59, 'prompt_tokens_details': {'cached_tokens': 0}}

The serve gate, which runs the bloomery-serve crate tests including the n range and queue-depth cases (n above the connection limit is a 400, and an n=2 request that finds room for one choice gets a 503 and starts none):

just gate-serve
test result: ok. 404 passed; 0 failed   (lib)
test hw_unsupported_fields_are_refused ... ok
test slots::hw_a_request_past_the_queue_depth_is_503 ... ok
test result: ok. 111 passed; 0 failed   (serve tests)
verdict PASS, rc 0

AI help

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

@github-actions github-actions Bot added documentation Improvements or additions to documentation serve The HTTP server: crates/serve labels Oct 29, 2026
@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review job on this PR finished green but posted no review. Its log shows both reviewers failing before they read the diff:

reviewer: codex error ... Failed to refresh token: Your access token could not be refreshed because your refresh token was already used.
reviewer: claude failed (limit: Credit balance is too low)

#962 and #963 show the same thing, with codex failed (auth: workspace routing discovery unauthorized (401)) in place of the refresh error. Since the job reports success either way, these PRs look reviewed in the checks list while nothing was posted.

(AI 코딩 에이전트가 작성한 코멘트이며, 내용은 제가 확인했습니다.)

@juliankang4
juliankang4 force-pushed the dgx-spark-q38-usab-n-choices branch from d779b63 to b98f3a6 Compare October 29, 2026 10:50

@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: Supporting multiple choices breaks an existing serving gate, and Events adds an unused Clone implementation.

Must fix

1. Update the existing gate for supported choice counts

crates/serve/src/api.rs:4342 accepts chat requests with n=2. The ignored hw_unsupported_fields_are_refused test sends that count at crates/serve/tests/serve.rs:440, then asserts 400 at line 449. Its default mock server now returns 200. just gate-serve includes ignored tests, so this assertion fails.
Cost: Update the gate with the feature so the required serving checks can pass.
Replace the gate's ("n", json!(2)) row with:

// PIN(2026-10-29): chat supports n=2; exercise a count beyond its capacity.
("n", json!(serve::MAX_CONNECTIONS + 1)),

2. Remove the unused Events Clone implementation

crates/serve/src/worker.rs:151 derives Clone, but every Events value is moved or borrowed. The multi-choice construction at api.rs:3369 clones the underlying sender before wrapping it. No caller needs the derived implementation.
Cost: Removing the derive keeps the new internal interface limited to its actual uses.
Replace the derived definition with:

pub(crate) struct Events {
    tx: mpsc::Sender<(usize, Msg)>,
    choice: usize,
}

Non-blocking

⚠ Test admission of the whole request: crates/serve/src/api.rs:3378.
Deleting admits(subs.len()) is not caught by the new HTTP tests: they submit multiple choices into an empty queue. The existing queue gate uses one-choice /completion requests. Extend it with an OpenAI request whose choices only partly fit; assert 503 and no added engine calls.

Checked

Elements: All Events references checked; its Clone implementation has no caller.
Admission: The batch check and enqueues hold the same board lock. Scheduler tests exercise Board::admits directly; they do not protect its HTTP call site.
Tests: Static inspection confirms the stale 400 assertion and the missing partial-capacity case. No tests were executed.
Gates: No existing pin or tolerance moved. The ignored rejection gate is inconsistent with the feature.
Escape catalog: C1–C4 do not match these findings. No ledger lessons apply.

Notes

The PR includes client-run output on GB10, but no just gate-* run or nvidia-smi output.

🔨 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/worker.rs Outdated
Comment on lines +151 to +152
#[derive(Clone)]
pub(crate) struct Events {

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.

Events is only moved or borrowed; the multi-choice path clones the sender before wrapping it. Remove the unused Clone implementation.

Suggested change
#[derive(Clone)]
pub(crate) struct Events {
pub(crate) struct Events {

…y choices of the prompt, queued together, choice i seeded with the request's seed plus i
@juliankang4
juliankang4 force-pushed the dgx-spark-q38-usab-n-choices branch from b98f3a6 to 874b40f Compare October 29, 2026 11:33

@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 prior findings are addressed, and no new must-fix defect survives the interdiff review.

Checked

Duplicates: 0 new named definitions; the new at_once closure was checked against HTTP helpers. Dryer reports 0 pairs.
Complexity: crapper reports run_choices 28 (new orchestration), chat 39→44 and completions 18→22 (choice loops), and step 28→30 (dispatch branches). These functions are not edited by the interdiff.
Silent failure: 2 changed sites followed. Channel timeout/disconnection becomes None and fails a named expect; a failed send cannot turn that failure into a passing test.
Tests: Static mutation check: dropping the capacity guard at sched.rs:244 makes the partial request wait and fail its expect. Removing the upper-bound filter at api.rs:4336 changes the rejection from 400 to 503 and fails the status assertion. Tests were not executed here; the PR reports gate-serve PASS.
Gates: The changed rejection case has PIN(2026-10-29) and its reason. No tolerance moved.
Concurrency: Batch admission and enqueue hold one board lock; disconnect cleanup removes all queued choices. Prompt reuse still calls the test engine's prefill, including an empty tail.
Escape catalog: No C1–C4 pattern matches. No ledger lessons apply.

Notes

The PR lacks the nvidia-smi output required for GPU evidence.

🔨 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 7163db3 into midagedev:main Oct 29, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation serve The HTTP server: crates/serve

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant