diff --git a/crates/cuda-driver/src/device_buffer.rs b/crates/cuda-driver/src/device_buffer.rs index 4f4af620..dd7fb524 100644 --- a/crates/cuda-driver/src/device_buffer.rs +++ b/crates/cuda-driver/src/device_buffer.rs @@ -73,24 +73,33 @@ impl DeviceBuffer<'_> { /// synchronization with the same poisoning/leak rule as whole-buffer reads; /// a failed synchronization never returns its bytes. pub fn copy_to_range(&self, offset: usize, output: &mut [u8]) -> Result<()> { + let staging = self.copy_range_staged(offset, output.len())?; + output.copy_from_slice(&staging); + Ok(()) + } + /// `copy_to_range` that hands the completed staging over instead of copying it into a second buffer: the same + /// transfer, synchronization and poisoning/leak rule, the same bytes, one allocation and one copy fewer. + pub fn copy_to_range_owned(&self, offset: usize, bytes: usize) -> Result> { + self.copy_range_staged(offset, bytes) + } + fn copy_range_staged(&self, offset: usize, bytes: usize) -> Result> { if self.context.poisoned.get() { return Err(Error::ContextPoisoned); } - let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, output.len())?; + let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, bytes)?; let mut staging = Vec::new(); - staging.try_reserve_exact(output.len()).map_err(|_| Error::HostAllocation)?; - staging.resize(output.len(), 0); + staging.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; + staging.resize(bytes, 0); let guard = self.context.enter()?; let copy = self.context.driver.api.copy_to(handle, &mut staging); let sync = self.context.driver.api.synchronize(); if sync.is_err() { self.context.poisoned.set(true); std::mem::forget(staging); - return combine(combine(copy, sync), guard.finish()); + return combine(combine(copy, sync), guard.finish()).map(|()| Vec::new()); } combine(copy, guard.finish())?; - output.copy_from_slice(&staging); - Ok(()) + Ok(staging) } pub fn copy_to(&self, output: &mut [u8]) -> Result<()> { let staging = self.staging(output.len())?; diff --git a/crates/cuda-driver/src/exact_fill.rs b/crates/cuda-driver/src/exact_fill.rs new file mode 100644 index 00000000..a9623a19 --- /dev/null +++ b/crates/cuda-driver/src/exact_fill.rs @@ -0,0 +1,93 @@ +//! A byte vector of a size known up front, filled by a copy without first being filled with zeros. +//! +//! The prefix-cache export (`OriginalQsaMappedJournal::export_pages_fast`) writes every byte of a fresh buffer. The +//! usual `resize(n, 0)` then touches the whole buffer once for nothing (a memset and the page faults of a fresh +//! allocation) before the copy touches it again. +use crate::{Error, Result}; +use std::mem::MaybeUninit; + +/// `out` becomes exactly `total` bytes written by `fill` into its spare capacity, with no zero fill first. +/// +/// `fill` gets `total` writable bytes and returns how many leading bytes it initialised. Anything but `total`, or an +/// error, leaves `out` empty: a half-written buffer is never exposed. A reused `out` keeps its capacity. +pub(crate) fn fill_exact( + out: &mut Vec, + total: usize, + fill: impl FnOnce(&mut [MaybeUninit]) -> Result, +) -> Result<()> { + out.clear(); + out.try_reserve_exact(total).map_err(|_| Error::HostAllocation)?; + let written = fill(&mut out.spare_capacity_mut()[..total])?; + if written != total { + return Err(Error::InvalidSize); + } + // SAFETY: `fill` reported that it initialised the first `total` bytes of the spare capacity, `total` bytes were + // reserved above, and `u8` has no invalid bit pattern. + unsafe { out.set_len(total) }; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A source split in pieces like the K/V page image: the pieces of the pattern in order. + fn pattern(len: usize) -> Vec { + (0..len).map(|i| (i.wrapping_mul(31) ^ (i >> 7)) as u8).collect() + } + + /// Copies `pieces` consecutive runs of `source` into `dst` the way the export copies its four runs. + fn copy_runs(source: &[u8], runs: &[usize], dst: &mut [MaybeUninit]) -> Result { + let (mut at, mut rest) = (0, dst); + for &n in runs { + let (piece, tail) = rest.split_at_mut(n); + for (d, s) in piece.iter_mut().zip(&source[at..at + n]) { + d.write(*s); + } + (at, rest) = (at + n, tail); + } + Ok(at) + } + + #[test] + fn the_unzeroed_fill_gives_the_bytes_of_the_zero_filled_copy() { + let source = pattern(4 * 1056 * 3); + let runs = [3 * 2048, 3 * 2048, 3 * 64, 3 * 64]; + let mut zeroed = vec![0u8; source.len()]; + zeroed.copy_from_slice(&source); + let mut fast = Vec::new(); + fill_exact(&mut fast, source.len(), |dst| copy_runs(&source, &runs, dst)).unwrap(); + assert_eq!(fast, zeroed); + assert_eq!(fast.len(), 4 * 1056 * 3); + } + + #[test] + fn a_reused_buffer_is_replaced_whatever_it_held_and_keeps_its_capacity() { + let source = pattern(512); + let mut out = vec![0xAAu8; 4096]; + let capacity = out.capacity(); + fill_exact(&mut out, 512, |dst| copy_runs(&source, &[256, 256], dst)).unwrap(); + assert_eq!(out, source); + assert_eq!(out.capacity(), capacity, "no new allocation for a smaller export"); + } + + #[test] + fn a_short_or_failed_fill_leaves_the_buffer_empty() { + let source = pattern(64); + let mut out = vec![1u8; 8]; + let short = fill_exact(&mut out, 64, |dst| copy_runs(&source, &[32], dst)); + assert!(matches!(short, Err(Error::InvalidSize))); + assert!(out.is_empty()); + let failed = fill_exact(&mut out, 64, |_| Err(Error::ContextPoisoned)); + assert!(matches!(failed, Err(Error::ContextPoisoned))); + assert!(out.is_empty()); + } + + #[test] + fn a_size_that_cannot_be_reserved_is_a_host_allocation_error() { + let mut out = Vec::new(); + let refused = fill_exact(&mut out, usize::MAX, |_| Ok(0)); + assert!(matches!(refused, Err(Error::HostAllocation))); + assert!(out.is_empty()); + } +} diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index b5fdcd71..3a861df7 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -182,6 +182,9 @@ mod qsa_index_ffi; mod qsa_prompt_index; // Genuine page4 INT8 owners and literal Original prompt/decode programs. +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[allow(unsafe_code)] +mod exact_fill; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod kv_stream_gpu; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] diff --git a/crates/cuda-driver/src/qsa_mapped_journal.rs b/crates/cuda-driver/src/qsa_mapped_journal.rs index a89a830c..37e8b675 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal.rs @@ -136,6 +136,14 @@ mod parked_tests { assert_eq!(*out, sub_span(kv, pages, 100, 150)); // beyond the reachable end is refused assert!(journal.export_pages(500, 13, out).is_err()); + // the fast export (drained context, no zero fill) returns the same bytes and refuses the same spans + let mut fast = vec![7u8; 3]; + journal.export_pages_fast(0, pages, &mut fast).unwrap(); + assert_eq!(fast, kv, "the fast export is byte for byte the export"); + journal.export_pages_fast(100, 50, &mut fast).unwrap(); + assert_eq!(fast, sub_span(kv, pages, 100, 150)); + assert!(journal.export_pages_fast(500, 13, &mut fast).is_err()); + assert!(journal.export_pages_fast(0, 0, &mut fast).is_err()); } /// Rolled back, the image is written back in two pieces, and malformed spans are refused. @@ -165,6 +173,16 @@ mod parked_tests { assert_eq!(out, kv); } + /// The fast export of the index image returns the rows of the export and refuses the same spans. + fn fast_rows_match(index: &OriginalQsaResidentIndex<'_>, rows: &[u8]) { + let (row, mut fast) = (OriginalQsaResidentIndex::ROW_BYTES, vec![7u8; 3]); + index.export_rows_fast(0, rows.len() / row, &mut fast).unwrap(); + assert_eq!(fast, rows, "the fast export is byte for byte the export"); + index.export_rows_fast(10, 20, &mut fast).unwrap(); + assert_eq!(fast, rows[10 * row..30 * row]); + assert!(index.export_rows_fast(rows.len() / row, 1, &mut fast).is_err(), "rows beyond end / 4 are refused"); + } + /// The index: pooled rows below end/4 plus a 2564-byte tail, written back whole and then in part. fn index_round_trip<'c>( index: &mut OriginalQsaResidentIndex<'c>, @@ -181,6 +199,7 @@ mod parked_tests { index.validate_checkpoint(&checkpoint).unwrap(); index.export_rows(0, cells / 4, out).unwrap(); assert_eq!(*out, rows, "the pooled rows come back"); + fast_rows_match(index, &rows); assert_eq!(index.export_tail(&checkpoint).unwrap(), tail_bytes, "the tail round-trips through the image"); // partial write-back: only the second half of the rows, on top of an image that already holds the first let second = rows[(cells / 8) * OriginalQsaResidentIndex::ROW_BYTES..].to_vec(); diff --git a/crates/cuda-driver/src/qsa_mapped_journal/original_qsa_mapped_journal.rs b/crates/cuda-driver/src/qsa_mapped_journal/original_qsa_mapped_journal.rs index 9f2c3b80..d49a700b 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal/original_qsa_mapped_journal.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal/original_qsa_mapped_journal.rs @@ -189,11 +189,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { pub const HOST_PAGE_BYTES: usize = QSA_PROMPT_HOST_PAGE_BYTES; /// Copy the pages `first_page..first_page + pages` of the reachable prefix out of the host image. pub fn export_pages(&self, first_page: usize, pages: usize, out: &mut Vec) -> Result<()> { - self.validate_context(self.owner.context)?; - // whole pages up to the one holding the last reachable cell (a request-end checkpoint ends inside a page) - if pages == 0 || first_page.checked_add(pages).is_none_or(|e| e > self.end.div_ceil(4)) { - return Err(Error::InvalidQwenShape); - } + self.check_export(first_page, pages)?; // the GPU wrote these cells through the mapped alias; every public writer drains, this keeps the read ordered // after it { @@ -217,6 +213,35 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { } Ok(()) } + /// The journal is this context's and the pages lie in the reachable prefix: whole pages up to the one holding the + /// last reachable cell (a request-end checkpoint ends inside a page). + fn check_export(&self, first_page: usize, pages: usize) -> Result<()> { + self.validate_context(self.owner.context)?; + if pages == 0 || first_page.checked_add(pages).is_none_or(|e| e > self.end.div_ceil(4)) { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + /// `export_pages` for a caller that has drained the context since the last enqueue (one + /// `Context::synchronize` for all the layers of a park, not one per layer) and for a buffer that is only ever + /// written by the copy: the bytes are the same as `export_pages`, with no synchronize and no zero fill first. + /// With an undrained context the cells the GPU wrote last may not have landed: the caller owns that ordering. + pub fn export_pages_fast(&self, first_page: usize, pages: usize, out: &mut Vec) -> Result<()> { + self.check_export(first_page, pages)?; + let m = self.owner.mapped.as_ref().ok_or(Error::ContextPoisoned)?; + let offsets = super::super::offsets()?; + let _p = crate::host_profile::span("export.copy_fast"); + crate::exact_fill::fill_exact(out, pages * Self::HOST_PAGE_BYTES, |dst| { + let mut rest = dst; + let mut written = 0; + for (i, &page) in super::super::PAGE.iter().enumerate() { + let (run, tail) = rest.split_at_mut(pages * page); + m.read_uninit(offsets[i] + first_page * page, run)?; + (written, rest) = (written + run.len(), tail); + } + Ok(written) + }) + } /// Put parked spans `(first_page, bytes)` back into the host image and make the journal's reachable prefix end at /// `end` cells: the cells below `end` that no span names must already hold the prefix (the caller's live-prefix /// bookkeeping). Any written cell may have a stale copy in the VRAM resident window, so the resolver is reset diff --git a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs index 5940ad22..ef090030 100644 --- a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs +++ b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs @@ -126,6 +126,17 @@ mod enabled { } Ok(()) } + /// `read` into bytes that are not initialised yet (the prefix-cache export fills a fresh buffer without + /// zeroing it first); every byte of `out` is written. + pub(crate) fn read_uninit(&self, o: usize, out: &mut [std::mem::MaybeUninit]) -> Result<()> { + let p = self.range(o, out.len())?; + // SAFETY: as `read`: `range` proved `[p, p + out.len())` lies inside the live allocation and `out` is a + // caller slice that cannot overlap it; the copy writes all `out.len()` bytes of `out`. + unsafe { + std::ptr::copy_nonoverlapping(p as *const u8, out.as_mut_ptr().cast::(), out.len()); + } + Ok(()) + } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { // SAFETY: `p` is the base returned by cuMemHostAlloc and not yet freed (`host` is cleared only after a @@ -174,6 +185,9 @@ impl MappedAllocation { pub(crate) fn read(&self, _: usize, _: &mut [u8]) -> Result<()> { Err(Error::UnsupportedPlatform) } + pub(crate) fn read_uninit(&self, _: usize, _: &mut [std::mem::MaybeUninit]) -> Result<()> { + Err(Error::UnsupportedPlatform) + } pub(crate) fn write(&mut self, _: usize, _: &[u8]) -> Result<()> { Err(Error::UnsupportedPlatform) } diff --git a/crates/cuda-driver/src/qsa_resident_index/qsa_resident_index_checkpoint_restore.rs b/crates/cuda-driver/src/qsa_resident_index/qsa_resident_index_checkpoint_restore.rs index 2f7ca089..e2b6a3bd 100644 --- a/crates/cuda-driver/src/qsa_resident_index/qsa_resident_index_checkpoint_restore.rs +++ b/crates/cuda-driver/src/qsa_resident_index/qsa_resident_index_checkpoint_restore.rs @@ -193,13 +193,7 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> { pub const TAIL_BYTES: usize = CHECKPOINT_BYTES; /// Copy the pooled key rows `first_row..first_row + rows` (all below the current end / 4) to the host. pub fn export_rows(&self, first_row: usize, rows: usize, out: &mut Vec) -> Result<()> { - self.validate()?; - if self.in_flight || self.unpublished { - return Err(Error::InvalidQwenShape); - } - if rows == 0 || first_row.checked_add(rows).is_none_or(|e| e > self.end / 4) { - return Err(Error::InvalidQwenShape); - } + self.check_export(first_row, rows)?; out.clear(); { let _p = crate::host_profile::span("export.index_alloc"); @@ -209,6 +203,28 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> { let _p = crate::host_profile::span("export.index_copy"); self.image[0].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(first_row * Self::ROW_BYTES, out) } + /// The image is settled and the rows lie below the current end / 4. + fn check_export(&self, first_row: usize, rows: usize) -> Result<()> { + self.validate()?; + if self.in_flight || self.unpublished { + return Err(Error::InvalidQwenShape); + } + if rows == 0 || first_row.checked_add(rows).is_none_or(|e| e > self.end / 4) { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + /// `export_rows` that takes the device read's own staging as the result instead of zero filling `out` and copying + /// the staging into it: the same bytes, one allocation, one zero fill and one copy fewer. `out` is replaced. + pub fn export_rows_fast(&self, first_row: usize, rows: usize, out: &mut Vec) -> Result<()> { + self.check_export(first_row, rows)?; + let _p = crate::host_profile::span("export.index_copy_fast"); + *out = self.image[0] + .as_ref() + .ok_or(Error::ContextPoisoned)? + .copy_to_range_owned(first_row * Self::ROW_BYTES, rows * Self::ROW_BYTES)?; + Ok(()) + } /// The bytes of a checkpoint of this lineage: everything `import` needs besides the rows below its end. pub fn export_tail(&self, s: &OriginalQsaIndexCheckpoint<'ctx>) -> Result> { self.validate()?; diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/owner_run_steps.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/owner_run_steps.rs index 52bf1fd1..92fe597e 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/owner_run_steps.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/owner_run_steps.rs @@ -231,6 +231,8 @@ fn run_generation( } }; let _ = emit_terminal(sink, terminal, clock); + // the response is out: an end-of-decode checkpoint the request deferred (LELEKA_PREFIX_PARK_ASYNC) is taken now + owner.prefix_after_response(); publish_prefix_summary(owner, shared); if let Some(lost) = owner.health() { // a lost physical owner cannot be repaired in place: stop serving, keep the process diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/stack_config_and_reports.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/stack_config_and_reports.rs index a7eab5dc..b47b2e9c 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/stack_config_and_reports.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/stack_config_and_reports.rs @@ -43,6 +43,7 @@ fn prefix_config(prefix: &super::super::PrefixCacheOptions) -> crate::qwen_forwa Some(bytes) => PrefixBudget::Bytes(bytes), }, block_tokens: prefix.block_tokens, + defer_decode_tail: crate::settings::process().serve.prefix_park_async, ..PrefixConfig::auto() }; if let Some(seconds) = prefix.retention_s { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs index 078f7ce3..35ea64e8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs @@ -12,7 +12,9 @@ use super::super::prompt_device_rows::{ use super::super::prompt_device_rows::{ PromptDeviceFinal, PromptDeviceNormedRows, PromptDeviceRows, PromptDeviceSource, }; -use super::super::qsa_index::prompt_device::resident_device::{ResidentQsaLayer, ResidentQsaOwners, ResidentQsaPrior}; +use super::super::qsa_index::prompt_device::resident_device::{ + ResidentQsaLayer, ResidentQsaOwners, ResidentQsaPrior, SpanExport, +}; use super::super::session::original_prompt::draft::{OriginalDraftCheckpoint, OriginalDraftSession}; use super::super::session::original_prompt::{ OriginalPromptInput, OriginalPromptTxn, OriginalSessionCheckpoint, ParkedBlock, ParkedSession, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/original_prompt_executor/construction_and_parking/session_park_and_qsa_owners.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/original_prompt_executor/construction_and_parking/session_park_and_qsa_owners.rs index c5bd6496..37a30ccc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/original_prompt_executor/construction_and_parking/session_park_and_qsa_owners.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/original_prompt_executor/construction_and_parking/session_park_and_qsa_owners.rs @@ -140,7 +140,18 @@ impl<'ctx> OriginalPromptExecutor<'ctx> { if self.layers.iter().flatten().count() != 12 { return Err(Error::IdentityMismatch); } - session.park_block(&self.layers, first, tokens) + let mode = self.span_export()?; + session.park_block(&self.layers, first, tokens, mode) + } + /// How this park reads the layers out: with `LELEKA_PREFIX_PARK_FAST` the context is drained here once, for all + /// twelve layers, instead of once per layer inside each read (nothing is enqueued between the reads). + fn span_export(&self) -> Result { + if !crate::settings::process().serve.prefix_park_fast { + return Ok(SpanExport::Checked); + } + let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_drain"); + self.context.synchronize().map_err(|_| Error::CudaExecution)?; + Ok(SpanExport::Drained) } /// Prefix cache: make the session and the twelve layers stand at `parked`, writing `blocks`. A failure poisons /// the executor, as for `restore_session`. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs index b81caebb..47104736 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs @@ -70,6 +70,10 @@ pub(crate) struct PrefixConfig { pub(crate) policy: PolicyParams, /// The laptop profile of `auto` (smaller floor and ceiling). pub(crate) laptop: bool, + /// `LELEKA_PREFIX_PARK_ASYNC`: the checkpoint at the end of the decode (`TailMode::Reply`) is not taken inside the + /// request but when the stack runs `after_response`, right after the response was published and before the next + /// request (default off). + pub(crate) defer_decode_tail: bool, } /// What the binding needs from the stack's owners. @@ -123,6 +127,8 @@ pub(super) enum ChunkOutcome { Rejected(Reject), /// The host is short of memory: nothing was built. LowMemory, + /// The end-of-decode checkpoint is left for `after_response` (`PrefixConfig::defer_decode_tail`). + Deferred, Admitted { tokens: usize, new_blocks: usize, @@ -131,6 +137,13 @@ pub(super) enum ChunkOutcome { }, } +/// The end-of-decode checkpoint a request left for after its response: the tokens the session holds and the prompt-end +/// checkpoint that stays (`Req::limit`, which `finish` forgets). +struct PendingTail { + consumed: Vec, + keep: Option, +} + struct Req { /// Last prompt position a checkpoint may cover (the last prompt token starts the first verify window). limit: usize, @@ -146,6 +159,8 @@ pub(super) struct PrefixServe { store: PrefixStore, live: Vec, req: Option, + /// The end-of-decode checkpoint the last request deferred; dropped by the next `begin` and by `invalidate`. + pending_tail: Option, /// Sizes measured on the last real payloads (the estimates for the next admission). seen_state_bytes: Option, seen_block_bytes: Option, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_config.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_config.rs index 6871db35..434963a0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_config.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_config.rs @@ -21,6 +21,7 @@ impl PrefixConfig { policy }, laptop: false, + defer_decode_tail: false, } } pub(crate) fn validate(&self, capacity: usize) -> Result<(), Error> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_after_phase_parking.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_after_phase_parking.rs index 87d91fbe..6f8bdab4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_after_phase_parking.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_after_phase_parking.rs @@ -183,6 +183,31 @@ impl PrefixServe { // the prompt-end checkpoint of this request stays: a client that resends the history without the reasoning // of the reply continues from the prompt, not from the decode end let keep = self.req.as_ref().map(|r| r.limit); + if self.cfg.defer_decode_tail { + self.pending_tail = Some(PendingTail { consumed: consumed.to_vec(), keep }); + return Ok(ChunkOutcome::Deferred); + } + self.take_decode_tail(device, consumed, keep) + } + + /// After the response of the request that deferred its end-of-decode checkpoint: take it now. The session stands + /// where the decode left it (nothing ran on the device since), so this is the checkpoint `after_decode` would + /// have taken. `None`: nothing was deferred. + pub(in super::super::super) fn after_response>( + &mut self, + device: &mut D, + ) -> Result, Error> { + let Some(PendingTail { consumed, keep }) = self.pending_tail.take() else { return Ok(None) }; + self.note = None; + self.take_decode_tail(device, &consumed, keep).map(Some) + } + + fn take_decode_tail>( + &mut self, + device: &mut D, + consumed: &[i32], + keep: Option, + ) -> Result { let outcome = self.admit_tail(device, consumed, keep)?; if matches!(outcome, ChunkOutcome::Admitted { .. } | ChunkOutcome::Exists) { // the buffer holds exactly these cells, and the node has a copy of them diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_store_and_shedding.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_store_and_shedding.rs index 1818289e..bddbac4a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_store_and_shedding.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/prefix_serve/prefix_serve_store_and_shedding.rs @@ -31,6 +31,7 @@ impl PrefixServe { store, live: Vec::new(), req: None, + pending_tail: None, seen_state_bytes: None, seen_block_bytes: None, park_ms_request: 0.0, @@ -162,6 +163,7 @@ impl PrefixServe { self.store.clear(); self.live.clear(); self.req = None; + self.pending_tail = None; } /// Head of a request: install the deepest checkpoint that is a prefix of `prompt`, if any (`None` = read from 0; @@ -172,9 +174,7 @@ impl PrefixServe { prompt: &[i32], ) -> Result, Error> { let g = self.block_tokens; - self.park_ms_request = 0.0; - self.consider_ms_request = 0.0; - self.admitted_request = 0; + self.start_request_counters(); if self.bypass { self.req = None; return Ok(None); @@ -195,6 +195,14 @@ impl PrefixServe { }; self.import_hit(device, prompt, (hit, limit), match_us) } + /// A new request: its counters start at zero, and a checkpoint the last request deferred and nobody took is + /// dropped (it names a device state that is gone). + fn start_request_counters(&mut self) { + self.pending_tail = None; + self.park_ms_request = 0.0; + self.consider_ms_request = 0.0; + self.admitted_request = 0; + } /// Where a hit lands in the positional buffer: how much of it the buffer already holds and what is copied back. fn import_plan(&self, hit: &Match, head: &[i32]) -> ImportPlan { let g = self.block_tokens; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs index c2d47e1c..f55bafbc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs @@ -236,6 +236,8 @@ fn governor() -> leleka_memory::Governor { leleka_memory::Governor::new(cfg, std::sync::Arc::new(leleka_memory::FakeProc::default())) } +#[path = "tests/deferred_decode_tail.rs"] +mod deferred_decode_tail; #[path = "tests/one_token_prompt_reads.rs"] mod one_token_prompt_reads; #[path = "tests/second_session.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/deferred_decode_tail.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/deferred_decode_tail.rs new file mode 100644 index 00000000..2b70a723 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/deferred_decode_tail.rs @@ -0,0 +1,123 @@ +//! `PrefixConfig::defer_decode_tail` (`LELEKA_PREFIX_PARK_ASYNC`): the checkpoint at the end of the decode is taken +//! after the response, from the same device state, and is the checkpoint the immediate path takes. +use super::*; + +fn deferring() -> PrefixServe { + PrefixServe::new(PrefixConfig { tail: TailMode::Reply, defer_decode_tail: true, ..cfg() }, 1024, 1 << 30, "test") +} + +/// An agent turn up to the end of the decode: `begin`, the prompt, the decode of `reply`; returns the session's +/// tokens and what `after_decode` answered. The request is not finished. +fn decode_turn( + s: &mut PrefixServe, + d: &mut Fake, + (prompt, reply): (&[i32], &[i32]), +) -> (Vec, ChunkOutcome) { + let (_, resume) = begin_request(s, d, prompt); + read_chunks(s, d, prompt, (resume, None)); + s.after_prefill(d, prompt).unwrap(); + let mut consumed = prompt[..prompt.len() - 1].to_vec(); + let decoded: Vec = + std::iter::once(prompt[prompt.len() - 1]).chain(reply[..reply.len() - 1].iter().copied()).collect(); + d.read(&decoded, consumed.len()); + consumed.extend_from_slice(&decoded); + let outcome = s.after_decode(d, &consumed).unwrap(); + (consumed, outcome) +} + +/// What a store holds, for comparing two caches. +fn shape(s: &PrefixServe) -> (usize, usize, usize, usize) { + (s.node_count(), s.block_count(), s.bytes(), s.live_tokens()) +} + +#[test] +fn the_deferral_is_off_by_default() { + assert!(!PrefixConfig::auto().defer_decode_tail); + assert!(!cfg().defer_decode_tail); +} + +#[test] +fn a_deferred_checkpoint_is_taken_after_the_response_and_equals_the_immediate_one() { + let (mut now, mut later) = (tail_serve(TailMode::Reply), deferring()); + let (mut d_now, mut d_later) = (Fake::new(), Fake::new()); + let (first, reply) = (session(1, 0, 4, 12), doc(33, 0, 300)); + let (consumed, immediate) = decode_turn(&mut now, &mut d_now, (&first, &reply)); + now.finish(true); + let (consumed_later, deferred) = decode_turn(&mut later, &mut d_later, (&first, &reply)); + assert_eq!(consumed, consumed_later); + assert_eq!(deferred, ChunkOutcome::Deferred); + let before = shape(&later); + assert!(before.0 < shape(&now).0, "the decode-end node is not in the store while the response is produced"); + // the request is finished (its claim on the buffer ends) and then the response is out + later.finish(true); + let taken = later.after_response(&mut d_later).unwrap().expect("a checkpoint was deferred"); + let ( + ChunkOutcome::Admitted { tokens, new_blocks, bytes, .. }, + ChunkOutcome::Admitted { tokens: t, new_blocks: n, bytes: b, .. }, + ) = (taken, immediate) + else { + panic!("both paths admit: {taken:?} / {immediate:?}"); + }; + assert_eq!((tokens, new_blocks, bytes), (t, n, b)); + assert_eq!(shape(&later), shape(&now), "the same nodes, blocks, bytes and live claim"); + assert_eq!(later.after_response(&mut d_later).unwrap(), None, "taken once"); +} + +#[test] +fn the_next_turn_resumes_from_the_deferred_checkpoint_exactly_as_from_the_immediate_one() { + let (mut now, mut later) = (tail_serve(TailMode::Reply), deferring()); + let (mut d_now, mut d_later) = (Fake::new(), Fake::new()); + let (first, reply) = (session(1, 0, 4, 12), doc(33, 0, 300)); + decode_turn(&mut now, &mut d_now, (&first, &reply)); + now.finish(true); + let (consumed, _) = decode_turn(&mut later, &mut d_later, (&first, &reply)); + later.finish(true); + later.after_response(&mut d_later).unwrap(); + let mut second = first.clone(); + second.extend(reply.iter().copied()); + second.extend(doc(34, 0, 60)); + let (a, b) = + (now.begin(&mut d_now, &second).unwrap().unwrap(), later.begin(&mut d_later, &second).unwrap().unwrap()); + assert_eq!(a.resume, consumed.len(), "the end of the previous decode"); + assert_eq!((a.resume, a.switched, a.branch, a.copied_tokens), (b.resume, b.switched, b.branch, b.copied_tokens)); + assert_eq!((d_now.position, d_now.digest), (d_later.position, d_later.digest)); +} + +#[test] +fn a_deferred_checkpoint_nobody_took_is_dropped_by_the_next_request_and_by_invalidate() { + let mut s = deferring(); + let mut d = Fake::new(); + let (first, reply) = (session(1, 0, 4, 12), doc(33, 0, 300)); + decode_turn(&mut s, &mut d, (&first, &reply)); + s.finish(true); + let nodes = s.node_count(); + // the next request starts first: the device state the checkpoint named is gone + s.begin(&mut d, &session(2, 0, 3, 5)).unwrap(); + assert_eq!(s.after_response(&mut d).unwrap(), None); + assert_eq!(s.node_count(), nodes, "nothing was parked"); + decode_turn(&mut s, &mut d, (&first, &reply)); + s.finish(true); + s.invalidate(); + assert_eq!(s.after_response(&mut d).unwrap(), None); + assert_eq!(s.node_count(), 0); +} + +#[test] +fn nothing_is_deferred_when_the_tail_is_off_or_the_request_bypasses_the_cache() { + let mut off = PrefixServe::::new( + PrefixConfig { tail: TailMode::Prompt, defer_decode_tail: true, ..cfg() }, + 1024, + 1 << 30, + "test", + ); + let mut d = Fake::new(); + let (first, reply) = (session(1, 0, 4, 12), doc(33, 0, 300)); + let (_, outcome) = decode_turn(&mut off, &mut d, (&first, &reply)); + assert_eq!(outcome, ChunkOutcome::Nothing); + assert_eq!(off.after_response(&mut d).unwrap(), None); + let mut bypass = deferring(); + bypass.set_bypass(true); + let (_, outcome) = decode_turn(&mut bypass, &mut Fake::new(), (&first, &reply)); + assert_eq!(outcome, ChunkOutcome::Nothing); + assert_eq!(bypass.after_response(&mut Fake::new()).unwrap(), None); +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_prefill_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_prefill_chunk.rs index 01a927f5..188caa45 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_prefill_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/original_serve_stack_methods/original_serve_stack_prefill_chunk.rs @@ -69,23 +69,28 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { pub(in super::super) fn prefix_after_decode(&mut self, consumed: &[i32]) { let Some(mut prefix) = self.prefix.take() else { return }; let _span = profile::span("prefix.after_decode"); - match prefix.after_decode(self, consumed) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - operator_text(&format!( - "prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} \ - park_ms={park_ms:.1}", - bytes >> 20 - )); - } - Ok(other) => operator_text(&format!( - "prefix tail (decode end) not taken: {other:?}: {}", - prefix.take_note().unwrap_or_default() - )), - Err(error) => { - operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")) - } + let taken = prefix.after_decode(self, consumed); + report_decode_tail(&mut prefix, taken.map(Some), "decode end"); + self.prefix = Some(prefix); + } + + /// After the response of a request was published (`LELEKA_PREFIX_PARK_ASYNC`): the end-of-decode checkpoint the + /// request deferred, taken before the next request can start. Nothing ran on the device since the decode ended, + /// so the parked bytes are those `prefix_after_decode` would have taken. Its profile sections are reported on + /// their own line, `park_deferred`. + pub(crate) fn prefix_after_response(&mut self) { + if self.state.broken.is_some() { + return; + } + let Some(mut prefix) = self.prefix.take() else { return }; + { + let _span = profile::span("prefix.after_response"); + let taken = prefix.after_response(self); + report_decode_tail(&mut prefix, taken, "decode end, after the response"); } self.prefix = Some(prefix); + self.note_memory(); + profile::report("park_deferred"); } /// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint @@ -150,6 +155,26 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { } } +/// The operator line of an end-of-decode checkpoint attempt (`None`: nothing was deferred, nothing to say). +fn report_decode_tail( + prefix: &mut PrefixServe, + taken: std::result::Result, Error>, + when: &str, +) { + match taken { + Ok(Some(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms })) => operator_text(&format!( + "prefix tail admit ({when}): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", + bytes >> 20 + )), + Ok(None | Some(ChunkOutcome::Deferred)) => {} + Ok(Some(other)) => operator_text(&format!( + "prefix tail ({when}) not taken: {other:?}: {}", + prefix.take_note().unwrap_or_default() + )), + Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the {when}; skipped")), + } +} + /// The chunk's loan from the expert cache: the smallest rung of the ladder that holds `count` rows, else the full loan. fn lend_tail<'l, 'ctx>( cache: &'l mut OriginalExpertCache<'ctx>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs index 740148db..765046c9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs @@ -32,6 +32,15 @@ pub(in crate::qwen_forward) struct ParkedLayerSpan { pub(in crate::qwen_forward) kv: Vec, pub(in crate::qwen_forward) index: Vec, } +/// How a layer's span is read out for the prefix cache; both give the same bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::qwen_forward) enum SpanExport { + /// Each read drains the context itself and fills a zeroed buffer (the reference path). + Checked, + /// The caller drained the context once for all the layers of the park: the reads skip their own drain and write + /// buffers that are not zeroed first (`LELEKA_PREFIX_PARK_FAST`). + Drained, +} /// A parked prefix to install into a resident layer: the layer's spans up to the position `end`, and the tail of its /// index checkpoint at that position. #[derive(Clone, Copy)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/resident_qsa_span_export_and_seal.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/resident_qsa_span_export_and_seal.rs index 471961e1..a89b6af4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/resident_qsa_span_export_and_seal.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/resident_qsa_span_export_and_seal.rs @@ -8,24 +8,45 @@ use super::*; impl<'ctx> ResidentQsaLayer<'ctx> { /// Bytes of the cells `first..first + tokens` of this layer as a prefix-cache span (host K/V pages and pooled index /// rows). `first` and `tokens` are multiples of four and lie below the layer's end. - pub(in crate::qwen_forward) fn export_span(&self, first: usize, tokens: usize) -> Result { + pub(in crate::qwen_forward) fn export_span( + &self, + first: usize, + tokens: usize, + mode: SpanExport, + ) -> Result { // `tokens` is a multiple of four for a grid block; a request-end checkpoint ends anywhere: whole pages cover // its cells, and only the complete 4-cell rows of the index image are copied (the checkpoint's tail carries // the partial one) if first % 4 != 0 || tokens == 0 || first + tokens > self.current.next_position() as usize { return Err(Error::InvalidPosition); } - let (mut kv, mut index) = (Vec::new(), Vec::new()); - { - let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_kv"); - self.kv.export_pages(first / 4, (first + tokens).div_ceil(4) - first / 4, &mut kv).map_err(device_error)?; + let kv = self.export_kv(first, tokens, mode)?; + let index = self.export_index(first, tokens, mode)?; + Ok(ParkedLayerSpan { first_token: first, tokens, kv, index }) + } + /// The host K/V pages of the cells `first..first + tokens`: whole pages, up to the one holding the last cell. + fn export_kv(&self, first: usize, tokens: usize, mode: SpanExport) -> Result> { + let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_kv"); + let (pages, mut kv) = ((first + tokens).div_ceil(4) - first / 4, Vec::new()); + match mode { + SpanExport::Checked => self.kv.export_pages(first / 4, pages, &mut kv), + SpanExport::Drained => self.kv.export_pages_fast(first / 4, pages, &mut kv), } - let rows = (first + tokens) / 4 - first / 4; + .map_err(device_error)?; + Ok(kv) + } + /// The pooled index rows of the complete 4-cell rows in `first..first + tokens` (none: an empty vector). + fn export_index(&self, first: usize, tokens: usize, mode: SpanExport) -> Result> { + let (rows, mut index) = ((first + tokens) / 4 - first / 4, Vec::new()); if rows > 0 { let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_index"); - self.index.export_rows(first / 4, rows, &mut index).map_err(device_error)?; + match mode { + SpanExport::Checked => self.index.export_rows(first / 4, rows, &mut index), + SpanExport::Drained => self.index.export_rows_fast(first / 4, rows, &mut index), + } + .map_err(device_error)?; } - Ok(ParkedLayerSpan { first_token: first, tokens, kv, index }) + Ok(index) } /// The tail of the layer's index checkpoint at its current end (what `import` needs besides the spans). pub(in crate::qwen_forward) fn export_tail(&self) -> Result> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs index 331ad078..76824491 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs @@ -4,7 +4,7 @@ use super::super::dense_weight_cache::DenseWeightCache; use super::super::prompt_device_rows::PromptWeights; use super::super::qsa_index::prompt_device::resident_device::{ - ParkedLayerSpan, ParkedPrefix, ResidentQsaLayer, ResidentQsaOwners, ResidentQsaPrior, ResidentQsaSeal, + ParkedLayerSpan, ParkedPrefix, ResidentQsaLayer, ResidentQsaOwners, ResidentQsaPrior, ResidentQsaSeal, SpanExport, }; use super::*; use std::cell::{Cell, RefCell}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/original_prompt_input/qwen_session.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/original_prompt_input/qwen_session.rs index c90b98d2..a08ddc85 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/original_prompt_input/qwen_session.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/original_prompt_input/qwen_session.rs @@ -241,6 +241,7 @@ impl<'driver> QwenSession<'driver> { layers: &[Option>; STATE_CAPACITY], first: usize, tokens: usize, + mode: SpanExport, ) -> Result { if self.state_lag.is_some() || (first + tokens) as u64 > self.next_position { return Err(Error::InvalidPosition); @@ -248,7 +249,7 @@ impl<'driver> QwenSession<'driver> { let mut out: [Option; STATE_CAPACITY] = std::array::from_fn(|_| None); for slot in 0..48 { match (&layers[slot], self.qsa_layers[slot]) { - (Some(layer), true) => out[slot] = Some(layer.export_span(first, tokens)?), + (Some(layer), true) => out[slot] = Some(layer.export_span(first, tokens, mode)?), (None, false) => {} _ => return Err(Error::IdentityMismatch), } diff --git a/crates/engine-qwen35-cuda/src/settings/serve.rs b/crates/engine-qwen35-cuda/src/settings/serve.rs index 842bdbd6..e2527f51 100644 --- a/crates/engine-qwen35-cuda/src/settings/serve.rs +++ b/crates/engine-qwen35-cuda/src/settings/serve.rs @@ -31,6 +31,13 @@ pub(crate) struct ServeSettings { /// `LELEKA_DRAFT_CHAIN_PIPELINE` is `1` or `on`: the MTP chain steps of a greedy draft run back to back, one /// stream drain for the run (identity and paired A/B of docs/experiments/decode-tail-5090.md). pub(crate) draft_chain_pipeline: bool, + /// `LELEKA_PREFIX_PARK_FAST` is `1` or `on`: the prefix-cache export of the K/V cells and index rows drains the + /// context once per park and writes into unzeroed buffers (the same bytes; identity and paired A/B of + /// docs/experiments/step-ledger.md row B3). + pub(crate) prefix_park_fast: bool, + /// `LELEKA_PREFIX_PARK_ASYNC` is `1` or `on`: the checkpoint at the end of a decode (`--prefix-cache-tail reply`) + /// is taken after the response was published, not before (row B3). + pub(crate) prefix_park_async: bool, } impl ServeSettings { @@ -47,6 +54,8 @@ impl ServeSettings { cpu_pool_plan: equals(env, "LELEKA_CPU_POOL_PLAN", "on"), prefill_loan_tiers: one_of(env, "LELEKA_PREFILL_LOAN_TIERS", &["1", "on"]), draft_chain_pipeline: one_of(env, "LELEKA_DRAFT_CHAIN_PIPELINE", &["1", "on"]), + prefix_park_fast: one_of(env, "LELEKA_PREFIX_PARK_FAST", &["1", "on"]), + prefix_park_async: one_of(env, "LELEKA_PREFIX_PARK_ASYNC", &["1", "on"]), } } } diff --git a/crates/engine-qwen35-cuda/src/settings/serve_tests.rs b/crates/engine-qwen35-cuda/src/settings/serve_tests.rs index bc9e8be9..6d7b0928 100644 --- a/crates/engine-qwen35-cuda/src/settings/serve_tests.rs +++ b/crates/engine-qwen35-cuda/src/settings/serve_tests.rs @@ -96,3 +96,15 @@ fn the_draft_chain_pipeline_is_one_or_on_and_off_by_default() { assert_eq!(serve(&[("LELEKA_DRAFT_CHAIN_PIPELINE", value)]).draft_chain_pipeline, want, "pipeline {value:?}"); } } + +#[test] +fn the_prefix_park_switches_are_one_or_on_and_off_by_default() { + let defaults = serve(&[]); + assert!(!defaults.prefix_park_fast && !defaults.prefix_park_async); + for (value, want) in [("1", true), ("on", true), ("0", false), ("off", false), ("yes", false), ("", false)] { + assert_eq!(serve(&[("LELEKA_PREFIX_PARK_FAST", value)]).prefix_park_fast, want, "fast {value:?}"); + assert_eq!(serve(&[("LELEKA_PREFIX_PARK_ASYNC", value)]).prefix_park_async, want, "async {value:?}"); + } + let fast_only = serve(&[("LELEKA_PREFIX_PARK_FAST", "1")]); + assert!(fast_only.prefix_park_fast && !fast_only.prefix_park_async, "the two switches are independent"); +}