Skip to content

The platform for continuously improving AI agents.

3.4 KB
Raw Blame
use std::{
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use anyhow::Result;
use trace_types::SpanSource;

use crate::{model::AmendReport, store::GraphStore};

pub const DEFAULT_SPAN_LIMIT: usize = 50_000;
const MS_PER_DAY: i64 = 24 * 60 * 60 * 1000;

pub struct GraphBuilder {
    source: Arc<dyn SpanSource>,
    store: GraphStore,
    window_days: u32,
    span_limit: usize,
}

impl GraphBuilder {
    pub fn new(source: Arc<dyn SpanSource>, store: GraphStore, window_days: u32) -> Self {
        Self {
            source,
            store,
            window_days: window_days.max(1),
            span_limit: DEFAULT_SPAN_LIMIT,
        }
    }

    pub fn with_span_limit(mut self, limit: usize) -> Self {
        self.span_limit = limit.max(1);
        self
    }

    pub fn store(&self) -> &GraphStore {
        &self.store
    }

    pub fn amend_once(&self) -> Result<AmendReport> {
        let since_ms = now_ms().saturating_sub(i64::from(self.window_days) * MS_PER_DAY);
        let spans = self.source.recent_spans(since_ms, self.span_limit)?;
        self.store.amend_spans(&spans)
    }
}

/// Spawns a background worker that runs an immediate startup amendment pass, then
/// periodically amends the execution graph as new traces arrive.
pub fn spawn_worker(builder: Arc<GraphBuilder>, interval: Duration) -> tokio::task::JoinHandle<()> {
    spawn_worker_with_delay(builder, Duration::ZERO, interval)
}

/// Spawns a background worker that waits `initial_delay` before its first pass,
/// then periodically amends the execution graph on `interval`.
pub fn spawn_worker_with_delay(
    builder: Arc<GraphBuilder>,
    initial_delay: Duration,
    interval: Duration,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        if !initial_delay.is_zero() {
            tokio::time::sleep(initial_delay).await;
        }
        let mut ticker = tokio::time::interval(interval);
        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
        loop {
            ticker.tick().await;
            let b = Arc::clone(&builder);
            match tokio::task::spawn_blocking(move || b.amend_once()).await {
                Ok(Ok(report)) => {
                    if report.amended_traces > 0 {
                        tracing::info!(
                            scanned_traces = report.scanned_traces,
                            amended_traces = report.amended_traces,
                            total_nodes = report.total_nodes,
                            total_edges = report.total_edges,
                            total_paths = report.total_paths,
                            revision = report.revision,
                            "execution graph amended"
                        );
                    } else {
                        tracing::debug!(
                            scanned_traces = report.scanned_traces,
                            revision = report.revision,
                            "execution graph sweep complete (no changes)"
                        );
                    }
                }
                Ok(Err(error)) => tracing::error!(?error, "execution graph sweep failed"),
                Err(error) => tracing::error!(?error, "execution graph sweep task panicked"),
            }
        }
    })
}

fn now_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or_default()
}