From f8e4945c607d52305fad61d2b349dd350e0fbc51 Mon Sep 17 00:00:00 2001 From: yatesdr <6937857+yatesdr@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:39:01 -0500 Subject: [PATCH] helios: retain measured snapshot cost after expiry and discover unmeasured cost once Prefill estimates already retain measured durations after TTL expiry and reset their rolling window on the next execution, whereas snapshot-copy cost used ActionCosts::fresh_duration and reverted to None after estimate_ttl_ns (30 s). Any decode longer than 30 s or any idle gap longer than 30 s caused terminal Endpoint captures and prefill Message extras to skip with unknown_cost even though a measured snapshot duration was already recorded. Separately, a warm restart against a persistent host prefix cache (--prefix-cache-disk or --prefix-cache-pool) starts with unmeasured Snapshot costs (nanos == 0); when incoming prompts hit cached anchors, no Anchor snapshot executes and terminal captures remained permanently stuck at unknown_cost. Replace fresh_duration (whose only callers were the three snapshot checks in checkpoints.rs) with ActionCosts::measured_duration, which scans declared batches in ascending order and returns the smallest declared batch with nanos != 0, retaining measured estimates across TTL expiry with parity to prefill pricing while ActionCosts::observe still resets the rolling window on the next run after expiry. For the remaining cold-start case where no Snapshot batch has been measured yet (nanos == 0), track at most one in-flight terminal discovery request via RequestScheduler::snapshot_discovery: Option. When checkpoint_extra_work_fraction > 0 and no discovery is in flight, allocate_terminal_capture prices that single capture at zero and records the handle only if snapshot storage is obtained; snapshot completion, status-3 fallback, finish, and cancel all clear the handle so subsequent requests recover immediately. Update docs/scheduling-runtime-design.md, docs/core-design.md, docs/cli-design.md, and helios/README.md, and add unit tests covering ascending-batch fallback and post-TTL retention, long decode/idle retention, single-flight cold discovery with cancel/storage/zero-fraction recovery, and end-to-end plan -> commit -> complete observation unblocking prefill extras. Related to #534 Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com> Design-Signed-Off-By: yatesdr; design-review=2e5b --- docs/cli-design.md | 4 +- docs/core-design.md | 15 +- docs/scheduling-runtime-design.md | 15 +- helios/README.md | 10 +- helios/src/scheduler.rs | 12 +- helios/src/scheduler/checkpoints.rs | 235 +++++++++++++++++++++++++--- helios/src/scheduler/cost.rs | 118 ++++++++++---- 7 files changed, 348 insertions(+), 61 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index 22ec7ac3a..e0b209176 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -718,7 +718,9 @@ 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 +completed productive decode (allowing at most one in-flight zero-priced discovery +copy when no snapshot cost has been measured yet and the fraction is positive). +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 d68ae6ac9..1f807a511 100644 --- a/docs/core-design.md +++ b/docs/core-design.md @@ -1455,12 +1455,15 @@ 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 +splitting its enclosing interval, plus its snapshot-copy time. Prefill and +snapshot-copy estimates retain measured costs after expiry, as ordinary dispatch +does. Unknown prefill costs or unmeasured snapshot-copy costs exclude prefill +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. When the fraction is positive and snapshot-copy cost has not +been measured yet, terminal capture allows at most one in-flight discovery copy +(priced at zero) to observe it. 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 ace317c9f..e8211498c 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -682,14 +682,23 @@ the natural-fit exploration limits in [Duration estimates](#duration-estimates), 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, applying the unknown-cost anchor and extra-cut rules in -[exact endpoint capture](core-design.md#exact-endpoint-capture). Productive +[exact endpoint capture](core-design.md#exact-endpoint-capture). Both prefill +and snapshot-copy predictions retain measured costs after expiry (using the +smallest measured snapshot batch until the smallest declared batch is observed, +and resetting the rolling window on the next execution). Unknown prefill costs +or unmeasured snapshot-copy costs disable prefill extras while preserving the +selected anchor; when the fraction is positive and no snapshot-copy cost has +been measured yet, terminal capture allows at most one in-flight discovery +capture (priced at zero) so requests whose anchor is already cached can observe +the snapshot cost. 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 -already executed. A row guarded for the later anchor protects it from earlier +If its work allowance is exceeded by the time prefill completes, its copy can be +skipped after the split has already executed. A row guarded for the later anchor +protects it from earlier optional captures; mandatory execution may revoke an unused guard. Armed destinations and in-flight copies retain their rows through GPU completion and cancellation. The alias-aware global allocator diff --git a/helios/README.md b/helios/README.md index d5fe1a76a..e51e89928 100644 --- a/helios/README.md +++ b/helios/README.md @@ -381,9 +381,13 @@ 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 -snapshot rows; the global allocator accounts for snapshot aliases, guards a later -anchor against earlier optional captures, and reclaims unused guards for +distinct terminal capture. Both prefill and snapshot-copy estimates retain +measured costs after expiry; unknown prefill or unmeasured snapshot costs +exclude prefill extras while preserving best-effort anchor retention, and a +positive fraction allows at most one in-flight terminal discovery copy when +snapshot cost is unmeasured. 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` diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index 02796d336..4cc453646 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -668,6 +668,7 @@ pub struct RequestScheduler { mixed_catalog: Vec<(usize, usize, usize)>, forecasts: rounds::Forecasts, costs: cost::ActionCosts, + snapshot_discovery: Option, refresh: refresh::RefreshState, tickets: HashMap, track_publications: bool, @@ -763,6 +764,7 @@ impl RequestScheduler { mixed_catalog: Vec::new(), forecasts, costs: cost::ActionCosts::default(), + snapshot_discovery: None, refresh: refresh::RefreshState::default(), tickets: HashMap::new(), track_publications: false, @@ -2790,7 +2792,9 @@ impl RequestScheduler { request.error_code = Some(record.error_code); request.terminal_snapshot_ready = false; request.phase = RequestPhase::Finishing; - + if self.snapshot_discovery == Some(lane.request) { + self.snapshot_discovery = None; + } } else if kind == GraphKind::Snapshot { if request.boundary_capture.is_some() { boundaries.push(lane.request); @@ -2798,6 +2802,9 @@ impl RequestScheduler { request.terminal_snapshot_ready = true; request.phase = RequestPhase::Finishing; self.stats.checkpoint_endpoint_captures += 1; + if self.snapshot_discovery == Some(lane.request) { + self.snapshot_discovery = None; + } } } else { if kind == GraphKind::Vision { @@ -3181,6 +3188,9 @@ impl RequestScheduler { } fn retire(&mut self, handle: RequestHandle, publish: bool) -> Result> { + if self.snapshot_discovery == Some(handle) { + self.snapshot_discovery = None; + } if self.request(handle)?.phase == RequestPhase::Inbound { for ticket in self.tickets.values_mut() { ticket.waiters.retain(|(waiter, _)| *waiter != handle); diff --git a/helios/src/scheduler/checkpoints.rs b/helios/src/scheduler/checkpoints.rs index 4c78290ad..10f888c8b 100644 --- a/helios/src/scheduler/checkpoints.rs +++ b/helios/src/scheduler/checkpoints.rs @@ -678,7 +678,7 @@ impl RequestScheduler { let Some(prefill) = accounting.initial_prefill_ns else { return (accounting, true, false); }; - let Some(copy_ns) = self.costs.fresh_duration(GraphKind::Snapshot, 1) else { + let Some(copy_ns) = self.costs.measured_duration(GraphKind::Snapshot, 1) else { return (accounting, true, false); }; let mut unknown = false; @@ -1013,7 +1013,7 @@ impl RequestScheduler { if capture.role == RetentionRole::Anchor { return Ok(true); } - if self.costs.fresh_duration(GraphKind::Snapshot, 1).is_none() { + if self.costs.measured_duration(GraphKind::Snapshot, 1).is_none() { return Ok(false); } let accounting = &self.request(handle)?.checkpoints; @@ -1066,6 +1066,13 @@ impl RequestScheduler { } } + fn snapshot_discovery_in_flight(&self) -> bool { + self.snapshot_discovery.is_some_and(|handle| { + self.request(handle) + .is_ok_and(|request| request.phase != RequestPhase::Finishing) + }) + } + pub(super) fn allocate_terminal_capture( &mut self, handle: RequestHandle, @@ -1080,11 +1087,12 @@ impl RequestScheduler { let (mut accounting, _, _) = self.checkpoint_selection(request); accounting.cuts.clear(); accounting.reserved_ns = 0; - let Some(cost) = self.costs.fresh_duration(GraphKind::Snapshot, 1) else { - self.stats.checkpoint_skip_unknown_cost += 1; - return Ok(None); - }; - let Some(prefill) = accounting.initial_prefill_ns else { + let measured = self.costs.measured_duration(GraphKind::Snapshot, 1); + let discovering = measured.is_none() + && self.policy.checkpoint_extra_work_fraction > 0.0 + && !self.snapshot_discovery_in_flight(); + let cost = measured.or_else(|| discovering.then_some(0)); + let (Some(cost), Some(prefill)) = (cost, accounting.initial_prefill_ns) else { self.stats.checkpoint_skip_unknown_cost += 1; return Ok(None); }; @@ -1110,6 +1118,9 @@ impl RequestScheduler { }; let snapshot = rows.and_then(|rows| rows.first().copied()); if snapshot.is_some() { + if discovering { + self.snapshot_discovery = Some(handle); + } accounting.reserved_ns = cost; let request = self.request_mut(handle)?; request.checkpoint_copy_ns = cost; @@ -1680,7 +1691,7 @@ mod tests { } #[test] - fn unknown_prefill_or_stale_snapshot_cost_disables_extras() { + fn unknown_prefill_or_unmeasured_snapshot_cost_disables_extras() { let mut scheduler = super::super::tests::scheduler(1, 128, 16); let mut spec = super::super::tests::spec(1024, 3); spec.message_boundaries = vec![128, 256, 512, 896]; @@ -1692,20 +1703,20 @@ mod tests { 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) - .unwrap(); - let (stale, _, _) = scheduler.checkpoint_selection(scheduler.request(handle).unwrap()); - assert_eq!(stale.initial_prefill_ns, Some(1_024_000)); - assert_eq!(stale.cuts.len(), 1); + measure(&mut scheduler, GraphKind::Snapshot, 1, 0); + let (unmeasured_snap, _, _) = + scheduler.checkpoint_selection(scheduler.request(handle).unwrap()); + assert_eq!(unmeasured_snap.initial_prefill_ns, Some(1_024_000)); + assert_eq!(unmeasured_snap.cuts.len(), 1); } #[test] - fn measured_prefill_costs_keep_extras_available_after_idle() { + fn measured_prefill_and_snapshot_costs_keep_extras_available_after_idle() { let mut scheduler = super::super::tests::scheduler(1, 128, 16); linear_costs(&mut scheduler); - scheduler.advance_to(scheduler.policy.estimate_ttl_ns).unwrap(); - measure(&mut scheduler, GraphKind::Snapshot, 1, 1); + scheduler + .advance_to(scheduler.policy.estimate_ttl_ns) + .unwrap(); let mut spec = super::super::tests::spec(1024, 3); spec.message_boundaries = vec![128, 256, 512, 896]; let handle = scheduler.admit(spec).unwrap(); @@ -1715,7 +1726,11 @@ mod tests { assert!(!budget); assert_eq!(selected.initial_prefill_ns, Some(1_024_000)); assert_eq!( - selected.cuts.iter().map(|cut| cut.endpoint).collect::>(), + selected + .cuts + .iter() + .map(|cut| cut.endpoint) + .collect::>(), [128, 256, 512, 896, 1024] ); } @@ -4924,4 +4939,188 @@ mod tests { assert_eq!(scheduler.request_anchor_endpoint(req_pres), Some(896)); scheduler.cancel(h_pres).unwrap(); } + + #[test] + fn measured_snapshot_cost_retains_terminal_captures_after_long_decode_or_idle() { + let mut scheduler = super::super::tests::scheduler(2, 128, 4); + linear_costs(&mut scheduler); + measure(&mut scheduler, GraphKind::Snapshot, 1, 100_000); + + // Advance past estimate_ttl_ns (e.g. >30 s decode or inter-turn pause). + let ttl = scheduler.policy.estimate_ttl_ns; + scheduler.advance_to(ttl).unwrap(); + assert_eq!( + scheduler.costs.measured_duration(GraphKind::Snapshot, 1), + Some(100_000) + ); + + // Work-budget check still enforces retained cost (allowance = 51_200 < 100_000). + let h_small = scheduler.admit(super::super::tests::spec(1024, 3)).unwrap(); + scheduler.request_mut(h_small).unwrap().consumed_tokens = 1027; + assert_eq!(scheduler.allocate_terminal_capture(h_small).unwrap(), None); + assert_eq!(scheduler.stats().checkpoint_skip_work_budget, 1); + assert_eq!(scheduler.stats().checkpoint_skip_unknown_cost, 0); + + // Requests fitting the retained-cost budget allocate terminal captures without + // unknown_cost skips even after TTL expiry. + let h_long = scheduler.admit(super::super::tests::spec(512, 16)).unwrap(); + { + let req = scheduler.request_mut(h_long).unwrap(); + req.consumed_tokens = 528; + req.checkpoints.productive_decode_ns = 35_000_000_000; + } + let row = scheduler + .allocate_terminal_capture(h_long) + .unwrap() + .expect("retained snapshot cost must allow terminal capture after long decode"); + assert_eq!(scheduler.request(h_long).unwrap().checkpoint_copy_ns, 100_000); + assert_eq!(scheduler.stats().checkpoint_skip_unknown_cost, 0); + scheduler.release_snapshot(row); + scheduler.cancel(h_small).unwrap(); + scheduler.cancel(h_long).unwrap(); + } + + fn clear_snapshot_costs(scheduler: &mut RequestScheduler) { + for batch in scheduler.costs.batches(GraphKind::Snapshot).to_vec() { + scheduler.costs.set_measured( + &ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Snapshot, + batch_capacity: batch, + token_capacity: 1, + packed_token_capacity: 0, + mixed: None, + lanes: vec![], + requires_feedback: false, + }, + 0, + ); + } + } + + #[test] + fn unmeasured_snapshot_cost_allows_one_inflight_terminal_discovery_and_recovers_on_cancel() { + let mut scheduler = super::super::tests::scheduler(3, 128, 3); + linear_costs(&mut scheduler); + // Simulate a warm restart whose restored anchor covers the prompt while no + // Snapshot has been observed yet (`nanos == 0`). + clear_snapshot_costs(&mut scheduler); + assert_eq!(scheduler.costs.measured_duration(GraphKind::Snapshot, 1), None); + + let anchor = publish_test_checkpoint(&mut scheduler, None, 7, 512, RetentionRole::Anchor); + let mut spec = super::super::tests::spec(512, 16); + spec.prompt.fill(7); + spec.message_boundaries = vec![512]; + let h1 = scheduler.admit(spec.clone()).unwrap(); + let h2 = scheduler.admit(spec).unwrap(); + for h in [h1, h2] { + let req = scheduler.request_mut(h).unwrap(); + assert_eq!(req.prefix, Some(anchor)); + req.consumed_tokens = 528; + req.checkpoints.productive_decode_ns = 10_000_000; + } + + // Storage refusal must not claim the single in-flight discovery slot. + let held1 = scheduler.reserve_snapshot(0).unwrap(); + let held2 = scheduler.reserve_snapshot(0).unwrap(); + assert_eq!(scheduler.allocate_terminal_capture(h1).unwrap(), None); + assert_eq!(scheduler.stats().checkpoint_skip_storage, 1); + assert_eq!(scheduler.stats().checkpoint_skip_unknown_cost, 0); + scheduler.release_snapshot(held1); + scheduler.release_snapshot(held2); + + // First eligible terminal capture claims discovery; concurrent second skips. + let row1 = scheduler + .allocate_terminal_capture(h1) + .unwrap() + .expect("first unmeasured terminal capture must run cold discovery"); + assert_eq!(scheduler.request(h1).unwrap().checkpoint_copy_ns, 0); + assert_eq!(scheduler.allocate_terminal_capture(h2).unwrap(), None); + assert_eq!(scheduler.stats().checkpoint_skip_unknown_cost, 1); + + // Cancelling the in-flight discovery request immediately frees discovery for h2. + scheduler.release_snapshot(row1); + scheduler.cancel(h1).unwrap(); + let row2 = scheduler + .allocate_terminal_capture(h2) + .unwrap() + .expect("cancelling discovery request must immediately release discovery slot"); + scheduler.release_snapshot(row2); + scheduler.cancel(h2).unwrap(); + + // Zero extra-work fraction must never discover unmeasured snapshot cost. + let mut zero = super::super::tests::scheduler(1, 128, 4); + zero.configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.0, + ..Default::default() + }) + .unwrap(); + linear_costs(&mut zero); + clear_snapshot_costs(&mut zero); + let h_zero = zero.admit(super::super::tests::spec(512, 16)).unwrap(); + { + let req = zero.request_mut(h_zero).unwrap(); + req.consumed_tokens = 528; + req.checkpoints.productive_decode_ns = 10_000_000; + } + assert_eq!(zero.allocate_terminal_capture(h_zero).unwrap(), None); + assert_eq!(zero.stats().checkpoint_skip_unknown_cost, 1); + zero.cancel(h_zero).unwrap(); + } + + #[test] + fn terminal_snapshot_discovery_end_to_end_plan_commit_complete_unblocks_subsequent_captures() { + let mut scheduler = super::super::tests::scheduler(2, 128, 8); + linear_costs(&mut scheduler); + // Simulate a warm restart: Anchor checkpoint is already resident, Snapshot is unmeasured. + clear_snapshot_costs(&mut scheduler); + assert_eq!(scheduler.costs.measured_duration(GraphKind::Snapshot, 1), None); + + let anchor = publish_test_checkpoint(&mut scheduler, None, 11, 512, RetentionRole::Anchor); + let mut spec = super::super::tests::spec(512, 2); + spec.prompt.fill(11); + spec.message_boundaries = vec![512]; + let h1 = scheduler.admit(spec).unwrap(); + assert_eq!(scheduler.request(h1).unwrap().prefix, Some(anchor)); + + // Drive h1 end-to-end through Restore -> Resume -> Decode -> terminal Snapshot -> Finish. + let mut saw_snapshot = false; + let mut fence = 1u64; + for _ in 0..16 { + if scheduler.request(h1).unwrap().phase == RequestPhase::Finishing { + break; + } + let step = scheduler.plan().expect("scheduler must produce a step"); + if step.kind == GraphKind::Snapshot { + saw_snapshot = true; + } + scheduler.commit(&step, Fence(fence)).unwrap(); + complete_test_step(&mut scheduler, &step, Fence(fence), 25_000); + fence += 1; + } + assert!( + saw_snapshot, + "warm-restart request hitting cached anchor must execute terminal discovery Snapshot" + ); + assert_eq!( + scheduler.costs.measured_duration(GraphKind::Snapshot, 1), + Some(25_000) + ); + assert_eq!(scheduler.stats().checkpoint_endpoint_captures, 1); + assert!(scheduler.finish(h1).unwrap().is_some()); + + // Subsequent request with multiple messages now sees measured Snapshot cost and + // enables prefill Message extras without any manual measure(...) call. + let mut follow_spec = super::super::tests::spec(1024, 3); + follow_spec.message_boundaries = vec![128, 256, 512, 896]; + let h2 = scheduler.admit(follow_spec).unwrap(); + let (selected, unknown, _) = + scheduler.checkpoint_selection(scheduler.request(h2).unwrap()); + assert!(!unknown); + assert!( + selected.cuts.len() > 1, + "observed Snapshot cost must immediately unblock prefill extras" + ); + scheduler.cancel(h2).unwrap(); + } } diff --git a/helios/src/scheduler/cost.rs b/helios/src/scheduler/cost.rs index c31539568..2e7211b17 100644 --- a/helios/src/scheduler/cost.rs +++ b/helios/src/scheduler/cost.rs @@ -865,11 +865,15 @@ impl ActionCosts { self.entry(key).is_some_and(|estimate| estimate.fresh(self.now_ns, self.ttl_ns)) } - pub fn fresh_duration(&self, kind: GraphKind, tokens: usize) -> Option { - let batch = self.batches(kind).first().copied()?; - let key = Key { drafts: 0, kind, batch, tokens, prefill: 0, packed: 0 }; - self.entry(key).filter(|estimate| estimate.fresh(self.now_ns, self.ttl_ns)) - .map(|estimate| estimate.nanos) + /// Returns the smallest declared batch with a positive measured duration, + /// retaining measured estimates after `ttl_ns` expiry just like prefill costs. + pub fn measured_duration(&self, kind: GraphKind, tokens: usize) -> Option { + self.batches(kind).iter().find_map(|&batch| { + let key = Key { drafts: 0, kind, batch, tokens, prefill: 0, packed: 0 }; + self.entry(key) + .map(|estimate| estimate.nanos) + .filter(|&nanos| nanos != 0) + }) } pub fn stale_keys(&self) -> impl Iterator + '_ { @@ -1038,37 +1042,93 @@ mod tests { assert_eq!(reversed.packed_round_duration(16, 6), Some(18_000_000)); } - #[test] - fn fresh_duration_uses_smallest_declared_batch_when_batch_one_is_absent() { - let graphs = vec![GraphDescriptor { - name: "snapshot-b2".into(), - kind: GraphKind::Snapshot, - sampling_mode: SamplingMode::General, - confidence_width: 0, - draft_tokens: 0, - handle: 1, - batch_capacity: 2, - token_capacity: 1, - packed_token_capacity: 0, - prefill_capacity: 0, - estimated_duration_ns: 0, - input_bindings: vec![], - tuned_bindings: vec![], - }]; - let mut costs = ActionCosts::prepared(&graphs, 1).unwrap(); - let step = ScheduledStep { + fn snapshot_fixture(batches: &[usize]) -> ActionCosts { + let graphs: Vec<_> = batches + .iter() + .map(|&batch| GraphDescriptor { + name: format!("snapshot-b{batch}"), + kind: GraphKind::Snapshot, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 1, + batch_capacity: batch, + token_capacity: 1, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }) + .collect(); + ActionCosts::prepared(&graphs, 1).unwrap() + } + + fn snapshot_step(batch: usize) -> ScheduledStep { + ScheduledStep { draft_tokens: 0, kind: GraphKind::Snapshot, - batch_capacity: 2, + batch_capacity: batch, token_capacity: 1, packed_token_capacity: 0, mixed: None, lanes: vec![], requires_feedback: false, - }; - assert_eq!(costs.fresh_duration(GraphKind::Snapshot, 1), None); - costs.set_measured(&step, 750_000); - assert_eq!(costs.fresh_duration(GraphKind::Snapshot, 1), Some(750_000)); + } + } + + #[test] + fn measured_duration_uses_smallest_measured_batch_and_retains_after_ttl() { + use crate::execution::ExecutionTiming; + + // Absent batch 1 falls back to batch 2. + let mut b2_only = snapshot_fixture(&[2]); + let step_b2 = snapshot_step(2); + assert_eq!(b2_only.measured_duration(GraphKind::Snapshot, 1), None); + b2_only.set_measured(&step_b2, 750_000); + assert_eq!( + b2_only.measured_duration(GraphKind::Snapshot, 1), + Some(750_000) + ); + + // Multi-batch catalog falls back to a measured wider batch when batch 1 is + // still unmeasured, prefers batch 1 once observed, retains after ttl expiry, + // and resets its rolling window on the next observation after expiry. + let mut costs = snapshot_fixture(&[1, 4]); + let ttl = 30_000_000_000u64; + costs.advance_to(0, ttl); + assert_eq!(costs.measured_duration(GraphKind::Snapshot, 1), None); + + let step_b1 = snapshot_step(1); + let step_b4 = snapshot_step(4); + costs.set_measured(&step_b4, 900_000); + assert_eq!( + costs.measured_duration(GraphKind::Snapshot, 1), + Some(900_000) + ); + + costs.set_measured(&step_b1, 400_000); + assert_eq!( + costs.measured_duration(GraphKind::Snapshot, 1), + Some(400_000) + ); + + costs.advance_to(ttl, ttl); + assert_eq!( + costs.measured_duration(GraphKind::Snapshot, 1), + Some(400_000) + ); + + let mut gpu_ns = [None; 16]; + gpu_ns[0] = Some(550_000); + costs.observe( + &step_b1, + ExecutionTiming { gpu_ns, wall_ns: 550_000, queued: false, readiness: None }, + ); + assert_eq!( + costs.measured_duration(GraphKind::Snapshot, 1), + Some(550_000) + ); } #[test]