use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use adk_core::{
AdkError, DurableRunStore, Enqueued, ErrorCategory, ErrorComponent, NewRun, RunFilter,
RunRecord, RunState, SpendLedger,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::audit;
use crate::bus::KernelEvent;
use crate::error::{KernelError, Result};
use crate::partition::PartitionId;
use crate::sched::QueueClass;
use crate::stores::{ProcessFilter, ProcessStore, SpendScope};
use crate::supervise::{ASLEEP_KEY_PREFIX, SPAWN_KEY_PREFIX, Supervision, transcript_counts};
use crate::wake::WakeSet;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Process {
pub run: RunRecord,
pub meta: ProcessMeta,
pub view: ProcessView,
}
impl Process {
pub fn new(run: RunRecord, meta: ProcessMeta) -> Self {
Self { run, meta, view: ProcessView::default() }
}
#[must_use]
pub fn with_view(mut self, view: ProcessView) -> Self {
self.view = view;
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProcessView {
#[serde(rename = "ageMs", with = "crate::serde_util::millis")]
pub age: Duration,
pub spend_today: u64,
#[serde(rename = "spend7d")]
pub spend_7d: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub burn_rate: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub projection: Option<u64>,
pub model_calls: u64,
pub tool_calls: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub loop_guard: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub goal: Option<GoalProgress>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct GoalProgress {
pub iteration: u32,
pub max_iterations: u32,
pub spend: u64,
#[serde(rename = "durationMs", with = "crate::serde_util::millis")]
pub duration: Duration,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_check_exit: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_check_tail: Option<String>,
}
impl GoalProgress {
pub fn new(iteration: u32, max_iterations: u32) -> Self {
Self { iteration, max_iterations, ..Self::default() }
}
#[must_use]
pub fn with_spend(mut self, micro_usd: u64) -> Self {
self.spend = micro_usd;
self
}
#[must_use]
pub fn with_duration(mut self, duration: Duration) -> Self {
self.duration = duration;
self
}
#[must_use]
pub fn with_last_check(mut self, exit: i32, tail: impl Into<String>) -> Self {
self.last_check_exit = Some(exit);
self.last_check_tail = Some(tail.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProcessMeta {
pub pid: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
#[serde(default)]
pub partition: PartitionId,
pub queue: QueueClass,
pub kind: ProcessKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wake: Option<WakeSet>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub suspended_by: Option<Suspension>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub suspend_requested: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agenda_item: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub labels: BTreeMap<String, String>,
}
impl ProcessMeta {
pub fn new(pid: impl Into<String>, queue: QueueClass, kind: ProcessKind) -> Self {
Self {
pid: pid.into(),
parent: None,
partition: PartitionId::default(),
queue,
kind,
wake: None,
suspended_by: None,
suspend_requested: false,
agenda_item: None,
labels: BTreeMap::new(),
}
}
#[must_use]
pub fn with_parent(mut self, parent: impl Into<String>) -> Self {
self.parent = Some(parent.into());
self
}
#[must_use]
pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
self.partition = partition.into();
self
}
#[must_use]
pub fn with_wake(mut self, wake: WakeSet) -> Self {
self.wake = Some(wake);
self
}
#[must_use]
pub fn with_suspension(mut self, suspension: Suspension) -> Self {
self.suspended_by = Some(suspension);
self
}
#[must_use]
pub fn with_agenda_item(mut self, item: impl Into<String>) -> Self {
self.agenda_item = Some(item.into());
self
}
#[must_use]
pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.labels.insert(key.into(), value.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum ProcessKind {
Interactive,
Goal,
Scheduled,
Triggered {
source: String,
},
Proposed,
Maintenance,
Subagent,
}
impl fmt::Display for ProcessKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Interactive => f.write_str("interactive"),
Self::Goal => f.write_str("goal"),
Self::Scheduled => f.write_str("scheduled"),
Self::Triggered { source } => write!(f, "triggered:{source}"),
Self::Proposed => f.write_str("proposed"),
Self::Maintenance => f.write_str("maintenance"),
Self::Subagent => f.write_str("subagent"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum Suspension {
Manual,
Preempted {
by: String,
},
Freeze,
Drain,
Paused {
agent: String,
},
}
impl fmt::Display for Suspension {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Manual => f.write_str("manual"),
Self::Preempted { by } => write!(f, "preempted by {by}"),
Self::Freeze => f.write_str("freeze"),
Self::Drain => f.write_str("drain"),
Self::Paused { agent } => write!(f, "{agent} paused"),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProcessSpec {
pub kind: ProcessKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
#[serde(default)]
pub partition: PartitionId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wake: Option<WakeSet>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agenda_item: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub labels: BTreeMap<String, String>,
}
impl ProcessSpec {
pub fn new(kind: ProcessKind) -> Self {
Self {
kind,
parent: None,
partition: PartitionId::default(),
wake: None,
agenda_item: None,
labels: BTreeMap::new(),
}
}
#[must_use]
pub fn with_parent(mut self, parent: impl Into<String>) -> Self {
self.parent = Some(parent.into());
self
}
#[must_use]
pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
self.partition = partition.into();
self
}
#[must_use]
pub fn with_wake(mut self, wake: WakeSet) -> Self {
self.wake = Some(wake);
self
}
#[must_use]
pub fn with_agenda_item(mut self, item: impl Into<String>) -> Self {
self.agenda_item = Some(item.into());
self
}
#[must_use]
pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.labels.insert(key.into(), value.into());
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RunUsage {
pub model_calls: u64,
pub tool_calls: u64,
pub cost_micro_usd: u64,
#[serde(default)]
pub total_tokens: u64,
#[serde(default)]
pub units: adk_core::UsageVector,
}
impl RunUsage {
pub fn new(model_calls: u64, tool_calls: u64, cost_micro_usd: u64) -> Self {
Self { model_calls, tool_calls, cost_micro_usd, ..Self::default() }
}
#[must_use]
pub fn with_total_tokens(mut self, total_tokens: u64) -> Self {
self.total_tokens = total_tokens;
self
}
#[must_use]
pub fn with_units(mut self, units: adk_core::UsageVector) -> Self {
self.units = units;
self
}
}
#[async_trait]
pub trait ProgressSource: Send + Sync {
async fn goal_progress(&self, _run: &RunRecord) -> Result<Option<GoalProgress>> {
Ok(None)
}
async fn loop_guard(&self, _run: &RunRecord) -> Result<Option<String>> {
Ok(None)
}
async fn usage(&self, _run: &RunRecord) -> Result<Option<RunUsage>> {
Ok(None)
}
fn attach(&self, _processes: ProcessHandle) {}
#[cfg(feature = "proc")]
fn attach_ledger(&self, _ledger: Arc<dyn crate::proc::LedgerSink>) {}
}
#[derive(Clone)]
pub struct ProcessHandle {
sup: std::sync::Weak<Supervision>,
}
impl fmt::Debug for ProcessHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProcessHandle").field("alive", &(self.sup.strong_count() > 0)).finish()
}
}
impl ProcessHandle {
pub(crate) fn new(sup: &Arc<Supervision>) -> Self {
Self { sup: Arc::downgrade(sup) }
}
pub async fn suspend(&self, pid: &str) -> Result<bool> {
let Some(sup) = self.sup.upgrade() else { return Ok(false) };
ProcessTable::supervised(sup, None).suspend(pid).await?;
Ok(true)
}
}
#[derive(Clone)]
pub struct ProcessTable {
runs: Arc<dyn DurableRunStore>,
processes: Arc<dyn ProcessStore>,
spend: Option<Arc<dyn SpendLedger>>,
progress: Option<Arc<dyn ProgressSource>>,
sup: Option<Arc<Supervision>>,
}
impl fmt::Debug for ProcessTable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProcessTable")
.field("spend", &self.spend.is_some())
.field("progress", &self.progress.is_some())
.field("supervised", &self.sup.is_some())
.finish_non_exhaustive()
}
}
fn not_found(pid: &str) -> KernelError {
KernelError::NotFound { pid: pid.to_string() }
}
impl ProcessTable {
pub fn new(runs: Arc<dyn DurableRunStore>, processes: Arc<dyn ProcessStore>) -> Self {
Self { runs, processes, spend: None, progress: None, sup: None }
}
pub(crate) fn supervised(sup: Arc<Supervision>, spend: Option<Arc<dyn SpendLedger>>) -> Self {
Self {
runs: Arc::clone(&sup.runs),
processes: Arc::clone(&sup.processes),
spend,
progress: sup.progress.clone(),
sup: Some(sup),
}
}
#[must_use]
pub fn with_spend_ledger(mut self, ledger: Arc<dyn SpendLedger>) -> Self {
self.spend = Some(ledger);
self
}
#[must_use]
pub fn with_progress_source(mut self, source: Arc<dyn ProgressSource>) -> Self {
self.progress = Some(source);
self
}
pub fn run_store(&self) -> &Arc<dyn DurableRunStore> {
&self.runs
}
pub fn process_store(&self) -> &Arc<dyn ProcessStore> {
&self.processes
}
fn now(&self) -> DateTime<Utc> {
self.sup.as_ref().map_or_else(Utc::now, |sup| sup.clock.now())
}
pub async fn ps(&self, filter: ProcessFilter) -> Result<Vec<Process>> {
let mut meta_filter = filter.clone();
meta_filter.states = Vec::new();
meta_filter.limit = None;
let mut rows: BTreeMap<String, (RunRecord, ProcessMeta)> = BTreeMap::new();
for meta in self.processes.list(&meta_filter).await? {
match self.runs.get(&meta.pid).await? {
Some(run) => {
rows.insert(meta.pid.clone(), (run, meta));
}
None => {
self.processes.delete(&meta.pid).await?;
}
}
}
if let Some(sup) = &self.sup {
for queue in &sup.queues {
let mut runs = RunFilter::default().queue(queue.as_str());
if !filter.states.is_empty() {
runs = runs.states(filter.states.iter().copied());
}
for run in self.runs.list(runs).await? {
if rows.contains_key(&run.run_id) {
continue;
}
let meta = sup.inferred_meta(&run);
if filter.matches(&meta) {
rows.insert(run.run_id.clone(), (run, meta));
}
}
}
}
let mut rows: Vec<(RunRecord, ProcessMeta)> = rows
.into_values()
.filter(|(run, _)| run.target != crate::wake::KERNEL_WAKE_TARGET)
.filter(|(run, _)| filter.states.is_empty() || filter.states.contains(&run.state))
.filter(|(run, _)| filter.target.as_ref().is_none_or(|target| *target == run.target))
.collect();
rows.sort_by(|(a, _), (b, _)| {
a.created_at.cmp(&b.created_at).then(a.run_id.cmp(&b.run_id))
});
if let Some(limit) = filter.limit {
rows.truncate(limit);
}
let now = self.now();
let mut processes = Vec::with_capacity(rows.len());
for (run, meta) in rows {
let view = self.view(&run, &meta, now).await;
processes.push(Process { run, meta, view });
}
Ok(processes)
}
pub async fn get(&self, pid: &str) -> Result<Option<Process>> {
let Some(run) = self.runs.get(pid).await? else {
return Ok(None);
};
let meta = self.meta(&run).await?;
let view = self.view(&run, &meta, self.now()).await;
Ok(Some(Process { run, meta, view }))
}
pub async fn spawn(&self, mut run: NewRun, mut spec: ProcessSpec) -> Result<Process> {
self.refuse_while_frozen()?;
if let Some(sup) = &self.sup {
if let Some(agent) = sup.targets.admit_spawn(&run.target).await? {
sup.targets.expect(&agent.id);
if spec.partition.as_str() == PartitionId::DEFAULT {
spec.partition = agent.area;
} else if spec.partition != agent.area {
return Err(KernelError::Config {
reason: format!(
"{} works in area `{}`, so a process of `{}` cannot run it \
(spec 3.2 K-I15)",
agent.display_name, agent.area, spec.partition
),
});
}
}
spec.partition = sup.partition_for(&run.target, spec.partition)?;
sup.check_session_partition(&run, &spec.partition).await?;
if let Some(max) = sup.quotas_of(&spec.partition).await.max_queued {
let queued = sup.queued_in(&spec.partition).await;
if queued >= max {
return Err(KernelError::Quota {
partition: spec.partition.to_string(),
reason: format!(
"{queued} processes queued, the most max_queued ({max}) allows"
),
});
}
}
}
let asleep = spec.wake.is_some();
let prefix = if asleep { ASLEEP_KEY_PREFIX } else { SPAWN_KEY_PREFIX };
let key = run.idempotency_key.take().unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
run.idempotency_key = Some(format!("{prefix}{key}"));
let record = match self.runs.enqueue(run).await? {
Enqueued::Created(record) => record,
Enqueued::Existing(record) => {
let meta = self.meta(&record).await?;
let view = self.view(&record, &meta, self.now()).await;
return Ok(Process { run: record, meta, view });
}
Enqueued::Rejected { blocking_run_id } => {
return Err(AdkError::new(
ErrorComponent::Server,
ErrorCategory::Conflict,
crate::error::SPAWN_REJECTED_CODE,
format!(
"run {blocking_run_id} holds the concurrency key and the run refuses to \
queue behind it; wait for it to finish or enqueue with OnConflict::Enqueue"
),
)
.into());
}
};
let mut labels = spec.labels;
if let Some(wake) = &spec.wake
&& wake.any_of.iter().any(|wake| matches!(wake, crate::wake::Wake::Cron { .. }))
{
labels.insert(crate::supervise::RECUR_LABEL.to_string(), serde_json::to_string(wake)?);
}
let meta = ProcessMeta {
pid: record.run_id.clone(),
parent: spec.parent,
partition: spec.partition,
queue: QueueClass::from_name(&record.queue),
kind: spec.kind,
wake: spec.wake,
suspended_by: None,
suspend_requested: asleep,
agenda_item: spec.agenda_item,
labels,
};
self.processes.put(meta.clone()).await?;
if let Some(sup) = &self.sup {
if asleep {
sup.roots_changed.notify_one();
}
sup.publish(KernelEvent::Process {
pid: meta.pid.clone(),
from: RunState::Queued,
to: RunState::Queued,
reason: Some(if asleep { "spawned asleep" } else { "spawned" }.to_string()),
});
sup.record(
audit::PROCESS_SPAWNED,
sup.actor_for(Some(&record)),
Supervision::process_fields(&meta, None, None),
)
.await;
sup.nudge();
}
let view = self.view(&record, &meta, self.now()).await;
Ok(Process { run: record, meta, view })
}
pub async fn kill(&self, pid: &str, reason: &str) -> Result<()> {
let run = self.runs.get(pid).await?.ok_or_else(|| not_found(pid))?;
if run.state.is_terminal() {
return Err(KernelError::InvalidState {
pid: pid.to_string(),
state: run.state,
action: "killed",
});
}
self.runs.request_cancel(pid).await?;
let meta = self.meta(&run).await?;
if run.state != RunState::Running {
let mut cleared = meta.clone();
if cleared.wake.take().is_some() {
self.processes.put(cleared).await?;
if let Some(sup) = &self.sup {
sup.roots_changed.notify_one();
}
}
}
if let Some(sup) = &self.sup {
sup.heartbeat_now();
if run.state != RunState::Running {
sup.publish(KernelEvent::Process {
pid: pid.to_string(),
from: run.state,
to: RunState::Cancelled,
reason: Some(reason.to_string()),
});
}
sup.record(
audit::PROCESS_KILLED,
sup.actor_for(Some(&run)),
Supervision::process_fields(&meta, Some(reason), None),
)
.await;
}
Ok(())
}
pub async fn nice(&self, pid: &str, queue: QueueClass) -> Result<Process> {
let run = self.runs.get(pid).await?.ok_or_else(|| not_found(pid))?;
let meta = self.meta(&run).await?;
let movable = match run.state {
RunState::Queued => true,
RunState::Waiting => meta.wake.is_some() && meta.suspended_by.is_none(),
_ => false,
};
if !movable {
return Err(KernelError::InvalidState {
pid: pid.to_string(),
state: run.state,
action: "moved to another queue (only a queued or sleeping process moves; \
suspend a running one first)",
});
}
if meta.queue == queue {
let view = self.view(&run, &meta, self.now()).await;
return Ok(Process { run, meta, view });
}
self.refuse_while_frozen()?;
self.runs.request_cancel(pid).await?;
if meta.wake.is_some() {
let mut cleared = meta.clone();
cleared.wake = None;
self.processes.put(cleared).await?;
}
let input = if run.checkpoint.is_some() {
serde_json::Value::String(String::new())
} else {
run.input.clone()
};
let mut next = NewRun::new(
queue.as_str(),
run.app_name.clone(),
run.user_id.clone(),
run.target.clone(),
input,
)
.with_max_attempts(run.max_attempts);
next.session_id = Some(crate::supervise::run_session(&run));
if let Some(key) = &run.concurrency_key {
next = next.with_concurrency_key(key.clone(), run.on_conflict);
}
next.not_before = run.not_before;
next.principal = run.principal.clone();
next.authenticated = run.authenticated;
let mut spec = ProcessSpec::new(meta.kind.clone()).with_parent(pid);
spec.partition = meta.partition.clone();
spec.wake = meta.wake.clone();
spec.agenda_item = meta.agenda_item.clone();
spec.labels = meta.labels.clone();
let moved = self.spawn(next, spec).await?;
if let Some(sup) = &self.sup {
sup.record(
audit::PROCESS_REQUEUED,
sup.actor_for(Some(&run)),
json!({
"pid": moved.meta.pid,
"parent": pid,
"partition": moved.meta.partition,
"queue": queue,
"kind": moved.meta.kind,
"from": meta.queue,
}),
)
.await;
}
Ok(moved)
}
pub async fn suspend(&self, pid: &str) -> Result<()> {
self.suspend_marked(pid, |by| {
by.get_or_insert(Suspension::Manual);
})
.await
}
pub(crate) async fn suspend_as(&self, pid: &str, suspension: Suspension) -> Result<()> {
self.suspend_marked(pid, |by| {
if *by != Some(Suspension::Manual) {
*by = Some(suspension);
}
})
.await
}
async fn suspend_marked(
&self,
pid: &str,
mark: impl FnOnce(&mut Option<Suspension>),
) -> Result<()> {
let run = self.runs.get(pid).await?.ok_or_else(|| not_found(pid))?;
if run.state.is_terminal() {
return Err(KernelError::InvalidState {
pid: pid.to_string(),
state: run.state,
action: "suspended",
});
}
let mut meta = self.meta(&run).await?;
mark(&mut meta.suspended_by);
meta.suspend_requested = run.state != RunState::Waiting;
self.processes.put(meta.clone()).await?;
match (run.state, &self.sup) {
(RunState::Running, Some(sup)) => {
sup.suspend_local(pid);
}
(RunState::Waiting, Some(sup)) => {
sup.record(
audit::PROCESS_SUSPENDED,
sup.actor_for(Some(&run)),
Supervision::process_fields(&meta, Some("suspended"), None),
)
.await;
}
_ => {}
}
Ok(())
}
pub async fn resume(&self, pid: &str) -> Result<()> {
let run = self.runs.get(pid).await?.ok_or_else(|| not_found(pid))?;
let mut meta = self.meta(&run).await?;
let queued_and_suspended = run.state == RunState::Queued && meta.suspend_requested;
if run.state != RunState::Waiting && !queued_and_suspended {
return Err(KernelError::InvalidState {
pid: pid.to_string(),
state: run.state,
action: "resumed (it is not suspended or asleep)",
});
}
if meta.suspended_by == Some(Suspension::Freeze) {
return Err(KernelError::InvalidState {
pid: pid.to_string(),
state: run.state,
action: "resumed before the freeze is lifted; run `adk-rust unfreeze`",
});
}
meta.suspended_by = None;
meta.suspend_requested = false;
meta.wake = None;
self.processes.put(meta.clone()).await?;
if run.state == RunState::Waiting {
self.runs.wake(pid).await?;
}
if let Some(sup) = &self.sup {
sup.record(
audit::PROCESS_RESUMED,
sup.actor_for(Some(&run)),
Supervision::process_fields(&meta, Some("resumed"), None),
)
.await;
sup.nudge();
}
Ok(())
}
fn refuse_while_frozen(&self) -> Result<()> {
match &self.sup {
Some(sup) => sup.governance.check().map_err(|error| KernelError::Frozen {
reason: sup.governance.reason().unwrap_or(error.message),
}),
None => Ok(()),
}
}
async fn meta(&self, run: &RunRecord) -> Result<ProcessMeta> {
let inferred = || match &self.sup {
Some(sup) => sup.inferred_meta(run),
None => Supervision::infer_meta(run),
};
Ok(self.processes.get(&run.run_id).await?.unwrap_or_else(inferred))
}
async fn view(&self, run: &RunRecord, meta: &ProcessMeta, now: DateTime<Utc>) -> ProcessView {
let mut view = ProcessView::default();
let local = self.sup.as_ref().and_then(|sup| {
sup.local.lock().unwrap_or_else(|e| e.into_inner()).get(&run.run_id).cloned()
});
let since = match (run.state, &local) {
(RunState::Running, Some(local)) => local.claimed_at,
_ => run.updated_at,
};
view.age = (now - since).to_std().unwrap_or_default();
let today = now.date_naive();
let scope = SpendScope::Process(run.run_id.clone());
match self.processes.spend(&scope, today, today).await {
Ok(spend) => view.spend_today = spend,
Err(error) => {
tracing::debug!(process.pid = %run.run_id, error = %error, "could not read today's spend")
}
}
match self.processes.spend(&scope, today - chrono::Days::new(6), today).await {
Ok(spend) => view.spend_7d = spend,
Err(error) => {
tracing::debug!(process.pid = %run.run_id, error = %error, "could not read the week's spend")
}
}
if run.state == RunState::Running
&& let Some(local) = &local
&& let (Some((first_at, first)), Some((last_at, last))) =
(local.samples.front(), local.samples.back())
{
let minutes = (*last_at - *first_at).num_milliseconds() as f64 / 60_000.0;
if minutes > 0.0 {
let rate = (last.saturating_sub(*first)) as f64 / minutes;
view.burn_rate = Some(rate);
let end_of_day =
(today + chrono::Days::new(1)).and_time(chrono::NaiveTime::MIN).and_utc();
let remaining = (end_of_day - now).num_milliseconds().max(0) as f64 / 60_000.0;
view.projection = Some(view.spend_today + (rate * remaining) as u64);
}
}
let sessions = self.sup.as_ref().and_then(|sup| sup.sessions.clone());
if let Some(sessions) = sessions
&& let Some(counts) = transcript_counts(sessions.as_ref(), run).await
{
view.model_calls = counts.model_calls;
view.tool_calls = counts.tool_calls;
} else if let Some(local) = &local
&& let Some(last) = &local.last
{
let base = local.baseline.clone().unwrap_or_default();
view.model_calls = last.model_calls.saturating_sub(base.model_calls);
view.tool_calls = last.tool_calls.saturating_sub(base.tool_calls);
} else if let Some(local) = &local {
view.model_calls = local.turn.model_calls;
view.tool_calls = local.turn.tool_calls;
}
let progress = self
.sup
.as_ref()
.and_then(|sup| {
sup.targets
.progress_of(&run.target)
.or_else(|| sup.partition_progress.get(&meta.partition).cloned())
})
.or_else(|| self.progress.clone());
if let Some(progress) = progress {
match progress.loop_guard(run).await {
Ok(verdict) => view.loop_guard = verdict,
Err(error) => {
tracing::debug!(process.pid = %run.run_id, error = %error, "could not read the loop guard")
}
}
if meta.kind == ProcessKind::Goal || run.target == crate::supervise::GOAL_TARGET {
match progress.goal_progress(run).await {
Ok(Some(mut goal)) => {
if goal.spend == 0 {
let from = run.created_at.date_naive();
goal.spend =
self.processes.spend(&scope, from, today).await.unwrap_or(0);
}
view.goal = Some(goal);
}
Ok(None) => {}
Err(error) => {
tracing::debug!(process.pid = %run.run_id, error = %error, "could not read the goal's progress")
}
}
}
}
view
}
}