STRA-338 size-fn: strata-control: worker generate, wrap-up, run_session within the function limits (fn>30 8 -> 0)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 18:36:15 +01:00
parent a8eae529ae
commit 85bd2ac8bb
3 changed files with 159 additions and 83 deletions
+6 -14
View File
@@ -73,20 +73,12 @@ pub(super) async fn generate(
}
.ok_or("engine exited before a terminal line")?;
watch.line_read();
match wire::parse_line(&line)? {
Some(Event::Error(message)) => {
run.engine_error(message).await;
return Ok(());
}
Some(Event::Done(done)) => {
if run.on_done(done, pipe).await?.is_break() {
return Ok(());
}
}
Some(Event::PromptProgress { .. }) if !run.first_pass => {}
Some(_) if run.stopped || run.wrap_pending => {}
Some(event) => run.on_event(event, pipe, stop_deadline.as_mut()).await?,
None => {}
if run
.on_line(&line, pipe, stop_deadline.as_mut())
.await?
.is_break()
{
return Ok(());
}
}
}
+37 -7
View File
@@ -164,6 +164,27 @@ impl<'a> Generation<'a> {
Ok(())
}
/// One line of the engine: an error or `DONE` ends the request, a token or progress goes to the client.
pub(super) async fn on_line(
&mut self,
line: &str,
pipe: &mut ChildStdin,
deadline: Pin<&mut Sleep>,
) -> Result<ControlFlow<()>, String> {
match wire::parse_line(line)? {
Some(Event::Error(message)) => {
self.engine_error(message).await;
return Ok(ControlFlow::Break(()));
}
Some(Event::Done(done)) => return self.on_done(done, pipe).await,
Some(Event::PromptProgress { .. }) if !self.first_pass => {}
Some(_) if self.stopped || self.wrap_pending => {}
Some(event) => self.on_event(event, pipe, deadline).await?,
None => {}
}
Ok(ControlFlow::Continue(()))
}
/// The engine reported an error: fail the request.
pub(super) async fn engine_error(&mut self, message: String) {
self.status.write().await.metrics.fail();
@@ -209,16 +230,28 @@ impl<'a> Generation<'a> {
let Some((_, plan)) = self.budget.take() else {
return Err("reasoning budget state lost".into());
};
let room = i64::from(self.command.request.max_new)
- i64::try_from(self.generated).unwrap_or(i64::MAX)
- i64::try_from(plan.wrap_up.len()).unwrap_or(i64::MAX);
if room < 1 {
if self.room_after_wrap_up(&plan) < 1 {
// No room left to answer: "length", as without a budget.
let finish = wire::Finish::Length;
let combined = combine_done(&self.passes[0], &self.passes, self.generated, finish);
self.finish_with(combined, false).await?;
return Ok(ControlFlow::Break(()));
}
self.deliver_wrap_up(&plan).await;
self.start_continuation(&plan, pipe).await?;
self.first_pass = false;
Ok(ControlFlow::Continue(()))
}
/// What is left of the output budget once the wrap-up text is delivered.
fn room_after_wrap_up(&self, plan: &wire::ReasoningPlan) -> i64 {
i64::from(self.command.request.max_new)
- i64::try_from(self.generated).unwrap_or(i64::MAX)
- i64::try_from(plan.wrap_up.len()).unwrap_or(i64::MAX)
}
/// Log the budget and hand the wrap-up tokens to the client.
async fn deliver_wrap_up(&mut self, plan: &wire::ReasoningPlan) {
crate::elog!(
"thinking budget reached ({} tokens): wrapping up the thinking",
plan.budget
@@ -227,9 +260,6 @@ impl<'a> Generation<'a> {
self.generated += 1;
deliver(self.command, &mut self.events, Event::Token(*id)).await;
}
self.start_continuation(&plan, pipe).await?;
self.first_pass = false;
Ok(ControlFlow::Continue(()))
}
/// The second pass: the prompt, this pass's tokens and the wrap-up text, with what is left of the output budget.
+116 -62
View File
@@ -78,6 +78,17 @@ async fn generate_within_deadline(
}
}
/// The command parked in the inbox, or else the next one from the queue.
async fn next_command(
inbox: &mut Option<GenerationCommand>,
requests: &mut mpsc::Receiver<GenerationCommand>,
) -> Option<GenerationCommand> {
match inbox.take() {
Some(command) => Some(command),
None => requests.recv().await,
}
}
/// The engine process and the channels one supervised session listens on.
struct Session<'a> {
config: &'a WorkerConfig,
@@ -103,34 +114,50 @@ pub(super) async fn run_session(
inbox: &mut Option<GenerationCommand>,
waiting: &mut Vec<LoadReply>,
) -> SessionExit {
let mut child = match spawn_engine(config, status, shutdown).await {
Ok(child) => child,
Err(exit) => return exit,
};
// Keep stdin outside Child: Child::wait closes any stdin it still owns.
let stdin = child.stdin.take();
let stdout = child.stdout.take().expect("piped engine stdout");
let lines = BufReader::new(stdout).lines();
let mut session = Session {
config,
status,
shutdown,
requests,
control,
inbox,
waiting,
child,
stdin,
lines,
requests_closed: false,
control_closed: false,
};
let mut session =
match Session::open(config, status, shutdown, requests, control, inbox, waiting).await {
Ok(session) => session,
Err(exit) => return exit,
};
match session.wait_ready().await {
Ok(max_context) => session.serve(max_context).await,
Err(exit) => exit,
}
}
impl<'a> Session<'a> {
/// Spawn the engine and attach the session to its pipes.
async fn open(
config: &'a WorkerConfig,
status: &'a RwLock<WorkerStatus>,
shutdown: &'a mut watch::Receiver<bool>,
requests: &'a mut mpsc::Receiver<GenerationCommand>,
control: &'a mut mpsc::Receiver<Control>,
inbox: &'a mut Option<GenerationCommand>,
waiting: &'a mut Vec<LoadReply>,
) -> Result<Self, SessionExit> {
let mut child = spawn_engine(config, status, shutdown).await?;
// Keep stdin outside Child: Child::wait closes any stdin it still owns.
let stdin = child.stdin.take();
let stdout = child.stdout.take().expect("piped engine stdout");
let lines = BufReader::new(stdout).lines();
Ok(Self {
config,
status,
shutdown,
requests,
control,
inbox,
waiting,
child,
stdin,
lines,
requests_closed: false,
control_closed: false,
})
}
}
impl Session<'_> {
/// The shutdown signal arrived: stop the engine through the protocol.
async fn stopped_by_shutdown(&mut self) -> SessionExit {
@@ -151,22 +178,8 @@ impl Session<'_> {
let startup_deadline = tokio::time::sleep(self.config.startup_timeout);
tokio::pin!(startup_deadline);
loop {
let line = tokio::select! {
biased;
_ = self.shutdown.changed() => return Err(self.stopped_by_shutdown().await),
_ = &mut startup_deadline => {
crate::elog!("Strata engine did not become ready before the startup timeout");
return Err(self.startup_failed().await);
}
message = self.control.recv(), if !self.control_closed => {
self.answer_starting_control(message);
continue;
}
command = self.requests.recv(), if !self.requests_closed => {
self.refuse_starting_request(command).await;
continue;
}
line = self.lines.next_line() => line,
let Some(line) = self.next_startup_line(startup_deadline.as_mut()).await? else {
continue;
};
if let Some(max_context) = self.on_startup_line(line).await? {
return Ok(max_context);
@@ -174,6 +187,31 @@ impl Session<'_> {
}
}
/// The next engine line before READY; `None` when a control message or request was answered instead.
async fn next_startup_line(
&mut self,
mut deadline: std::pin::Pin<&mut tokio::time::Sleep>,
) -> Result<Option<std::io::Result<Option<String>>>, SessionExit> {
let line = tokio::select! {
biased;
_ = self.shutdown.changed() => return Err(self.stopped_by_shutdown().await),
_ = &mut deadline => {
crate::elog!("Strata engine did not become ready before the startup timeout");
return Err(self.startup_failed().await);
}
message = self.control.recv(), if !self.control_closed => {
self.answer_starting_control(message);
return Ok(None);
}
command = self.requests.recv(), if !self.requests_closed => {
self.refuse_starting_request(command).await;
return Ok(None);
}
line = self.lines.next_line() => line,
};
Ok(Some(line))
}
fn answer_starting_control(&mut self, message: Option<Control>) {
match message {
Some(Control::Reconfigure { reply, .. }) => {
@@ -247,12 +285,7 @@ impl Session<'_> {
return exit;
}
},
command = async {
match self.inbox.take() {
Some(command) => Some(command),
None => self.requests.recv().await,
}
}, if !self.requests_closed => {
command = next_command(self.inbox, self.requests), if !self.requests_closed => {
if let Some(exit) = self.serve_command(command, max_context).await {
return exit;
}
@@ -283,21 +316,7 @@ impl Session<'_> {
idle_for: Option<Duration>,
reply: oneshot::Sender<leleka_serving_policy::idle::Outcome>,
) -> Option<SessionExit> {
let idle_s = self
.status
.read()
.await
.last_activity
.map_or(f64::MAX, |at| at.elapsed().as_secs_f64());
let outcome = leleka_serving_policy::idle::decide(
leleka_serving_policy::idle::Situation {
supported: true,
loaded: true,
busy: self.inbox.is_some() || !self.requests.is_empty(),
idle_s,
},
idle_for.map(|d| d.as_secs_f64()),
);
let outcome = self.unload_outcome(idle_for).await;
if outcome == leleka_serving_policy::idle::Outcome::Unloaded {
update(self.status, WorkerState::Unloaded, None).await;
stop(&mut self.child, &mut self.stdin).await;
@@ -311,6 +330,28 @@ impl Session<'_> {
None
}
/// What the idle policy decides about unloading right now.
async fn unload_outcome(
&self,
idle_for: Option<Duration>,
) -> leleka_serving_policy::idle::Outcome {
let idle_s = self
.status
.read()
.await
.last_activity
.map_or(f64::MAX, |at| at.elapsed().as_secs_f64());
leleka_serving_policy::idle::decide(
leleka_serving_policy::idle::Situation {
supported: true,
loaded: true,
busy: self.inbox.is_some() || !self.requests.is_empty(),
idle_s,
},
idle_for.map(|d| d.as_secs_f64()),
)
}
/// One request: run it on the engine unless the client left or the queue ticket was lost.
async fn serve_command(
&mut self,
@@ -329,11 +370,24 @@ impl Session<'_> {
// Retain the command activity until protocol cleanup,
// including STOP/QUIT and failed-process termination.
let _activity = command.activity.take();
// The encoder and the engine never use the GPU at the same time.
let _turn = match &self.config.vision {
let _turn = self.vision_turn().await;
self.generate_or_shutdown(command, max_context).await
}
/// The encoder and the engine never use the GPU at the same time.
async fn vision_turn(&self) -> Option<tokio::sync::OwnedMutexGuard<()>> {
match &self.config.vision {
Some(vision) => Some(vision.gate.clone().lock_owned().await),
None => None,
};
}
}
/// Run the command on the engine, unless the supervisor shuts down first.
async fn generate_or_shutdown(
&mut self,
mut command: GenerationCommand,
max_context: usize,
) -> Option<SessionExit> {
tokio::select! {
(timed_out, result) = generate_within_deadline(
&mut self.stdin,