use super::*;
use crate::blocks::{validate_span_blocks_at, CLEARED_GPU_TABLE_ENTRY};
const TABLE_BLOCKS: u32 = 96;
fn card() -> u64 {
approx_twin("test-salt", 0, Some("card-turn-end"))
}
fn conv(len: usize) -> Vec<u32> {
(0..len as u32).map(|i| 1_000 + i).collect()
}
fn cs_at(pos: usize) -> Vec<u8> {
(pos as u64).to_le_bytes().to_vec()
}
fn fresh() -> (ServeBlockCache, BlockPools) {
let mut cache = ServeBlockCache::new();
cache.set_approx_retain(true);
(cache, BlockPools::records_only_with_capacities(256, 256, 2).unwrap())
}
struct Turn {
tbl: BlockTable,
st: LaneBlockState,
history: Vec<u32>,
full_gpu: Vec<u64>,
win_gpu: Vec<u64>,
bound: Option<(usize, Vec<u8>)>,
landed: usize,
}
impl Turn {
fn begin(cache: &mut ServeBlockCache, pools: &mut BlockPools, prompt_len: usize) -> Turn {
Turn::begin_in(cache, pools, prompt_len, TABLE_BLOCKS)
}
fn begin_in(cache: &mut ServeBlockCache, pools: &mut BlockPools, prompt_len: usize, table_blocks: u32) -> Turn {
let prompt = conv(prompt_len);
let mut tbl = BlockTable::new(table_blocks).unwrap();
let mut st = LaneBlockState { owner: card(), ..Default::default() };
let bound = cache.match_and_bind(pools, &mut tbl, &mut st, &prompt);
let mut p = bound.as_ref().map_or(0, |b| b.0);
while p < prompt_len {
let next = effective_pf_target(p, prompt_len);
cache.ensure_span_blocks(pools, &mut tbl, p, next - p).unwrap();
validate_span_blocks_at(&tbl, pools, p, next - p, WINDOW, BLOCK).expect("a prefill span reads live blocks");
cache.finish_prefill_span(pools, &mut tbl, &mut st, &prompt, p, next - p, || cs_at(next));
p = next;
}
let landed = if prompt_len.is_multiple_of(BLOCK) { prompt_len } else { (prompt_len - 1) / BLOCK * BLOCK };
let mut history = prompt;
history.push(1_000 + prompt_len as u32); Turn {
tbl,
st,
history,
full_gpu: vec![CLEARED_GPU_TABLE_ENTRY; table_blocks as usize],
win_gpu: vec![CLEARED_GPU_TABLE_ENTRY; table_blocks as usize],
bound,
landed,
}
}
fn written(&self) -> usize {
self.st.written
}
fn sample(&mut self) {
self.history.push(1_000 + self.history.len() as u32);
}
fn decode(&mut self, cache: &mut ServeBlockCache, pools: &mut BlockPools) {
let pos = self.st.written;
cache.ensure_span_blocks(pools, &mut self.tbl, pos, 1).unwrap();
validate_span_blocks_at(&self.tbl, pools, pos, 1, WINDOW, BLOCK).expect("a decode step reads live blocks");
cache.finish_decode_span(pools, &mut self.tbl, &mut self.st, pos);
cache.seal_decode_block(pools, &self.tbl, &mut self.st, &self.history, pos, || cs_at(pos + 1));
if (pos + 1).is_multiple_of(BLOCK) {
self.landed = pos + 1;
}
self.sample();
}
fn verify(&mut self, cache: &mut ServeBlockCache, pools: &mut BlockPools, k: usize, n_keep: usize) {
assert!(n_keep <= 1 + k);
let p0 = self.st.written;
let alloc = cache.ensure_span_blocks_tracking(pools, &mut self.tbl, p0, 1 + k).unwrap();
validate_span_blocks_at(&self.tbl, pools, p0, 1 + k, WINDOW, BLOCK).expect("a verify step reads live blocks");
cache
.finish_verify_span_to_slices(
pools,
&mut self.tbl,
&mut self.st,
&alloc,
p0,
n_keep,
&mut self.full_gpu,
&mut self.win_gpu,
)
.expect("finalize the verify step");
if n_keep == 0 {
return;
}
while self.history.len() < p0 + n_keep {
self.sample();
}
cache.seal_decode_block(pools, &self.tbl, &mut self.st, &self.history, p0 + n_keep - 1, || cs_at(p0 + n_keep));
if (p0 + n_keep).is_multiple_of(BLOCK) {
self.landed = p0 + n_keep;
}
self.sample();
}
fn end(mut self, cache: &mut ServeBlockCache, pools: &mut BlockPools, cancelled: bool) -> usize {
let written = self.st.written;
let committed = self.history[..written].to_vec();
cache.release_lane_with_toks(pools, &mut self.tbl, &mut self.st, Some(&committed), cancelled);
written
}
}
fn next_turn_binds(cache: &mut ServeBlockCache, pools: &mut BlockPools, prompt_len: usize) -> (usize, Vec<u8>) {
let turn = Turn::begin(cache, pools, prompt_len);
let bound = turn.bound.clone().unwrap_or((0, Vec::new()));
turn.end(cache, pools, false);
bound
}
fn drain(mut cache: ServeBlockCache, mut pools: BlockPools) {
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
const PROMPTS: [usize; 4] = [1_500, 1_536, 1_599, 2_113];
#[test]
fn single_token_reply_ending_at_every_offset_leaves_a_start_at_its_last_block_boundary() {
let mut dropped = Vec::new();
for prompt_len in PROMPTS {
for offset in 0..BLOCK {
let (mut cache, mut pools) = fresh();
let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
let end = (prompt_len / BLOCK + 3) * BLOCK + offset;
while turn.written() < end {
turn.decode(&mut cache, &mut pools);
}
let written = turn.end(&mut cache, &mut pools, false);
assert_eq!(written, end);
let last_boundary = end / BLOCK * BLOCK;
let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
dropped.push((prompt_len, offset, at));
}
drain(cache, pools);
}
}
assert!(dropped.is_empty(), "turn-end start not saved: (prompt, offset past the boundary, next turn bound at) {dropped:?}");
}
#[test]
fn a_reply_shorter_than_a_block_resumes_from_the_prompt_start() {
for prompt_len in PROMPTS {
let (mut cache, mut pools) = fresh();
let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
let prompt_start = turn.landed;
let end = prompt_start + BLOCK - 1;
while turn.written() < end {
turn.decode(&mut cache, &mut pools);
}
turn.end(&mut cache, &mut pools, false);
let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
assert_eq!((at, cs), (prompt_start, cs_at(prompt_start)), "prompt {prompt_len}");
drain(cache, pools);
}
}
#[test]
fn second_turn_reply_ending_at_every_offset_leaves_a_start_at_its_last_block_boundary() {
let mut dropped = Vec::new();
for offset in 0..BLOCK {
let (mut cache, mut pools) = fresh();
let mut one = Turn::begin(&mut cache, &mut pools, 1_500);
while one.written() < 1_700 {
one.decode(&mut cache, &mut pools);
}
one.end(&mut cache, &mut pools, false);
let mut two = Turn::begin(&mut cache, &mut pools, 2_000);
assert_eq!(two.bound.as_ref().map(|b| b.0), Some(1_664), "turn 2 resumes past turn 1's reply");
assert!(two.st.approx_path);
let end = 2_176 + offset;
while two.written() < end {
two.decode(&mut cache, &mut pools);
}
two.end(&mut cache, &mut pools, false);
let last_boundary = end / BLOCK * BLOCK;
let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
dropped.push((offset, at));
}
drain(cache, pools);
}
assert!(dropped.is_empty(), "turn-end start not saved: (offset past the boundary, next turn bound at) {dropped:?}");
}
const K: usize = 4;
const SHAPES: [(&str, &[usize]); 5] = [
("every step keeps 2", &[2]),
("every step keeps 3", &[3]),
("every step keeps 5", &[5]),
("mixed 1,3,5,2,4", &[1, 3, 5, 2, 4]),
("mixed 5,5,1", &[5, 5, 1]),
];
#[test]
fn verify_step_reply_keeps_the_start_of_the_last_boundary_a_step_landed_on() {
let mut dropped = Vec::new();
let mut ran = 0usize;
for (name, shape) in SHAPES {
for prompt_len in PROMPTS {
for offset in 0..BLOCK {
let (mut cache, mut pools) = fresh();
let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
let end = (prompt_len / BLOCK + 3) * BLOCK + offset;
let mut step = 0usize;
while turn.written() < end {
let n_keep = shape[step % shape.len()].min(end - turn.written());
turn.verify(&mut cache, &mut pools, K, n_keep);
step += 1;
}
let landed = turn.landed;
turn.end(&mut cache, &mut pools, false);
let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
if (at, &cs) != (landed, &cs_at(landed)) {
dropped.push((name, prompt_len, offset, landed, at));
}
ran += 1;
drain(cache, pools);
}
}
}
assert!(
dropped.is_empty(),
"{} of {ran} replies lost their checkpoint: (shape, prompt, offset, last landed boundary, next turn bound at) {:?}",
dropped.len(),
&dropped[..dropped.len().min(24)]
);
}
#[test]
fn forced_close_between_verify_steps_ending_at_every_offset_keeps_its_last_checkpoint() {
let mut dropped = Vec::new();
for offset in 0..BLOCK {
let (mut cache, mut pools) = fresh();
let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
let end = 1_728 + offset;
let close_at = 1_590;
while turn.written() < close_at {
let n_keep = 3.min(close_at - turn.written());
turn.verify(&mut cache, &mut pools, K, n_keep);
}
for _ in 0..12 {
turn.decode(&mut cache, &mut pools); }
while turn.written() < end {
let n_keep = 5.min(end - turn.written());
turn.verify(&mut cache, &mut pools, K, n_keep);
}
let landed = turn.landed;
assert!(landed >= 1_600);
turn.end(&mut cache, &mut pools, false);
let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
if (at, &cs) != (landed, &cs_at(landed)) {
dropped.push((offset, landed, at));
}
drain(cache, pools);
}
assert!(dropped.is_empty(), "checkpoint lost: (offset, last landed boundary, next turn bound at) {dropped:?}");
}
#[test]
fn cancelled_turn_at_every_offset_keeps_its_last_checkpoint_and_its_prompt_start() {
let mut dropped = Vec::new();
for offset in 0..BLOCK {
for cancelled_in_verify in [false, true] {
let (mut cache, mut pools) = fresh();
let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
let prompt_start = turn.landed;
let end = 1_664 + offset;
while turn.written() < end {
turn.decode(&mut cache, &mut pools);
}
if cancelled_in_verify {
turn.verify(&mut cache, &mut pools, K, 0); }
assert_eq!(turn.written(), end);
turn.end(&mut cache, &mut pools, true);
let retry = next_turn_binds(&mut cache, &mut pools, 1_500);
assert_eq!(retry, (prompt_start, cs_at(prompt_start)), "a retry resumes from the prompt start");
let last_boundary = end / BLOCK * BLOCK;
let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
dropped.push((offset, cancelled_in_verify, at));
}
drain(cache, pools);
}
}
assert!(dropped.is_empty(), "turn-end start not saved: (offset, cancelled in a verify step, bound at) {dropped:?}");
}
#[test]
fn reply_at_the_length_limit_at_every_offset_leaves_a_start_at_its_last_block_boundary() {
let mut dropped = Vec::new();
for offset in 0..BLOCK {
let (mut cache, mut pools) = fresh();
let max_ctx = 2_240 + offset + 2;
let blocks = u32::try_from(max_ctx.div_ceil(BLOCK)).unwrap();
let mut turn = Turn::begin_in(&mut cache, &mut pools, 2_113, blocks);
while turn.written() + 2 < max_ctx {
turn.decode(&mut cache, &mut pools);
}
let end = turn.end(&mut cache, &mut pools, false);
assert_eq!(end, 2_240 + offset);
let last_boundary = end / BLOCK * BLOCK;
let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 1);
if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
dropped.push((offset, at));
}
drain(cache, pools);
}
assert!(dropped.is_empty(), "turn-end start not saved: (offset past the boundary, next turn bound at) {dropped:?}");
}
#[test]
fn window_ring_wrap_and_pre_wrap_replies_keep_last_boundary_and_partial_tail() {
let mut dropped = Vec::new();
for (prompt_len, boundary) in [(80usize, 192usize), (896usize, WINDOW)] {
for offset in 0..BLOCK {
let (mut cache, mut pools) = fresh();
let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
let end = boundary + offset;
while turn.written() < end {
turn.decode(&mut cache, &mut pools);
}
let written = turn.end(&mut cache, &mut pools, false);
assert_eq!(written, end);
let next_prompt = conv(end + 100);
let obs = cache.observe_prior(card(), &next_prompt);
assert!(obs.has_prior);
assert_eq!(obs.total_len, end);
assert_eq!(obs.proven_common_len, end, "partial-block tail must capture all {offset} trailing tokens");
assert_eq!(obs.first_divergent_pos, None);
let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
if (at, &cs) != (boundary, &cs_at(boundary)) {
dropped.push((prompt_len, boundary, offset, at));
}
drain(cache, pools);
}
}
assert!(
dropped.is_empty(),
"window wrap/pre-wrap turn-end start lost: (prompt, boundary, offset, next turn bound at) {dropped:?}"
);
}
#[test]
fn stitched_lane_ending_at_every_offset_keeps_turn_end_start_and_never_spills_or_donates_approx() {
let kvb = 1u32;
let mut pools = BlockPools::with_capacities(160, 96, kvb).unwrap();
let file_span: Vec<u32> = (0..3_200u32).map(|i| 50_000 + i).collect();
let mut donor_prompt: Vec<u32> = (0..128u32).map(|i| 2_000 + i).collect();
donor_prompt.extend_from_slice(&file_span); donor_prompt.extend((0..257u32).map(|i| 4_000 + i));
let mut card_prompt: Vec<u32> = (0..128u32).map(|i| 6_000 + i).collect();
card_prompt.extend_from_slice(&file_span); card_prompt.extend((0..1_680u32).map(|i| 60_000 + i)); let prompt_len = card_prompt.len();
let reply_boundary = (prompt_len / BLOCK + 2) * BLOCK;
let mut dropped = Vec::new();
for offset in 0..BLOCK {
let dir = (offset == BLOCK - 1).then(|| ScratchDir::new("turn-end-stitch-approx"));
let mut cache = match &dir {
Some(d) => ServeBlockCache::with_spill(SpillStore::open_with_kvb(&d.0, 64 * 1024 * 1024, kvb).unwrap()),
None => ServeBlockCache::new(),
};
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
{
let mut dtbl = BlockTable::new(96).unwrap();
let mut dst = LaneBlockState::default();
assert!(cache.match_and_bind(&mut pools, &mut dtbl, &mut dst, &donor_prompt).is_none());
let mut p = 0usize;
while p < donor_prompt.len() {
let next = effective_pf_target(p, donor_prompt.len());
cache.ensure_span_blocks(&mut pools, &mut dtbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut dtbl, &mut dst, &donor_prompt, p, next - p, || cs_at(next));
p = next;
}
cache.release_lane(&mut pools, &mut dtbl, &mut dst);
}
let mut tbl = BlockTable::new(112).unwrap();
let mut st = LaneBlockState { owner: card(), prompt_len, ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &card_prompt).is_none());
let plans = cache.plan_stitches(&pools, 0, &card_prompt, 0);
assert_eq!(plans.len(), 1);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, plans[0].stitch_start).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, 0, plans[0].stitch_start, || {
cs_at(plans[0].stitch_start)
});
let out = cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &card_prompt, &plans[0]);
assert!(matches!(out, StitchApplyOutcome::Applied { .. }));
assert!(st.stitched_approx && st.approx_path);
let mut p = st.written;
while p < prompt_len {
let next = effective_pf_target(p, prompt_len);
cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
validate_span_blocks_at(&tbl, &pools, p, next - p, WINDOW, BLOCK).expect("stitched heal reads live blocks");
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, p, next - p, || cs_at(next));
p = next;
}
let end = reply_boundary + offset;
let mut history = card_prompt.clone();
history.push(70_000);
while st.written < end {
let pos = st.written;
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
validate_span_blocks_at(&tbl, &pools, pos, 1, WINDOW, BLOCK).expect("stitched decode reads live blocks");
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
cache.seal_decode_block(&mut pools, &tbl, &mut st, &history, pos, || cs_at(pos + 1));
history.push(70_000 + (history.len() - prompt_len) as u32);
}
cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&history[..end]), false);
let mut next_prompt = history[..end].to_vec();
next_prompt.extend((0..100u32).map(|i| 80_000 + i));
let mut tbl2 = BlockTable::new(112).unwrap();
let mut st2 = LaneBlockState { owner: card(), ..Default::default() };
let bound = cache.match_and_bind(&mut pools, &mut tbl2, &mut st2, &next_prompt);
let (at, cs) = bound.clone().unwrap_or((0, Vec::new()));
if (at, &cs) != (reply_boundary, &cs_at(reply_boundary)) {
dropped.push((offset, at));
} else {
let mut p2 = at;
while p2 < next_prompt.len() {
let next = effective_pf_target(p2, next_prompt.len());
cache.ensure_span_blocks(&mut pools, &mut tbl2, p2, next - p2).unwrap();
validate_span_blocks_at(&tbl2, &pools, p2, next - p2, WINDOW, BLOCK)
.expect("next turn after stitched reply reads live blocks");
cache.finish_prefill_span(&mut pools, &mut tbl2, &mut st2, &next_prompt, p2, next - p2, || cs_at(next));
p2 = next;
}
}
cache.release_lane(&mut pools, &mut tbl2, &mut st2);
if dir.is_some() {
let mut stranger: Vec<u32> = (0..1_100u32).map(|i| 90_000 + i).collect();
stranger.extend_from_slice(&history[3_328..end]);
stranger.extend((0..1_600u32).map(|i| 95_000 + i));
assert!(cache.plan_stitches(&pools, 0, &stranger, 0).is_empty(), "approx starts are never stitch donors");
let approx_ids: Vec<SealedId> =
cache.starts.iter().filter(|(_, s)| s.approx).map(|(&id, _)| id).collect();
assert!(!approx_ids.is_empty(), "stitched turn must hold approximate starts before eviction");
for sid in approx_ids {
assert!(cache.evict_start(&mut pools, sid));
}
assert_eq!(cache.stats().starts_spilled, 0, "approximate starts are never spilled to disk");
assert!(cache.spilled_starts.is_empty());
}
cache.shutdown(&mut pools);
assert_zero_pool_leaks(&pools);
}
assert!(dropped.is_empty(), "stitched turn-end start not saved: (offset, next turn bound at) {dropped:?}");
}
#[test]
fn verify_step_with_crossed_boundary_cs_saves_the_reply_last_boundary_at_every_offset() {
let mut dropped = Vec::new();
for (name, shape) in SHAPES {
for prompt_len in PROMPTS {
for offset in 0..BLOCK {
let (mut cache, mut pools) = fresh();
let mut turn = Turn::begin(&mut cache, &mut pools, prompt_len);
let end = (prompt_len / BLOCK + 3) * BLOCK + offset;
let mut step = 0usize;
while turn.written() < end {
let p0 = turn.written();
let n_keep = shape[step % shape.len()].min(end - p0);
let step_end = p0 + n_keep;
let boundary = step_end / BLOCK * BLOCK;
let crossed = (cache.keeps_turn_end_start(&turn.st)
&& !step_end.is_multiple_of(BLOCK)
&& boundary > p0)
.then(|| (boundary, cs_at(boundary)));
let alloc = cache.ensure_span_blocks_tracking(&mut pools, &mut turn.tbl, p0, 1 + K).unwrap();
validate_span_blocks_at(&turn.tbl, &pools, p0, 1 + K, WINDOW, BLOCK).unwrap();
cache
.finish_verify_span_to_slices(
&mut pools,
&mut turn.tbl,
&mut turn.st,
&alloc,
p0,
n_keep,
&mut turn.full_gpu,
&mut turn.win_gpu,
)
.unwrap();
while turn.history.len() < step_end {
turn.sample();
}
cache.seal_verify_step(
&mut pools,
&turn.tbl,
&mut turn.st,
&turn.history,
step_end - 1,
crossed,
|| cs_at(step_end),
);
turn.sample();
step += 1;
}
let committed = turn.history[..end].to_vec();
let outcome = cache.release_lane_with_toks(&mut pools, &mut turn.tbl, &mut turn.st, Some(&committed), false);
assert_eq!(outcome, TurnEndStart::Saved);
assert_eq!(outcome.record_tag(), "saved");
assert_eq!(cache.stats().turn_end_starts_saved, 1);
assert_eq!(cache.stats().turn_end_starts_not_saved, [0; TurnEndMiss::ALL.len()]);
let last_boundary = end / BLOCK * BLOCK;
let (at, cs) = next_turn_binds(&mut cache, &mut pools, end + 100);
if (at, &cs) != (last_boundary, &cs_at(last_boundary)) {
dropped.push((name, prompt_len, offset, last_boundary, at));
}
drain(cache, pools);
}
}
}
assert!(dropped.is_empty(), "crossed-boundary verify lost its last boundary: {dropped:?}");
}
#[test]
fn checkpoint_guards_ignore_zero_crossed_preserve_earlier_hold_on_miss_and_drop_on_rebind() {
let (mut cache, mut pools) = fresh();
for (miss, tag) in [
(TurnEndMiss::NoCheckpoint, "not_saved:no_checkpoint"),
(TurnEndMiss::Behind, "not_saved:behind"),
(TurnEndMiss::OffPath, "not_saved:off_path"),
(TurnEndMiss::BlockMissing, "not_saved:block_missing"),
(TurnEndMiss::BlockNotLive, "not_saved:block_not_live"),
] {
assert!(!miss.name().is_empty());
assert_eq!(TurnEndStart::NotSaved(miss).record_tag(), tag);
}
assert_eq!(TurnEndStart::NotDue.record_tag(), "not_due");
{
let mut tbl = BlockTable::new(TABLE_BLOCKS).unwrap();
let mut st = LaneBlockState { owner: card(), prompt_len: 4, ..Default::default() };
let toks = conv(16);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, 5).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, 4);
cache.seal_verify_step(&mut pools, &tbl, &mut st, &toks, 4, Some((0, cs_at(0))), || cs_at(5));
assert!(st.turn_ckpt.is_none());
assert_eq!(cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&toks[..5]), false), TurnEndStart::NotDue);
}
{
let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
while turn.written() < 1_600 {
turn.decode(&mut cache, &mut pools);
}
assert!(turn.st.turn_ckpt.is_some());
while turn.written() < 1_663 {
turn.decode(&mut cache, &mut pools);
}
cache.ensure_span_blocks(&mut pools, &mut turn.tbl, 1_663, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut turn.tbl, &mut turn.st, 1_663);
turn.tbl.clear_kind_entry(&mut pools.window, BlockIndex::new(10)).unwrap();
cache.seal_decode_block(&mut pools, &turn.tbl, &mut turn.st, &turn.history, 1_663, || cs_at(1_664));
let committed = turn.history[..1_664].to_vec();
let outcome = cache.release_lane_with_toks(&mut pools, &mut turn.tbl, &mut turn.st, Some(&committed), false);
assert_eq!(outcome, TurnEndStart::NotSaved(TurnEndMiss::Behind));
let (at, cs) = next_turn_binds(&mut cache, &mut pools, 1_764);
assert_eq!((at, cs), (1_600, cs_at(1_600)), "earlier valid checkpoint at 1,600 must still be saved");
}
{
let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
while turn.written() < 1_663 {
turn.decode(&mut cache, &mut pools);
}
assert!(turn.st.turn_ckpt.is_some());
turn.tbl.clear_entries(&mut pools).unwrap();
for id in turn.st.sealed.drain(..) {
cache.tree.unpin(id);
}
let _ = cache.match_and_bind(&mut pools, &mut turn.tbl, &mut turn.st, &conv(1_500));
assert!(turn.st.turn_ckpt.is_none());
cache.release_lane(&mut pools, &mut turn.tbl, &mut turn.st);
}
{
let mut turn = Turn::begin(&mut cache, &mut pools, 1_500);
while turn.written() < 1_664 + 63 {
turn.decode(&mut cache, &mut pools);
}
assert!(turn.st.turn_ckpt.is_some());
let evicted = cache.release_lane_invalid(&mut pools, &mut turn.tbl, &mut turn.st);
assert!(evicted >= 1);
}
drain(cache, pools);
}
#[test]
fn stitched_lane_trailing_guard_never_enters_turn_checkpoint_or_tree_handles() {
let kvb = 1u32;
let mut pools = BlockPools::with_capacities(160, 96, kvb).unwrap();
let mut cache = ServeBlockCache::new();
cache.set_kv_stitch(true);
cache.set_approx_retain(true);
let file_span: Vec<u32> = (0..3_200u32).map(|i| 50_000 + i).collect();
let mut donor_prompt: Vec<u32> = (0..128u32).map(|i| 2_000 + i).collect();
donor_prompt.extend_from_slice(&file_span); donor_prompt.extend((0..257u32).map(|i| 4_000 + i)); {
let mut dtbl = BlockTable::new(96).unwrap();
let mut dst = LaneBlockState::default();
assert!(cache.match_and_bind(&mut pools, &mut dtbl, &mut dst, &donor_prompt).is_none());
let mut p = 0usize;
while p < donor_prompt.len() {
let next = effective_pf_target(p, donor_prompt.len());
cache.ensure_span_blocks(&mut pools, &mut dtbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut dtbl, &mut dst, &donor_prompt, p, next - p, || cs_at(next));
p = next;
}
cache.release_lane(&mut pools, &mut dtbl, &mut dst);
}
let mut card_prompt: Vec<u32> = (0..128u32).map(|i| 6_000 + i).collect();
card_prompt.extend_from_slice(&file_span); card_prompt.extend((0..1_680u32).map(|i| 60_000 + i));
{
let mut tbl = BlockTable::new(112).unwrap();
let mut st = LaneBlockState { owner: card(), prompt_len: 3_328, ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &card_prompt).is_none());
let plans = cache.plan_stitches(&pools, 0, &card_prompt, 0);
assert_eq!(plans.len(), 1);
let heal_start = plans[0].heal_start;
assert_eq!(heal_start, 1_792);
let hb = heal_start / BLOCK;
st.prompt_len = heal_start;
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, plans[0].stitch_start).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, 0, plans[0].stitch_start, || {
cs_at(plans[0].stitch_start)
});
assert!(matches!(cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &card_prompt, &plans[0]), StitchApplyOutcome::Applied { .. }));
let guard_w = tbl.get(BlockKind::Window, BlockIndex::new((hb - 1) as u32)).unwrap().expect("stitch zero guard");
assert!(cache.is_stitch_guard(guard_w));
assert!(!cache.entry_is_valid_kv(&pools, BlockKind::Window, guard_w));
let b1 = heal_start + BLOCK;
let step1_end = b1 + 3;
cache.ensure_span_blocks(&mut pools, &mut tbl, heal_start, BLOCK + 3).unwrap();
let fe_hb = tbl.get(BlockKind::Full, BlockIndex::new(hb as u32)).unwrap().unwrap();
pools.full.record_mut(fe_hb.slot()).unwrap().set_length(BLOCK as u32).unwrap();
tbl.clear_kind_entry(&mut pools.window, BlockIndex::new(hb as u32)).unwrap();
tbl.fill(&mut pools.window, BlockIndex::new(hb as u32), guard_w.slot(), guard_w.generation()).unwrap();
st.written = step1_end;
cache.seal_verify_step(
&mut pools,
&tbl,
&mut st,
&card_prompt[..step1_end],
step1_end - 1,
Some((b1, cs_at(b1))),
|| cs_at(step1_end),
);
assert_eq!(st.sealed.len(), hb + 1);
assert_eq!(cache.tree.handle(st.sealed[hb]).unwrap().window(), None, "guard_w must never become an EntryTree Window handle");
assert!(st.turn_ckpt.is_none(), "TurnCheckpoint must never hold a stitch zero guard");
assert_eq!(st.turn_ckpt_miss, Some(TurnEndMiss::BlockNotLive));
let b2 = b1 + BLOCK;
let guard_refs_before = pools.window.record(guard_w.slot()).unwrap().refs();
for pos in step1_end..b2 {
cache.ensure_span_blocks(&mut pools, &mut tbl, pos, 1).unwrap();
cache.finish_decode_span(&mut pools, &mut tbl, &mut st, pos);
}
let we_next = tbl.get(BlockKind::Window, BlockIndex::new((hb + 1) as u32)).unwrap().unwrap();
assert!(!cache.is_stitch_guard(we_next));
cache.seal_verify_step(&mut pools, &tbl, &mut st, &card_prompt[..b2], b2 - 1, None, || cs_at(b2));
assert_eq!(st.sealed.len(), hb + 2);
assert_eq!(cache.tree.handle(st.sealed[hb + 1]).unwrap().window(), Some(we_next));
assert!(st.turn_ckpt.is_none(), "trailing window still holds guard_w: no TurnCheckpoint may be taken");
assert_eq!(st.turn_ckpt_miss, Some(TurnEndMiss::BlockNotLive));
assert_eq!(pools.window.record(guard_w.slot()).unwrap().refs(), guard_refs_before, "guard_w gained zero checkpoint refs");
let out = cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&card_prompt[..b2]), false);
assert_eq!(out, TurnEndStart::NotSaved(TurnEndMiss::BlockNotLive));
assert!(
cache.starts.values().all(|s| s.entries.iter().all(|&(_, _, e)| !cache.is_stitch_guard(e))),
"no retained start may ever hold a stitch guard"
);
}
{
let prompt_len = card_prompt.len(); let mut tbl = BlockTable::new(112).unwrap();
let mut st = LaneBlockState { owner: card(), prompt_len, ..Default::default() };
assert!(cache.match_and_bind(&mut pools, &mut tbl, &mut st, &card_prompt).is_none());
let plans = cache.plan_stitches(&pools, 0, &card_prompt, 0);
cache.ensure_span_blocks(&mut pools, &mut tbl, 0, plans[0].stitch_start).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, 0, plans[0].stitch_start, || {
cs_at(plans[0].stitch_start)
});
assert!(matches!(cache.apply_stitch_plan(&mut pools, &mut tbl, &mut st, &card_prompt, &plans[0]), StitchApplyOutcome::Applied { .. }));
let mut p = st.written;
while p < prompt_len {
let next = effective_pf_target(p, prompt_len);
cache.ensure_span_blocks(&mut pools, &mut tbl, p, next - p).unwrap();
cache.finish_prefill_span(&mut pools, &mut tbl, &mut st, &card_prompt, p, next - p, || cs_at(next));
p = next;
}
let mut history = card_prompt.clone();
history.push(70_000);
let mut full_gpu = vec![CLEARED_GPU_TABLE_ENTRY; 112];
let mut win_gpu = vec![CLEARED_GPU_TABLE_ENTRY; 112];
let end = 5_120 + 63;
while st.written < end {
let p0 = st.written;
let n_keep = 5.min(end - p0);
let step_end = p0 + n_keep;
let boundary = step_end / BLOCK * BLOCK;
let crossed = (!step_end.is_multiple_of(BLOCK) && boundary > p0).then(|| (boundary, cs_at(boundary)));
let alloc = cache.ensure_span_blocks_tracking(&mut pools, &mut tbl, p0, 1 + K).unwrap();
cache.finish_verify_span_to_slices(&mut pools, &mut tbl, &mut st, &alloc, p0, n_keep, &mut full_gpu, &mut win_gpu).unwrap();
while history.len() < step_end {
history.push(70_000 + (history.len() - prompt_len) as u32);
}
cache.seal_verify_step(&mut pools, &tbl, &mut st, &history, step_end - 1, crossed, || cs_at(step_end));
history.push(70_000 + (history.len() - prompt_len) as u32);
}
let ckpt = st.turn_ckpt.as_ref().expect("healed stitched lane holds TurnCheckpoint at 5,120");
assert_eq!(ckpt.end, 5_120);
assert!(ckpt.window.iter().all(|&(_, we)| !cache.is_stitch_guard(we) && cache.entry_is_valid_kv(&pools, BlockKind::Window, we)));
let out = cache.release_lane_with_toks(&mut pools, &mut tbl, &mut st, Some(&history[..end]), false);
assert_eq!(out, TurnEndStart::Saved);
assert!(cache.starts.values().all(|s| s.entries.iter().all(|&(_, _, e)| !cache.is_stitch_guard(e))));
}
drain(cache, pools);
}