diff --git a/docs/cli-design.md b/docs/cli-design.md index 7a3a9f961..a1de8c84d 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -696,15 +696,16 @@ 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`. With a nonzero fraction, the -scheduler considers the last eligible message endpoint as a best-effort -conversation anchor even when timing estimates are unavailable; when the fraction -is zero, an interior message endpoint is used as the anchor only when splitting -prefill there adds zero predicted prefill work, and otherwise the prompt end acts -as the anchor. Zero snapshot capacity disables all checkpoint cuts. Earlier messages -and a distinct prompt end consume the fraction of estimated uncached prefill -work; a distinct terminal endpoint earns its allowance from completed productive -decode. Extra work includes snapshot copies and additional prefill caused by +`[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. +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 +split, earlier messages, and a distinct prompt end share the fraction of estimated +uncached prefill work; a distinct terminal endpoint earns its allowance from +completed productive decode. Extra work includes snapshot copies and additional prefill caused by splitting chunks. Snapshot storage remains globally shared and reclaimable for mandatory execution. This option requires no core re-export. diff --git a/docs/core-design.md b/docs/core-design.md index 0db26a73f..9bda8a034 100644 --- a/docs/core-design.md +++ b/docs/core-design.md @@ -1434,25 +1434,27 @@ reuse depends on the actual prepared prefix identity; context-dependent changes to earlier tokens cannot reuse a checkpoint for different tokens. The scheduler chooses the last eligible complete-message boundary as the request's -conversation anchor. If no message boundary is eligible, the prompt end is the -anchor. When snapshot storage has zero capacity, the scheduler emits no checkpoint -cuts. Under a nonzero extra-work fraction, anchor retention is best effort and -independent of duration estimates; when `scheduler_checkpoint_extra_work_fraction` -is zero, an interior message boundary is retained as the anchor only if splitting -prefill there adds zero predicted prefill work, otherwise the prompt end serves as -the anchor. Earlier complete-message boundaries 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 use a request-local work allowance. Its prefill component is -`scheduler_checkpoint_extra_work_fraction` times the estimated uncached prefill -work, with a default fraction of 0.05. An extra endpoint charges the additional -predicted prefill time caused by splitting its enclosing interval, plus its -snapshot-copy time. Prefill estimates retain measured costs after expiry, as -ordinary dispatch does. Unknown prefill costs or unknown or stale snapshot-copy -costs exclude extras without excluding the selected anchor; when the fraction is -zero, unknown prefill costs fall back from an interior message boundary to the -prompt-end anchor. Productive completed decode +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. + +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 +splitting its enclosing interval, plus its snapshot-copy time. Prefill estimates +retain measured costs after expiry, as ordinary dispatch does. Unknown prefill +costs or unknown or stale snapshot-copy costs exclude extras without excluding the +selected anchor; under a nonzero fraction unknown prefill costs retain the last +eligible interior message boundary as a best-effort anchor, whereas under a zero +fraction unknown prefill costs fall back to the prompt-end anchor. Productive completed decode earns the same fraction of measured decode time for a distinct terminal endpoint. A coincident prompt and terminal endpoint uses one capture. Mandatory conditioned-input state transfers do not consume this allowance. Preemption diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index 1adb19266..5c0f01bff 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -312,7 +312,9 @@ work, including optional cuts and their split and copy budgets ([checkpoint retention](#prerequisites-and-completion)), without quoting snapshot storage. Estimates and quoted selections are cached separately within each planning scope. Both paths reuse a stored selection when it contains any -non-anchor cut. Submission quotes storage for the winning prompt row. When no +non-anchor cut or an unreached anchor cut with an active guard, spent extra +work, or a nonzero charged split. Submission quotes storage for the winning +prompt row. When no quote fails, estimated and submitted work agree. Storage shortage can change which cuts fit the work budget, so the estimate and quoted selection can differ in either direction. If the quoted work differs from the winning estimate, an @@ -626,15 +628,14 @@ feedback. Dependency checks apply to the actual selected program. A finishing prefill exposes its decoder and checkpoint operation only after completion. Checkpoint retention uses the exact token endpoints supplied by the native -frontend. Zero snapshot capacity disables all checkpoint cuts. Otherwise, the last -eligible completed message is a best-effort conversation anchor, falling back to -the prompt end when no message is eligible or when -`scheduler_checkpoint_extra_work_fraction` is zero and splitting prefill at an -interior message boundary would add predicted prefill work. Earlier -messages are considered in reverse order, followed by a distinct prompt end. -Additional prefill splits and snapshot copies must fit a request-local allowance -of `scheduler_checkpoint_extra_work_fraction` times estimated uncached prefill -work, defaulting to 0.05. Prefill predictions use measured costs, including stale +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. +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 capacities other than the chunk's pricing capacity: the smallest catalog @@ -642,12 +643,12 @@ capacity covering the tokens remaining before the chunk's limit, falling back to the largest catalog capacity when none does. Pure prefill dispatch discovers only the natural-fit capacity, and an atomic span can make the natural fit smaller than the pricing capacity. An unmeasured pricing capacity that consumes -additional tokens leaves the prefill cost unknown. Unknown prefill costs and -unknown or stale snapshot-copy costs disable extras while preserving the -selected anchor; when the fraction is zero, unknown prefill costs fall back from -an interior message boundary to the prompt-end anchor. Productive completed -decode earns the same fraction of measured time for a distinct terminal capture. -There is no fixed capture count or concurrency-based snapshot share. +additional tokens leaves the prefill cost unknown, applying the unknown-cost +anchor and extra-cut rules in +[exact endpoint capture](core-design.md#exact-endpoint-capture). Productive +completed decode earns the same fraction of measured time for a distinct +terminal capture. There is no fixed capture count or concurrency-based snapshot +share. An extra prefill cut is selected only with an obtainable snapshot destination. If its cost expires after dispatch, its copy can be skipped after the split has diff --git a/helios/README.md b/helios/README.md index 9c5f7b782..98d516fde 100644 --- a/helios/README.md +++ b/helios/README.md @@ -369,18 +369,18 @@ 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 prioritizes the last eligible message boundary, -using the prompt end when no message boundary is eligible. Earlier messages and -a distinct prompt end compete within a work allowance of -`scheduler_checkpoint_extra_work_fraction` times estimated uncached prefill work, -defaulting to 0.05. Extra captures charge snapshot-copy cost and additional prefill -caused by splitting chunks. Productive completed decode earns the same fraction -of measured time for a distinct terminal capture. Unknown costs exclude extras -while preserving best-effort anchor retention. There is no capture-count cap or -per-request share of snapshot rows. The global allocator accounts for snapshot -aliases, guards a later anchor against earlier optional captures, and reclaims -unused guards for mandatory execution. Only obtainable capture destinations -introduce prefill cuts. See [checkpoint ownership](../docs/core-design.md#exact-endpoint-capture). `prefill_chunk_size` must be 64-aligned, at least 64, and within the +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 +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 +snapshot rows; the global allocator accounts for snapshot aliases, guards a later +anchor against earlier optional captures, and reclaims unused guards for +mandatory execution. Only obtainable capture destinations introduce prefill cuts. +See [checkpoint ownership](../docs/core-design.md#exact-endpoint-capture). `prefill_chunk_size` must be 64-aligned, at least 64, and within the context capacity. Batched graphs declare batch capacities in `1..=request_slots` (at most 64); Helios enumerates and schedules whatever valid batch capacities the loaded core provides rather than requiring a hardcoded bucket list. diff --git a/helios/src/scheduler/boundary_tests.rs b/helios/src/scheduler/boundary_tests.rs index a97ab3813..3f70af619 100644 --- a/helios/src/scheduler/boundary_tests.rs +++ b/helios/src/scheduler/boundary_tests.rs @@ -71,8 +71,7 @@ fn scheduler_with_concurrency(snapshots: u32, mtp: bool, page_tokens: usize, act }, ) .unwrap(); - s.measured_graph_durations(&super::tests::duration_graphs(4)) - .unwrap(); + super::tests::permissive_checkpoint_costs(&mut s, 4, None); if mtp { s.enable_speculation(&[1, 2, 4, 8]).unwrap(); } @@ -425,6 +424,8 @@ fn exact_system_prompt_terminal_endpoints_and_partial_restore_pages() { for system in [1, 2, 3, 10, 15, 63, 64, 65, 66, 67, 127, 255, 256, 257, 511] { for mtp in [false, true] { let mut s = scheduler_with_concurrency(8, mtp, page_tokens, 2); + s.prefill_graphs(super::tests::STANDARD_PREFILL_CAPACITIES) + .unwrap(); let prompt = system + 67; let h = s.admit(spec(Some(system), prompt, 3)).unwrap(); stop_at_capture(&mut s, h, system as u64); @@ -555,6 +556,8 @@ fn boundary_snapshots_are_optional_and_cancel_behind_fence() { #[test] fn duplicate_boundary_publication_does_not_remap_live_partial_pages() { let mut s = scheduler_with_concurrency(6, false, 64, 2); + s.prefill_graphs(super::tests::STANDARD_PREFILL_CAPACITIES) + .unwrap(); let a = s.admit(spec(Some(10), 70, 2)).unwrap(); let b = s.admit(spec(Some(10), 70, 2)).unwrap(); stop_at_capture(&mut s, a, 10); diff --git a/helios/src/scheduler/checkpoint_lifecycle_tests.rs b/helios/src/scheduler/checkpoint_lifecycle_tests.rs index b867e0750..9ac7b2c05 100644 --- a/helios/src/scheduler/checkpoint_lifecycle_tests.rs +++ b/helios/src/scheduler/checkpoint_lifecycle_tests.rs @@ -153,6 +153,12 @@ fn edge(before: [u64; 16], action: [u64; 3], after: [u64; 16]) { fn checkpoint_reservations_match_lifecycle_model() { for cancellation in 0..5 { let mut scheduler = tests::scheduler(2, 64, 3); + scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 1.0, + ..Default::default() + }) + .unwrap(); let handles = [0, 1].map(|slot| { let mut spec = tests::spec(64, 16); spec.prompt[0] += slot; @@ -300,7 +306,7 @@ fn unused_anchor_guards_revoke_oldest_first_without_cancelling_requests() { } #[test] -fn zero_budget_multi_chunk_fallback_reservations_match_lifecycle_model() { +fn budgeted_anchor_multi_chunk_fallback_reservations_match_lifecycle_model() { for cancellation in 0..5 { let mut scheduler = tests::scheduler(2, 64, 3); let mut graphs = tests::duration_graphs(2); @@ -360,7 +366,7 @@ fn zero_budget_multi_chunk_fallback_reservations_match_lifecycle_model() { .request(handle) .unwrap() .checkpoint_capture - .expect("multi-chunk prefill must retain zero-budget prompt-end anchor fallback"); + .expect("multi-chunk prefill must retain budgeted-anchor prompt-end fallback"); assert_eq!(capture.role, RetentionRole::Anchor); assert_eq!(capture.endpoint, 1024); let snapshot = capture.snapshot; @@ -436,7 +442,7 @@ fn zero_budget_multi_chunk_fallback_reservations_match_lifecycle_model() { } #[test] -fn zero_budget_interior_anchor_drift_and_mixed_shift_match_lifecycle_model() { +fn budgeted_anchor_interior_drift_and_mixed_shift_match_lifecycle_model() { // 1. Aligned interior boundary (512 in 1024) with upward GPU EWMA drift on chunk 1 // arms and publishes 512 once and leaves chunk 2 free of duplicate Anchor capture. let mut scheduler = tests::scheduler(2, 64, 3); @@ -485,7 +491,7 @@ fn zero_budget_interior_anchor_drift_and_mixed_shift_match_lifecycle_model() { .request(handle) .unwrap() .checkpoint_capture - .expect("aligned zero-budget interior boundary must arm Anchor capture"); + .expect("aligned budgeted-anchor interior boundary must arm Anchor capture"); assert_eq!(capture.role, RetentionRole::Anchor); assert_eq!(capture.endpoint, 512); let request = handle.slot as u64 + 1; diff --git a/helios/src/scheduler/checkpoints.rs b/helios/src/scheduler/checkpoints.rs index ddaa34d81..791ef4e2d 100644 --- a/helios/src/scheduler/checkpoints.rs +++ b/helios/src/scheduler/checkpoints.rs @@ -25,7 +25,7 @@ pub struct CheckpointAccounting { pub productive_decode_ns: u64, pub extra_spent_ns: u64, baseline_interval: Option<(usize, usize)>, - zero_budget_anchor: Option<(usize, usize, usize)>, + budgeted_anchor: Option<(usize, usize, usize)>, window_ends: Vec, reserved_ns: u64, cuts: Vec, @@ -93,6 +93,10 @@ fn allowance(work: u64, fraction: f64) -> u64 { ((work as f64) * fraction).floor().min(u64::MAX as f64) as u64 } +fn anchor_split_affordable(budget_base: u64, split_ns: u64, spent_ns: u64, fraction: f64) -> bool { + split_ns == 0 || spent_ns.saturating_add(split_ns) <= allowance(budget_base, fraction) +} + #[derive(Clone, Copy, Debug)] struct PrefillCatalogCost { capacity: usize, @@ -427,28 +431,39 @@ impl RequestScheduler { selection } - fn anchor_split_is_zero_cost( + fn split_overhead_ns( + request: &LiveRequest, + catalog: &[PrefillCatalogCost], + terminal_window: usize, + left: usize, + whole: u64, + endpoint: usize, + right: usize, + ) -> Option { + let before = Self::interval_prefill_ns(request, catalog, terminal_window, left, endpoint)?; + let after = Self::interval_prefill_ns(request, catalog, terminal_window, endpoint, right)?; + Some(before.saturating_add(after).saturating_sub(whole)) + } + + fn anchor_split_ns( request: &LiveRequest, catalog: &[PrefillCatalogCost], terminal_window: usize, start: usize, end: usize, anchor: usize, - ) -> bool { - let Some(whole) = Self::interval_prefill_ns(request, catalog, terminal_window, start, end) - else { - return false; - }; - let Some(before) = - Self::interval_prefill_ns(request, catalog, terminal_window, start, anchor) - else { - return false; - }; - let Some(after) = Self::interval_prefill_ns(request, catalog, terminal_window, anchor, end) - else { - return false; - }; - before.saturating_add(after).saturating_sub(whole) == 0 + ) -> Option<(u64, u64)> { + let whole = Self::interval_prefill_ns(request, catalog, terminal_window, start, end)?; + let split_ns = Self::split_overhead_ns( + request, + catalog, + terminal_window, + start, + whole, + anchor, + end, + )?; + Some((whole, split_ns)) } pub(super) fn request_anchor_endpoint(&self, request: &LiveRequest) -> Option { @@ -456,13 +471,10 @@ impl RequestScheduler { return None; } let raw_anchor = request.checkpoint_anchor(); - if self.policy.checkpoint_extra_work_fraction != 0.0 - || 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 { return Some(raw_anchor); } - if let Some((latched_raw, latched_prompt, chosen)) = request.checkpoints.zero_budget_anchor + if let Some((latched_raw, latched_prompt, chosen)) = request.checkpoints.budgeted_anchor && latched_raw == raw_anchor && latched_prompt == request.prompt_tokens { @@ -510,7 +522,8 @@ impl RequestScheduler { } else { self.terminal_prefill_window() }; - if Self::anchor_split_is_zero_cost( + let fraction = self.policy.checkpoint_extra_work_fraction; + let keep_raw = match Self::anchor_split_ns( request, &catalog, terminal_window, @@ -518,6 +531,15 @@ impl RequestScheduler { request.prompt_tokens, raw_anchor, ) { + Some((whole, split_ns)) => anchor_split_affordable( + request.checkpoints.initial_prefill_ns.unwrap_or(whole), + split_ns, + request.checkpoints.extra_spent_ns, + fraction, + ), + None => fraction > 0.0, + }; + if keep_raw { Some(raw_anchor) } else { Some(request.prompt_tokens) @@ -537,10 +559,18 @@ impl RequestScheduler { #[cfg(test)] tests::SELECTIONS.set(tests::SELECTIONS.get() + 1); let mut accounting = request.checkpoints.clone(); + let start = Self::prefill_cursor(request); if accounting .cuts .iter() .any(|cut| cut.role != RetentionRole::Anchor) + || accounting.cuts.iter().any(|cut| { + cut.role == RetentionRole::Anchor + && cut.endpoint > start + && (request.anchor_guard.is_some() + || accounting.extra_spent_ns > 0 + || cut.split_ns > 0) + }) { return (accounting, false, false); } @@ -550,7 +580,6 @@ impl RequestScheduler { return (accounting, false, false); } let raw_anchor = request.checkpoint_anchor(); - let start = Self::prefill_cursor(request); let (baseline_start, baseline_end) = *accounting.baseline_interval.get_or_insert(( request.admission_reused_tokens as usize, request.prompt_tokens, @@ -570,15 +599,15 @@ impl RequestScheduler { baseline_end, ); } - // Under a zero extra-work budget, an interior message boundary is kept - // as the anchor only when splitting prefill at that boundary adds zero - // predicted prefill work; otherwise fall back to the zero-split prompt - // end and latch the chosen anchor across remaining prefill chunks. - let anchor = if raw_anchor < request.prompt_tokens - && self.policy.checkpoint_extra_work_fraction == 0.0 - { + 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. + let (anchor, anchor_split_ns) = if raw_anchor < request.prompt_tokens { if raw_anchor > start { - let chosen = if Self::anchor_split_is_zero_cost( + let (chosen, split_ns) = match Self::anchor_split_ns( request, &catalog, terminal_window, @@ -586,36 +615,49 @@ impl RequestScheduler { request.prompt_tokens, raw_anchor, ) { - raw_anchor - } else { - request.prompt_tokens + Some((whole, split_ns)) => { + let budget_base = accounting.initial_prefill_ns.unwrap_or(whole); + if anchor_split_affordable( + budget_base, + split_ns, + accounting.extra_spent_ns, + fraction, + ) { + (raw_anchor, split_ns) + } else { + (request.prompt_tokens, 0) + } + } + None if fraction > 0.0 => (raw_anchor, 0), + None => (request.prompt_tokens, 0), }; - accounting.zero_budget_anchor = Some((raw_anchor, request.prompt_tokens, chosen)); - chosen + accounting.budgeted_anchor = Some((raw_anchor, request.prompt_tokens, chosen)); + (chosen, split_ns) } else if request.prefix_tokens != raw_anchor as u64 - && let Some((latched_raw, latched_prompt, chosen)) = accounting.zero_budget_anchor + && let Some((latched_raw, latched_prompt, chosen)) = accounting.budgeted_anchor && latched_raw == raw_anchor && latched_prompt == request.prompt_tokens { - chosen + (chosen, 0) } else { - accounting.zero_budget_anchor = + accounting.budgeted_anchor = Some((raw_anchor, request.prompt_tokens, raw_anchor)); - raw_anchor + (raw_anchor, 0) } } else { - accounting.zero_budget_anchor = None; - raw_anchor + accounting.budgeted_anchor = None; + (raw_anchor, 0) }; if anchor > start { + accounting.reserved_ns = accounting.reserved_ns.saturating_add(anchor_split_ns); accounting.cuts.push(Cut { endpoint: anchor, role: RetentionRole::Anchor, - split_ns: 0, + split_ns: anchor_split_ns, copy_ns: 0, }); } - if self.policy.checkpoint_extra_work_fraction == 0.0 { + if fraction == 0.0 { return (accounting, false, false); } let Some(prefill) = accounting.initial_prefill_ns else { @@ -626,13 +668,13 @@ impl RequestScheduler { }; let mut unknown = false; let mut budget = false; - let available = allowance(prefill, self.policy.checkpoint_extra_work_fraction); + let available = allowance(prefill, fraction); let mut candidates: Vec<_> = request .message_boundaries .iter() .rev() .copied() - .filter(|&end| start < end && end < anchor && request.checkpoint_endpoint_eligible(end)) + .filter(|&end| start < end && end < raw_anchor && request.checkpoint_endpoint_eligible(end)) .map(|end| (end, RetentionRole::Message)) .collect(); if start < request.prompt_tokens && request.prompt_tokens != anchor { @@ -673,21 +715,15 @@ impl RequestScheduler { } }; whole.and_then(|whole| { - let before = Self::interval_prefill_ns( + Self::split_overhead_ns( request, &catalog, terminal_window, left, - endpoint, - )?; - let after = Self::interval_prefill_ns( - request, - &catalog, - terminal_window, + whole, endpoint, right, - )?; - Some(before.saturating_add(after).saturating_sub(whole)) + ) }) }; let Some(split_ns) = split else { @@ -854,17 +890,16 @@ impl RequestScheduler { return Ok(()); } let prompt_tokens = request.prompt_tokens; - let latch = (self.policy.checkpoint_extra_work_fraction == 0.0 - && raw_anchor < prompt_tokens + let latch = (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)); let epoch = request.checkpoints.demand_epoch; let key = request.history.key_at(anchor as u64); if let Some(target) = latch - && request.checkpoints.zero_budget_anchor != Some(target) + && request.checkpoints.budgeted_anchor != Some(target) { - self.request_mut(handle)?.checkpoints.zero_budget_anchor = Some(target); + self.request_mut(handle)?.checkpoints.budgeted_anchor = Some(target); } if let Some(id) = key.and_then(|key| self.cache.ready_by_prefix(&key)) { let promoted = self.cache.checkpoint(id)?.retention_rank().role < RetentionRole::Anchor; @@ -1521,14 +1556,11 @@ mod tests { let request = scheduler.request(handles[0]).unwrap(); let catalog = scheduler.prefill_catalog_costs(request); let max_cap = *scheduler.prefill_catalog.last().unwrap(); - assert!(RequestScheduler::anchor_split_is_zero_cost( - request, - &catalog, - 0, - 0, - max_cap * 10, - max_cap * 4, - )); + assert_eq!( + RequestScheduler::anchor_split_ns(request, &catalog, 0, 0, max_cap * 10, max_cap * 4) + .map(|(_, split)| split), + Some(0) + ); } #[test] @@ -1642,6 +1674,7 @@ mod tests { let (unknown, _, _) = scheduler.checkpoint_selection(scheduler.request(handle).unwrap()); assert_eq!(unknown.initial_prefill_ns, None); assert_eq!(unknown.cuts.len(), 1); + assert_eq!(unknown.cuts[0].endpoint, 896); linear_costs(&mut scheduler); scheduler .advance_to(scheduler.policy.estimate_ttl_ns) @@ -1800,32 +1833,35 @@ mod tests { let handle = scheduler.admit(spec).unwrap(); let (selected, _, _) = scheduler.checkpoint_selection(scheduler.request(handle).unwrap()); assert_eq!(selected.initial_prefill_ns, Some(400)); + // Anchor 896 adds 110 ns of split work (410 + 100 - 400), leaving 90 ns of the 200 ns + // budget for optional cuts; 640 (split 90 + copy 1) exceeds the remaining budget, while + // 768, 512, 256 (split 20), and 1024 fit with exact telescoping total 134 ns <= 200 ns. assert_eq!( selected .cuts .iter() .map(|cut| cut.endpoint) .collect::>(), - [256, 512, 640, 768, 896, 1024] + [256, 512, 768, 896, 1024] ); - assert_eq!(selected.reserved_ns, 115); + assert_eq!(selected.reserved_ns, 134); assert_eq!( selected .cuts .iter() - .find(|cut| cut.endpoint == 256) + .find(|cut| cut.endpoint == 896) .unwrap() .split_ns, - 20 + 110 ); assert_eq!( selected .cuts .iter() - .find(|cut| cut.endpoint == 640) + .find(|cut| cut.endpoint == 256) .unwrap() .split_ns, - 90 + 20 ); scheduler.request_mut(handle).unwrap().phase = RequestPhase::Prefill; let plan = scheduler.plan().unwrap(); @@ -1834,7 +1870,7 @@ mod tests { scheduler.commit(&plan, Fence(1)).unwrap(); let accounting = scheduler.request(handle).unwrap().checkpoint_accounting(); assert_eq!(accounting.extra_spent_ns, 20); - assert_eq!(accounting.reserved_ns, 94); + assert_eq!(accounting.reserved_ns, 113); assert!( scheduler .request(handle) @@ -2026,8 +2062,44 @@ mod tests { assert!(!unknown, "short terminal prefill must not report unknown_cost"); assert!(!budget); assert_eq!(selected.initial_prefill_ns, Some(100_000)); + // Splitting 96 at 94 adds +100% (>5% budget), so anchor falls back to 96. let endpoints: Vec<_> = selected.cuts.iter().map(|cut| cut.endpoint).collect(); - assert_eq!(endpoints, vec![94, 96]); + assert_eq!(endpoints, vec![96]); + scheduler.cancel(handle).unwrap(); + + // With TerminalPrefill(64) = 50_000 and TerminalPrefill(128) = 100_000 measured + // (leaving 256, 512 and all non-terminal Prefill unmeasured), aligned 64 in 128 + // has 0 split cost and captures both Anchor(64) and Endpoint(128) under default 0.05. + let caps64 = [64usize, 128, 256, 512]; + let mut sched64 = super::super::tests::scheduler(1, 128, 16); + sched64.prefill_graphs(&caps64).unwrap(); + sched64.terminal_prefill_graphs(&caps64).unwrap(); + let mut graphs64 = super::super::tests::duration_graphs(1); + let term64: Vec<_> = graphs64 + .iter() + .filter(|g| g.kind == GraphKind::Prefill && caps64.contains(&g.token_capacity)) + .cloned() + .map(|mut g| { + g.kind = GraphKind::TerminalPrefill; + g.name = format!("terminal-{}", g.token_capacity); + g + }) + .collect(); + graphs64.extend(term64); + sched64.graph_durations(&graphs64).unwrap(); + measure(&mut sched64, GraphKind::TerminalPrefill, 64, 50_000); + measure(&mut sched64, GraphKind::TerminalPrefill, 128, 100_000); + measure(&mut sched64, GraphKind::Snapshot, 1, 1_000); + let mut spec64 = super::super::tests::spec(128, 3); + spec64.message_boundaries = vec![64]; + let h64 = sched64.admit(spec64).unwrap(); + let (sel64, unk64, bud64) = + sched64.checkpoint_selection(sched64.request(h64).unwrap()); + assert!(!unk64, "short terminal prefill must not report unknown_cost"); + assert!(!bud64); + assert_eq!(sel64.initial_prefill_ns, Some(100_000)); + let ep64: Vec<_> = sel64.cuts.iter().map(|cut| cut.endpoint).collect(); + assert_eq!(ep64, vec![64, 128]); // Partial terminal catalog [256, 512] (window 128): only TerminalPrefill(512) // and Snapshot(1) are measured; unmeasured non-terminal Prefill(128) and @@ -3008,7 +3080,10 @@ mod tests { ); scheduler.cancel(aligned).unwrap(); - // Part B: nonzero fraction still keeps the unaligned interior boundary (200) as Anchor. + // Part B: nonzero fraction budgets interior anchor splits against the extra-work + // allowance. Splitting 1024 at 200 on [128, 256, 512] adds 128_000 ns (+12.5%): 0.05 + // (51_200 ns) falls back to 1024, while 0.15 (153_600 ns) keeps 200 and accounts for + // its 128_000 ns split cost. let mut nonzero_scheduler = super::super::tests::scheduler(2, 128, 16); linear_costs(&mut nonzero_scheduler); nonzero_scheduler @@ -3020,13 +3095,31 @@ mod tests { let mut nonzero_spec = super::super::tests::spec(1024, 4); nonzero_spec.prompt.fill(77); nonzero_spec.message_boundaries = vec![200]; - let nonzero = nonzero_scheduler.admit(nonzero_spec).unwrap(); - let (nonzero_sel, _, _) = + let nonzero = nonzero_scheduler.admit(nonzero_spec.clone()).unwrap(); + let (over_budget_sel, _, _) = nonzero_scheduler.checkpoint_selection(nonzero_scheduler.request(nonzero).unwrap()); - assert_eq!(nonzero_sel.cuts[0].endpoint, 200); - assert_eq!(nonzero_sel.cuts[0].role, RetentionRole::Anchor); + assert_eq!(over_budget_sel.cuts.len(), 1); + assert_eq!(over_budget_sel.cuts[0].endpoint, 1024); + assert_eq!(over_budget_sel.cuts[0].role, RetentionRole::Anchor); + assert_eq!(over_budget_sel.cuts[0].split_ns, 0); + assert_eq!(over_budget_sel.reserved_ns, 0); nonzero_scheduler.cancel(nonzero).unwrap(); + nonzero_scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.15, + ..Default::default() + }) + .unwrap(); + let in_budget = nonzero_scheduler.admit(nonzero_spec).unwrap(); + let (in_budget_sel, _, _) = + nonzero_scheduler.checkpoint_selection(nonzero_scheduler.request(in_budget).unwrap()); + assert_eq!(in_budget_sel.cuts[0].endpoint, 200); + assert_eq!(in_budget_sel.cuts[0].role, RetentionRole::Anchor); + assert_eq!(in_budget_sel.cuts[0].split_ns, 128_000); + assert_eq!(in_budget_sel.reserved_ns, 128_000 + 1); + nonzero_scheduler.cancel(in_budget).unwrap(); + // Part C: zero fraction with an active decoder and Mixed prefill catalog preserves // the prompt-end fallback (1024) after crossing interior boundary 200. let mut mixed_scheduler = super::super::tests::scheduler(2, 128, 16); @@ -3748,7 +3841,7 @@ mod tests { let (initial_sel, _, _) = scheduler.checkpoint_selection(scheduler.request(handle).unwrap()); assert_eq!( - initial_sel.zero_budget_anchor, + initial_sel.budgeted_anchor, Some((200, 1024, 1024)), "initial zero-budget selection should latch (raw_anchor=200, prompt=1024, chosen=1024)" ); @@ -3814,7 +3907,7 @@ mod tests { assert_eq!( scheduler.checkpoint_cut(scheduler.request(readmitted).unwrap()), None, - "Restore commit must not fabricate a zero_budget_anchor latch at 1124 before prefill completes" + "Restore commit must not fabricate a budgeted_anchor latch at 1124 before prefill completes" ); complete_test_step(&mut scheduler, &restore, Fence(1), 10_000); @@ -3923,7 +4016,7 @@ mod tests { // 1. A cached 1024-token Anchor whose cache parent is a 128-token system-prompt // checkpoint (where 128..640..1024 = 512 + 384 looks zero-cost while 640 is absent) // still refreshes demand_epoch on 1024 instead of returning non-existent 640. - // 2. promote_request_anchor latches zero_budget_anchor on the first step so subsequent + // 2. promote_request_anchor latches budgeted_anchor on the first step so subsequent // decode steps do zero catalog allocations / interval_prefill_ns calls (STRIDE_RUNS == 0). let mut scheduler = super::super::tests::scheduler(2, 128, 16); scheduler.prefill_graphs(&[128, 512]).unwrap(); @@ -4004,9 +4097,9 @@ mod tests { .request(handle) .unwrap() .checkpoints - .zero_budget_anchor, + .budgeted_anchor, Some((640, 1024, 1024)), - "promote_request_anchor must latch zero_budget_anchor on full-prompt cache hits" + "promote_request_anchor must latch budgeted_anchor on full-prompt cache hits" ); complete_test_step(&mut scheduler, &restore, Fence(1), 10_000); @@ -4085,7 +4178,7 @@ mod tests { .request(ep_handle) .unwrap() .checkpoints - .zero_budget_anchor, + .budgeted_anchor, Some((512, 1024, 512)) ); complete_test_step(&mut scheduler, &ep_restore, Fence(4), 10_000); @@ -4105,4 +4198,575 @@ mod tests { ); scheduler.cancel(ep_handle).unwrap(); } + + #[test] + fn default_fraction_budgets_interior_anchor_splits_and_preserves_prefix_and_terminal_capture() { + // SM120-like prefill catalog: fixed weight-read floor makes splitting a 453-token + // turn at raw_anchor=450 add 18 ms (+62%), while splitting a 32K cold prompt at + // raw_anchor=31_997 adds 18 ms (+4.0% <= 5%). + let template = super::super::tests::scheduler(2, 128, 16); + let mut scheduler = RequestScheduler::new( + [11; 32], + SchedulerLimits { + request_slots: 4, + max_active: 4, + max_sequence_tokens: 65_536, + prefill_chunk_size: 16_384, + pages: 4096, + snapshots: 16, + }, + template.capabilities.clone(), + ) + .unwrap(); + let caps = [128usize, 512, 1024, 2048, 4096, 8192, 16_384]; + scheduler.prefill_graphs(&caps).unwrap(); + let mut graphs = super::super::tests::duration_graphs(4); + graphs.retain(|g| g.kind != GraphKind::Prefill || caps.contains(&g.token_capacity)); + for cap in [16_384usize] { + graphs.push(crate::execution::GraphDescriptor { + tuned_bindings: vec![], + confidence_width: 0, + draft_tokens: 0, + packed_token_capacity: 0, + name: format!("prefill{cap}"), + kind: GraphKind::Prefill, + sampling_mode: crate::execution::SamplingMode::General, + handle: 1, + batch_capacity: 1, + token_capacity: cap, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + }); + } + scheduler.measured_graph_durations(&graphs).unwrap(); + measure(&mut scheduler, GraphKind::Prefill, 128, 18_000_000); + measure(&mut scheduler, GraphKind::Prefill, 512, 29_000_000); + measure(&mut scheduler, GraphKind::Prefill, 1024, 39_000_000); + measure(&mut scheduler, GraphKind::Prefill, 2048, 52_000_000); + measure(&mut scheduler, GraphKind::Prefill, 4096, 83_000_000); + measure(&mut scheduler, GraphKind::Prefill, 8192, 135_000_000); + measure(&mut scheduler, GraphKind::Prefill, 16_384, 225_000_000); + measure(&mut scheduler, GraphKind::Snapshot, 1, 4_500_000); + // Default checkpoint_extra_work_fraction is 0.05. + assert_eq!(scheduler.policy.checkpoint_extra_work_fraction, 0.05); + + // Case 1: 453-token turn with raw_anchor=450 (+18 ms > 1.45 ms) falls back to 453, + // runs in a single prefill launch, captures 453 as Anchor, and still allows terminal capture. + let mut short_spec = super::super::tests::spec(453, 8); + short_spec.prompt = (1..=453u32).collect(); + short_spec.message_boundaries = vec![450]; + let short = scheduler.admit(short_spec.clone()).unwrap(); + let (short_sel, _, _) = scheduler.checkpoint_selection(scheduler.request(short).unwrap()); + assert_eq!(short_sel.cuts.len(), 1); + assert_eq!(short_sel.cuts[0].endpoint, 453); + assert_eq!(short_sel.cuts[0].role, RetentionRole::Anchor); + assert_eq!(short_sel.cuts[0].split_ns, 0); + assert_eq!(short_sel.reserved_ns, 0); + + let mut fence_id = 0u64; + let mut prefills = 0usize; + while scheduler.request(short).unwrap().generated_tokens < 4 { + let plan = scheduler.plan().unwrap(); + if plan.kind.is_prefill() { + prefills += 1; + assert_eq!(plan.lanes[0].tokens, 453); + } + fence_id += 1; + let fence = Fence(fence_id); + scheduler.commit(&plan, fence).unwrap(); + let dur = match plan.kind { + GraphKind::Prefill => 29_000_000, + GraphKind::Snapshot => 4_500_000, + GraphKind::Decode => 30_000_000, + _ => 50_000, + }; + complete_test_step(&mut scheduler, &plan, fence, dur); + } + assert_eq!(prefills, 1); + assert_eq!(scheduler.stats().checkpoint_anchor_captures, 1); + let short_hist = scheduler.request(short).unwrap().history.clone(); + assert!(scheduler.cache.ready_by_prefix(&short_hist.key_at(450).unwrap()).is_none()); + assert!(scheduler.cache.ready_by_prefix(&short_hist.key_at(453).unwrap()).is_some()); + // Productive decode (3 steps * 30 ms = 90 ms; total allowance = 0.05 * 119 ms = 5.95 ms >= 4.5 ms) + // funds terminal capture cleanly under default 0.05. + let terminal_row = scheduler.allocate_terminal_capture(short).unwrap(); + assert!(terminal_row.is_some(), "terminal capture must remain funded under default 0.05"); + scheduler.release_snapshot(terminal_row.unwrap()); + scheduler.cancel(short).unwrap(); + + // Turn 2 matching Turn 1's 453-token prompt hits Anchor(453) and latches O(1). + let turn2 = scheduler.admit(short_spec).unwrap(); + assert_eq!(scheduler.request(turn2).unwrap().admission_reused_tokens, 453); + let restore = scheduler.plan().unwrap(); + assert_eq!(restore.kind, GraphKind::Restore); + fence_id += 1; + scheduler.commit(&restore, Fence(fence_id)).unwrap(); + assert_eq!( + scheduler.request(turn2).unwrap().checkpoints.budgeted_anchor, + Some((450, 453, 453)) + ); + complete_test_step(&mut scheduler, &restore, Fence(fence_id), 200_000); + STRIDE_RUNS.set(0); + let resume = scheduler.plan().unwrap(); + assert_eq!(resume.kind, GraphKind::Resume); + fence_id += 1; + scheduler.commit(&resume, Fence(fence_id)).unwrap(); + assert_eq!(STRIDE_RUNS.get(), 0); + scheduler.cancel(turn2).unwrap(); + + // Case 2: 6,400-token prompt with aligned shared system prefix at 2,048 and unaligned + // raw_anchor=6,397: 6,397 (+18 ms > 6.75 ms) falls back to 6,400, while aligned earlier + // message boundary 2,048 (0 split + 4.5 ms copy <= 6.75 ms) is still captured as Message. + let mut med_spec = super::super::tests::spec(6400, 4); + med_spec.prompt = (10_000..16_400u32).collect(); + med_spec.message_boundaries = vec![2048, 6397]; + let med = scheduler.admit(med_spec).unwrap(); + let (med_sel, _, _) = scheduler.checkpoint_selection(scheduler.request(med).unwrap()); + let med_cuts: Vec<_> = med_sel.cuts.iter().map(|c| (c.endpoint, c.role)).collect(); + assert_eq!( + med_cuts, + vec![(2048, RetentionRole::Message), (6400, RetentionRole::Anchor)], + "earlier aligned system-prompt cut must survive interior anchor fallback" + ); + scheduler.cancel(med).unwrap(); + + // Case 3: 32,000-token cold prompt (2 * 16,384 = 450 ms, 5% = 22.5 ms) with + // raw_anchor=31,997 (+18 ms <= 22.5 ms): retains 31,997 as Anchor and accounts its + // 18 ms split in reserved_ns so total extra work stays within 5%. + let mut long_spec = super::super::tests::spec(32_000, 4); + long_spec.prompt = (20_000..52_000u32).collect(); + long_spec.message_boundaries = vec![16_384, 31_997]; + let long = scheduler.admit(long_spec).unwrap(); + let (long_sel, _, _) = scheduler.checkpoint_selection(scheduler.request(long).unwrap()); + assert_eq!(long_sel.initial_prefill_ns, Some(450_000_000)); + let anchor_cut = long_sel + .cuts + .iter() + .find(|c| c.role == RetentionRole::Anchor) + .unwrap(); + assert_eq!(anchor_cut.endpoint, 31_997); + assert_eq!(anchor_cut.split_ns, 18_000_000); + // 16_384 adds 0 split + 4.5 ms copy => 18 ms + 4.5 ms = 22.5 ms == exact 5% budget! + let endpoints: Vec<_> = long_sel.cuts.iter().map(|c| (c.endpoint, c.role)).collect(); + assert_eq!( + endpoints, + vec![(16_384, RetentionRole::Message), (31_997, RetentionRole::Anchor)] + ); + assert_eq!(long_sel.reserved_ns, 22_500_000); + scheduler.cancel(long).unwrap(); + } + + #[test] + fn default_fraction_anchor_guard_revocation_preserves_charged_anchor_split() { + let mut scheduler = super::super::tests::scheduler(1, 128, 16); + scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.5, + ..Default::default() + }) + .unwrap(); + for (tokens, nanos) in [(128, 100), (256, 110), (512, 200)] { + measure(&mut scheduler, GraphKind::Prefill, tokens, nanos); + } + measure(&mut scheduler, GraphKind::Snapshot, 1, 1); + // Boundaries [768, 896]: anchor 896 has split_ns=110, message 768 has split_ns=0, copy=1, + // prompt end 1024 is excluded by setting fraction so only 896+768 fit (allowance=111 -> 0.279). + scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.279, + ..Default::default() + }) + .unwrap(); + let mut spec = super::super::tests::spec(1024, 3); + spec.message_boundaries = vec![768, 896]; + let handle = scheduler.admit(spec).unwrap(); + let (sel, _, _) = scheduler.checkpoint_selection(scheduler.request(handle).unwrap()); + assert_eq!( + sel.cuts.iter().map(|c| (c.endpoint, c.role, c.split_ns)).collect::>(), + vec![(768, RetentionRole::Message, 0), (896, RetentionRole::Anchor, 110)] + ); + assert_eq!(sel.reserved_ns, 111); + + // Execute through 768 (which commits Message(768), spends copy=1, and reserves anchor_guard). + let mut fence_id = 0u64; + while scheduler.request(handle).unwrap().prefix_tokens < 768 { + let plan = scheduler.plan().unwrap(); + fence_id += 1; + let fence = Fence(fence_id); + scheduler.commit(&plan, fence).unwrap(); + complete_test_step(&mut scheduler, &plan, fence, 200); + } + assert!(scheduler.request(handle).unwrap().anchor_guard.is_some()); + assert_eq!(scheduler.request(handle).unwrap().checkpoints.extra_spent_ns, 1); + assert_eq!(scheduler.request(handle).unwrap().checkpoints.reserved_ns, 110); + + // Revoke the anchor guard under memory pressure: the remaining Anchor(896) must keep its + // charged split_ns=110 rather than re-pricing 768..1024 as 90 ns. + assert!(scheduler.revoke_unused_anchor_guards()); + assert!(scheduler.request(handle).unwrap().anchor_guard.is_none()); + let (after_revoke, _, _) = + scheduler.checkpoint_selection(scheduler.request(handle).unwrap()); + assert_eq!( + after_revoke.cuts.iter().map(|c| (c.endpoint, c.role, c.split_ns)).collect::>(), + vec![(896, RetentionRole::Anchor, 110)] + ); + assert_eq!(after_revoke.reserved_ns, 110); + + // Finish prefill through 896: total extra_spent_ns = 1 (copy at 768) + 110 (split at 896). + let prefill_896 = scheduler.plan().unwrap(); + assert_eq!(prefill_896.kind, GraphKind::Prefill); + assert_eq!(prefill_896.lanes[0].tokens, 128); + fence_id += 1; + scheduler.commit(&prefill_896, Fence(fence_id)).unwrap(); + assert_eq!(scheduler.request(handle).unwrap().checkpoints.extra_spent_ns, 111); + assert_eq!(scheduler.request(handle).unwrap().checkpoints.reserved_ns, 0); + scheduler.cancel(handle).unwrap(); + } + + #[test] + fn default_fraction_c16_short_prompts_skip_interior_anchor_tails_and_reach_full_batch() { + let template = super::super::tests::scheduler(16, 128, 32); + let mut scheduler = RequestScheduler::new( + [12; 32], + SchedulerLimits { + request_slots: 16, + max_active: 16, + max_sequence_tokens: 8192, + prefill_chunk_size: 1024, + pages: 1024, + snapshots: 32, + }, + template.capabilities.clone(), + ) + .unwrap(); + scheduler.prefill_graphs(&[128, 512, 1024]).unwrap(); + let mut graphs = super::super::tests::duration_graphs(16); + graphs.retain(|g| g.kind != GraphKind::Prefill || [128, 512, 1024].contains(&g.token_capacity)); + for graph in &mut graphs { + graph.estimated_duration_ns = match (graph.kind, graph.token_capacity) { + (GraphKind::Prefill, 128) => 18_000_000, + (GraphKind::Prefill, 512) => 29_000_000, + (GraphKind::Prefill, 1024) => 39_000_000, + (GraphKind::Decode, _) => 5_500_000 + (graph.batch_capacity as u64) * 800_000, + (GraphKind::Speculative, _) => 6_000_000 + (graph.batch_capacity as u64) * 700_000, + (GraphKind::Snapshot, _) => 300_000, + (GraphKind::Init, _) => 50_000, + _ => 500_000, + }; + } + scheduler.measured_graph_durations(&graphs).unwrap(); + scheduler.enable_speculation(&[1, 2, 4, 8]).unwrap(); + assert_eq!(scheduler.policy.checkpoint_extra_work_fraction, 0.05); + + let mut handles = Vec::new(); + for i in 0..16usize { + let prompt_len = 450 + i; + let mut spec = super::super::tests::spec(prompt_len, 256); + spec.prompt = (0..prompt_len).map(|t| (i * 1000 + t + 1) as u32).collect(); + spec.message_boundaries = vec![prompt_len - 3]; + handles.push(scheduler.admit(spec).unwrap()); + } + + let mut now_ns = 0u64; + let mut prefill_launches = 0usize; + let mut max_decode_batch = 0usize; + let mut decode_steps = 0usize; + for step_idx in 1..=500u64 { + scheduler.advance_to(now_ns).unwrap(); + let Some(plan) = scheduler.plan() else { + break; + }; + let dur_ns = plan.estimated_duration_ns(); + if plan.kind.is_prefill() { + prefill_launches += 1; + } else if matches!(plan.kind, GraphKind::Decode | GraphKind::Speculative) { + decode_steps += 1; + max_decode_batch = max_decode_batch.max(plan.lanes.len()); + } + let fence = Fence(step_idx); + scheduler.commit(&plan, fence).unwrap(); + now_ns += dur_ns; + scheduler.advance_to(now_ns).unwrap(); + complete_test_step(&mut scheduler, &plan, fence, dur_ns); + if max_decode_batch == 16 && decode_steps >= 4 { + break; + } + } + assert_eq!( + prefill_launches, 16, + "default 0.05 fraction must complete 16 short prompts in 16 single-launch prefills" + ); + assert_eq!(max_decode_batch, 16); + assert!( + scheduler.allocate_terminal_capture(handles[0]).unwrap().is_some(), + "terminal capture must stay available under default 0.05" + ); + } + + #[test] + fn anchor_only_multi_chunk_prefill_preserves_split_cost_and_budget() { + let mut scheduler = super::super::tests::scheduler(1, 128, 16); + 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.28, + ..Default::default() + }) + .unwrap(); + + let mut spec = super::super::tests::spec(1024, 3); + spec.message_boundaries = vec![896]; + let handle = scheduler.admit(spec).unwrap(); + + let whole_ns = 400u64; + let budget = allowance(whole_ns, 0.28); + assert_eq!(budget, 112); + + let (initial_sel, _, _) = scheduler.checkpoint_selection(scheduler.request(handle).unwrap()); + assert_eq!( + initial_sel + .cuts + .iter() + .map(|c| (c.endpoint, c.role, c.split_ns)) + .collect::>(), + vec![(896, RetentionRole::Anchor, 110)] + ); + assert_eq!(initial_sel.reserved_ns, 110); + assert_eq!(initial_sel.extra_spent_ns, 0); + + let mut fence_id = 0u64; + let mut actual_prefill_ns = 0u64; + let mut actual_optional_copy_ns = 0u64; + let mut snapshot_endpoints = Vec::new(); + let mut checked_intermediate_768 = false; + + for _ in 0..32 { + let req = scheduler.request(handle).unwrap(); + if req.consumed_tokens == 768 && req.phase == RequestPhase::Prefill { + assert!(req.anchor_guard.is_none()); + assert_eq!(req.checkpoints.extra_spent_ns, 0); + let (mid_sel, _, _) = scheduler.checkpoint_selection(req); + assert_eq!( + mid_sel + .cuts + .iter() + .map(|c| (c.endpoint, c.role, c.split_ns)) + .collect::>(), + vec![(896, RetentionRole::Anchor, 110)], + "intermediate chunk 512..768 must preserve Anchor(896) split_ns=110 without admitting Endpoint(1024)" + ); + assert_eq!(mid_sel.reserved_ns, 110); + checked_intermediate_768 = true; + } + let plan = scheduler.plan().unwrap(); + if matches!(plan.kind, GraphKind::Decode | GraphKind::Speculative | GraphKind::Resume) { + break; + } + let dur = match (plan.kind, plan.token_capacity) { + (GraphKind::Prefill, 128) => { + actual_prefill_ns += 100; + 100 + } + (GraphKind::Prefill, 256) => { + actual_prefill_ns += 110; + 110 + } + (GraphKind::Prefill, 512) => { + actual_prefill_ns += 200; + 200 + } + (GraphKind::Snapshot, 1) => { + let ep = scheduler.request(handle).unwrap().consumed_tokens as usize; + snapshot_endpoints.push(ep); + if ep != 896 { + actual_optional_copy_ns += 5; + } + 5 + } + _ => 1, + }; + fence_id += 1; + let fence = Fence(fence_id); + scheduler.commit(&plan, fence).unwrap(); + complete_test_step(&mut scheduler, &plan, fence, dur); + } + + assert!( + checked_intermediate_768, + "multi-chunk prefill must visit intermediate cursor 768 before Anchor(896)" + ); + assert_eq!( + snapshot_endpoints, + vec![896], + "Endpoint(1024) must not be erroneously admitted when Anchor(896) already consumes 110 of 112 ns" + ); + let actual_extra_ns = actual_prefill_ns.saturating_sub(whole_ns) + actual_optional_copy_ns; + let final_req = scheduler.request(handle).unwrap(); + assert_eq!(actual_extra_ns, 110); + assert_eq!( + final_req.checkpoints.extra_spent_ns, actual_extra_ns, + "recorded extra_spent_ns must equal actual extra GPU work" + ); + assert!( + actual_extra_ns <= budget, + "actual extra GPU work {actual_extra_ns} must stay within allowance {budget}" + ); + assert_eq!(final_req.checkpoints.reserved_ns, 0); + scheduler.cancel(handle).unwrap(); + } + + #[test] + fn zero_split_interior_anchor_retained_when_extra_spent_exceeds_available() { + let mut scheduler = super::super::tests::scheduler(1, 128, 16); + for (tokens, nanos) in [(128, 100), (256, 110), (512, 200)] { + measure(&mut scheduler, GraphKind::Prefill, tokens, nanos); + } + measure(&mut scheduler, GraphKind::Snapshot, 1, 50); + scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.5, + ..Default::default() + }) + .unwrap(); + + let mut spec = super::super::tests::spec(1024, 3); + spec.message_boundaries = vec![256, 512]; + let handle = scheduler.admit(spec).unwrap(); + + // Advance through Message(256), spending split_ns=20 + copy_ns=50 = 70 ns. + let mut fence_id = 0u64; + while scheduler.request(handle).unwrap().prefix_tokens < 256 { + let plan = scheduler.plan().unwrap(); + let dur = match (plan.kind, plan.token_capacity) { + (GraphKind::Prefill, 128) => 100, + (GraphKind::Prefill, 256) => 110, + (GraphKind::Prefill, 512) => 200, + (GraphKind::Snapshot, 1) => 50, + _ => 1, + }; + fence_id += 1; + let fence = Fence(fence_id); + scheduler.commit(&plan, fence).unwrap(); + complete_test_step(&mut scheduler, &plan, fence, dur); + } + assert_eq!(scheduler.request(handle).unwrap().checkpoints.extra_spent_ns, 70); + + // Lower fraction so available (allowance(400, 0.05) = 20) < extra_spent_ns (70), and clear + // reservations/guard so checkpoint_selection_uncached re-evaluates raw_anchor=512. + // From start=256 to 1024, whole=256+512=310 and 256..512 + 512..1024 = 110+200 = 310 (split_ns == 0). + scheduler.policy.checkpoint_extra_work_fraction = 0.05; + let req_mut = scheduler.request_mut(handle).unwrap(); + req_mut.anchor_guard = None; + req_mut.checkpoints.clear_reservations(); + + let (sel, _, _) = scheduler.checkpoint_selection(scheduler.request(handle).unwrap()); + assert_eq!( + sel.cuts + .iter() + .map(|c| (c.endpoint, c.role, c.split_ns)) + .collect::>(), + vec![(512, RetentionRole::Anchor, 0)], + "zero-cost interior anchor must be retained even when extra_spent_ns > available" + ); + assert_eq!(sel.reserved_ns, 0); + assert_eq!(sel.budgeted_anchor, Some((512, 1024, 512))); + assert_eq!( + scheduler.request_anchor_endpoint(scheduler.request(handle).unwrap()), + Some(512) + ); + scheduler.cancel(handle).unwrap(); + } + + #[test] + fn request_anchor_endpoint_matches_selection_with_spent_budget_and_no_latch() { + let mut scheduler = super::super::tests::scheduler(1, 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.30, + ..Default::default() + }) + .unwrap(); + + // Prompt 0..1024 with interior boundary 896: + // whole = 200 + 200 = 400 ns (allowance at 0.30 = 120 ns), + // split_ns = (200 + 110 + 100) + 100 - 400 = 110 ns. + let mut spec = super::super::tests::spec(1024, 3); + spec.message_boundaries = vec![896]; + let handle = scheduler.admit(spec).unwrap(); + + // (a) extra_spent_ns = 20 pushes 20 + 110 = 130 > 120 without a matching latch: + // both request_anchor_endpoint and checkpoint_selection must fall back to 1024. + { + let req = scheduler.request_mut(handle).unwrap(); + req.checkpoints.initial_prefill_ns = Some(400); + req.checkpoints.extra_spent_ns = 20; + req.checkpoints.budgeted_anchor = None; + } + let req = scheduler.request(handle).unwrap(); + let (sel, _, _) = scheduler.checkpoint_selection(req); + assert_eq!(sel.cuts[0].endpoint, 1024); + assert_eq!(scheduler.request_anchor_endpoint(req), Some(1024)); + + // (b) Stale latch (mismatched prompt length) with extra_spent_ns > 0 must also agree. + { + let req = scheduler.request_mut(handle).unwrap(); + req.checkpoints.budgeted_anchor = Some((896, 960, 896)); + } + let req = scheduler.request(handle).unwrap(); + let (sel, _, _) = scheduler.checkpoint_selection(req); + assert_eq!(sel.cuts[0].endpoint, 1024); + assert_eq!(scheduler.request_anchor_endpoint(req), Some(1024)); + + // (c) Smaller initial_prefill_ns = 300 (allowance = 90 < 110) with zero extra_spent_ns: + // both sites must use initial_prefill_ns rather than whole = 400 and fall back to 1024. + { + let req = scheduler.request_mut(handle).unwrap(); + req.checkpoints.initial_prefill_ns = Some(300); + req.checkpoints.extra_spent_ns = 0; + req.checkpoints.budgeted_anchor = None; + } + let req = scheduler.request(handle).unwrap(); + let (sel, _, _) = scheduler.checkpoint_selection(req); + assert_eq!(sel.cuts[0].endpoint, 1024); + assert_eq!(scheduler.request_anchor_endpoint(req), Some(1024)); + + // (d) Fitting spent budget (10 + 110 = 120 <= 120) without a latch retains 896 on both. + { + let req = scheduler.request_mut(handle).unwrap(); + req.checkpoints.initial_prefill_ns = Some(400); + req.checkpoints.extra_spent_ns = 10; + req.checkpoints.budgeted_anchor = None; + } + let req = scheduler.request(handle).unwrap(); + let (sel, _, _) = scheduler.checkpoint_selection(req); + assert_eq!(sel.cuts[0].endpoint, 896); + assert_eq!(scheduler.request_anchor_endpoint(req), Some(896)); + scheduler.cancel(handle).unwrap(); + + // (e) Zero-split interior boundary (512 in 1024, split_ns == 0) remains retained even + // when extra_spent_ns exceeds allowance and no budgeted_anchor latch exists. + let mut zero_split_spec = super::super::tests::spec(1024, 3); + zero_split_spec.message_boundaries = vec![512]; + let zero_handle = scheduler.admit(zero_split_spec).unwrap(); + { + let req = scheduler.request_mut(zero_handle).unwrap(); + req.checkpoints.initial_prefill_ns = Some(400); + req.checkpoints.extra_spent_ns = 1_000; + req.checkpoints.budgeted_anchor = None; + } + let zero_req = scheduler.request(zero_handle).unwrap(); + let (zero_sel, _, _) = scheduler.checkpoint_selection(zero_req); + assert_eq!(zero_sel.cuts[0].endpoint, 512); + assert_eq!(scheduler.request_anchor_endpoint(zero_req), Some(512)); + scheduler.cancel(zero_handle).unwrap(); + } } diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index 99d58599f..46c8e5b9d 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -4830,6 +4830,11 @@ fn terminal_prefill_selects_last_chunk_and_protects_small_tail_window() { #[test] fn terminal_prefill_runs_at_checkpoint_boundary_cut() { let mut s = engine_with_terminal_prefill(&[256, 512]); + s.configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.2, + ..Default::default() + }) + .unwrap(); let handle = s .admit(RequestSpec { prompt: vec![9; 1536], @@ -5243,6 +5248,11 @@ fn short_prefill_tail_caps_service_price_on_decode_transition() { } } set_cost(&mut s, GraphKind::TerminalPrefill, 1, 128, 25 * MS); + s.configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 1.0, + ..Default::default() + }) + .unwrap(); let mut sp = super::tests::spec(30, 64); sp.message_boundaries = vec![28]; let handle = s.admit(sp).unwrap(); @@ -7044,6 +7054,13 @@ fn first_output_wait_scales_by_incumbent_decode_batch_and_chunk_fraction() { fn forced_anchor_cut_preserves_first_output_wait_clock_without_exempting_service_price() { let mut s = interactive_engine(4, false); s.prefill_graphs(&[64, 128, 256, 512, 1024, 2048, 4096]).unwrap(); + // Permit the 202 + 2 interior anchor split explicitly so this test exercises + // wait-clock preservation across a retained anchor cut. + s.configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.50, + ..PolicyConfig::default() + }) + .unwrap(); set_cost(&mut s, GraphKind::Prefill, 1, 64, 5 * MS); set_cost(&mut s, GraphKind::Prefill, 1, 128, 7 * MS); set_cost(&mut s, GraphKind::Prefill, 1, 256, 10 * MS); diff --git a/helios/src/scheduler/tests.rs b/helios/src/scheduler/tests.rs index 14ac3a1f2..3e9450f69 100644 --- a/helios/src/scheduler/tests.rs +++ b/helios/src/scheduler/tests.rs @@ -158,6 +158,31 @@ pub(crate) fn duration_graphs(active: usize) -> Vec, +) { + if let Some(capacities) = prefill_capacities { + scheduler.prefill_graphs(capacities).unwrap(); + } + let mut graphs = duration_graphs(active); + for g in &mut graphs { + if g.kind == GraphKind::Prefill { + g.estimated_duration_ns = 100_000 + g.token_capacity as u64; + } + } + scheduler.measured_graph_durations(&graphs).unwrap(); + scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 1.0, + ..Default::default() + }) + .unwrap(); +} + fn duration_graphs_for_batches(active: usize, batches: &[usize]) -> Vec { let mut graphs = Vec::new(); for &batch in batches @@ -3302,6 +3327,7 @@ fn pinned_checkpoints_survive_eviction_pressure_until_unpinned() { fn prefill_to_publication_boundary(tokens: usize, boundary: usize) -> (RequestScheduler, RequestHandle) { let mut scheduler = host_scheduler(1, 8, 4); + permissive_checkpoint_costs(&mut scheduler, 1, Some(STANDARD_PREFILL_CAPACITIES)); let handle = scheduler .admit(RequestSpec { message_boundaries: vec![boundary], diff --git a/helios/src/scheduler/vision_window_tests.rs b/helios/src/scheduler/vision_window_tests.rs index 22f19ef66..1df43d04f 100644 --- a/helios/src/scheduler/vision_window_tests.rs +++ b/helios/src/scheduler/vision_window_tests.rs @@ -386,6 +386,12 @@ fn window_boundaries_keep_bidirectional_image_spans_inside_one_prefill() { #[test] fn partial_image_prefix_reuse_preserves_canonical_indices_and_only_counts_initial_reuse() { let mut scheduler = scheduler(64, 4); + scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.1, + ..Default::default() + }) + .unwrap(); let images = inputs(12); let endpoint = images[4].token_span.start + 512; let mut specification = specification(&images); diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 28e8e8dba..f477e74cd 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -1539,9 +1539,11 @@ fn packing_sees_reserved_pages_and_pack_failure_retains_submission_until_drain() #[test] fn exact_system_and_prompt_checkpoints_publish_only_after_snapshot_completion() { let fixture = Fixture::new(); + let boundary = fixture.config.limits.prefill_chunk_size; + let prompt_len = boundary + 3; let (sender, receiver) = mpsc::channel(); - let (mut incoming, mut generation) = fixture.incoming(vec![0; 13], 2); - incoming.prompt.message_boundaries = vec![10]; + let (mut incoming, mut generation) = fixture.incoming(vec![0; prompt_len], 2); + incoming.prompt.message_boundaries = vec![boundary]; sender.send(vec![incoming]).unwrap(); let mut worker = fixture.worker(receiver); let mut graphs = crate::model::testing::manifest(&fixture.config).graphs; @@ -1555,7 +1557,7 @@ fn exact_system_and_prompt_checkpoints_publish_only_after_snapshot_completion() advance(&mut worker, GraphKind::Prefill, 2, None); assert_eq!( worker.scheduler.request(handle).unwrap().consumed_tokens, - 10 + boundary as u64 ); assert_eq!(worker.scheduler.stats().message_checkpoints, 0); assert!(!worker.publish().unwrap()); @@ -1565,7 +1567,7 @@ fn exact_system_and_prompt_checkpoints_publish_only_after_snapshot_completion() .iter() .find(|u| u.buffer == "state_expected_consumed") .unwrap(); - assert_eq!(&expected.bytes[..8], &10i64.to_le_bytes()); + assert_eq!(&expected.bytes[..8], &(boundary as i64).to_le_bytes()); assert_eq!(worker.scheduler.stats().message_checkpoints, 0); worker .complete(GraphKind::Snapshot, completion(&worker, &snapshot, 3, None)) @@ -1582,7 +1584,7 @@ fn exact_system_and_prompt_checkpoints_publish_only_after_snapshot_completion() advance(&mut worker, GraphKind::Prefill, 4, Some(1)); assert_eq!( worker.scheduler.request(handle).unwrap().consumed_tokens, - 13 + prompt_len as u64 ); assert_eq!(worker.scheduler.stats().prompt_checkpoints, 0); assert!(!worker.publish().unwrap()); @@ -1595,7 +1597,10 @@ fn exact_system_and_prompt_checkpoints_publish_only_after_snapshot_completion() assert!(!worker.publish().unwrap()); assert_eq!(worker.scheduler.stats().snapshot_publications, 3); let metrics = fixture.metrics.snapshot(false); - assert_eq!((metrics.prefill_tokens, metrics.generated_tokens), (13, 2)); + assert_eq!( + (metrics.prefill_tokens, metrics.generated_tokens), + (prompt_len as u64, 2) + ); let mut finished = 0; while let Ok(event) = generation.events.try_recv() { if let GenerationEvent::Finished { @@ -1613,7 +1618,7 @@ fn exact_system_and_prompt_checkpoints_publish_only_after_snapshot_completion() } } assert_eq!(finished, 1); - let (repeat, _generation) = fixture.incoming(vec![0; 13], 2); + let (repeat, _generation) = fixture.incoming(vec![0; prompt_len], 2); sender.send(vec![repeat]).unwrap(); assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); let live = worker @@ -1622,12 +1627,12 @@ fn exact_system_and_prompt_checkpoints_publish_only_after_snapshot_completion() .unwrap(); assert_eq!( (live.phase, live.reused_prompt_tokens()), - (RequestPhase::Restore, 13) + (RequestPhase::Restore, prompt_len as u64) ); advance(&mut worker, GraphKind::Restore, 8, None); advance(&mut worker, GraphKind::Resume, 9, Some(1)); let metrics = fixture.metrics.snapshot(false); - assert_eq!((metrics.prefill_tokens, metrics.generated_tokens), (13, 3)); + assert_eq!((metrics.prefill_tokens, metrics.generated_tokens), (prompt_len as u64, 3)); } #[test] @@ -3893,6 +3898,13 @@ fn exercise_text_preemption( graph.estimated_duration_ns = if graph.kind == GraphKind::Snapshot { 10 } else { 1000 }; } worker.scheduler.measured_graph_durations(&graphs).unwrap(); + worker + .scheduler + .configure_policy(crate::scheduler::PolicyConfig { + checkpoint_extra_work_fraction: 1.0, + ..Default::default() + }) + .unwrap(); assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); assert_eq!(worker.active.iter().flatten().count(), 2); assert_eq!(worker.scheduler.free_page_count(), 2); diff --git a/verification/helios-lifecycle/check.py b/verification/helios-lifecycle/check.py index 2af7e88f3..0c3bbdf47 100644 --- a/verification/helios-lifecycle/check.py +++ b/verification/helios-lifecycle/check.py @@ -670,10 +670,10 @@ def run_aux(test): "queued lane must retain full target and draft page reservation"), ]) check_mutations(cargo, ROOT / "helios/src/scheduler/checkpoints.rs", CHECKS[7][1], [ - ("dropped multi-chunk zero-budget fallback", - "accounting.zero_budget_anchor = Some((raw_anchor, request.prompt_tokens, chosen));", - "accounting.zero_budget_anchor = None;", - "multi-chunk prefill must retain zero-budget prompt-end anchor fallback"), + ("dropped multi-chunk budgeted-anchor fallback", + "accounting.budgeted_anchor = Some((raw_anchor, request.prompt_tokens, chosen));", + "accounting.budgeted_anchor = None;", + "multi-chunk prefill must retain budgeted-anchor prompt-end fallback"), ]) restored_bin = build_test_binary(cargo) run_observed_checks(restored_bin, directory, args.java, jar, args.jobs)