diff --git a/crates/cuda-driver/src/mtp_original_full_drafter.rs b/crates/cuda-driver/src/mtp_original_full_drafter.rs index be6e39cb..4bd93d92 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter.rs @@ -232,7 +232,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { || a >= rows || first > prior.0.end || first - .checked_add(rows.max(a + self.max_t.saturating_sub(1))) + .checked_add(rows.max(a + 1)) .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) { return Err(Error::InvalidQwenShape); @@ -409,7 +409,12 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { ids[0] = output.token; probabilities[0] = output.probability; count = 1; - let limit = (self.max_t as i32 - 1).min(max_drafts); + // draft j writes the cell first + a + j, and the ring ends at MTP_ORIGINAL_MAX_CELLS (upstream `max_steps`) + let limit = crate::original_mtp_actor::chain_end_within_cells( + (self.max_t as i32 - 1).min(max_drafts), + first.saturating_add(a), + MTP_ORIGINAL_MAX_CELLS, + ); let mut j = 1usize; while (j as i32) < limit && probabilities[j - 1] >= min_p { let _span_chain = crate::host_profile::span("mtp.chain_step"); diff --git a/crates/cuda-driver/src/mtp_original_full_round.rs b/crates/cuda-driver/src/mtp_original_full_round.rs index 4d97cdd1..283e31a6 100644 --- a/crates/cuda-driver/src/mtp_original_full_round.rs +++ b/crates/cuda-driver/src/mtp_original_full_round.rs @@ -102,7 +102,7 @@ impl<'ctx> OriginalMtpDraftProgram<'ctx>{ if self.j!=0||self.rows!=window.rows()||a>=self.rows{return Err(Error::InvalidQwenShape);} window.validate_context(self.program.context)?;window.validate_selection(&selection)?;window.validate_mtp_geometry()?; let o=&self.program.tail; - if selection.vocabulary()!=o.weights.id_vocab||window.first_position().checked_add(self.rows.max(a+o.max_t.saturating_sub(1))).is_none_or(|n|n>MTP_ORIGINAL_MAX_CELLS){return Err(Error::InvalidProjectionShape);} + if selection.vocabulary()!=o.weights.id_vocab||window.first_position().checked_add(self.rows.max(a+1)).is_none_or(|n|n>MTP_ORIGINAL_MAX_CELLS){return Err(Error::InvalidProjectionShape);} let source=window.residuals()?; if let Some(captured)=&self.direct_window{ // Original bind uses Verifier::final_R_all(), a real DEVICE span. @@ -149,7 +149,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx>{ /// verifier window of repeated rows is constructed. pub(crate) fn stage_first_residual(&self,window:Rc>,selection:NativeHeadSelection,rows:usize)->Result<()>{ self.validate_context(self.inner.context)?;window.validate_context(self.inner.context)?;window.validate_mtp_geometry()?;window.validate_selection(&selection)?; - if window.rows()!=1||rows==0||rows>self.inner.max_t||window.first_position().checked_add(rows.max(self.inner.max_t.saturating_sub(1))).is_none_or(|n|n>MTP_ORIGINAL_MAX_CELLS)||selection.vocabulary()!=self.inner.weights.id_vocab{return Err(Error::InvalidQwenShape);} + if window.rows()!=1||rows==0||rows>self.inner.max_t||window.first_position().checked_add(rows.max(1)).is_none_or(|n|n>MTP_ORIGINAL_MAX_CELLS)||selection.vocabulary()!=self.inner.weights.id_vocab{return Err(Error::InvalidQwenShape);} let source=window.residuals()?;let o=&self.inner; if source.qwen_address()%16!=0{return Err(Error::InvalidSize);} let dest=o.mapped_address(o.mapped_window_offset(),rows*40960)?; @@ -236,7 +236,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx>{ /// before capture. Repeated scratch rows do not become verification results. pub(super) fn stage_first_residual_direct(&self,window:Rc>,selection:NativeHeadSelection,rows:usize)->Result<()>{ let o=&self.inner;o.validate(o.context)?;window.validate_context(o.context)?;window.validate_mtp_geometry()?;window.validate_selection(&selection)?; - if window.rows()!=1||rows==0||rows>o.max_t||window.first_position().checked_add(rows.max(o.max_t.saturating_sub(1))).is_none_or(|n|n>MTP_ORIGINAL_MAX_CELLS)||selection.vocabulary()!=o.weights.id_vocab{return Err(Error::InvalidQwenShape);} + if window.rows()!=1||rows==0||rows>o.max_t||window.first_position().checked_add(rows.max(1)).is_none_or(|n|n>MTP_ORIGINAL_MAX_CELLS)||selection.vocabulary()!=o.weights.id_vocab{return Err(Error::InvalidQwenShape);} let src=window.residuals()?.qwen_address();let dst=window.actual_mtp_residual_bank(rows)?.qwen_address(); // Exact row0 self-copy is Original; all later rows are disjoint, whole-owned. if src!=dst||src%16!=0{return Err(Error::InvalidProjectionShape);} diff --git a/crates/cuda-driver/src/original_mtp_actor.rs b/crates/cuda-driver/src/original_mtp_actor.rs index 3b7d45c3..ea0f4977 100644 --- a/crates/cuda-driver/src/original_mtp_actor.rs +++ b/crates/cuda-driver/src/original_mtp_actor.rs @@ -103,6 +103,15 @@ impl DraftSettings { } } +/// Upstream 41cf05a0 (`mtp.cpp`, `max_steps = min(.., max_cells - (p + a))`): draft `j` writes its K/V at cell `draft_cell + j` +/// and the cells end at `max_cells` (the page table has no page past it), so near the context's end a round drafts only the +/// cells that exist. `continuation_end` is [`DraftSettings::continuation_end`] (the loop runs while `j < end`, draft 0 always +/// runs); the result is never above it, and at least 1 for any `draft_cell < max_cells`. +pub fn chain_end_within_cells(continuation_end: i32, draft_cell: usize, max_cells: usize) -> i32 { + let room = i32::try_from(max_cells.saturating_sub(draft_cell)).unwrap_or(i32::MAX); + continuation_end.min(room) +} + pub fn validate_max_t(max_t: i32) -> ActorResult<()> { if (1..=VERIFY_MAX_T).contains(&max_t) { Ok(()) @@ -236,6 +245,26 @@ mod tests { } } + #[test] + fn the_chain_stops_at_the_last_cell_that_exists() { + // far from the end: unchanged + for end in [-5, 0, 1, 3, 7] { + assert_eq!(chain_end_within_cells(end, 1000, 262_144), end); + } + // draft j writes cell c + j: with c = max_cells - k only k drafts fit (cells c .. max_cells - 1) + for k in 1..=10usize { + let c = 262_144 - k; + assert_eq!(chain_end_within_cells(7, c, 262_144), (k as i32).min(7), "k {k}"); + // the last draft's cell is inside + let n = chain_end_within_cells(7, c, 262_144) as usize; + assert!(c + n - 1 < 262_144); + } + // a cell at or past the end leaves no draft (the callers refuse such a cell before this); no overflow + assert_eq!(chain_end_within_cells(7, 262_144, 262_144), 0); + assert_eq!(chain_end_within_cells(7, usize::MAX, 262_144), 0); + assert_eq!(chain_end_within_cells(7, 0, usize::MAX), 7); + } + #[test] fn destructor_slots_are_complete_ordered_and_distinct() { let mut seen = std::collections::HashSet::new(); diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs index 21d48b6c..3a1370e8 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_engine.rs @@ -542,6 +542,8 @@ mod tests { fail:Option<&'static str>,fail_restore:Option<&'static str>, /// tokens the "MTP" drafts: chain of the model, shifted by `skew` to force rejections skew:i32,sampler_cell:i64, + /// the highest cell (+1) a verify window row or a draft touched + max_end:i64, } struct Win {inputs:Vec,outputs:Vec,position:i64} struct Fake {w:Rc>,pending_commit:Option,pending_position:i64} @@ -581,6 +583,7 @@ mod tests { // the window must see the committed branch (async commit already published) let outputs:Vec=inputs.iter().map(|&x|model(x)).collect(); self.w.borrow_mut().sampler_cell=position+inputs.len() as i64; + {let mut w=self.w.borrow_mut();w.max_end=w.max_end.max(position+inputs.len() as i64);} Ok(Win{inputs:inputs.to_vec(),outputs,position}) } fn validate_window(&self,w:&Win,position:i64,inputs:&[i32])->Result<()> { @@ -614,7 +617,9 @@ mod tests { while ids.len()=min_p { let last=*ids.last().unwrap();ids.push(model(last));probs.push(0.9); } - let _=w;Ok(DraftCompletion{ids,probabilities:probs,first_cell:position+a as i64,accepted_row:a}) + let _=w; + {let mut wd=self.w.borrow_mut();wd.max_end=wd.max_end.max(position+a as i64+ids.len() as i64);} + Ok(DraftCompletion{ids,probabilities:probs,first_cell:position+a as i64,accepted_row:a}) } fn drain_draft(&mut self)->Result<()> {self.log("drain-draft");Ok(())} fn draft_first(&mut self,_:&i32,_t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,_c:bool)->Result { @@ -1051,10 +1056,14 @@ mod tests { assert!(OriginalServeSettings{vocabulary:0,..s}.controller().is_err()); } - fn serve(p:&[i32],max_new:usize,eos:&[i32],mut cancel:impl FnMut()->bool,fail_emit_after:Option) + fn serve(p:&[i32],max_new:usize,eos:&[i32],cancel:impl FnMut()->bool,fail_emit_after:Option) ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine) { + let (r,out,c,e,_)=serve_in(p,max_new,eos,cancel,fail_emit_after,4096);(r,out,c,e) + } + fn serve_in(p:&[i32],max_new:usize,eos:&[i32],mut cancel:impl FnMut()->bool,fail_emit_after:Option,max_context:i64) + ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine,Rc>) { let (f,w)=Fake::new(p); - let s=OriginalServeSettings{max_t:4,mtp_max_t:0,max_context:4096,vocabulary:VOCAB,suffix_min_match:0,coupled:false,adaptive:None,request_min_p:None}; + let s=OriginalServeSettings{max_t:4,mtp_max_t:0,max_context,vocabulary:VOCAB,suffix_min_match:0,coupled:false,adaptive:None,request_min_p:None}; let mut e=OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_t-1).unwrap(); let mut c=s.controller().unwrap(); let mut out=Vec::new(); @@ -1063,7 +1072,24 @@ mod tests { if fail_emit_after.is_some_and(|n|out.len()>=n) {return Err(Error::InputRead);} out.extend_from_slice(t);wc.borrow_mut().committed.extend_from_slice(t);Ok(()) },&mut cancel,||0.0); - (r,out,c,e) + (r,out,c,e,w) + } + + /// Upstream 41cf05a0 `e85567b6`: through the real engine (plan, cap and cross-check of the chain), a request that runs to the + /// context's end never touches a cell past it, whatever the distance of the last windows to it. + #[test] + fn serve_request_to_the_context_end_stays_inside_the_cells_and_ends_as_context() { + let p=prompt_long(); + for k in 1..=9i64 { + let max_context=p.len() as i64-1+k; + let (r,out,c,e,w)=serve_in(&p,1000,&[],||false,None,max_context); + let r=r.unwrap_or_else(|err|panic!("k {k}: {err:?}")); + assert_eq!(r.stop,ServeStop::Context,"k {k}"); + assert_eq!(out.len() as i64,k,"k {k}: one token per row that fits"); + let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} + assert!(w.borrow().max_end<=max_context,"k {k}: touched cell {} of {max_context}",w.borrow().max_end); + assert!(c.finished()&&!c.is_failed()&&!e.is_poisoned()&&!e.commit_pending(),"k {k}"); + } } #[test] diff --git a/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs b/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs index 8d38d9c0..176eb2a9 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_spec_controller.rs @@ -86,6 +86,8 @@ pub(crate) struct OriginalSpecController { /// position when the request ends and a checkpoint of both can be taken there. Off unless the caller asks, per request. final_draft:bool, adaptive:Option,plan:Option,stats:SpecStats, + /// The last draft stage ran a chain shortened by the context's end: the next stage restores the full chain in the engine's plan. + chain_clamped:bool, } /// Holds the authentic complete verification receipt until MTP catch-up has /// consumed all T residuals. It cannot be cloned or used as a state checkpoint. @@ -123,7 +125,7 @@ impl OriginalSpecController { let suffix=SuffixDrafter::new(config.suffix_min_match.max(1),64,cap)?; let policy=DraftPolicy::new(config.max_t,0.03)?; let adaptive=config.adaptive.map(AdaptivePolicy::new); - Ok(Self{config,policy,suffix,request:None,rounds:0,failed:false,owner:Rc::new(()),final_draft:false,adaptive,plan:None,stats:SpecStats::default()}) + Ok(Self{config,policy,suffix,request:None,rounds:0,failed:false,owner:Rc::new(()),final_draft:false,adaptive,plan:None,stats:SpecStats::default(),chain_clamped:false}) } /// See `final_draft`; set before `begin_request`. pub(crate) fn set_final_draft(&mut self,on:bool) {self.final_draft=on;} @@ -210,11 +212,17 @@ impl OriginalSpecController { } let r=self.request.as_ref().ok_or(Error::IdentityMismatch)?; let p=r.position; - if p.checked_add(t as i64).ok_or(Error::Overflow)?>self.config.max_context { - // Original serve breaks its loop as length; it never silently - // shrinks the configured verify window to fit remaining context. + // Rows p .. p+t-1 each need a cell: past `max_context` there is none. Upstream 41cf05a0 (`e85567b6`, generate.cpp + // `room`): near the context's end the window takes only the rows that fit (the admission checked the prompt, `max_new` + // and 8 cells of margin, which a full window of up to 8 rows can overrun). No room at all ends the request as length. + let room=self.config.max_context.checked_sub(p).ok_or(Error::Overflow)?; + if room<1 { self.request.as_mut().ok_or(Error::IdentityMismatch)?.finished=true;return Ok(None); } + if (t as i64)>room { + // A shrunk window is not the policy's offer: its observation would teach the wrong width. + t=room as usize;choice=None;if t==1 {lookup=false;} + } if r.consumed.len().checked_add(t).ok_or(Error::Overflow)?>r.consumed.capacity() {return Err(Error::InputAllocation.into());} if self.config.suffix_min_match>0 {self.suffix.reserve_append(t)?;} let mut inputs=[0;MAX_T];inputs[0]=r.input; @@ -289,7 +297,16 @@ impl OriginalSpecController { else { // the chain of this round: the request's (`mtp_t - 1` drafts down to `min_p`) or the adaptive plan let (chain,floor)=match self.plan {Some(p)=>(p.max_drafts,p.min_p),None=>(self.config.mtp_t-1,r.min_p)}; - let planned=if self.plan.is_some() {engine.set_draft_plan(chain,floor)} else {Ok(())}; + // Draft j writes its K/V at the cell p+a+j, and cells end at `max_context`: near the context's end the + // round drafts only the cells that exist (upstream `max_steps = min(.., max_cells - (p + a))`, mtp.cpp). + // Draft 0 always fits: the window's rows did, and a < t. + let cell=round.position.saturating_add(round.accepted as i64); + let room=usize::try_from(self.config.max_context.saturating_sub(cell)).unwrap_or(0).max(1); + let clamped=chain>room; + let chain=chain.min(room); + // A fixed chain never needed a plan; a clamped one does (and restores the full chain on the next round). + let planned=if self.plan.is_some()||clamped||self.chain_clamped {engine.set_draft_plan(chain,floor)} else {Ok(())}; + self.chain_clamped=clamped; let preparation=DraftPreparation::new(self.config.max_t,chain,self.config.vocabulary); match (planned,preparation) { (Err(e),_)|(_,Err(e))=>Err(e.into()), @@ -370,6 +387,8 @@ mod tests { log:Vec,committed:Vec,fail:Option<(&'static str,Error)>, bad_draft:Option,probs:Vec,drafted:usize, bad_output:Option<(usize,i32)>,cancel_after_verify:bool, + /// the highest cell a window row or a draft touched (+1), and the chain lengths the controller asked for + max_end:i64,plans:Vec<(usize,f32)>, } impl Fake { fn new(prompt_prefix:&[i32])->Self {Self{committed:prompt_prefix.to_vec(),probs:vec![0.9;8],..Default::default()}} @@ -389,12 +408,14 @@ mod tests { fn replay_target_kv(&mut self,v:&Verif,p:i64,outputs:&[i32])->Result<()> { self.trip("replay")?;assert_eq!(v.position,p);assert_eq!(v.outputs,outputs);Ok(()) } + fn set_draft_plan(&mut self,max_drafts:usize,min_p:f32)->Result<()> {self.plans.push((max_drafts,min_p));Ok(())} fn full_target_seed(&mut self,v:&Verif,row:usize,cell:i64,token:i32,_coupled:bool)->Result { self.trip("seed")?;assert_eq!(cell,v.position+row as i64);assert_eq!(token,v.outputs[row]); + self.max_end=self.max_end.max(cell+1); Ok(self.pick(0,next(token))) } fn full_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { - self.trip("chain")?;assert!(cell>0);Ok(self.pick(j,next(previous_token))) + self.trip("chain")?;assert!(cell>0);self.max_end=self.max_end.max(cell+1);Ok(self.pick(j,next(previous_token))) } fn stage_coupled_history(&mut self,_:&[i32],_:i32)->Result<()> {self.trip("stage_history")} fn drain_draft(&mut self)->Result<()> {self.trip("drain_draft")} @@ -411,6 +432,7 @@ mod tests { fn apply_pending(&mut self)->Result<()> {self.trip("apply_pending")} fn verify(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { self.trip("verify")?;assert_eq!(consumed,self.committed.as_slice()); + self.max_end=self.max_end.max(position+inputs.len() as i64); let mut outputs:Vec=inputs.iter().map(|&x|next(x)).collect(); if let Some((i,v))=self.bad_output {if i(Fake,Vec,OriginalSpecController) { + use super::super::original_spec_adaptive::AdaptiveConfig; + let p=prompt(prompt_len);let mut e=Fake::new(&p[..prompt_len-1]); + let mut cfg=SpecConfig::new(max_t,mtp,64,VOCAB,suffix,false).unwrap();cfg.max_context=max_context; + if adaptive {cfg=cfg.with_adaptive(Some(AdaptiveConfig::new(max_t,max_t-1)));} + let mut c=OriginalSpecController::new(cfg).unwrap(); + c.begin_request(&p,max_new,min_p,&[]).unwrap(); + let out=drive(&mut c,&mut e,&mut||false).unwrap(); + c.finish_request(&mut e).unwrap(); + (e,out,c) + } + #[test] - fn a_window_that_would_pass_the_context_ends_the_request_as_length() { + fn a_window_near_the_context_end_takes_only_the_rows_that_fit() { let p=prompt(4);let mut e=Fake::new(&p[..3]); let mut cfg=SpecConfig::new(4,4,6,VOCAB,0,false).unwrap();cfg.max_context=6; let mut c=OriginalSpecController::new(cfg).unwrap(); begin(&mut c,&p,100,&[]); let out=drive(&mut c,&mut e,&mut||false).unwrap(); - // position 3 + T=1 fits, then 4 + 4 > 6 ends the loop without shrinking T - assert!(out.len()<100&&c.finished()); - assert!(e.committed.len()<=6); + // position 3: T=1; position 4: T=4 does not fit (4 + 4 > 6), so the window shrinks to the 2 rows left, not to "length" + assert!(c.finished()); + assert_eq!(e.committed.len(),6,"every cell of the context is used"); + assert_eq!(out,expected(&p,3),"the tokens of rows 3, 4 and 5 are all emitted"); + assert!(e.max_end<=6,"no row or draft past the context: {}",e.max_end); + } + + #[test] + fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end() { + // every distance k of the first window from the end, every window shape: fixed, min_p, suffix lookup, adaptive + for max_t in [2usize,4,6,8] { + for k in 1..=(max_t as i64+3) { + for (suffix,min_p,adaptive) in [(0usize,0.0f32,false),(3,0.0,false),(0,0.5,false),(3,0.5,true),(0,0.0,true)] { + let prompt_len=10usize; + let max_context=prompt_len as i64-1+k; + let (e,out,c)=run_to_the_end(max_context,prompt_len,1000,max_t,max_t,suffix,min_p,adaptive); + let tag=format!("max_t {max_t} k {k} suffix {suffix} min_p {min_p} adaptive {adaptive}"); + assert!(e.max_end<=max_context,"{tag}: touched cell {} of {max_context}",e.max_end); + // the request ended because the context is full, with the greedy text of every row that fits + assert_eq!(e.committed.len() as i64,max_context,"{tag}"); + assert_eq!(out,expected(&prompt(prompt_len),k as usize),"{tag}"); + assert!(c.finished()&&!c.is_failed(),"{tag}"); + assert_eq!(e.count("begin_adaptation"),e.count("join_adaptation"),"{tag}"); + assert_eq!(e.count("drain_verified"),e.count("verify"),"{tag}"); + } + } + } + } + + #[test] + fn the_chain_is_shortened_near_the_end_and_restored_after_it() { + // fixed window, perfect drafter: 4-wide windows, 3 drafts. The last round before the end drafts only the cells left. + let (e,_,_)=run_to_the_end(30,10,1000,4,4,0,0.0,false); + assert!(e.max_end<=30); + // plans: a clamped chain is asked for explicitly, never longer than the cells left + assert!(e.plans.iter().all(|&(n,_)|(1..=3).contains(&n)),"{:?}",e.plans); + assert!(e.plans.iter().any(|&(n,_)|n<3),"the last rounds draft fewer than the full chain: {:?}",e.plans); + // a request that never gets near the end never sets a plan (the fixed chain needs none) + let (e,_,_)=run_to_the_end(4096,10,40,4,4,0,0.0,false); + assert!(e.plans.is_empty(),"{:?}",e.plans); + } + + #[test] + fn a_chain_clamped_by_one_request_is_restored_for_the_next() { + let p=prompt(10); + let mut e=Fake::new(&p[..9]); + let mut cfg=SpecConfig::new(4,4,64,VOCAB,0,false).unwrap();cfg.max_context=20; + let mut c=OriginalSpecController::new(cfg).unwrap(); + c.begin_request(&p,1000,0.0,&[]).unwrap(); + drive(&mut c,&mut e,&mut||false).unwrap();c.finish_request(&mut e).unwrap(); + assert!(e.plans.last().is_some_and(|&(n,_)|n<3),"the request ended on a clamped chain: {:?}",e.plans); + // a short request on the same controller: its first drafting round puts the full chain back + let mut e2=Fake::new(&p[..9]); + c.begin_request(&p,3,0.0,&[]).unwrap(); + drive(&mut c,&mut e2,&mut||false).unwrap(); + assert_eq!(e2.plans.first().map(|x|x.0),Some(3),"{:?}",e2.plans); } #[test] diff --git a/docs/upstream-port-plan.md b/docs/upstream-port-plan.md index 824a3962..31f71cd6 100644 --- a/docs/upstream-port-plan.md +++ b/docs/upstream-port-plan.md @@ -19,7 +19,7 @@ the run-to-run control); **L** live Codex session. |---|---|---|---|---| | 0.1 | Control-token text in messages becomes real special tokens (`c16f31f8`, `98b7ea94`, `0d613031`) | swap ``, `` and the other control literals in message text (user, tool, system, assistant history, tool-call arguments, tool descriptions) for private-use marks before the template renders; after it encode those spans as plain text (`Tokenizer::encode` plain spans); the template's own markers stay special; same path for token counting | U (injection fixtures), L | **U done** (2026-10-25, native Windows `cargo test`: leleka-tokenizer lib 11 + marked 7 + fast_path 7 + oracle 3, strata-control 259 lib + 33 backend_worker_http, leleka-runtime lib 504, all green; the injection fixtures are in `crates/tokenizer/tests/marked.rs`, `responses.rs` tests and `backend_worker_http.rs`). `leleka_tokenizer::LiteralMarks` maps every type 3/4 literal to a plane-15 private-use mark (a forged mark is escaped); `render_request` marks instructions, message text, reasoning, call arguments, tool outputs, tool descriptions/schemas; the gateway's own ``/`` markers stay literal; `Tokenizer::encode_marked` is the one path for generation and `/input_tokens`; the text contract carries the marked string and `leleka-runtime` `prepare_prompt` reads it with `encode_marked`. Not done: `strata-desktop-core` (`runtime_gateway`, `runtime_tools`) still renders unmarked text; replayed assistant text keeps its marks too (a model-written `` in history is replayed as text); an engine older than this change reads the marks as private-use characters. **L todo** (live Codex session) | | 0.2 | `--dump-logits` header lies on native packs (`504579da`) | check every parity harness that compared against it | U | todo | -| 0.3 | Spec window / MTP drafts near the context end run past `max_cells` (`e85567b6`) | test the controller at `max_context - k` | U | todo | +| 0.3 | Spec window / MTP drafts near the context end run past `max_cells` (`e85567b6`) | test the controller at `max_context - k` | U | **U done** (2026-10-26, server `rnr5090`, `cargo test --release`: `leleka-runtime` lib `original_spec_controller` + `original_serve_engine` 60 passed, `leleka-cuda-driver --features cuda-driver` lib 382 passed). Ours was not the upstream crash (the serve loop ended as length instead of "ran out of context") but had the same hole in two places: (a) `verify_commit` ended the request when `p + t > max_context` instead of taking the rows that fit (upstream generate.cpp `room`), losing up to 7 tokens at the end of a context, and the MTP chain drafted `mtp_t - 1` cells whatever the context had left (upstream `mtp.cpp`: `max_steps = min(.., max_cells - (p + a))`); (b) the driver refused a draft launch when `first + a + max_t - 1 > 262144` (`mtp_original_full_drafter.rs`, `mtp_original_full_round.rs`) although only draft 0 was needed: a request admitted at the edge (`n + max_new + 8 = 262144`, a window of up to 8 rows plus accept 7) died with `InvalidQwenShape`. Now: the window shrinks to `max_context - p` (no room = finished as context; a shrunk window is not observed by the adaptive policy), the chain is clamped to `max_context - (p + a)` through `set_draft_plan` and restored on the next round, `chain_end_within_cells` bounds the driver's chain loop, the staging checks bound what is staged (`first + max(rows, a + 1)`). Tests: `spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end` (max_t 2/4/6/8, k = 1..max_t+3 from the end, fixed / suffix / min_p / adaptive: no row or draft cell >= max_context, text = greedy of every row that fits), `a_window_near_the_context_end_takes_only_the_rows_that_fit`, `the_chain_is_shortened_near_the_end_and_restored_after_it`, `a_chain_clamped_by_one_request_is_restored_for_the_next`, `serve_request_to_the_context_end_stays_inside_the_cells_and_ends_as_context` (real engine over the fake port), `the_chain_stops_at_the_last_cell_that_exists` (driver). Mutation check: with the window shrink and the chain clamp removed, 5 of these fail. Not verified on a model (no GPU run: the driver check relaxation is exercised only by the pure helper test). Open: the MTP ring is fixed at `MTP_ORIGINAL_MAX_CELLS` = 262144 cells while `leleka_context::geometry::MAX_CELLS` is 524288: a 512K context cannot draft past cell 262143 (not changed here) | | 0.4 | PLE `gather_batch` matches prefetched rows by position (`36381540`) | test reordered and duplicated keys on our async PLE reader | U | todo | | 0.5 | Conversation/prefix cache edge cases (`8824e217` cancelled between windows loses the restored conversation; `940011da` full cache drops instead of evicting; `aece46db` 1-token prompt with spec) | tests on the prefix store and serve loop | U | todo | | 0.6 | Callback-thread affinity (`0e20d9ae`, `c08fd902`): one no-op host callback before the host thread pins itself; claimed 142.8 -> 207.8 tok/s on a 5090 + 9950X | check our host functions (`compute_drain`, DMA staging); microbench the callback latency on the server | R | todo |