Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions crates/tinycomputer-engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down
256 changes: 256 additions & 0 deletions crates/tinycomputer-engine/src/task/budget.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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<Cell>,
}

impl TaskCallBudget {
pub(super) fn for_cell(cell: Weak<Cell>) -> 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<HostWorkGuard> {
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<HostWorkGuard> {
self.begin(true)
}

fn begin(&self, payment_checkpoint: bool) -> Option<HostWorkGuard> {
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<HostWork>,
}

/// 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<HostWork>,
}

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<u64> {
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<Cell>,
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).
Expand Down
5 changes: 5 additions & 0 deletions crates/tinycomputer-engine/src/task/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -160,6 +161,8 @@ pub struct FailedStepRecovery {
pub remaining_model_calls: u32,
/// Time left in the task budget, when bounded.
pub remaining_ms: Option<u64>,
/// 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.
Expand Down Expand Up @@ -205,6 +208,8 @@ pub struct PlanRecoveryRequest {
pub remaining_model_calls: u32,
/// Time left in the task budget, when bounded.
pub remaining_ms: Option<u64>,
/// 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.
Expand Down
11 changes: 7 additions & 4 deletions crates/tinycomputer-engine/src/task/persistence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -415,10 +415,10 @@ fn build_cell(
) -> Arc<Cell> {
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,
Expand All @@ -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,
Expand All @@ -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 {
Expand Down
Loading
Loading