From bfae28a601b5a1ba66e2cea114e8472a8a5247db Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:16:59 -0600 Subject: [PATCH] helios/scheduler: preserve interior anchor for open-reasoning prompts Why Commit 4cc6f2fd budgets every interior conversation anchor (`raw_anchor < prompt_tokens`) against `scheduler_checkpoint_extra_work_fraction` (default 0.05), falling back to `prompt_tokens` whenever splitting prefill at `raw_anchor` exceeds the request's extra-work allowance. When a chat template opens a reasoning block after the last complete-message boundary (`output.content.start == OutputStart::Reasoning`, such as `\n` on reasoning-enabled Qwen, Nemotron, or DeepSeek models), OpenAI-compatible clients strip reasoning text from subsequent assistant history. Turn k+1 therefore diverges from Turn k inside `[raw_anchor, prompt_tokens)`. Because `PrefixCheckpointCache::lookup` matches exact published checkpoints across all core types, falling back to `prompt_tokens` leaves Turn k with no checkpoint that is a prefix of Turn k+1 and forces full re-prefill on subsequent turns. Requests that do not open a reasoning block (`OutputStart::Content`, `OutputStart::RecipientHeader`, `OutputStart::RecipientFrame`, `OutputStart::ToolBody`, and raw completions) do not suffer this stripped-suffix divergence: Turn k's prompt-end and terminal checkpoints remain exact prefixes of Turn k+1. Interior-anchor budgeting should therefore remain active for all non-reasoning-open requests (including multi-turn continuations with `admission_reused_tokens > 0`), while retaining `raw_anchor` specifically when `output.content.start == OutputStart::Reasoning` under a nonzero extra-work fraction. What - Added `pub preserve_message_anchor: bool` to `Prompt` (`helios/src/server/runtime.rs`), `RequestSpec`, and `LiveRequest` (`helios/src/scheduler.rs`), populated in `prepare_validated_inference` (`helios/src/server/request.rs`) as `output.as_ref().is_some_and(|o| o.content.start == OutputStart::Reasoning)` and propagated across admission and preemption readmission via `Incoming::spec`. - Added one shared predicate `RequestScheduler::budget_interior_anchor` in `helios/src/scheduler/checkpoints.rs` returning `self.policy.checkpoint_extra_work_fraction == 0.0 || !request.preserve_message_anchor`, consumed by `request_anchor_endpoint`, `checkpoint_selection_uncached`, and `promote_request_anchor`. - When `!budget_interior_anchor(request)` (`fraction > 0.0` and `preserve_message_anchor == true`), `request_anchor_endpoint` returns `Some(raw_anchor)` immediately, `checkpoint_selection_uncached` retains `(raw_anchor, 0)` without debiting `split_ns` and clears `accounting.budgeted_anchor = None`, and `promote_request_anchor` skips latching `budgeted_anchor`. - When `budget_interior_anchor(request)` is true (`fraction == 0.0`, or `preserve_message_anchor == false`), the existing interior-anchor budgeting logic runs unchanged, including when `admission_reused_tokens > 0`. - Synchronized present-state documentation (`docs/scheduling-runtime-design.md`, `helios/README.md`, `docs/core-design.md`, `docs/cli-design.md`) and added unit tests in `helios/src/scheduler/checkpoints.rs` and `helios/src/server/runtime/phase_tests.rs` covering preserved interior anchors at 0.05, strict zero-fraction fallback, non-preserved continuations with reused prefixes, `OutputStart::Reasoning` vs `OutputStart::Content`, `OutputStart::RecipientHeader`, `OutputStart::RecipientFrame` (ATEM and TMLv0), and raw completions preparation, plus readmission propagation. No CLI, Protobuf, model-core ABI, or `unsafe` changes; existing signed cores load and serve unchanged. Result Restores Turn k -> k+1 exact message-anchor prefix reuse for open-reasoning conversations under the default `scheduler_checkpoint_extra_work_fraction = 0.05` while keeping interior-anchor split budgeting active for `OutputStart::Content`, `OutputStart::RecipientHeader`, `OutputStart::RecipientFrame`, `OutputStart::ToolBody`, and raw completions, and preserving strict zero-split opt-out at `fraction == 0.0`. Evidence Verified on clean `git archive` via release `cargo check` and `cargo test` across `eos`, `selene`, `selene-manager`, `helios` (`--features runtime-core,server`), `flare`, and `flare-cli`, TLA+ lifecycle models and mutation verification (`verification/helios-lifecycle/check.py --mutations`), core-boundary and design-review hook pytest suites, and scratch fault-mutation checks reverting `budget_interior_anchor` and widening the `OutputStart::Reasoning` predicate. Live 3-model GB10 `flare run` A/B results comparing `07e666e6` against `298d3e68` (prior to rebasing onto `cc0a49d2`, which kept all production code and documentation byte-identical and only initialized `preserve_message_anchor: false` on four additional test `RequestSpec` literals on `main`) are reported in the PR description. Limitations: chat templates that inject a self-closed empty reasoning suffix when `enable_thinking=false` (such as `\n\n\n\n`, which resolves to `OutputStart::Content`) remain budgeted with `preserve_message_anchor = false`; `scripts/scheduling_sim` and `cargo kani` do not model checkpoint anchor selection. Discord: Dooner Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> --- docs/cli-design.md | 12 +- docs/core-design.md | 26 +- docs/scheduling-runtime-design.md | 13 +- helios/README.md | 14 +- helios/src/model/packed_round_tests.rs | 2 +- helios/src/model/tests.rs | 13 +- helios/src/scheduler.rs | 5 + helios/src/scheduler/boundary_tests.rs | 1 + .../scheduler/checkpoint_lifecycle_tests.rs | 1 + helios/src/scheduler/checkpoints.rs | 171 +++++++++++- helios/src/scheduler/policy_tests.rs | 24 +- helios/src/scheduler/tests.rs | 2 + helios/src/server/request.rs | 4 + helios/src/server/runtime.rs | 8 + helios/src/server/runtime/phase_tests.rs | 248 ++++++++++++++++++ helios/src/server/runtime/prompt_tests.rs | 1 + 16 files changed, 510 insertions(+), 35 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index a1de8c84d..c4c52ec0b 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -696,10 +696,14 @@ The controls use the core's captured snapshot graphs and require no re-export. `--scheduler-checkpoint-extra-work-fraction FRACTION` bounds optional checkpoint work relative to productive request work. The default is `0.05`; values must be finite and in `[0,1]`. It overrides -`[server] scheduler_checkpoint_extra_work_fraction`. An interior message endpoint before the prompt end serves as the conversation -anchor only when splitting prefill there adds predicted prefill work within the -request's extra-work allowance (reducing to zero added prefill work when the -fraction is zero), and otherwise the zero-split prompt end acts as the anchor. +`[server] scheduler_checkpoint_extra_work_fraction`. Under a nonzero fraction, +an interior message endpoint before the prompt end is retained without charging +its split when the generation prompt opens a reasoning block +(`output.content.start == OutputStart::Reasoning`). Otherwise an interior +message endpoint serves as the conversation anchor only when splitting prefill +there adds predicted prefill work within the request's extra-work allowance +(reducing to zero added prefill work when the fraction is zero), and the +zero-split prompt end acts as the anchor when it does not. When timing estimates are unavailable, a nonzero fraction keeps the last eligible message endpoint as a best-effort anchor while zero falls back to the prompt end. Zero snapshot capacity disables all checkpoint cuts. Any retained interior anchor diff --git a/docs/core-design.md b/docs/core-design.md index 09826a289..d68ae6ac9 100644 --- a/docs/core-design.md +++ b/docs/core-design.md @@ -1436,16 +1436,22 @@ to earlier tokens cannot reuse a checkpoint for different tokens. The scheduler chooses the last eligible complete-message boundary as the request's candidate conversation anchor, or the prompt end if no message boundary is eligible. When snapshot storage has zero capacity, the scheduler emits no -checkpoint cuts. An interior message boundary before the prompt end is retained as -the conversation anchor only when splitting prefill there adds predicted prefill -work within the request's extra-work allowance (`scheduler_checkpoint_extra_work_fraction` -times estimated uncached prefill work, reducing to exact zero split cost when the -fraction is zero); otherwise the zero-split prompt end serves as the anchor. When -an interior anchor is retained, its predicted split overhead is charged against -that same extra-work allowance while its single anchor snapshot copy remains -uncharged. Earlier complete-message boundaries before that candidate anchor -compete in reverse message order; a distinct prompt end follows them. There is no -capture-count limit or allocation of a fixed snapshot share to each request. +checkpoint cuts. When `scheduler_checkpoint_extra_work_fraction > 0` and the +generation prompt opens a reasoning block +(`output.content.start == OutputStart::Reasoning`), an interior message +boundary before the prompt end is retained as the conversation anchor without +charging its split so stripped reasoning tags do not invalidate multi-turn +prefix reuse. Otherwise an interior message boundary is retained only when +splitting prefill there adds predicted prefill work within the request's +extra-work allowance (`scheduler_checkpoint_extra_work_fraction` times +estimated uncached prefill work, reducing to exact zero split cost when the +fraction is zero), with the zero-split prompt end serving as the anchor when it +does not; when such a budgeted interior anchor is retained, its predicted split +overhead is charged against that same extra-work allowance while its single +anchor snapshot copy remains uncharged. Earlier complete-message boundaries +before that candidate anchor compete in reverse message order; a distinct +prompt end follows them. There is no capture-count limit or allocation of a +fixed snapshot share to each request. Extra captures share this request-local work allowance, with a default fraction of 0.05. An extra endpoint charges the additional predicted prefill time caused by diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index b29c91bb9..ace317c9f 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -664,11 +664,14 @@ prefill exposes its decoder and checkpoint operation only after completion. Checkpoint retention uses the exact token endpoints supplied by the native frontend under the anchor-budgeting and shared request-local allowance rules in [exact endpoint capture](core-design.md#exact-endpoint-capture): zero snapshot -capacity disables cuts; an interior message boundary is retained as the -conversation anchor only when its predicted prefill split fits the -`scheduler_checkpoint_extra_work_fraction` allowance (defaulting to 0.05, -charging the split while leaving the anchor snapshot copy uncharged); and -earlier messages plus a distinct prompt end compete within that same allowance. +capacity disables cuts; when `scheduler_checkpoint_extra_work_fraction > 0` +(defaulting to 0.05), an interior message boundary is retained without charging +its split if the generation prompt opens a reasoning block +(`output.content.start == OutputStart::Reasoning`, so stripped reasoning tags +do not invalidate multi-turn prefix reuse), and otherwise is retained only when +its predicted prefill split fits that allowance (charging the split while +leaving the anchor snapshot copy uncharged); earlier messages plus a distinct +prompt end compete within that same allowance. Prefill predictions use measured costs, including stale estimates retained for dispatch ranking. Pricing skips unmeasured capacities that consume no additional tokens over a smaller capacity, and unmeasured diff --git a/helios/README.md b/helios/README.md index 41f91e8b7..d5fe1a76a 100644 --- a/helios/README.md +++ b/helios/README.md @@ -370,11 +370,15 @@ capacity. Among candidates of one graph kind and cohort that perform the same logical work, selection first discards any shape whose capacities are all at least as large as another candidate's and larger in at least one. An unmeasured prefill graph is not explored when a smaller loaded capacity consumes the same -tokens. Checkpoint selection uses the last eligible message boundary as the -conversation anchor only when its predicted prefill split fits the request-local -`scheduler_checkpoint_extra_work_fraction` allowance (defaulting to 0.05), -otherwise falling back to the prompt end. A retained interior anchor charges its -split against that allowance (leaving its snapshot copy uncharged), and earlier +tokens. Checkpoint selection retains the last eligible interior message +boundary as the conversation anchor without charging its split when +`scheduler_checkpoint_extra_work_fraction > 0` (defaulting to 0.05) and the +generation prompt opens a reasoning block +(`output.content.start == OutputStart::Reasoning`), so stripped reasoning tags +do not invalidate multi-turn prefix reuse. Otherwise an interior message +boundary is kept only when its predicted prefill split fits that request-local +allowance (charging the split while leaving the anchor snapshot copy +uncharged), falling back to the prompt end when it does not, and earlier messages plus a distinct prompt end compete for the remaining headroom. Productive completed decode earns the same fraction of measured time for a distinct terminal capture. There is no capture-count cap or per-request share of diff --git a/helios/src/model/packed_round_tests.rs b/helios/src/model/packed_round_tests.rs index e3ecd4b3b..165c7a329 100644 --- a/helios/src/model/packed_round_tests.rs +++ b/helios/src/model/packed_round_tests.rs @@ -118,7 +118,7 @@ fn packed_combined_packing_preserves_sparse_slot_keys_and_ceiling_padding() { for _ in 0..4 { let prompt = vec![7; 64]; let h = scheduler.admit(RequestSpec { prompt_logprobs: false, message_boundaries: vec![], prompt: prompt.clone(), conditioning: vec![], - max_new_tokens: 64, grammar_constrained: false, growable_output: false }).unwrap(); + max_new_tokens: 64, grammar_constrained: false, growable_output: false, preserve_message_anchor: false }).unwrap(); admissions[h.slot as usize] = Some(Admission { prompt_logprobs: false, handle: h, sampling: SamplingParameters::default(), core_parameters: Default::default(), max_new_tokens: 64, prompt, data: PromptData { positions: (0..64).map(|i| [i; 3]).collect(), diff --git a/helios/src/model/tests.rs b/helios/src/model/tests.rs index 2f9189c5c..96e7b3bfb 100644 --- a/helios/src/model/tests.rs +++ b/helios/src/model/tests.rs @@ -131,6 +131,7 @@ fn generic_core_parameters_resolve_pack_and_enforce_text_forward_contracts() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }; // Unified validation rejects out-of-range and non-canonical -0.0 values in plan_admission_with_core_parameters. let out_of_range = @@ -378,6 +379,7 @@ fn core_parameters_pack_sparse_permuted_rows_and_preserve_prefix_values() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }; let requests = [0.125f32, 0.25, 0.5, 0.75] .into_iter() @@ -526,6 +528,7 @@ fn admission_histogram_seed_and_partial_page_uploads_preserve_native_semantics() grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let mut admissions: [Option; 4] = std::array::from_fn(|_| None); @@ -674,6 +677,7 @@ fn large_prefill_uploads_preserve_token_position_and_image_indices_without_tail_ grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let mut admissions: [Option; 4] = std::array::from_fn(|_| None); @@ -986,6 +990,7 @@ fn packing_follows_value_bindings_after_buffers_and_model_are_renamed() { grammar_constrained: true, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let mut admissions: [Option; 4] = std::array::from_fn(|_| None); @@ -1101,6 +1106,7 @@ fn legacy_copy_bindings_pack_neutral_sentinels_without_copy_proposals() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let step = scheduler.plan().unwrap(); @@ -1231,6 +1237,7 @@ fn mixed_native_uploads_pack_prompt_after_the_decode_extent_and_sample_only_elig grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); admissions[h.slot as usize] = Some(Admission { @@ -1444,6 +1451,7 @@ fn state_transfer_and_resume_upload_fixture() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let mut admissions: [_; 4] = std::array::from_fn(|_| None); @@ -1663,6 +1671,7 @@ fn grammar_packing_fixture() -> ( grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); admissions.push(Some(Admission { @@ -1896,6 +1905,7 @@ fn prefill_compacts_execution_feature_indices_and_preserves_admission_metadata() grammar_constrained: false, prompt_logprobs: false, growable_output: true, + preserve_message_anchor: false, }) .unwrap(); scheduler @@ -2004,7 +2014,7 @@ fn committed_generation_cursors_require_feedback_while_unused_prompt_positions_d } scheduler.measured_graph_durations(&manifest.graphs).unwrap(); let handle = scheduler.admit(RequestSpec { message_boundaries: vec![], prompt: vec![7; 64], conditioning: vec![], - max_new_tokens: 64, grammar_constrained: false, prompt_logprobs: false, growable_output: false }).unwrap(); + max_new_tokens: 64, grammar_constrained: false, prompt_logprobs: false, growable_output: false, preserve_message_anchor: false }).unwrap(); let mut admissions: [Option; 4] = std::array::from_fn(|_| None); admissions[handle.slot as usize] = Some(Admission { handle, sampling: SamplingParameters::default(), core_parameters: Default::default(), @@ -2264,6 +2274,7 @@ fn prompt_lookahead_packing_distributes_budget_across_single_multi_and_mixed_lan grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); admissions[h.slot as usize] = Some(Admission { diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index c65da9953..02796d336 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -155,6 +155,9 @@ pub struct RequestSpec { /// request decodes. When pages run out the scheduler may preempt such a request: /// it finishes through its terminal checkpoint and the runtime readmits its history. pub growable_output: bool, + /// Retain the last eligible interior message boundary as the conversation anchor + /// under nonzero `checkpoint_extra_work_fraction` instead of budgeting its split. + pub preserve_message_anchor: bool, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -225,6 +228,7 @@ pub struct LiveRequest { pub generated_tokens: u32, pub prompt_tokens: usize, pub grammar_constrained: bool, + pub preserve_message_anchor: bool, pub error_code: Option, prompt_logprobs: bool, execution_limit: u64, @@ -1845,6 +1849,7 @@ impl RequestScheduler { generated_tokens: 0, prompt_tokens: spec.prompt.len(), grammar_constrained: spec.grammar_constrained, + preserve_message_anchor: spec.preserve_message_anchor, prompt_logprobs: spec.prompt_logprobs, execution_limit: execution_limit as u64, error_code: None, diff --git a/helios/src/scheduler/boundary_tests.rs b/helios/src/scheduler/boundary_tests.rs index 3f70af619..590d95a7b 100644 --- a/helios/src/scheduler/boundary_tests.rs +++ b/helios/src/scheduler/boundary_tests.rs @@ -86,6 +86,7 @@ fn spec(system: Option, prompt: usize, output: u32) -> RequestSpec { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, } } fn run_step(s: &mut RequestScheduler) -> ScheduledPlan { diff --git a/helios/src/scheduler/checkpoint_lifecycle_tests.rs b/helios/src/scheduler/checkpoint_lifecycle_tests.rs index 9ac7b2c05..b002e8ce2 100644 --- a/helios/src/scheduler/checkpoint_lifecycle_tests.rs +++ b/helios/src/scheduler/checkpoint_lifecycle_tests.rs @@ -1000,6 +1000,7 @@ fn deferred_prefill_reservations_match_lifecycle_model() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let init = s.plan().unwrap(); diff --git a/helios/src/scheduler/checkpoints.rs b/helios/src/scheduler/checkpoints.rs index 791ef4e2d..4c78290ad 100644 --- a/helios/src/scheduler/checkpoints.rs +++ b/helios/src/scheduler/checkpoints.rs @@ -466,12 +466,19 @@ impl RequestScheduler { Some((whole, split_ns)) } + fn budget_interior_anchor(&self, request: &LiveRequest) -> bool { + self.policy.checkpoint_extra_work_fraction == 0.0 || !request.preserve_message_anchor + } + pub(super) fn request_anchor_endpoint(&self, request: &LiveRequest) -> Option { if self.limits.snapshots == 0 { return None; } let raw_anchor = request.checkpoint_anchor(); - if raw_anchor >= request.prompt_tokens || request.prefix_tokens == raw_anchor as u64 { + if raw_anchor >= request.prompt_tokens + || request.prefix_tokens == raw_anchor as u64 + || !self.budget_interior_anchor(request) + { return Some(raw_anchor); } if let Some((latched_raw, latched_prompt, chosen)) = request.checkpoints.budgeted_anchor @@ -600,13 +607,21 @@ impl RequestScheduler { ); } let fraction = self.policy.checkpoint_extra_work_fraction; - // An interior message boundary is kept as the conversation anchor only - // when its predicted prefill split overhead fits the request's extra-work - // allowance (reducing to exact zero split cost when `fraction == 0.0`). - // Unknown prefill costs retain best-effort interior anchors under nonzero - // fractions and fall back to the zero-split prompt end under zero fraction. + // Under a nonzero fraction, requests whose generation prompt opens a + // reasoning block (`preserve_message_anchor`, set when + // `output.content.start == OutputStart::Reasoning`) retain `raw_anchor` + // without charging its split so stripped reasoning tags do not break + // multi-turn reuse. + // Otherwise an interior message boundary is kept only when its predicted + // split overhead fits the request's extra-work allowance (reducing to + // exact zero split cost when `fraction == 0.0`). Unknown prefill costs + // retain best-effort interior anchors under nonzero fractions and fall + // back to the zero-split prompt end under zero fraction. let (anchor, anchor_split_ns) = if raw_anchor < request.prompt_tokens { - if raw_anchor > start { + if !self.budget_interior_anchor(request) { + accounting.budgeted_anchor = None; + (raw_anchor, 0) + } else if raw_anchor > start { let (chosen, split_ns) = match Self::anchor_split_ns( request, &catalog, @@ -890,7 +905,8 @@ impl RequestScheduler { return Ok(()); } let prompt_tokens = request.prompt_tokens; - let latch = (raw_anchor < prompt_tokens + let latch = (self.budget_interior_anchor(request) + && raw_anchor < prompt_tokens && request.prefix_tokens != raw_anchor as u64 && request.consumed_tokens >= prompt_tokens as u64) .then_some((raw_anchor, prompt_tokens, anchor)); @@ -4769,4 +4785,143 @@ mod tests { assert_eq!(scheduler.request_anchor_endpoint(zero_req), Some(512)); scheduler.cancel(zero_handle).unwrap(); } + + #[test] + fn preserved_message_anchor_retains_interior_boundary_and_respects_zero_fraction() { + let mut scheduler = super::super::tests::scheduler(2, 128, 16); + scheduler.prefill_graphs(&[128, 256, 512]).unwrap(); + for (tokens, nanos) in [(128, 100), (256, 110), (512, 200)] { + measure(&mut scheduler, GraphKind::Prefill, tokens, nanos); + } + measure(&mut scheduler, GraphKind::Snapshot, 1, 5); + scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.05, + ..Default::default() + }) + .unwrap(); + + // Prompt 0..1024 with interior boundary 896: + // whole = 200 + 200 = 400 ns (allowance at 0.05 = 20 ns), + // split_ns = (200 + 110 + 100) + 100 - 400 = 110 ns > 20 ns. + let mut spec = super::super::tests::spec(1024, 3); + spec.message_boundaries = vec![896]; + spec.preserve_message_anchor = true; + let handle = scheduler.admit(spec).unwrap(); + + // Nonzero fraction retains raw_anchor without charging split_ns or setting budgeted_anchor, + // leaving the full 20 ns extra-work allowance available for the optional Endpoint copy (5 ns). + let req = scheduler.request(handle).unwrap(); + let (sel, _, _) = scheduler.checkpoint_selection(req); + assert_eq!(sel.cuts[0].endpoint, 896); + assert_eq!(sel.cuts[0].role, RetentionRole::Anchor); + assert_eq!(sel.cuts[0].split_ns, 0); + assert_eq!(sel.cuts.len(), 2); + assert_eq!(sel.cuts[1].endpoint, 1024); + assert_eq!(sel.cuts[1].role, RetentionRole::Endpoint); + assert_eq!(sel.reserved_ns, 5); + assert_eq!(sel.budgeted_anchor, None); + assert_eq!(scheduler.request_anchor_endpoint(req), Some(896)); + + // Even with a stale fallback latch and exhausted extra_spent_ns, both paths agree on 896 + // and checkpoint_selection clears budgeted_anchor. + { + let req = scheduler.request_mut(handle).unwrap(); + req.checkpoints.extra_spent_ns = 1_000; + req.checkpoints.budgeted_anchor = Some((896, 1024, 1024)); + } + let req = scheduler.request(handle).unwrap(); + let (sel, _, _) = scheduler.checkpoint_selection(req); + assert_eq!(sel.cuts[0].endpoint, 896); + assert_eq!(sel.cuts[0].split_ns, 0); + assert_eq!(sel.budgeted_anchor, None); + assert_eq!(scheduler.request_anchor_endpoint(req), Some(896)); + + scheduler.cancel(handle).unwrap(); + + // Zero fraction strictly enforces zero-split fallback even when preserve_message_anchor is true. + let mut zero_scheduler = super::super::tests::scheduler(2, 128, 16); + zero_scheduler.prefill_graphs(&[128, 256, 512]).unwrap(); + for (tokens, nanos) in [(128, 100), (256, 110), (512, 200)] { + measure(&mut zero_scheduler, GraphKind::Prefill, tokens, nanos); + } + measure(&mut zero_scheduler, GraphKind::Snapshot, 1, 5); + zero_scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.0, + ..Default::default() + }) + .unwrap(); + let mut zero_spec = super::super::tests::spec(1024, 3); + zero_spec.message_boundaries = vec![896]; + zero_spec.preserve_message_anchor = true; + let zero_handle = zero_scheduler.admit(zero_spec).unwrap(); + let zero_req = zero_scheduler.request(zero_handle).unwrap(); + let (sel, _, _) = zero_scheduler.checkpoint_selection(zero_req); + assert_eq!(sel.cuts[0].endpoint, 1024); + assert_eq!(sel.cuts[0].role, RetentionRole::Anchor); + assert_eq!(zero_scheduler.request_anchor_endpoint(zero_req), Some(1024)); + zero_scheduler.cancel(zero_handle).unwrap(); + } + + #[test] + fn non_preserved_continuation_with_reused_prefix_still_budgets_interior_anchor() { + let mut scheduler = super::super::tests::scheduler(2, 128, 16); + scheduler.prefill_graphs(&[128, 256, 512]).unwrap(); + for (tokens, nanos) in [(128, 100), (256, 110), (512, 200)] { + measure(&mut scheduler, GraphKind::Prefill, tokens, nanos); + } + measure(&mut scheduler, GraphKind::Snapshot, 1, 5); + scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.05, + ..Default::default() + }) + .unwrap(); + + // Publish a reusable 512-token prefix checkpoint so Turn 2 enters with admission_reused_tokens == 512. + let prefix_tokens: Vec = (0..512).map(|i| (i % 100) as u32 + 1).collect(); + let mut turn1_spec = super::super::tests::spec(512, 3); + turn1_spec.prompt = prefix_tokens.clone(); + let turn1 = scheduler.admit(turn1_spec).unwrap(); + let mut fence = 1u64; + while scheduler.request(turn1).unwrap().phase != RequestPhase::Decode { + let step = scheduler.plan().unwrap(); + scheduler.commit(&step, Fence(fence)).unwrap(); + complete_test_step(&mut scheduler, &step, Fence(fence), 50); + fence += 1; + } + scheduler.cancel(turn1).unwrap(); + + // Turn 2 extends the cached 512-token prefix to 1024 tokens with interior boundary 896. + // Uncached interval 512..1024: whole = 200 ns (allowance at 0.05 = 10 ns), + // split_ns = (110 + 100) + 100 - 200 = 110 ns > 10 ns. + let mut turn2_prompt = prefix_tokens; + turn2_prompt.extend((512..1024).map(|i| (i % 100) as u32 + 1)); + + let mut non_preserved = super::super::tests::spec(1024, 3); + non_preserved.prompt = turn2_prompt.clone(); + non_preserved.message_boundaries = vec![896]; + non_preserved.preserve_message_anchor = false; + let h_non = scheduler.admit(non_preserved).unwrap(); + let req_non = scheduler.request(h_non).unwrap(); + assert_eq!(req_non.admission_reused_tokens, 512); + let (sel_non, _, _) = scheduler.checkpoint_selection(req_non); + assert_eq!(sel_non.cuts[0].endpoint, 1024); + assert_eq!(scheduler.request_anchor_endpoint(req_non), Some(1024)); + scheduler.cancel(h_non).unwrap(); + + let mut preserved = super::super::tests::spec(1024, 3); + preserved.prompt = turn2_prompt; + preserved.message_boundaries = vec![896]; + preserved.preserve_message_anchor = true; + let h_pres = scheduler.admit(preserved).unwrap(); + let req_pres = scheduler.request(h_pres).unwrap(); + assert_eq!(req_pres.admission_reused_tokens, 512); + let (sel_pres, _, _) = scheduler.checkpoint_selection(req_pres); + assert_eq!(sel_pres.cuts[0].endpoint, 896); + assert_eq!(sel_pres.cuts[0].split_ns, 0); + assert_eq!(scheduler.request_anchor_endpoint(req_pres), Some(896)); + scheduler.cancel(h_pres).unwrap(); + } } diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index faa653c0d..19944eae7 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -144,6 +144,7 @@ fn add(s: &mut RequestScheduler, id: u32, prompt: usize, output: u32) -> Request grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap() } @@ -1214,6 +1215,7 @@ fn long_conversations_use_work_budget_and_cross_unselected_messages() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }).unwrap()); } let mut full_chunks = 0; @@ -1800,6 +1802,7 @@ fn prerequisite_cohort_accounts_for_ready_batch_mates() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); for handle in [decode, prefill] { @@ -2431,6 +2434,7 @@ fn mixed_cancellation_keeps_other_rows_live_and_retires_pages_only_after_complet grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .is_err() ); @@ -3185,7 +3189,7 @@ fn terminal_snapshot_publishes_exact_partial_page_for_shared_cache_geometries() s.commit(&plan, fence).unwrap(); let spec = RequestSpec { prompt: vec![1; page_tokens + 1], message_boundaries: vec![], conditioning: vec![], max_new_tokens: 1, grammar_constrained: false, - prompt_logprobs: false, growable_output: false }; + prompt_logprobs: false, growable_output: false, preserve_message_anchor: false }; assert_eq!(s.plan_admission(&spec).unwrap().resident_tokens(), 0); assert_eq!(s.stats().snapshot_publications, publications); complete_timed(&mut s, &plan, fence, 0, true, gpu_time(MS / 10)); @@ -3280,6 +3284,7 @@ fn feedback_prefill_tails_progress_before_existing_generations_finish() { grammar_constrained: false, prompt_logprobs: false, growable_output: true, + preserve_message_anchor: false, }) .unwrap() }) @@ -3541,6 +3546,7 @@ fn retiring_boundary_capture_stamps_terminal_start_and_resuming_capture_leaves_i grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); initialize(&mut s, handle); @@ -4844,6 +4850,7 @@ fn terminal_prefill_runs_at_checkpoint_boundary_cut() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let init = s.plan().unwrap(); @@ -5013,6 +5020,7 @@ fn deferred_prefill_requires_terminal_prefill_for_small_cuts_refresh_and_decode( grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); initialize(&mut s, handle); @@ -5158,6 +5166,7 @@ fn mixed_graphs_excluded_for_deferred_prefill_and_prompt_logprobs() { grammar_constrained: false, prompt_logprobs: true, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let (scored_rate, _) = s.service_rates(s.request(scored).unwrap()); @@ -6175,6 +6184,7 @@ fn cold_scored_prefill_checkpoint_cuts_and_atomic_spans_use_natural_fit_discover grammar_constrained: false, prompt_logprobs: true, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); assert_eq!(measured_step(&mut scored, 150_000, 0).kind, GraphKind::Init); @@ -6202,6 +6212,7 @@ fn cold_scored_prefill_checkpoint_cuts_and_atomic_spans_use_natural_fit_discover grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); assert_eq!(measured_step(&mut cut_sched, 150_000, 0).kind, GraphKind::Init); @@ -6291,6 +6302,7 @@ fn run_turn_to_completion( grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let reused = s.request(h).unwrap().admission_reused_tokens; @@ -7284,6 +7296,7 @@ fn first_output_wait_pricing_is_inert_for_throughput_zero_decoders_and_score_onl grammar_constrained: false, prompt_logprobs: true, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); initialize(&mut scored, score_only); @@ -7361,6 +7374,7 @@ fn forced_anchor_cut_preserves_first_output_wait_clock_without_exempting_service grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let arrival_ns = s.now_ns; @@ -7406,6 +7420,7 @@ fn forced_anchor_cut_preserves_first_output_wait_clock_without_exempting_service grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let long_arrival = s.now_ns; @@ -7588,6 +7603,7 @@ fn anchor_wait_preservation_at_bucket_capacity_and_reset_on_message_cut() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let arrival_a = s.now_ns; @@ -7620,6 +7636,7 @@ fn anchor_wait_preservation_at_bucket_capacity_and_reset_on_message_cut() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let arrival_m = s.now_ns; @@ -7694,6 +7711,7 @@ fn terminal_prefill_clearing_deferred_state_at_interior_anchor_preserves_wait() grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); initialize(&mut s, handle); @@ -9156,6 +9174,7 @@ fn first_output_wait_preserved_across_age_priced_non_terminal_prefill_chunks() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let msg_arrival = plain.now_ns; @@ -9271,6 +9290,7 @@ fn deferred_terminal_prefill_at_checkpoint_cut_credits_reconciled_segment_wait() grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); let arrival = s.now_ns; @@ -9373,6 +9393,7 @@ fn deferred_terminal_prefill_at_checkpoint_cut_credits_reconciled_segment_wait() grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); initialize(&mut s, multi); @@ -9421,6 +9442,7 @@ fn deferred_terminal_prefill_at_checkpoint_cut_credits_reconciled_segment_wait() grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); initialize(&mut s, fresh_cut); diff --git a/helios/src/scheduler/tests.rs b/helios/src/scheduler/tests.rs index bb75a29c9..6f1c39f67 100644 --- a/helios/src/scheduler/tests.rs +++ b/helios/src/scheduler/tests.rs @@ -252,6 +252,7 @@ pub(super) fn spec(tokens: usize, max_new: u32) -> RequestSpec { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, } } fn records( @@ -2425,6 +2426,7 @@ fn declared_model_capabilities_drive_state_slots_and_vision_buckets() { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }) .unwrap(); assert_eq!(s.request(handle).unwrap().state_slot, StateSlotId(1)); diff --git a/helios/src/server/request.rs b/helios/src/server/request.rs index 399e9fe3e..bde28ab42 100644 --- a/helios/src/server/request.rs +++ b/helios/src/server/request.rs @@ -424,6 +424,9 @@ pub(super) fn prepare_validated_inference( .cloned() }) .flatten(); + let preserve_message_anchor = output + .as_ref() + .is_some_and(|o| o.content.start == crate::output::tagged::OutputStart::Reasoning); Ok(PreparedInference { prompt: Prompt { tokens, @@ -446,6 +449,7 @@ pub(super) fn prepare_validated_inference( .as_ref() .map_or_else(Vec::new, |options| options.ids.clone()), prompt_logprobs: opts.prompt_logprobs.is_some(), + preserve_message_anchor, }, output, rendered_prompt: rendered.text, diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 2f9b6bfd6..94297c958 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -47,6 +47,9 @@ pub struct Prompt { pub logprobs: bool, pub logprob_token_ids: Vec, pub prompt_logprobs: bool, + /// Retain the last eligible interior message boundary as the conversation anchor + /// under nonzero `checkpoint_extra_work_fraction`. + pub preserve_message_anchor: bool, } #[derive(Clone)] @@ -282,6 +285,7 @@ impl Incoming { && !self.speculative_grammar_reasoning(), prompt_logprobs: self.prompt_scored < self.prompt_score_end, growable_output: true, + preserve_message_anchor: self.prompt.preserve_message_anchor, } } @@ -3500,6 +3504,7 @@ mod tests { grammar_constrained, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }; let constrained = scheduler.admit(spec(7, true)).unwrap(); assert_eq!( @@ -3585,6 +3590,7 @@ mod tests { ignore_eos: false, grammar: None, grammar_reasoning: None, + preserve_message_anchor: false, }, events, admission: Mutex::new(Some(admission)), @@ -3770,6 +3776,7 @@ mod tests { grammar_constrained, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, } } @@ -4271,6 +4278,7 @@ mod tests { grammar_constrained: false, prompt_logprobs: false, growable_output: false, + preserve_message_anchor: false, }; let active = scheduler.admit(spec()).unwrap(); let rejected = scheduler.admit(spec()).unwrap_err(); diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 703c0a8a2..d609589ec 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -212,6 +212,7 @@ impl Fixture { logprobs: false, logprob_token_ids: vec![], prompt_logprobs: false, + preserve_message_anchor: false, ignore_eos: false, grammar: None, grammar_reasoning: None, @@ -3999,6 +4000,7 @@ fn exercise_text_preemption( prompt: vec![3; page_tokens * 5], max_new_tokens: 1, growable_output: false, + preserve_message_anchor: false, message_boundaries: vec![], conditioning: vec![], grammar_constrained: false, @@ -5775,6 +5777,7 @@ fn host_prefix_selects_whole_required_images_and_compacts_feature_indices() { grammar_constrained: false, prompt_logprobs: false, growable_output: true, + preserve_message_anchor: false, }) .unwrap(); worker.scheduler.set_vision_images(occupied, &[64]).unwrap(); @@ -6515,6 +6518,7 @@ fn unpinned_checkpoint( grammar_constrained: false, prompt_logprobs: false, growable_output: true, + preserve_message_anchor: false, }; let plan = worker.scheduler.plan_admission(&spec).unwrap(); let key = plan.history().key_at(end as u64).unwrap(); @@ -6676,6 +6680,7 @@ fn publication_copy_pins_survive_ancestor_compaction() { grammar_constrained: false, prompt_logprobs: false, growable_output: true, + preserve_message_anchor: false, }; let plan = worker.scheduler.plan_admission(&spec).unwrap(); let key = plan.history().key_at(64).unwrap(); @@ -6849,6 +6854,7 @@ fn publication_retries_wait_for_progress_and_abandon_evicted_ids() { grammar_constrained: false, prompt_logprobs: false, growable_output: true, + preserve_message_anchor: false, }; worker.scheduler.admit(spec).unwrap(); worker.service_store().unwrap(); @@ -7111,6 +7117,7 @@ fn core_parameter_preemption_preserves_prefix_identity_and_packed_value_on_forwa grammar_constrained: false, prompt_logprobs: false, growable_output: true, + preserve_message_anchor: false, }; let running = worker .active @@ -8341,6 +8348,247 @@ fn prepare_inference_enables_speculative_grammar_reasoning_only_for_eligible_env assert!(incoming.spec().grammar_constrained); } +#[test] +fn prepare_inference_sets_preserve_message_anchor_and_preserves_across_readmission() { + use crate::model::contract::{ReasoningParser, ReasoningParserKind, ToolParser, ToolParserKind}; + use crate::output::tagged::OutputStart; + use crate::server::protocol::{Protocol, decode}; + use serde_json::json; + + let prepare = |fixture: &Fixture, protocol: Protocol, body: serde_json::Value| { + let decoded = decode(protocol, body, false).unwrap(); + let compiler = crate::grammar::GrammarCompiler::new( + fixture.frontend.tokenizer(), + fixture.config.contract.vocabulary, + &fixture.config.eos_token_ids, + &[], + ) + .unwrap(); + crate::server::request::prepare_inference( + &fixture.frontend, + None, + &compiler, + &fixture.config, + &decoded.request, + 0, + false, + ) + .unwrap() + }; + + // 1. OutputStart::Reasoning sets preserve_message_anchor = true and carries it through readmission. + let reasoning_fixture = Fixture::reasoning(); + let reasoning_body = json!({ + "model": "qwen-worker-phases", + "messages": [{"role": "user", "content": "a"}], + "add_generation_prompt": true, + "max_tokens": 1 + }); + let prepared_reasoning = prepare(&reasoning_fixture, Protocol::Chat, reasoning_body.clone()); + assert_eq!( + prepared_reasoning.output.as_ref().unwrap().content.start, + OutputStart::Reasoning + ); + assert!(prepared_reasoning.prompt.preserve_message_anchor); + let (incoming, _generation, _, _) = + prepared_budget_request(&reasoning_fixture, Protocol::Chat, reasoning_body); + assert!(incoming.prompt.preserve_message_anchor); + assert!(incoming.spec().preserve_message_anchor); + let (sender, receiver) = mpsc::channel(); + sender.send(vec![incoming]).unwrap(); + let mut worker = reasoning_fixture.worker(receiver); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let handle = worker.active[0].as_ref().unwrap().request; + assert!(worker.scheduler.request(handle).unwrap().preserve_message_anchor); + let mut seq = 1u64; + while worker.scheduler.request(handle).unwrap().phase != RequestPhase::Finishing { + let step = worker.scheduler.plan().unwrap(); + let kind = step.kind; + let prompt_tokens = worker.scheduler.request(handle).unwrap().prompt_tokens as u64; + let emits = match kind { + GraphKind::Prefill => { + step.lanes[0].start_position + step.lanes[0].tokens as u64 == prompt_tokens + } + GraphKind::Decode => true, + _ => false, + }; + advance(&mut worker, kind, seq, emits.then_some(1)); + seq += 1; + } + worker.park(0, &[], 6).unwrap(); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let readmitted = worker.active.iter().flatten().next().unwrap().request; + assert!(worker.scheduler.request(readmitted).unwrap().preserve_message_anchor); + + // 2. OutputStart::Content sets preserve_message_anchor = false (both plain and closed-think templates). + let content_fixture = Fixture::new(); + let prepared_plain = prepare( + &content_fixture, + Protocol::Chat, + json!({ + "model": "qwen-worker-phases", + "messages": [{"role": "user", "content": "a"}], + "add_generation_prompt": true, + "max_tokens": 8 + }), + ); + assert!(!prepared_plain.prompt.preserve_message_anchor); + let mut closed_think_fixture = Fixture::with_template( + b"a{% mark %}assistant", + &["", "", ""], + &["assistant"], + ); + closed_think_fixture.config.contract.frontend.assistant_marker = "assistant".into(); + closed_think_fixture.config.contract.frontend.reasoning = Some(ReasoningParser { + kind: ReasoningParserKind::ThinkTags, + open: "".into(), + close: "".into(), + wrapping_newlines: 0, + terminal_markers: vec![], + }); + let prepared_content = prepare( + &closed_think_fixture, + Protocol::Chat, + json!({ + "model": "qwen-worker-phases", + "messages": [{"role": "user", "content": "a"}], + "add_generation_prompt": true, + "max_tokens": 8 + }), + ); + assert_eq!( + prepared_content.output.as_ref().unwrap().content.start, + OutputStart::Content + ); + assert!(!prepared_content.prompt.preserve_message_anchor); + + // 3. OutputStart::RecipientHeader (normal ATEM chat turn) sets preserve_message_anchor = false. + let mut atem_fixture = Fixture::with_template( + b"a<|eot|>{% mark %}{% if add_generation_prompt %}<|start|>assistant{% endif %}", + &["", "<|start|>", "<|message|>", "<|eom|>", "<|eot|>"], + &["assistant"], + ); + atem_fixture.config.contract.frontend.assistant_marker = "<|start|>assistant".into(); + atem_fixture.config.contract.frontend.message_end_markers = + vec!["<|eom|>".into(), "<|eot|>".into()]; + atem_fixture.config.contract.frontend.tools = Some(ToolParser { + kind: ToolParserKind::Atem, + wrapping_newlines: 0, + tag_separator: String::new(), + open: String::new(), + close: String::new(), + }); + atem_fixture.config.contract.frontend.reasoning = Some(ReasoningParser { + kind: ReasoningParserKind::RecipientHeaders, + open: "<|start|>assistant to=self<|message|>".into(), + close: "<|eom|>".into(), + wrapping_newlines: 0, + terminal_markers: vec![], + }); + let prepared_recipient_header = prepare( + &atem_fixture, + Protocol::Chat, + json!({ + "model": "qwen-worker-phases", + "messages": [{"role": "user", "content": "a"}], + "add_generation_prompt": true, + "max_tokens": 8 + }), + ); + assert_eq!( + prepared_recipient_header.output.as_ref().unwrap().content.start, + OutputStart::RecipientHeader + ); + assert!(!prepared_recipient_header.prompt.preserve_message_anchor); + + // 4. OutputStart::RecipientFrame (ATEM add_generation_prompt=false and normal TMLv0 chat turn) + // sets preserve_message_anchor = false. + let prepared_atem_frame = prepare( + &atem_fixture, + Protocol::Chat, + json!({ + "model": "qwen-worker-phases", + "messages": [{"role": "user", "content": "a"}], + "chat_template_kwargs": {"add_generation_prompt": false}, + "max_tokens": 8 + }), + ); + assert_eq!( + prepared_atem_frame.output.as_ref().unwrap().content.start, + OutputStart::RecipientFrame + ); + assert!(!prepared_atem_frame.prompt.preserve_message_anchor); + + let mut tml_fixture = Fixture::with_template( + b"<|begin_of_text|><|message_user|><|content_text|>a<|end_message|>{% mark %}", + &[ + "", + "<|message_model|>", + "<|message_user|>", + "<|message_system|>", + "<|message_tool|>", + "<|content_text|>", + "<|content_thinking|>", + "<|content_invoke_tool_json|>", + "<|content_invoke_tool_text|>", + "<|content_tool_error|>", + "<|content_xml|>", + "<|content_image|>", + "<|end_message|>", + "<|content_model_end_sampling|>", + "<|begin_of_text|>", + ], + &[], + ); + tml_fixture.config.contract.frontend.assistant_marker = "<|message_model|>".into(); + tml_fixture.config.contract.frontend.message_end_markers = vec![ + "<|end_message|>".into(), + "<|content_model_end_sampling|>".into(), + ]; + tml_fixture.config.contract.frontend.tools = Some(ToolParser { + kind: ToolParserKind::TmlJson, + wrapping_newlines: 0, + tag_separator: String::new(), + open: String::new(), + close: String::new(), + }); + tml_fixture.config.contract.frontend.reasoning = Some(ReasoningParser { + kind: ReasoningParserKind::ContentHeaders, + open: "<|content_thinking|>".into(), + close: "<|end_message|>".into(), + wrapping_newlines: 0, + terminal_markers: vec![], + }); + let prepared_tml_frame = prepare( + &tml_fixture, + Protocol::Chat, + json!({ + "model": "qwen-worker-phases", + "messages": [{"role": "user", "content": "a"}], + "add_generation_prompt": true, + "max_tokens": 8 + }), + ); + assert_eq!( + prepared_tml_frame.output.as_ref().unwrap().content.start, + OutputStart::RecipientFrame + ); + assert!(!prepared_tml_frame.prompt.preserve_message_anchor); + + // 5. Raw completions prompt (no output config) sets preserve_message_anchor = false. + let prepared_completions = prepare( + &reasoning_fixture, + Protocol::Completions, + json!({ + "model": "qwen-worker-phases", + "prompt": "a", + "max_tokens": 8 + }), + ); + assert!(prepared_completions.output.is_none()); + assert!(!prepared_completions.prompt.preserve_message_anchor); +} + #[test] fn forced_reasoning_close_readmission_anchors_first_output_wait_with_and_without_prior_publication() { // Case 1: With a prior graph publication, host-published close tokens advance diff --git a/helios/src/server/runtime/prompt_tests.rs b/helios/src/server/runtime/prompt_tests.rs index d9a5b9c7b..7a2ebd8f3 100644 --- a/helios/src/server/runtime/prompt_tests.rs +++ b/helios/src/server/runtime/prompt_tests.rs @@ -53,6 +53,7 @@ fn prompt_prefill_gpu_and_native_costs() { }, core_parameters: Default::default(), max_new_tokens: budget, reasoning_cut: None, stop_sequences: vec![], stop_strings: vec![], grammar: None, grammar_reasoning: None, ignore_eos: false, logprobs: false, logprob_token_ids: vec![], prompt_logprobs: scored, + preserve_message_anchor: false, }; runtime.metrics().scheduler_trace.drain(&mut samples); let started = Instant::now();