diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index b1e3ff89d..01a2356f2 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -65,9 +65,9 @@ pub use shape::{Harvest, RECORDS_CHARS, Shaper}; pub use task::{ BrowserRunner, CaptureFuture, ContinuePaidAtShopRequest, ContinuePaymentRequest, FailedStepRecovery, FailedStepRecoveryFuture, FailedStepRecoveryResult, FlowFuture, FlowRunner, - MAX_AWAIT_MS, MAX_TASKS, PageOriginFuture, PausedTaskError, PlanRecoveryFuture, - PlanRecoveryRequest, PlanRecoveryResult, PrepareFuture, SecretHost, SecretTypeRequest, Tasks, - TextFuture, capabilities, + HostWorkGuard, MAX_AWAIT_MS, MAX_TASKS, PageOriginFuture, PausedTaskError, PlanRecoveryFuture, + PlanRecoveryRequest, PlanRecoveryResult, PrepareFuture, SecretHost, SecretTypeRequest, + TaskBudgetScope, TaskCallBudget, Tasks, TextFuture, capabilities, }; pub use tinycomputer_bus::DesktopResponse; #[cfg(feature = "desktop")] diff --git a/crates/tinycomputer-engine/src/task/budget.rs b/crates/tinycomputer-engine/src/task/budget.rs index 22a73bf16..f22fea781 100644 --- a/crates/tinycomputer-engine/src/task/budget.rs +++ b/crates/tinycomputer-engine/src/task/budget.rs @@ -2,6 +2,10 @@ //! what the task has not spent, and ending a task whose time ran out. use std::collections::BTreeMap; +use std::fmt; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Weak}; +use std::time::Instant; use tinycomputer_bus::RunFlowRequest; use tinycomputer_bus::agent::{TaskConstraints, TaskStatus}; @@ -13,6 +17,258 @@ use super::publish::{publish, stopped_summary}; use super::store::{Cell, Run}; use super::{DEFAULT_MODEL_CALLS, DEFAULT_VOTES, FlowRunner}; +/// A handle to reserve host model calls against this task's Jev evaluation +/// budget. Hosts must reserve before starting provider I/O; a reservation is +/// not refunded when that I/O fails or is cancelled. +#[derive(Clone)] +pub struct TaskCallBudget { + cell: Weak, +} + +impl TaskCallBudget { + pub(super) fn for_cell(cell: Weak) -> Self { + Self { cell } + } + + /// Starts one host-work interval. Its elapsed time is charged when the + /// returned guard is dropped, even if a callback retains its scope. + #[must_use] + pub fn begin_work(&self) -> Option { + self.begin(false) + } + + /// Starts a scoped payment-mapping interval on the task's one available + /// non-continuable payment checkpoint. This is host-only authority; generic + /// task continuation remains unavailable at that checkpoint. + #[must_use] + pub fn begin_payment_work(&self) -> Option { + self.begin(true) + } + + fn begin(&self, payment_checkpoint: bool) -> Option { + let cell = self.cell.upgrade()?; + let mut state = cell.state.lock().ok()?; + let is_payment_checkpoint = matches!( + &cell.view.borrow().status, + tinycomputer_bus::agent::TaskStatus::Checkpoint { + continuable: false, + .. + } + ); + let authorized_payment_checkpoint = payment_checkpoint + && state.payment_checkpoint == super::store::PaymentCheckpointState::Available + && is_payment_checkpoint; + let state_allows_work = if payment_checkpoint { + state.host_work == super::store::HostWorkState::Closed && authorized_payment_checkpoint + } else { + state.host_work == super::store::HostWorkState::Open + }; + if !state_allows_work + || state + .budget + .max_elapsed_ms + .is_some_and(|max| state.spent.elapsed_ms >= max) + { + return None; + } + state.host_work = if payment_checkpoint { + super::store::HostWorkState::PaymentActive + } else { + super::store::HostWorkState::Active + }; + drop(state); + Some(HostWorkGuard { + inner: Arc::new(HostWork { + cell: Arc::downgrade(&cell), + started: Instant::now(), + charged: AtomicBool::new(false), + payment_checkpoint, + }), + }) + } +} + +impl fmt::Debug for TaskCallBudget { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TaskCallBudget") + .finish_non_exhaustive() + } +} + +/// One cloneable host-work interval, shared with the request passed to the +/// host callback. Its owning guard charges active time once when dropped. +#[derive(Clone)] +pub struct TaskBudgetScope { + inner: Arc, +} + +/// Owns one host-work interval. The task is charged when this guard is dropped, +/// even if a callback retained a clone of its [`TaskBudgetScope`]. +pub struct HostWorkGuard { + inner: Arc, +} + +impl HostWorkGuard { + /// A cloneable view a host callback can retain and use for live checks. + #[must_use] + pub fn scope(&self) -> TaskBudgetScope { + TaskBudgetScope { + inner: self.inner.clone(), + } + } +} + +impl fmt::Debug for HostWorkGuard { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("HostWorkGuard") + .finish_non_exhaustive() + } +} + +impl Drop for HostWorkGuard { + fn drop(&mut self) { + self.inner.charge(); + } +} + +impl TaskBudgetScope { + /// Reserves one task model call before the host starts a provider request. + /// The reservation remains spent if the request fails or is cancelled. + #[must_use] + pub fn try_reserve_model_call(&self) -> bool { + let Some(cell) = self.inner.cell.upgrade() else { + return false; + }; + let Ok(mut state) = cell.state.lock() else { + return false; + }; + if !self.inner.is_active(&cell, &state) { + return false; + } + if state.budget.max_elapsed_ms.is_some_and(|max| { + state.spent.elapsed_ms.saturating_add( + u64::try_from(self.inner.started.elapsed().as_millis()).unwrap_or(u64::MAX), + ) >= max + }) { + return false; + } + let max = state.budget.max_model_calls.unwrap_or(DEFAULT_MODEL_CALLS); + if state.spent.model_calls >= max { + return false; + } + state.spent.model_calls = state.spent.model_calls.saturating_add(1); + true + } + + /// The calls remaining at this instant, including other host reservations. + #[must_use] + pub fn remaining_model_calls(&self) -> u32 { + let Some(cell) = self.inner.cell.upgrade() else { + return 0; + }; + let Ok(state) = cell.state.lock() else { + return 0; + }; + if !self.inner.is_active(&cell, &state) { + return 0; + } + if state.budget.max_elapsed_ms.is_some_and(|max| { + state.spent.elapsed_ms.saturating_add( + u64::try_from(self.inner.started.elapsed().as_millis()).unwrap_or(u64::MAX), + ) >= max + }) { + return 0; + } + state + .budget + .max_model_calls + .unwrap_or(DEFAULT_MODEL_CALLS) + .saturating_sub(state.spent.model_calls) + } + + /// The task's remaining active time at this instant, including this host + /// work interval. `None` means the task has no elapsed-time cap. + #[must_use] + pub fn remaining_ms(&self) -> Option { + let cell = self.inner.cell.upgrade()?; + let state = cell.state.lock().ok()?; + if !self.inner.is_active(&cell, &state) { + return Some(0); + } + state.budget.max_elapsed_ms.map(|max| { + max.saturating_sub(state.spent.elapsed_ms).saturating_sub( + u64::try_from(self.inner.started.elapsed().as_millis()).unwrap_or(u64::MAX), + ) + }) + } +} + +impl fmt::Debug for TaskBudgetScope { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TaskBudgetScope") + .finish_non_exhaustive() + } +} + +struct HostWork { + cell: Weak, + started: Instant, + charged: AtomicBool, + payment_checkpoint: bool, +} + +impl HostWork { + fn is_active(&self, cell: &Cell, state: &super::store::State) -> bool { + if self.charged.load(Ordering::Acquire) { + return false; + } + match state.host_work { + super::store::HostWorkState::Active => !self.payment_checkpoint, + super::store::HostWorkState::PaymentActive => { + self.payment_checkpoint + && state.payment_checkpoint == super::store::PaymentCheckpointState::Available + && matches!( + &cell.view.borrow().status, + tinycomputer_bus::agent::TaskStatus::Checkpoint { + continuable: false, + .. + } + ) + } + super::store::HostWorkState::Open | super::store::HostWorkState::Closed => false, + } + } + + fn charge(&self) { + let Some(cell) = self.cell.upgrade() else { + self.charged.store(true, Ordering::Release); + return; + }; + let Ok(mut state) = cell.state.lock() else { + self.charged.store(true, Ordering::Release); + return; + }; + if self.charged.swap(true, Ordering::AcqRel) { + return; + } + state.host_work = match state.host_work { + super::store::HostWorkState::PaymentActive | super::store::HostWorkState::Closed => { + super::store::HostWorkState::Closed + } + super::store::HostWorkState::Active | super::store::HostWorkState::Open => { + super::store::HostWorkState::Open + } + }; + state.spent.elapsed_ms = state + .spent + .elapsed_ms + .saturating_add(u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX)); + } +} + /// Builds the next `RunFlowRequest` for `run`, capped at what the task's /// budget has not already spent, along with the constraints to run it under /// and how much of `max_elapsed_ms` remains (`None` when it is unbounded). diff --git a/crates/tinycomputer-engine/src/task/mod.rs b/crates/tinycomputer-engine/src/task/mod.rs index 59b4d6d0d..66720ef5a 100644 --- a/crates/tinycomputer-engine/src/task/mod.rs +++ b/crates/tinycomputer-engine/src/task/mod.rs @@ -121,6 +121,7 @@ fn redact_value(value: &mut serde_json::Value, redact: &impl Fn(&str) -> String) } pub use browser::BrowserRunner; +pub use budget::{HostWorkGuard, TaskBudgetScope, TaskCallBudget}; pub use controller::{ContinuePaidAtShopRequest, ContinuePaymentRequest, Tasks}; pub use describe::capabilities; pub(crate) use names::input_kind; @@ -160,6 +161,8 @@ pub struct FailedStepRecovery { pub remaining_model_calls: u32, /// Time left in the task budget, when bounded. pub remaining_ms: Option, + /// The shared task budget for host model calls and active recovery time. + pub host_budget: TaskBudgetScope, } /// What a host's bounded failed-step recovery did. @@ -205,6 +208,8 @@ pub struct PlanRecoveryRequest { pub remaining_model_calls: u32, /// Time left in the task budget, when bounded. pub remaining_ms: Option, + /// The shared task budget for host model calls and active planning time. + pub host_budget: TaskBudgetScope, } /// A same-task plan the host derived, or why it could not derive one. diff --git a/crates/tinycomputer-engine/src/task/persistence.rs b/crates/tinycomputer-engine/src/task/persistence.rs index 1aea8c0ae..e8a0ffe54 100644 --- a/crates/tinycomputer-engine/src/task/persistence.rs +++ b/crates/tinycomputer-engine/src/task/persistence.rs @@ -12,7 +12,7 @@ use tinycomputer_core::{Facts, SecretFactHandle}; use super::interpret::Resume; use super::publish::{needs_input, publish}; use super::store::{Cell, Spent, State}; -use super::{MAX_TASKS, Tasks}; +use super::{MAX_TASKS, TaskCallBudget, Tasks}; use crate::rescue::Rescuer; use crate::{UsageRecorder, shape::Shaper}; @@ -415,10 +415,10 @@ fn build_cell( ) -> Arc { let usage = Arc::new(UsageRecorder::from_snapshot(task.usage)); task.view.usage = usage.snapshot(); - Arc::new(Cell { + let cell = Arc::new(Cell { view: tokio::sync::watch::Sender::new(task.view.clone()), state: std::sync::Mutex::new(State { - usage, + usage: usage.clone(), flow: task.flow, handoff_to_planner: task.handoff_to_planner, goal: task.goal, @@ -437,6 +437,7 @@ fn build_cell( resume: task.resume, payment_checkpoint: super::store::PaymentCheckpointState::Unavailable, spent: task.spent, + host_work: super::store::HostWorkState::Open, rescues: task.rescues, output: task.output, artifacts: task.artifacts, @@ -447,7 +448,9 @@ fn build_cell( rescuer, shaper, planner, - }) + }); + usage.set_task_call_budget(TaskCallBudget::for_cell(Arc::downgrade(&cell))); + cell } fn resumable(status: &TaskStatus) -> bool { diff --git a/crates/tinycomputer-engine/src/task/plan_recovery.rs b/crates/tinycomputer-engine/src/task/plan_recovery.rs index 361d039cb..479fd6873 100644 --- a/crates/tinycomputer-engine/src/task/plan_recovery.rs +++ b/crates/tinycomputer-engine/src/task/plan_recovery.rs @@ -1,5 +1,7 @@ //! Host-supplied planning on the existing task and browser session. +use std::time::Duration; + use tinycomputer_bus::Flow; use super::store::Cell; @@ -16,11 +18,14 @@ pub(super) async fn host_plan( guide: String, ) -> Result { let id = { cell.view.borrow().id.clone() }; - let (constraints, budget, spent, known_names, secret_names, facts) = { + let (constraints, budget, spent, known_names, secret_names, facts, task_budget) = { let state = cell .state .lock() .map_err(|_| "task state is unavailable".to_owned())?; + let Some(task_budget) = state.usage.task_call_budget() else { + return Err("the task model-call budget is unavailable".to_owned()); + }; ( state.constraints.clone(), state.budget, @@ -38,8 +43,17 @@ pub(super) async fn host_plan( .map(str::to_owned) .collect::>(), state.facts.clone(), + task_budget, ) }; + let Some(work) = task_budget.begin_work() else { + return Err("the task host-work budget is unavailable".to_owned()); + }; + let host_budget = work.scope(); + let remaining_ms = budget + .max_elapsed_ms + .map(|max| max.saturating_sub(spent.elapsed_ms)); + let timeout_ms = host_budget.remaining_ms().or(remaining_ms); let request = PlanRecoveryRequest { task: id.clone(), task_text: runner.redact(&id, &task_text), @@ -55,11 +69,18 @@ pub(super) async fn host_plan( .max_model_calls .unwrap_or(DEFAULT_MODEL_CALLS) .saturating_sub(spent.model_calls), - remaining_ms: budget - .max_elapsed_ms - .map(|max| max.saturating_sub(spent.elapsed_ms)), + remaining_ms, + host_budget, + }; + let recovery = runner.recover_plan(request); + let result = if let Some(timeout_ms) = timeout_ms { + tokio::time::timeout(Duration::from_millis(timeout_ms), recovery) + .await + .map_err(|_| "the host plan recovery exceeded the task time budget".to_owned())? + } else { + recovery.await }; - let flow = match runner.recover_plan(request).await { + let flow = match result { PlanRecoveryResult::Plan(flow) => flow, PlanRecoveryResult::GiveUp(reason) => { return Err(runner.redact(&id, &reason)); @@ -80,5 +101,6 @@ pub(super) async fn host_plan( let Some(flow) = redact_task_data(runner, &id, flow) else { return Err("the host plan could not be safely redacted".to_owned()); }; + drop(work); Ok(flow) } diff --git a/crates/tinycomputer-engine/src/task/publish.rs b/crates/tinycomputer-engine/src/task/publish.rs index 0bc9a71f0..96e3f9514 100644 --- a/crates/tinycomputer-engine/src/task/publish.rs +++ b/crates/tinycomputer-engine/src/task/publish.rs @@ -25,6 +25,7 @@ pub(super) fn stopped_summary(status: &TaskStatus) -> String { /// Updates a task's view: status, summary, progress, step, and next calls. pub(super) fn publish(cell: &Cell, status: TaskStatus, summary: &str) { + let terminal = status.is_final(); let waits = matches!( status, TaskStatus::NeedsInput { .. } @@ -35,6 +36,9 @@ pub(super) fn publish(cell: &Cell, status: TaskStatus, summary: &str) { cell.state .lock() .map_or((0.0, None, TaskUsage::default()), |mut state| { + if terminal { + state.host_work = super::store::HostWorkState::Closed; + } // The wait starts when the task first asks; publishing the same // pause again does not restart it. state.waiting_since = if waits { diff --git a/crates/tinycomputer-engine/src/task/recovery.rs b/crates/tinycomputer-engine/src/task/recovery.rs index 8a502d5a9..ed0d28e71 100644 --- a/crates/tinycomputer-engine/src/task/recovery.rs +++ b/crates/tinycomputer-engine/src/task/recovery.rs @@ -49,83 +49,103 @@ pub(super) async fn rescued( if let Some(briefing) = fallback_briefing && exact_top_level_tail(&briefing) { - let (constraints, budget, spent) = { - let Ok(state) = cell.state.lock() else { - return Ok(failed_status(failed, reason, hint)); - }; - (state.constraints.clone(), state.budget, state.spent) - }; - let remaining_actions = budget - .max_actions - .unwrap_or(120) - .saturating_sub(spent.actions); - let remaining_model_calls = budget - .max_model_calls - .unwrap_or(super::DEFAULT_MODEL_CALLS) - .saturating_sub(spent.model_calls); - let remaining_ms = budget - .max_elapsed_ms - .map(|max| max.saturating_sub(spent.elapsed_ms)); - let request = FailedStepRecovery { - task: cell.view.borrow().id.clone(), - briefing: briefing.clone(), - constraints, - remaining_actions, - remaining_model_calls, - remaining_ms, - }; - let timeout_ms = remaining_ms - .unwrap_or(RESCUE_TIMEOUT_MS) - .min(RESCUE_TIMEOUT_MS); - let recovered = tokio::time::timeout( - Duration::from_millis(timeout_ms), - runner.recover_failed_step(request), + match recover_failed_step(cell, runner, run, &briefing, failed, reason.clone(), hint).await + { + Ok(recovered) => return Err(recovered), + Err(next_hint) => hint = next_hint, + } + } + Ok(failed_status(failed, reason, hint)) +} + +async fn recover_failed_step( + cell: &Cell, + runner: &dyn FlowRunner, + run: &Run, + briefing: &Briefing, + failed: usize, + failure: String, + hint: String, +) -> Result { + let (constraints, budget, spent, task_budget) = { + let state = cell.state.lock().map_err(|_| hint.clone())?; + let task_budget = state.usage.task_call_budget().ok_or_else(|| hint.clone())?; + ( + state.constraints.clone(), + state.budget, + state.spent, + task_budget, ) - .await; - match recovered { - Ok(FailedStepRecoveryResult::Completed { - reason: recovery_reason, - actions, - model_calls: _, - }) => { - let tail = resumed(&briefing, Vec::new(), 0); - // A final failed step has no remaining Run. Letting an empty - // flow reach RunFlow would turn completion into a false failure. - if tail.steps.is_empty() { - return Ok(failed_status( - failed, - reason, - format!( - "{hint}; host recovery completed the last step but no safe tail exists" - ), - )); - } - if let Ok(mut state) = cell.state.lock() { - state.spent.actions = state.spent.actions.saturating_add(actions); - state.rescues.push(Rescue { - step: failed, - failure: reason, - reason: recovery_reason, - steps: Vec::new(), - covers: 0, - outcome: RescueOutcome::Recovered, - }); - } - return Err(Run { - flow: tail, - allow_destructive: run.allow_destructive, - rescue: None, - }); - } - Ok(FailedStepRecoveryResult::GiveUp { reason: why }) => { - hint = format!("{hint}; host recovery gave up: {why}"); + }; + let Some(work) = task_budget.begin_work() else { + return Err(format!("{hint}; the task host-work budget is unavailable")); + }; + let host_budget = work.scope(); + let remaining_actions = budget + .max_actions + .unwrap_or(120) + .saturating_sub(spent.actions); + let remaining_model_calls = budget + .max_model_calls + .unwrap_or(super::DEFAULT_MODEL_CALLS) + .saturating_sub(spent.model_calls); + let remaining_ms = budget + .max_elapsed_ms + .map(|max| max.saturating_sub(spent.elapsed_ms)); + let timeout_ms = host_budget + .remaining_ms() + .or(remaining_ms) + .unwrap_or(RESCUE_TIMEOUT_MS) + .min(RESCUE_TIMEOUT_MS); + let request = FailedStepRecovery { + task: cell.view.borrow().id.clone(), + briefing: briefing.clone(), + constraints, + remaining_actions, + remaining_model_calls, + remaining_ms, + host_budget, + }; + let recovered = tokio::time::timeout( + Duration::from_millis(timeout_ms), + runner.recover_failed_step(request), + ) + .await; + drop(work); + match recovered { + Ok(FailedStepRecoveryResult::Completed { + reason, + actions, + model_calls: _, + }) => { + let tail = resumed(briefing, Vec::new(), 0); + if tail.steps.is_empty() { + return Err(format!( + "{hint}; host recovery completed the last step but no safe tail exists" + )); } - Err(_) => { - hint = format!("{hint}; host recovery took too long"); + if let Ok(mut state) = cell.state.lock() { + state.spent.actions = state.spent.actions.saturating_add(actions); + state.rescues.push(Rescue { + step: failed, + failure, + reason, + steps: Vec::new(), + covers: 0, + outcome: RescueOutcome::Recovered, + }); } + Ok(Run { + flow: tail, + allow_destructive: run.allow_destructive, + rescue: None, + }) + } + Ok(FailedStepRecoveryResult::GiveUp { reason }) => { + Err(format!("{hint}; host recovery gave up: {reason}")) } + Err(_) => Err(format!("{hint}; host recovery took too long")), } - Ok(failed_status(failed, reason, hint)) } fn failed_status(failed: usize, reason: String, hint: String) -> TaskStatus { diff --git a/crates/tinycomputer-engine/src/task/store.rs b/crates/tinycomputer-engine/src/task/store.rs index 9e4f06f39..7ff03023f 100644 --- a/crates/tinycomputer-engine/src/task/store.rs +++ b/crates/tinycomputer-engine/src/task/store.rs @@ -19,7 +19,7 @@ use super::drive::{drive, plan_then_drive}; use super::errors::too_many; use super::interpret::Resume; use super::publish::{next_calls, publish}; -use super::{MAX_TASKS, Tasks}; +use super::{MAX_TASKS, TaskCallBudget, Tasks}; use crate::UsageRecorder; use crate::rescue::Rescuer; use crate::shape::Shaper; @@ -85,6 +85,8 @@ pub(super) struct State { /// human intervention that splits a task into several runs still cannot /// exceed its declared budget by starting each run with a fresh one. pub(super) spent: Spent, + /// Host model work is single-flight and closed after terminal task status. + pub(super) host_work: HostWorkState, /// Every rescue so far, in order. pub(super) rescues: Vec, /// The shape the caller wants the answer in, if any. @@ -144,7 +146,7 @@ impl Tasks { let cell = Arc::new(Cell { view: watch::Sender::new(view), state: Mutex::new(State { - usage, + usage: usage.clone(), flow: flow.clone(), handoff_to_planner: request.handoff_to_planner, goal: request.task.clone().unwrap_or_default(), @@ -163,6 +165,7 @@ impl Tasks { resume: None, payment_checkpoint: PaymentCheckpointState::Unavailable, spent: Spent::default(), + host_work: HostWorkState::Open, rescues: Vec::new(), output: request.output.clone(), artifacts: Vec::new(), @@ -174,6 +177,7 @@ impl Tasks { shaper: self.shaper.clone(), planner: self.planner.clone(), }); + usage.set_task_call_budget(TaskCallBudget::for_cell(Arc::downgrade(&cell))); let mut tasks = self.cells.lock().ok()?; while tasks.len() >= MAX_TASKS { let oldest_final = tasks @@ -365,6 +369,14 @@ pub(super) enum PaymentCheckpointState { Closed, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum HostWorkState { + Open, + Active, + PaymentActive, + Closed, +} + pub(super) struct WorkerCompletion(watch::Sender); impl WorkerCompletion { diff --git a/crates/tinycomputer-engine/src/task/task_tests.rs b/crates/tinycomputer-engine/src/task/task_tests.rs index cfca0b7fd..78870cd16 100644 --- a/crates/tinycomputer-engine/src/task/task_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests.rs @@ -84,6 +84,14 @@ struct Script { recoveries: Mutex>, /// The host's planless recovery response. plan_recovery: Mutex>, + /// Reserve host model calls in tests that exercise the task-wide budget. + reserve_host_calls: Mutex, + /// Whether each scripted host reservation was accepted. + host_call_reservations: Mutex>, + /// Delay inside the host plan-recovery callback. + plan_recovery_delay: Mutex, + /// Whether failed-step recovery remains pending until its budget timeout. + hang_recovery: Mutex, /// Planless recovery requests, including named-only facts. plan_requests: Mutex>, } @@ -108,13 +116,30 @@ impl FlowRunner for Script { } fn recover_failed_step(&self, request: FailedStepRecovery) -> FailedStepRecoveryFuture { + let reserve = *self.reserve_host_calls.lock().unwrap(); + let reservation = reserve.then(|| request.host_budget.try_reserve_model_call()); + if let Some(accepted) = reservation { + self.host_call_reservations.lock().unwrap().push(accepted); + } + let hang = *self.hang_recovery.lock().unwrap(); self.recoveries.lock().unwrap().push(request); - let result = self.recovery.lock().unwrap().take().unwrap_or_else(|| { + let result = if reservation == Some(false) { FailedStepRecoveryResult::GiveUp { - reason: "no scripted recovery".to_owned(), + reason: "the task model-call budget is spent".to_owned(), + } + } else { + self.recovery.lock().unwrap().take().unwrap_or_else(|| { + FailedStepRecoveryResult::GiveUp { + reason: "no scripted recovery".to_owned(), + } + }) + }; + Box::pin(async move { + if hang { + std::future::pending::().await; } - }); - Box::pin(async move { result }) + result + }) } fn plan_recovery_enabled(&self) -> bool { @@ -122,14 +147,28 @@ impl FlowRunner for Script { } fn recover_plan(&self, request: PlanRecoveryRequest) -> PlanRecoveryFuture { + let reserve = *self.reserve_host_calls.lock().unwrap(); + let reservation = reserve.then(|| request.host_budget.try_reserve_model_call()); + if let Some(accepted) = reservation { + self.host_call_reservations.lock().unwrap().push(accepted); + } + let delay = *self.plan_recovery_delay.lock().unwrap(); self.plan_requests.lock().unwrap().push(request); - let result = self - .plan_recovery - .lock() - .unwrap() - .take() - .unwrap_or_else(|| PlanRecoveryResult::GiveUp("no scripted plan recovery".to_owned())); - Box::pin(async move { result }) + let result = if reservation == Some(false) { + PlanRecoveryResult::GiveUp("the task model-call budget is spent".to_owned()) + } else { + self.plan_recovery + .lock() + .unwrap() + .take() + .unwrap_or_else(|| { + PlanRecoveryResult::GiveUp("no scripted plan recovery".to_owned()) + }) + }; + Box::pin(async move { + tokio::time::sleep(delay).await; + result + }) } fn visible_text(&self, _task: &TaskId) -> super::TextFuture { diff --git a/crates/tinycomputer-engine/src/task/task_tests/payment_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/payment_tests.rs index a143538fe..84b087a8b 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/payment_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/payment_tests.rs @@ -151,6 +151,37 @@ async fn generic_continue_and_missing_handles_cannot_authorize_a_payment_checkpo assert_eq!(script.requests.lock().unwrap().len(), 1); } +#[tokio::test] +async fn host_payment_mapping_can_reserve_at_its_checkpoint_until_cancelled() { + let (tasks, _script, started) = payment_task(vec![payment_checkpoint()], false); + assert!(matches!( + settle(&tasks, &started.id).await.status, + TaskStatus::Checkpoint { + continuable: false, + .. + } + )); + let cell = tasks.cells.lock().unwrap().values().next().unwrap().clone(); + let budget = cell.state.lock().unwrap().usage.task_call_budget().unwrap(); + assert!( + budget.begin_work().is_none(), + "generic host work cannot reopen a final payment checkpoint" + ); + let work = budget + .begin_payment_work() + .expect("the host may map payment details at its checkpoint"); + let scope = work.scope(); + assert!(scope.try_reserve_model_call()); + + let _ = tasks.cancel(&started.id); + assert!( + !scope.try_reserve_model_call(), + "cancelling closes the host-only payment mapping grant" + ); + assert_eq!(scope.remaining_model_calls(), 0); + assert_eq!(scope.remaining_ms(), Some(0)); +} + #[tokio::test] async fn a_cancelled_payment_checkpoint_cannot_be_reauthorized() { let (tasks, script, started) = payment_task(vec![payment_checkpoint()], false); diff --git a/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs index 921b098b3..918d2aa44 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs @@ -1,6 +1,7 @@ //! Tests for planning a plain-language task before running it. use super::super::store::Run; +use super::failed_at_step_two; use super::*; use crate::planner::{LanguageModel, Planner, Turn}; use tinycomputer_bus::agent::SurfaceKind; @@ -66,14 +67,13 @@ async fn a_plain_language_task_is_planned_then_run() { Ok(r#"{"app": "Mail", "steps": [{"enter": {"recipient": "${email}"}}]}"#), ); assert!(tasks.planner_configured()); - let started = tasks - .start(&StartTaskRequest { - task: Some("email Sam".to_owned()), - facts: BTreeMap::from([("email".to_owned(), "sam@example.com".to_owned())]), - ..StartTaskRequest::default() - }) - .data - .unwrap(); + let reply = tasks.start(&StartTaskRequest { + task: Some("email Sam".to_owned()), + facts: BTreeMap::from([("email".to_owned(), "sam@example.com".to_owned())]), + ..StartTaskRequest::default() + }); + assert!(reply.ok, "{:?}", reply.error); + let started = reply.data.unwrap(); assert_eq!(started.summary, "Planning the task."); assert!(matches!( settle(&tasks, &started.id).await.status, @@ -637,6 +637,199 @@ async fn host_recovers_a_failed_planner_without_replacing_the_task() { assert_eq!(script.plan_requests.lock().unwrap()[0].task, started.id); } +#[tokio::test] +async fn plan_recovery_and_a_later_failed_step_share_one_host_call_budget() { + let plan = flow(json!({"app":"browser","steps":[ + {"browse":"https://flights.test"}, + "search for flights", + "open the cheapest result" + ]})); + let (tasks, script) = planned(vec![failed_at_step_two()], Err("planner failed")); + *script.plan_recovery.lock().unwrap() = Some(PlanRecoveryResult::Plan(plan)); + *script.reserve_host_calls.lock().unwrap() = true; + let started = tasks + .start(&StartTaskRequest { + task: Some("find the cheapest flight".to_owned()), + budget: tinycomputer_bus::agent::TaskBudget { + max_model_calls: Some(1), + ..tinycomputer_bus::agent::TaskBudget::default() + }, + ..StartTaskRequest::default() + }) + .data + .unwrap(); + + assert!(matches!( + settle(&tasks, &started.id).await.status, + TaskStatus::Failed { .. } + )); + assert_eq!( + script.plan_requests.lock().unwrap()[0].remaining_model_calls, + 1 + ); + assert_eq!(script.requests.lock().unwrap()[0].max_model_calls, 0); + let recovery = script.recoveries.lock().unwrap(); + assert_eq!(recovery.len(), 1); + assert_eq!(recovery[0].remaining_model_calls, 0); + assert_eq!( + *script.host_call_reservations.lock().unwrap(), + [true, false] + ); + let cell = tasks.cells.lock().unwrap().values().next().unwrap().clone(); + assert_eq!(cell.state.lock().unwrap().spent.model_calls, 1); +} + +#[tokio::test] +async fn failed_native_handoff_charges_host_plan_elapsed_once() { + let prefix = flow(json!({"app":"browser","steps":["safe prefix"]})); + let (tasks, script) = planned( + vec![ + finished_run(FlowStopReason::Completed, vec![], &[], None), + finished_run(FlowStopReason::Completed, vec![], &[], None), + ], + Err("planner failed"), + ); + *script.plan_recovery.lock().unwrap() = Some(PlanRecoveryResult::Plan(flow(json!({ + "app":"browser","steps":["host continuation"] + })))); + let delay = std::time::Duration::from_millis(40); + *script.plan_recovery_delay.lock().unwrap() = delay; + let max_elapsed_ms = 10_000; + let started = tasks + .start(&StartTaskRequest { + task: Some("buy a lamp".to_owned()), + flow: Some(prefix), + handoff_to_planner: true, + constraints: TaskConstraints { + surfaces: vec![SurfaceKind::Browser], + ..TaskConstraints::default() + }, + budget: tinycomputer_bus::agent::TaskBudget { + max_elapsed_ms: Some(max_elapsed_ms), + ..tinycomputer_bus::agent::TaskBudget::default() + }, + ..StartTaskRequest::default() + }) + .data + .unwrap(); + assert!(matches!( + settle(&tasks, &started.id).await.status, + TaskStatus::Done { .. } + )); + + let remaining_before_host = script.plan_requests.lock().unwrap()[0] + .remaining_ms + .unwrap(); + let spent_after_host = tasks + .cells + .lock() + .unwrap() + .values() + .next() + .unwrap() + .state + .lock() + .unwrap() + .spent + .elapsed_ms; + let already_spent = max_elapsed_ms.saturating_sub(remaining_before_host); + let host_elapsed = spent_after_host.saturating_sub(already_spent); + assert!( + (u64::try_from(delay.as_millis()).unwrap()..=100).contains(&host_elapsed), + "host plan elapsed must be charged once after the native PlanningDebit, got {host_elapsed} ms" + ); +} + +#[tokio::test] +async fn a_retained_plan_scope_cannot_reserve_after_its_guard_is_dropped() { + let (tasks, script) = controller(vec![finished_run( + FlowStopReason::StoppedBeforeDestructive, + vec![step( + "1", + "stop_before", + "pay now", + StepOutcome::Gated, + "found payment", + )], + &[], + Some("Pay now"), + )]); + *script.plan_recovery.lock().unwrap() = Some(PlanRecoveryResult::Plan(flow(json!({ + "app":"browser","steps":[{"stop_before":"pay now"}] + })))); + let reply = tasks.start(&StartTaskRequest { + task: Some("buy a lamp".to_owned()), + constraints: TaskConstraints { + payment: tinycomputer_bus::agent::PaymentMode::FillThenApprove, + surfaces: vec![SurfaceKind::Browser], + origins: vec![".shop.example".to_owned()], + ..TaskConstraints::default() + }, + budget: tinycomputer_bus::agent::TaskBudget { + max_elapsed_ms: Some(1_000), + ..tinycomputer_bus::agent::TaskBudget::default() + }, + ..StartTaskRequest::default() + }); + assert!(reply.ok, "{:?}", reply.error); + let started = reply.data.unwrap(); + assert!(matches!( + settle(&tasks, &started.id).await.status, + TaskStatus::NeedsApproval { .. } + )); + + let scope = script.plan_requests.lock().unwrap()[0].host_budget.clone(); + assert_eq!(scope.remaining_model_calls(), 0); + assert_eq!(scope.remaining_ms(), Some(0)); + assert!(!scope.try_reserve_model_call()); +} + +#[tokio::test] +async fn a_host_scope_cannot_reserve_when_the_task_time_budget_is_exhausted() { + let (tasks, _) = controller(vec![finished_run( + FlowStopReason::StoppedBeforeDestructive, + vec![step( + "1", + "stop_before", + "sending the email", + StepOutcome::Gated, + "found Send", + )], + &[], + Some("Send"), + )]); + let max_elapsed_ms = 10_000; + let started = tasks + .start(&StartTaskRequest { + flow: Some(flow( + json!({"app":"Mail","steps":[{"stop_before":"sending the email"}]}), + )), + budget: tinycomputer_bus::agent::TaskBudget { + max_elapsed_ms: Some(max_elapsed_ms), + ..tinycomputer_bus::agent::TaskBudget::default() + }, + ..StartTaskRequest::default() + }) + .data + .unwrap(); + assert!(matches!( + settle(&tasks, &started.id).await.status, + TaskStatus::NeedsApproval { .. } + )); + + let cell = tasks.cells.lock().unwrap().values().next().unwrap().clone(); + let budget = cell.state.lock().unwrap().usage.task_call_budget().unwrap(); + let work = budget + .begin_work() + .expect("a paused non-terminal task permits a host-work scope"); + let scope = work.scope(); + cell.state.lock().unwrap().spent.elapsed_ms = max_elapsed_ms; + + assert_eq!(scope.remaining_ms(), Some(0)); + assert_eq!(scope.remaining_model_calls(), 0); + assert!(!scope.try_reserve_model_call()); +} + #[tokio::test] async fn a_planned_task_reports_usage_from_warmup_and_run() { let script = Arc::new(Script { diff --git a/crates/tinycomputer-engine/src/task/task_tests/rescue_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/rescue_tests.rs index db5b93c7b..6eacb442c 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/rescue_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/rescue_tests.rs @@ -183,6 +183,80 @@ async fn host_recovery_fails_closed_for_a_nested_failed_step() { ); } +#[tokio::test] +async fn a_cancelled_host_recovery_keeps_its_call_reservation_and_elapsed_time() { + let (tasks, script) = controller(vec![failed_at_step_two()]); + *script.reserve_host_calls.lock().unwrap() = true; + *script.hang_recovery.lock().unwrap() = true; + let view = tasks + .start(&StartTaskRequest { + flow: Some(flow(flights())), + task: Some("find the cheapest flight".to_owned()), + budget: TaskBudget { + max_model_calls: Some(1), + max_elapsed_ms: Some(40), + ..TaskBudget::default() + }, + ..StartTaskRequest::default() + }) + .data + .unwrap(); + + assert!(matches!( + settle(&tasks, &view.id).await.status, + TaskStatus::Failed { .. } + )); + assert_eq!(*script.host_call_reservations.lock().unwrap(), [true]); + assert_eq!( + script.recoveries.lock().unwrap()[0].remaining_model_calls, + 1 + ); + let cell = tasks.cells.lock().unwrap().values().next().unwrap().clone(); + let state = cell.state.lock().unwrap(); + assert_eq!(state.spent.model_calls, 1); + assert!( + (20..=100).contains(&state.spent.elapsed_ms), + "cancelled host work should charge its active interval once, got {} ms", + state.spent.elapsed_ms + ); +} + +#[tokio::test] +async fn a_cancelled_task_closes_a_retained_host_budget_scope() { + let (tasks, script) = controller(vec![failed_at_step_two()]); + *script.reserve_host_calls.lock().unwrap() = true; + *script.hang_recovery.lock().unwrap() = true; + let view = tasks + .start(&StartTaskRequest { + flow: Some(flow(flights())), + task: Some("find the cheapest flight".to_owned()), + budget: TaskBudget { + max_model_calls: Some(2), + max_elapsed_ms: Some(10_000), + ..TaskBudget::default() + }, + ..StartTaskRequest::default() + }) + .data + .unwrap(); + for _ in 0..100 { + if !script.recoveries.lock().unwrap().is_empty() { + break; + } + tokio::task::yield_now().await; + } + assert_eq!(script.recoveries.lock().unwrap().len(), 1); + assert!(matches!( + tasks.cancel_and_wait(&view.id).await.data.unwrap().status, + TaskStatus::Cancelled + )); + + let scope = script.recoveries.lock().unwrap()[0].host_budget.clone(); + assert_eq!(scope.remaining_model_calls(), 0); + assert_eq!(scope.remaining_ms(), Some(0)); + assert!(!scope.try_reserve_model_call()); +} + #[tokio::test] async fn a_failed_step_is_rescued_and_the_task_finishes() { let (tasks, script, model) = rescued( diff --git a/crates/tinycomputer-engine/src/usage.rs b/crates/tinycomputer-engine/src/usage.rs index db6468e8a..6a1e246f6 100644 --- a/crates/tinycomputer-engine/src/usage.rs +++ b/crates/tinycomputer-engine/src/usage.rs @@ -4,6 +4,8 @@ use std::sync::Mutex; use tinycomputer_bus::agent::{ModelUsage, TaskUsage}; +use crate::task::TaskCallBudget; + /// The model role whose provider-reported usage is being recorded. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ModelRole { @@ -25,6 +27,7 @@ pub enum ModelRole { #[derive(Debug, Default)] pub struct UsageRecorder { usage: Mutex, + task_budget: Mutex>, } impl UsageRecorder { @@ -33,9 +36,28 @@ impl UsageRecorder { pub fn from_snapshot(snapshot: TaskUsage) -> Self { Self { usage: Mutex::new(snapshot), + task_budget: Mutex::new(None), } } + /// The task's opaque host-call budget, when this recorder belongs to a + /// managed task. Hosts use it to reserve work that happens outside a + /// flow run, such as payment-field mapping. + #[must_use] + pub fn task_call_budget(&self) -> Option { + self.task_budget + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + pub(super) fn set_task_call_budget(&self, budget: TaskCallBudget) { + *self + .task_budget + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(budget); + } + /// Records one model call for `role`, retaining only reported values. pub fn record_call( &self,