diff --git a/crates/vetta-infer-gw/src/serve.rs b/crates/vetta-infer-gw/src/serve.rs index 0642aa5..48d0af7 100644 --- a/crates/vetta-infer-gw/src/serve.rs +++ b/crates/vetta-infer-gw/src/serve.rs @@ -293,12 +293,16 @@ pub fn serve_gen( } // Persistent KV states: size once to a 4096-bucket cap >= max_seq and reuse // across requests (no per-request ~3.75 GB alloc/free sawtooth). Grow only when - // a request crosses the bucket. `cap` is the KV stride passed to the forwards. - let cap = max_seq.next_multiple_of(4096).min(MAX_CONTEXT); - if eng.states_cap.get() < cap || eng.states.borrow().len() != eng.n_layers { + // a request crosses the bucket. + let need = max_seq.next_multiple_of(4096).min(MAX_CONTEXT); + if eng.states_cap.get() < need || eng.states.borrow().len() != eng.n_layers { *eng.states.borrow_mut() = (0..eng.n_layers).map(|_| None).collect(); - eng.states_cap.set(cap); + eng.states_cap.set(need); } + // KV stride = the PERSISTENT cap, which may exceed this request's bucket after + // a longer session. Reuse it (restore/forward take this, not `need`) so returning + // from a long context to a short one does NOT reallocate the KV from scratch. + let cap = eng.states_cap.get(); let mut states = eng.states.borrow_mut(); // Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore