feat(serve): mode17 serve driver, OriginalSpecController::new selection and explicit operator factory

serve_request is generate.cpp's serve loop over any OriginalSpecEngine;
OriginalServeSettings::mode17 is the single production caller of
OriginalSpecController::new. spawn_backend_experimental_original_serve selects it
and fails closed at load until the verified-window host owners exist.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 15:21:00 +02:00
co-authored by Claude Sonnet 5.5
parent af29c7416a
commit ec21c754b6
2 changed files with 162 additions and 1 deletions
+31
View File
@@ -8,6 +8,7 @@ mod measurement;
use crate::{
model_binding::qwen4exp_input::{InputBindingError, InputConstants, ModelBinding},
qwen_forward::{
original_serve_engine::OriginalServeSettings,
contract::{Dimension, Position, TokenId},
dense_weight_cache::DenseWeightCache,
executor::{QwenForward, TargetStepProduct},
@@ -251,6 +252,36 @@ pub fn spawn_backend_experimental_optimized_windowed256_streamed_spill(
}),
})
}
/// Explicit Original-literal mode17 serve operator mode: the generate.cpp serve loop
/// (`OriginalSpecController` over `OriginalServeEngine`) instead of the Rust-native decoder.
/// Selection builds the production controller with the literal mode17 settings, then loads
/// fail closed until the verified-window host owners exist (see PORT-GAPS-MODE17.md rows 2/3/5:
/// the unbound Verifier window producers, the CPU pool/PCIe plan callbacks and verified-window
/// session publication). No default or fallback path is substituted.
pub fn spawn_backend_experimental_original_serve(
config: NativeBackendConfig,
ranked_profile: RankedExpertProfileSource,
) -> Result<Box<dyn Backend>, BackendError> {
if !cfg!(all(target_os = "linux", target_arch = "x86_64")) {
return Err(unsupported("Original serve CUDA owners require Linux x86_64"));
}
if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some()
|| config.mtp_source.is_none() || ranked_profile.path.as_os_str().is_empty()
|| ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA
|| config.context_tokens == 0 || config.context_tokens > 262_144
{
return Err(invalid("Original serve requires inherited sealed KAR, MTP, pinned profile and a valid context"));
}
let settings = OriginalServeSettings::mode17(
i64::from(config.context_tokens),
248_320,
OriginalServeSettings::coupled_from_environment(),
);
settings.controller().map_err(|_| invalid("Original serve controller configuration was refused"))?;
Err(unsupported(
"Original mode17 serve is selected but the verified-window host owners are not wired in this build",
))
}
/// Additional retained whole-buffer owners; distinct unadopted operator mode.
pub fn spawn_backend_experimental_optimized_windowed256_retained_scratch(
config: NativeBackendConfig,
@@ -8,7 +8,7 @@
//! `OriginalMtpDrafter::draft_from_verifier` owners. No default port exists:
//! a missing owner is `Error::Unsupported`, never a synthesized result.
use super::contract::{Error,Result};
use super::original_spec_controller::OriginalSpecEngine;
use super::original_spec_controller::{OriginalSpecController,OriginalSpecEngine,SpecConfig,SpecError};
use super::original_spec_draft::{DraftPick,OriginalDraftEngine,OriginalFirstDraftEngine};
use super::original_spec_policy::MAX_T;
use std::rc::Rc;
@@ -330,6 +330,69 @@ impl<P:OriginalServePort> OriginalFirstDraftEngine<P::Seed> for OriginalServeEng
}
}
/// Original `generate` serve settings for mode17: `--spec 4` verify width, prompt lookup on
/// (`--suffix-draft 3`), which makes the MTP keep 4-wide windows (`mtp_max_t = spec`) and the
/// verifier take windows up to `spec + 2` (`kVerifyMaxT` 8), coupled draft sampling per env.
#[derive(Clone,Copy,Debug,PartialEq)]
pub(crate) struct OriginalServeSettings {
pub(crate) max_t:usize,pub(crate) mtp_max_t:usize,pub(crate) max_context:i64,pub(crate) vocabulary:u32,
pub(crate) suffix_min_match:usize,pub(crate) coupled:bool,
}
impl OriginalServeSettings {
pub(crate) fn mode17(max_context:i64,vocabulary:u32,coupled:bool)->Self {
const SPEC:usize=4;const SUFFIX:usize=3;
Self{max_t:(SPEC+2).min(MAX_T),mtp_max_t:SPEC,max_context,vocabulary,suffix_min_match:SUFFIX,coupled}
}
/// `STRATA_SPEC_COUPLED`: set, non-empty and not "0" (read once by the operator, not per request).
pub(crate) fn coupled_from_environment()->bool {
std::env::var("STRATA_SPEC_COUPLED").is_ok_and(|v|!v.is_empty()&&v!="0")
}
/// Draft cap the engine shares with the controller's `DraftPreparation`.
pub(crate) fn max_drafts(&self)->usize {self.mtp_max_t.min(self.max_t).saturating_sub(1)}
/// The one production call of `OriginalSpecController::new`.
pub(crate) fn controller(&self)->Result<OriginalSpecController> {
OriginalSpecController::new(SpecConfig::new(self.max_t,self.mtp_max_t,self.max_context,self.vocabulary,
self.suffix_min_match,self.coupled)?)
}
}
#[derive(Clone,Copy,Debug,Eq,PartialEq)]
pub(crate) enum ServeStop {Eos,Length,Context}
#[derive(Clone,Copy,Debug,Eq,PartialEq)]
pub(crate) struct ServeOutcome {pub(crate) stop:ServeStop,pub(crate) produced:usize,pub(crate) rounds:usize}
/// generate.cpp's serve loop for one request: begin, then verify/commit, emit the committed
/// tokens, finish the round (draft + adaptive join + drain), repeat; `finish_request` waits the
/// last commit before anything reads the session. `emit` runs only AFTER the commit succeeded.
pub(crate) fn serve_request<E:OriginalSpecEngine>(controller:&mut OriginalSpecController,engine:&mut E,
prompt:&[i32],max_new:usize,min_p:f32,eos:&[i32],mut emit:impl FnMut(&[i32])->Result<()>,
mut cancel:impl FnMut()->bool,mut clock_ms:impl FnMut()->f64)->std::result::Result<ServeOutcome,SpecError> {
controller.begin_request(prompt,max_new,min_p,eos)?;
let (mut produced,mut rounds,mut stop)=(0usize,0usize,None);
let looped=(||->std::result::Result<(),SpecError> {
while !controller.finished() {
let started=clock_ms();
let Some(round)=controller.verify_commit(engine,&mut cancel)? else {break};
let emitted=emit(round.tokens());
produced+=round.tokens().len();rounds+=1;
if round.stopped_on_eos() {stop=Some(ServeStop::Eos);}
// A failed emit still finishes the round (drain + join) before reporting.
let finished=controller.finish_round(engine,round,||clock_ms()-started,&mut cancel);
emitted?;finished?;
}
Ok(())
})();
if let Err(e)=looped {
// Close the request best-effort (waits the last commit) so the controller is reusable
// unless a restore/finish failure already marked it failed.
let _=controller.finish_request(engine);return Err(e);
}
controller.finish_request(engine)?;
let stop=stop.unwrap_or(if produced>=max_new {ServeStop::Length} else {ServeStop::Context});
Ok(ServeOutcome{stop,produced,rounds})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -832,4 +895,71 @@ mod tests {
assert_eq!(batch.ids()[0],model(outs[0]));
e.drain_verified(v).unwrap();
}
#[test]
fn mode17_settings_follow_generate_defaults() {
let s=OriginalServeSettings::mode17(4096,VOCAB,false);
assert_eq!((s.max_t,s.mtp_max_t,s.suffix_min_match),(6,4,3));
assert_eq!(s.max_drafts(),3);
let c=s.controller().unwrap();
assert!(c.finished()&&!c.is_failed());
assert!(OriginalServeSettings{max_context:0,..s}.controller().is_err());
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<usize>)
->(std::result::Result<ServeOutcome,SpecError>,Vec<i32>,OriginalSpecController,OriginalServeEngine<Fake>) {
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};
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();
let wc=Rc::clone(&w);
let r=serve_request(&mut c,&mut e,p,max_new,0.0,eos,|t|{
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)
}
#[test]
fn serve_request_emits_the_greedy_text_and_reports_the_stop() {
let p=prompt_long();
let (r,out,mut c,_e)=serve(&p,10,&[],||false,None);
let r=r.unwrap();
assert_eq!(r.stop,ServeStop::Length);
assert!(r.produced>=10&&r.rounds>=1);
assert_eq!(out.len(),r.produced);
let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);}
// the controller is reusable for the next request
assert!(c.begin_request(&p,1,0.0,&[]).is_ok());
}
#[test]
fn serve_request_stops_on_eos() {
let p=prompt_long();
let third={let mut x=*p.last().unwrap();for _ in 0..3 {x=model(x);}x};
let (r,out,_c,_e)=serve(&p,50,&[third],||false,None);
assert_eq!(r.unwrap().stop,ServeStop::Eos);
assert_eq!(out.last(),Some(&third));
}
#[test]
fn serve_request_cancellation_rolls_back_and_closes_the_request() {
let p=prompt_long();
let mut calls=0;
let (r,_out,c,e)=serve(&p,50,&[],move||{calls+=1;calls>3},None);
assert_eq!(r.err(),Some(SpecError::Cancelled));
assert!(c.finished(),"a cancelled request is closed");
assert!(!e.commit_pending());
}
#[test]
fn serve_request_a_failed_emit_still_finishes_the_round_and_closes_the_request() {
let p=prompt_long();
let (r,out,c,e)=serve(&p,50,&[],||false,Some(1));
assert_eq!(r.err(),Some(SpecError::Forward(Error::InputRead)));
assert!(!out.is_empty());
assert!(c.finished()&&!e.commit_pending());
}
}