Skip to content

The platform for continuously improving AI agents.

46.9 KB
Raw Blame
use std::{
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
    path::Path,
    sync::{Arc, Mutex},
    time::{SystemTime, UNIX_EPOCH},
};

use anyhow::{Context, Result, bail};
use duckdb::{Connection, OptionalExt, params};
use trace_types::SpanRecord;

use crate::{
    extract::{ExtractedTrace, extract_trace, round_usd},
    model::{
        AmendReport, AmendStatus, CodebaseContext, EdgeKind, EvalKind, ExecutionGraph, GraphEdge,
        GraphNode, GraphPath, NodeCodeContext, NodeKind, PathCodeContext, PathDetail,
        PathEvalSummary, PathLlmCallSummary, PathToolCallSummary, PathTraceEvalSummary,
        PathTraceRef, TraceAmendOutcome,
    },
};

const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS graph_meta (
    id INTEGER PRIMARY KEY,
    revision BIGINT NOT NULL,
    last_amended_at_ns BIGINT NOT NULL
);

CREATE TABLE IF NOT EXISTS graph_traces (
    trace_id VARCHAR PRIMARY KEY,
    service_name VARCHAR NOT NULL,
    span_count BIGINT NOT NULL,
    path_id VARCHAR NOT NULL,
    fingerprint VARCHAR NOT NULL,
    extracted_json JSON NOT NULL,
    start_time_ns BIGINT NOT NULL,
    amended_at_ns BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS graph_traces_service_idx ON graph_traces (service_name);
CREATE INDEX IF NOT EXISTS graph_traces_path_idx ON graph_traces (path_id);
CREATE INDEX IF NOT EXISTS graph_traces_start_idx ON graph_traces (start_time_ns);

CREATE TABLE IF NOT EXISTS graph_nodes (
    node_id VARCHAR PRIMARY KEY,
    node_json JSON NOT NULL,
    trace_count BIGINT NOT NULL,
    span_count BIGINT NOT NULL
);

CREATE TABLE IF NOT EXISTS graph_edges (
    edge_id VARCHAR PRIMARY KEY,
    edge_json JSON NOT NULL,
    transition_count BIGINT NOT NULL,
    trace_count BIGINT NOT NULL
);

CREATE TABLE IF NOT EXISTS graph_paths (
    path_id VARCHAR PRIMARY KEY,
    path_json JSON NOT NULL,
    trace_count BIGINT NOT NULL,
    last_seen_ns BIGINT NOT NULL
);

CREATE TABLE IF NOT EXISTS graph_context (
    id INTEGER PRIMARY KEY,
    context_json JSON NOT NULL
);
";

const READ_POOL_SIZE: usize = 4;

#[derive(Clone)]
pub struct GraphStore {
    writer: Arc<Mutex<Connection>>,
    readers: Arc<Mutex<Vec<Connection>>>,
    read_pool_size: usize,
}

struct Reader<'a> {
    conn: Option<Connection>,
    pool: &'a Mutex<Vec<Connection>>,
    max_size: usize,
}

impl std::ops::Deref for Reader<'_> {
    type Target = Connection;

    fn deref(&self) -> &Connection {
        self.conn
            .as_ref()
            .expect("reader holds a connection until dropped")
    }
}

impl Drop for Reader<'_> {
    fn drop(&mut self) {
        if let Some(conn) = self.conn.take() {
            let mut pool = lock(self.pool);
            if pool.len() < self.max_size {
                pool.push(conn);
            }
        }
    }
}

fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

impl GraphStore {
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        if trace_types::cleanup_stale_temp_dir(path) {
            tracing::info!(?path, "removed stale graph duckdb temp directory");
        }
        Self::init(Connection::open(path)?, Some(path))
    }

    pub fn open_in_memory() -> Result<Self> {
        Self::init(Connection::open_in_memory()?, None)
    }

    pub fn in_memory() -> Result<Self> {
        Self::open_in_memory()
    }

    /// Initializes a `GraphStore` on a sibling connection to an already-open
    /// per-project DuckDB database (sharing one `.duckdb` file with `otel` and `signals`).
    pub fn from_shared_connection(conn: Connection, read_pool_size: usize) -> Result<Self> {
        Self::init_schema(conn, read_pool_size.clamp(1, 16))
    }

    fn init(conn: Connection, db_path: Option<&Path>) -> Result<Self> {
        let cfg = trace_types::DuckDbConfig::from_env("GRAPH_DB_MEMORY_LIMIT", READ_POOL_SIZE);
        conn.execute_batch("SET preserve_insertion_order = false;")
            .context("setting graph duckdb preserve_insertion_order = false")?;
        if let Some(path) = db_path {
            let tmp_dir = trace_types::temp_dir_for_db(path);
            let escaped = trace_types::escape_sql_string(&tmp_dir.to_string_lossy());
            conn.execute_batch(&format!("SET temp_directory = '{escaped}';"))
                .with_context(|| format!("setting graph duckdb temp_directory = {}", tmp_dir.display()))?;
            tracing::info!(temp_directory = %tmp_dir.display(), "configured graph duckdb temp_directory");
        }
        if let Some(ref limit) = cfg.memory_limit {
            conn.execute_batch(&format!("SET memory_limit = '{limit}';"))
                .with_context(|| format!("setting graph duckdb memory_limit = {limit}"))?;
            tracing::info!(memory_limit = %limit, "configured graph duckdb memory_limit");
        }
        if let Some(ref max_temp) = cfg.max_temp_directory_size {
            conn.execute_batch(&format!("SET max_temp_directory_size = '{max_temp}';"))
                .with_context(|| {
                    format!("setting graph duckdb max_temp_directory_size = {max_temp}")
                })?;
            tracing::info!(
                max_temp_directory_size = %max_temp,
                "configured graph duckdb max_temp_directory_size"
            );
        }
        if let Some(threads) = cfg.threads {
            conn.execute_batch(&format!("SET threads = {threads};"))
                .with_context(|| format!("setting graph duckdb threads = {threads}"))?;
            tracing::info!(threads, "configured graph duckdb threads");
        }
        if let Some(ref flush_threshold) = cfg.allocator_flush_threshold {
            if let Err(err) = conn.execute_batch(&format!(
                "SET allocator_flush_threshold = '{flush_threshold}';"
            )) {
                tracing::debug!(
                    ?err,
                    allocator_flush_threshold = %flush_threshold,
                    "skipping unsupported graph duckdb allocator_flush_threshold"
                );
            } else {
                tracing::info!(
                    allocator_flush_threshold = %flush_threshold,
                    "configured graph duckdb allocator_flush_threshold"
                );
            }
        }
        if let Err(err) = conn.execute_batch("SET allocator_background_threads = true;") {
            tracing::debug!(
                ?err,
                "skipping unsupported graph duckdb allocator_background_threads"
            );
        }
        if let Some(ref checkpoint_threshold) = cfg.checkpoint_threshold {
            if let Err(err) = conn.execute_batch(&format!(
                "SET checkpoint_threshold = '{checkpoint_threshold}';"
            )) {
                tracing::debug!(
                    ?err,
                    checkpoint_threshold = %checkpoint_threshold,
                    "skipping unsupported graph duckdb checkpoint_threshold"
                );
            } else {
                tracing::info!(
                    checkpoint_threshold = %checkpoint_threshold,
                    "configured graph duckdb checkpoint_threshold"
                );
            }
        }
        Self::init_schema(conn, cfg.read_pool_size)
    }

    fn init_schema(conn: Connection, read_pool_size: usize) -> Result<Self> {
        conn.execute_batch(SCHEMA)
            .context("creating execution graph schema")?;
        conn.execute(
            "INSERT INTO graph_meta (id, revision, last_amended_at_ns)
             VALUES (1, 0, 0)
             ON CONFLICT (id) DO NOTHING",
            [],
        )
        .context("initializing graph_meta row")?;

        let readers = (0..read_pool_size)
            .map(|_| conn.try_clone())
            .collect::<duckdb::Result<Vec<_>>>()?;

        Ok(Self {
            writer: Arc::new(Mutex::new(conn)),
            readers: Arc::new(Mutex::new(readers)),
            read_pool_size,
        })
    }

    fn reader(&self) -> Result<Reader<'_>> {
        let pooled = lock(&self.readers).pop();
        let conn = match pooled {
            Some(conn) => conn,
            None => lock(&self.writer).try_clone()?,
        };
        Ok(Reader {
            conn: Some(conn),
            pool: &self.readers,
            max_size: self.read_pool_size,
        })
    }

    pub fn revision(&self) -> Result<u64> {
        let conn = self.reader()?;
        let (rev, _) = read_meta(&conn)?;
        Ok(rev)
    }

    /// Idempotently amends the execution graph with all spans of a single trace.
    ///
    /// - Re-amending an identical trace is a strict no-op (does not bump revision or double-count).
    /// - Re-amending an existing `trace_id` with additional/updated spans cleanly replaces its
    ///   contribution and bumps `revision`.
    pub fn amend_trace(&self, spans: &[SpanRecord]) -> Result<TraceAmendOutcome> {
        if spans.is_empty() {
            let revision = self.revision()?;
            return Ok(TraceAmendOutcome {
                trace_id: String::new(),
                path_id: String::new(),
                status: AmendStatus::Skipped,
                revision,
            });
        }

        let first_trace_id = &spans[0].trace_id;
        if spans.iter().any(|s| &s.trace_id != first_trace_id) {
            bail!("amend_trace expects spans from a single trace_id; use amend_spans for batches");
        }

        let Some(extracted) = extract_trace(spans) else {
            let revision = self.revision()?;
            return Ok(TraceAmendOutcome {
                trace_id: first_trace_id.clone(),
                path_id: String::new(),
                status: AmendStatus::Skipped,
                revision,
            });
        };

        let conn = lock(&self.writer);
        let existing_fp: Option<String> = conn
            .query_row(
                "SELECT fingerprint FROM graph_traces WHERE trace_id = ?",
                params![extracted.trace_id],
                |row| row.get(0),
            )
            .optional()?;

        if existing_fp.as_deref() == Some(extracted.fingerprint.as_str()) {
            let (revision, _) = read_meta(&conn)?;
            return Ok(TraceAmendOutcome {
                trace_id: extracted.trace_id,
                path_id: extracted.path_id,
                status: AmendStatus::Unchanged,
                revision,
            });
        }

        let status = if existing_fp.is_some() {
            AmendStatus::Updated
        } else {
            AmendStatus::Inserted
        };

        let now = now_ns();
        let extracted_json = serde_json::to_string(&extracted)?;
        let (prev_rev, _) = read_meta(&conn)?;
        let next_rev = prev_rev + 1;

        with_transaction(&conn, || {
            upsert_trace_row(&conn, &extracted, &extracted_json, now)?;
            update_meta(&conn, next_rev, now)?;
            let _ = rebuild_materialized(&conn, next_rev, now)?;
            Ok(())
        })?;

        Ok(TraceAmendOutcome {
            trace_id: extracted.trace_id,
            path_id: extracted.path_id,
            status,
            revision: next_rev,
        })
    }

    /// Groups a batch of spans by `trace_id` and incrementally amends all new or updated traces
    /// in a single transaction + materialized refresh.
    pub fn amend_spans(&self, spans: &[SpanRecord]) -> Result<AmendReport> {
        let mut by_trace: BTreeMap<&str, Vec<SpanRecord>> = BTreeMap::new();
        for span in spans {
            if span.trace_id.trim().is_empty() {
                continue;
            }
            by_trace
                .entry(span.trace_id.as_str())
                .or_default()
                .push(span.clone());
        }

        let scanned_traces = by_trace.len();
        if scanned_traces == 0 {
            let conn = self.reader()?;
            let (revision, _) = read_meta(&conn)?;
            let (total_nodes, total_edges, total_paths) = read_materialized_counts(&conn)?;
            return Ok(AmendReport {
                scanned_traces: 0,
                amended_traces: 0,
                skipped_traces: 0,
                total_nodes,
                total_edges,
                total_paths,
                revision,
            });
        }

        let extracted_batch: Vec<ExtractedTrace> = by_trace
            .into_values()
            .filter_map(|trace_spans| extract_trace(&trace_spans))
            .collect();

        let conn = lock(&self.writer);
        let existing_fps = load_all_fingerprints(&conn)?;

        let mut to_upsert: Vec<(ExtractedTrace, String)> = Vec::new();
        let mut skipped_traces = 0usize;

        for extracted in extracted_batch {
            if existing_fps
                .get(&extracted.trace_id)
                .is_some_and(|fp| fp == &extracted.fingerprint)
            {
                skipped_traces += 1;
                continue;
            }
            let json = serde_json::to_string(&extracted)?;
            to_upsert.push((extracted, json));
        }

        let amended_traces = to_upsert.len();
        if amended_traces == 0 {
            let (revision, _) = read_meta(&conn)?;
            let (total_nodes, total_edges, total_paths) = read_materialized_counts(&conn)?;
            return Ok(AmendReport {
                scanned_traces,
                amended_traces: 0,
                skipped_traces,
                total_nodes,
                total_edges,
                total_paths,
                revision,
            });
        }

        let now = now_ns();
        let (prev_rev, _) = read_meta(&conn)?;
        let next_rev = prev_rev + 1;

        let graph = with_transaction(&conn, || {
            for (extracted, json) in &to_upsert {
                upsert_trace_row(&conn, extracted, json, now)?;
            }
            update_meta(&conn, next_rev, now)?;
            rebuild_materialized(&conn, next_rev, now)
        })?;

        Ok(AmendReport {
            scanned_traces,
            amended_traces,
            skipped_traces,
            total_nodes: graph.nodes.len(),
            total_edges: graph.edges.len(),
            total_paths: graph.paths.len(),
            revision: next_rev,
        })
    }

    pub fn get_graph(
        &self,
        service_name: Option<&str>,
        limit_paths: usize,
    ) -> Result<ExecutionGraph> {
        let conn = self.reader()?;
        let (revision, last_amended_at_ns) = read_meta(&conn)?;

        if let Some(service) = service_name.map(str::trim).filter(|s| !s.is_empty()) {
            let traces = load_traces_for_service(&conn, service)?;
            let mut graph = aggregate_traces(&traces, revision, last_amended_at_ns);
            if limit_paths > 0 && graph.paths.len() > limit_paths {
                graph.paths.truncate(limit_paths);
            }
            return Ok(graph);
        }

        let nodes = load_materialized_nodes(&conn)?;
        let edges = load_materialized_edges(&conn)?;
        let mut paths = load_materialized_paths(&conn)?;
        let context = load_materialized_context(&conn)?
            .unwrap_or_else(|| CodebaseContext {
                revision,
                last_amended_at_ns,
                ..Default::default()
            });

        if limit_paths > 0 && paths.len() > limit_paths {
            paths.truncate(limit_paths);
        }

        Ok(ExecutionGraph {
            nodes,
            edges,
            paths,
            context,
        })
    }

    pub fn list_paths(
        &self,
        service_name: Option<&str>,
        node_id: Option<&str>,
        limit: usize,
    ) -> Result<Vec<GraphPath>> {
        let conn = self.reader()?;
        let node_filter = node_id.map(str::trim).filter(|s| !s.is_empty());

        let mut paths = if let Some(service) = service_name.map(str::trim).filter(|s| !s.is_empty())
        {
            let (revision, last_amended_at_ns) = read_meta(&conn)?;
            let traces = load_traces_for_service(&conn, service)?;
            aggregate_traces(&traces, revision, last_amended_at_ns).paths
        } else {
            load_materialized_paths(&conn)?
        };

        if let Some(nid) = node_filter {
            paths.retain(|p| p.node_ids.iter().any(|id| id == nid));
        }

        if limit > 0 && paths.len() > limit {
            paths.truncate(limit);
        }

        Ok(paths)
    }

    pub fn get_path_detail(&self, path_id: &str, trace_limit: usize) -> Result<Option<PathDetail>> {
        let conn = self.reader()?;
        let traces = load_traces_for_path(&conn, path_id)?;
        if traces.is_empty() {
            return Ok(None);
        }

        let total_traces: i64 =
            conn.query_row("SELECT count(*) FROM graph_traces", [], |row| row.get(0))?;
        let path = aggregate_single_path(&traces);
        let share_of_traces = if total_traces > 0 {
            path.trace_count as f64 / total_traces as f64
        } else {
            0.0
        };

        let llm_calls = aggregate_path_llm_calls(&traces);
        let tool_calls = aggregate_path_tool_calls(&traces);
        let evals = aggregate_path_evals(&traces);
        let code_context = aggregate_path_code_context(&traces);

        let mut trace_refs: Vec<PathTraceRef> = traces
            .iter()
            .map(|t| {
                let eval_summary = build_trace_eval_summary(t);
                PathTraceRef {
                    trace_id: t.trace_id.clone(),
                    service_name: t.service_name.clone(),
                    root_span_name: t.root_span_name.clone(),
                    start_time_ns: t.start_time_ns,
                    duration_ms: t.duration_ms,
                    status_code: t.status_code,
                    span_count: t.span_count,
                    llm_calls: t.llm_calls.len() as u64,
                    tool_calls: t.tool_calls.len() as u64,
                    total_tokens: t.total_tokens,
                    cost_usd: t.total_cost_usd,
                    eval_summary,
                    output_label: t.output_label.clone(),
                }
            })
            .collect();

        trace_refs.sort_by(|a, b| {
            b.start_time_ns
                .cmp(&a.start_time_ns)
                .then_with(|| a.trace_id.cmp(&b.trace_id))
        });
        if trace_limit > 0 && trace_refs.len() > trace_limit {
            trace_refs.truncate(trace_limit);
        }

        Ok(Some(PathDetail {
            path,
            share_of_traces,
            llm_calls,
            tool_calls,
            evals,
            code_context,
            traces: trace_refs,
        }))
    }
}

fn with_transaction<T>(conn: &Connection, f: impl FnOnce() -> Result<T>) -> Result<T> {
    conn.execute_batch("BEGIN TRANSACTION")
        .context("starting graph transaction")?;
    match f() {
        Ok(val) => {
            conn.execute_batch("COMMIT")
                .context("committing graph transaction")?;
            Ok(val)
        }
        Err(err) => {
            let _ = conn.execute_batch("ROLLBACK");
            Err(err)
        }
    }
}

fn upsert_trace_row(
    conn: &Connection,
    extracted: &ExtractedTrace,
    extracted_json: &str,
    amended_at_ns: i64,
) -> Result<()> {
    conn.execute(
        "INSERT INTO graph_traces (
            trace_id, service_name, span_count, path_id, fingerprint,
            extracted_json, start_time_ns, amended_at_ns
         ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
         ON CONFLICT (trace_id) DO UPDATE SET
            service_name = EXCLUDED.service_name,
            span_count = EXCLUDED.span_count,
            path_id = EXCLUDED.path_id,
            fingerprint = EXCLUDED.fingerprint,
            extracted_json = EXCLUDED.extracted_json,
            start_time_ns = EXCLUDED.start_time_ns,
            amended_at_ns = EXCLUDED.amended_at_ns",
        params![
            extracted.trace_id,
            extracted.service_name,
            extracted.span_count as i64,
            extracted.path_id,
            extracted.fingerprint,
            extracted_json,
            extracted.start_time_ns,
            amended_at_ns,
        ],
    )?;
    Ok(())
}

fn update_meta(conn: &Connection, revision: u64, last_amended_at_ns: i64) -> Result<()> {
    conn.execute(
        "UPDATE graph_meta SET revision = ?, last_amended_at_ns = ? WHERE id = 1",
        params![revision as i64, last_amended_at_ns],
    )?;
    Ok(())
}

fn read_meta(conn: &Connection) -> Result<(u64, i64)> {
    let row: Option<(i64, i64)> = conn
        .query_row(
            "SELECT revision, last_amended_at_ns FROM graph_meta WHERE id = 1",
            [],
            |r| Ok((r.get(0)?, r.get(1)?)),
        )
        .optional()?;
    Ok(row.map(|(r, ts)| (r.max(0) as u64, ts)).unwrap_or((0, 0)))
}

fn load_all_fingerprints(conn: &Connection) -> Result<HashMap<String, String>> {
    let mut stmt = conn.prepare("SELECT trace_id, fingerprint FROM graph_traces")?;
    let rows = stmt
        .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))?
        .collect::<duckdb::Result<HashMap<_, _>>>()?;
    Ok(rows)
}

fn load_all_traces(conn: &Connection) -> Result<Vec<ExtractedTrace>> {
    let mut stmt = conn.prepare(
        "SELECT extracted_json::VARCHAR FROM graph_traces ORDER BY start_time_ns ASC, trace_id ASC",
    )?;
    let traces = stmt
        .query_map([], |row| {
            let text: String = row.get(0)?;
            serde_json::from_str::<ExtractedTrace>(&text).map_err(|err| {
                duckdb::Error::FromSqlConversionFailure(
                    0,
                    duckdb::types::Type::Text,
                    Box::new(err),
                )
            })
        })?
        .collect::<duckdb::Result<Vec<_>>>()?;
    Ok(traces)
}

fn load_traces_for_service(conn: &Connection, service_name: &str) -> Result<Vec<ExtractedTrace>> {
    let mut stmt = conn.prepare(
        "SELECT extracted_json::VARCHAR FROM graph_traces
         WHERE service_name = ?
         ORDER BY start_time_ns ASC, trace_id ASC",
    )?;
    let traces = stmt
        .query_map(params![service_name], |row| {
            let text: String = row.get(0)?;
            serde_json::from_str::<ExtractedTrace>(&text).map_err(|err| {
                duckdb::Error::FromSqlConversionFailure(
                    0,
                    duckdb::types::Type::Text,
                    Box::new(err),
                )
            })
        })?
        .collect::<duckdb::Result<Vec<_>>>()?;
    Ok(traces)
}

fn load_traces_for_path(conn: &Connection, path_id: &str) -> Result<Vec<ExtractedTrace>> {
    let mut stmt = conn.prepare(
        "SELECT extracted_json::VARCHAR FROM graph_traces
         WHERE path_id = ?
         ORDER BY start_time_ns DESC, trace_id ASC",
    )?;
    let traces = stmt
        .query_map(params![path_id], |row| {
            let text: String = row.get(0)?;
            serde_json::from_str::<ExtractedTrace>(&text).map_err(|err| {
                duckdb::Error::FromSqlConversionFailure(
                    0,
                    duckdb::types::Type::Text,
                    Box::new(err),
                )
            })
        })?
        .collect::<duckdb::Result<Vec<_>>>()?;
    Ok(traces)
}

fn rebuild_materialized(
    conn: &Connection,
    revision: u64,
    last_amended_at_ns: i64,
) -> Result<ExecutionGraph> {
    let traces = load_all_traces(conn)?;
    let graph = aggregate_traces(&traces, revision, last_amended_at_ns);

    conn.execute("DELETE FROM graph_nodes", [])?;
    for node in &graph.nodes {
        let json = serde_json::to_string(node)?;
        conn.execute(
            "INSERT INTO graph_nodes (node_id, node_json, trace_count, span_count)
             VALUES (?, ?, ?, ?)",
            params![
                node.node_id,
                json,
                node.trace_count as i64,
                node.span_count as i64
            ],
        )?;
    }

    conn.execute("DELETE FROM graph_edges", [])?;
    for edge in &graph.edges {
        let json = serde_json::to_string(edge)?;
        conn.execute(
            "INSERT INTO graph_edges (edge_id, edge_json, transition_count, trace_count)
             VALUES (?, ?, ?, ?)",
            params![
                edge.edge_id,
                json,
                edge.transition_count as i64,
                edge.trace_count as i64
            ],
        )?;
    }

    conn.execute("DELETE FROM graph_paths", [])?;
    for path in &graph.paths {
        let json = serde_json::to_string(path)?;
        conn.execute(
            "INSERT INTO graph_paths (path_id, path_json, trace_count, last_seen_ns)
             VALUES (?, ?, ?, ?)",
            params![
                path.path_id,
                json,
                path.trace_count as i64,
                path.last_seen_ns
            ],
        )?;
    }

    let ctx_json = serde_json::to_string(&graph.context)?;
    conn.execute(
        "INSERT INTO graph_context (id, context_json)
         VALUES (1, ?)
         ON CONFLICT (id) DO UPDATE SET context_json = EXCLUDED.context_json",
        params![ctx_json],
    )?;

    Ok(graph)
}

fn read_materialized_counts(conn: &Connection) -> Result<(usize, usize, usize)> {
    let nodes: i64 = conn.query_row("SELECT count(*) FROM graph_nodes", [], |r| r.get(0))?;
    let edges: i64 = conn.query_row("SELECT count(*) FROM graph_edges", [], |r| r.get(0))?;
    let paths: i64 = conn.query_row("SELECT count(*) FROM graph_paths", [], |r| r.get(0))?;
    Ok((
        nodes.max(0) as usize,
        edges.max(0) as usize,
        paths.max(0) as usize,
    ))
}

fn load_materialized_nodes(conn: &Connection) -> Result<Vec<GraphNode>> {
    let mut stmt = conn.prepare(
        "SELECT node_json::VARCHAR FROM graph_nodes
         ORDER BY trace_count DESC, span_count DESC, node_id ASC",
    )?;
    let items = stmt
        .query_map([], |row| {
            let text: String = row.get(0)?;
            serde_json::from_str::<GraphNode>(&text).map_err(|err| {
                duckdb::Error::FromSqlConversionFailure(
                    0,
                    duckdb::types::Type::Text,
                    Box::new(err),
                )
            })
        })?
        .collect::<duckdb::Result<Vec<_>>>()?;
    Ok(items)
}

fn load_materialized_edges(conn: &Connection) -> Result<Vec<GraphEdge>> {
    let mut stmt = conn.prepare(
        "SELECT edge_json::VARCHAR FROM graph_edges
         ORDER BY transition_count DESC, trace_count DESC, edge_id ASC",
    )?;
    let items = stmt
        .query_map([], |row| {
            let text: String = row.get(0)?;
            serde_json::from_str::<GraphEdge>(&text).map_err(|err| {
                duckdb::Error::FromSqlConversionFailure(
                    0,
                    duckdb::types::Type::Text,
                    Box::new(err),
                )
            })
        })?
        .collect::<duckdb::Result<Vec<_>>>()?;
    Ok(items)
}

fn load_materialized_paths(conn: &Connection) -> Result<Vec<GraphPath>> {
    let mut stmt = conn.prepare(
        "SELECT path_json::VARCHAR FROM graph_paths
         ORDER BY trace_count DESC, last_seen_ns DESC, path_id ASC",
    )?;
    let items = stmt
        .query_map([], |row| {
            let text: String = row.get(0)?;
            serde_json::from_str::<GraphPath>(&text).map_err(|err| {
                duckdb::Error::FromSqlConversionFailure(
                    0,
                    duckdb::types::Type::Text,
                    Box::new(err),
                )
            })
        })?
        .collect::<duckdb::Result<Vec<_>>>()?;
    Ok(items)
}

fn load_materialized_context(conn: &Connection) -> Result<Option<CodebaseContext>> {
    let text: Option<String> = conn
        .query_row(
            "SELECT context_json::VARCHAR FROM graph_context WHERE id = 1",
            [],
            |row| row.get(0),
        )
        .optional()?;
    match text {
        Some(raw) => Ok(Some(serde_json::from_str(&raw)?)),
        None => Ok(None),
    }
}

#[derive(Default)]
struct GlobalNodeAgg {
    label: String,
    kind: Option<NodeKind>,
    services: BTreeSet<String>,
    span_count: u64,
    trace_count: u64,
    error_count: u64,
    total_duration_ms: f64,
    total_tokens: u64,
    total_cost_usd: f64,
    is_entry: bool,
    is_exit: bool,
    has_self_loop: bool,
    filepaths: BTreeSet<String>,
    functions: BTreeSet<String>,
    namespaces: BTreeSet<String>,
    capabilities: BTreeSet<String>,
    models: BTreeSet<String>,
    tools: BTreeSet<String>,
    span_types: BTreeSet<String>,
}

#[derive(Default)]
struct GlobalEdgeAgg {
    from_node_id: String,
    to_node_id: String,
    kind: Option<EdgeKind>,
    transition_count: u64,
    trace_count: u64,
    is_loop: bool,
    total_gap_ms: f64,
}

pub(crate) fn aggregate_traces(
    traces: &[ExtractedTrace],
    revision: u64,
    last_amended_at_ns: i64,
) -> ExecutionGraph {
    let mut node_map: BTreeMap<String, GlobalNodeAgg> = BTreeMap::new();
    let mut edge_map: BTreeMap<String, GlobalEdgeAgg> = BTreeMap::new();
    let mut path_groups: HashMap<&str, Vec<&ExtractedTrace>> = HashMap::new();

    let mut all_services: BTreeSet<String> = BTreeSet::new();
    let mut total_spans: u64 = 0;

    for trace in traces {
        total_spans += trace.span_count;
        for svc in &trace.services {
            all_services.insert(svc.clone());
        }
        path_groups
            .entry(trace.path_id.as_str())
            .or_default()
            .push(trace);

        for obs in &trace.nodes {
            let agg = node_map.entry(obs.node_id.clone()).or_default();
            if agg.label.is_empty() {
                agg.label = obs.label.clone();
                agg.kind = Some(obs.kind);
            }
            agg.services.extend(obs.services.iter().cloned());
            agg.span_count += obs.span_count;
            agg.trace_count += 1;
            agg.error_count += obs.error_count;
            agg.total_duration_ms += obs.total_duration_ms;
            agg.total_tokens += obs.total_tokens;
            agg.total_cost_usd += obs.total_cost_usd;
            agg.is_entry |= obs.is_entry;
            agg.is_exit |= obs.is_exit;
            agg.has_self_loop |= obs.has_self_loop;
            agg.filepaths
                .extend(obs.code_context.filepaths.iter().cloned());
            agg.functions
                .extend(obs.code_context.functions.iter().cloned());
            agg.namespaces
                .extend(obs.code_context.namespaces.iter().cloned());
            agg.capabilities
                .extend(obs.code_context.capabilities.iter().cloned());
            agg.models.extend(obs.code_context.models.iter().cloned());
            agg.tools.extend(obs.code_context.tools.iter().cloned());
            agg.span_types
                .extend(obs.code_context.span_types.iter().cloned());
        }

        for obs in &trace.edges {
            let agg = edge_map.entry(obs.edge_id.clone()).or_default();
            if agg.from_node_id.is_empty() {
                agg.from_node_id = obs.from_node_id.clone();
                agg.to_node_id = obs.to_node_id.clone();
                agg.kind = Some(obs.kind);
            }
            agg.transition_count += obs.transition_count;
            agg.trace_count += 1;
            agg.is_loop |= obs.is_loop;
            agg.total_gap_ms += obs.total_gap_ms;
        }
    }

    let mut nodes: Vec<GraphNode> = node_map
        .into_iter()
        .map(|(node_id, agg)| {
            let avg_duration_ms = if agg.span_count > 0 {
                agg.total_duration_ms / agg.span_count as f64
            } else {
                0.0
            };
            GraphNode {
                node_id,
                label: agg.label,
                kind: agg.kind.unwrap_or(NodeKind::Span),
                services: agg.services.into_iter().collect(),
                span_count: agg.span_count,
                trace_count: agg.trace_count,
                error_count: agg.error_count,
                avg_duration_ms,
                total_tokens: agg.total_tokens,
                total_cost_usd: round_usd(agg.total_cost_usd),
                is_entry: agg.is_entry,
                is_exit: agg.is_exit,
                has_self_loop: agg.has_self_loop,
                code_context: NodeCodeContext {
                    filepaths: agg.filepaths.into_iter().collect(),
                    functions: agg.functions.into_iter().collect(),
                    namespaces: agg.namespaces.into_iter().collect(),
                    capabilities: agg.capabilities.into_iter().collect(),
                    models: agg.models.into_iter().collect(),
                    tools: agg.tools.into_iter().collect(),
                    span_types: agg.span_types.into_iter().collect(),
                },
            }
        })
        .collect();

    nodes.sort_by(|a, b| {
        b.trace_count
            .cmp(&a.trace_count)
            .then_with(|| b.span_count.cmp(&a.span_count))
            .then_with(|| a.node_id.cmp(&b.node_id))
    });

    let mut edges: Vec<GraphEdge> = edge_map
        .into_iter()
        .map(|(edge_id, agg)| {
            let avg_gap_ms = if agg.transition_count > 0 {
                agg.total_gap_ms / agg.transition_count as f64
            } else {
                0.0
            };
            GraphEdge {
                edge_id,
                from_node_id: agg.from_node_id,
                to_node_id: agg.to_node_id,
                kind: agg.kind.unwrap_or(EdgeKind::Next),
                transition_count: agg.transition_count,
                trace_count: agg.trace_count,
                is_loop: agg.is_loop,
                avg_gap_ms,
            }
        })
        .collect();

    edges.sort_by(|a, b| {
        b.transition_count
            .cmp(&a.transition_count)
            .then_with(|| b.trace_count.cmp(&a.trace_count))
            .then_with(|| a.edge_id.cmp(&b.edge_id))
    });

    let mut paths: Vec<GraphPath> = path_groups
        .into_values()
        .map(|group| aggregate_path_refs(&group))
        .collect();

    paths.sort_by(|a, b| {
        b.trace_count
            .cmp(&a.trace_count)
            .then_with(|| b.last_seen_ns.cmp(&a.last_seen_ns))
            .then_with(|| a.path_id.cmp(&b.path_id))
    });

    let node_kinds: HashMap<&str, NodeKind> = nodes
        .iter()
        .map(|n| (n.node_id.as_str(), n.kind))
        .collect();

    let mut entrypoints = BTreeSet::new();
    let mut exits = BTreeSet::new();
    let mut models = BTreeSet::new();
    let mut tools = BTreeSet::new();
    let mut code_files = BTreeSet::new();
    let mut code_functions = BTreeSet::new();
    let mut capabilities = BTreeSet::new();
    let mut loop_nodes = BTreeSet::new();

    for node in &nodes {
        all_services.extend(node.services.iter().cloned());
        if node.is_entry {
            entrypoints.insert(node.node_id.clone());
        }
        if node.is_exit {
            exits.insert(node.node_id.clone());
        }
        if node.has_self_loop {
            loop_nodes.insert(node.node_id.clone());
        }
        if node.kind == NodeKind::Tool {
            tools.insert(node.label.clone());
        }
        models.extend(node.code_context.models.iter().cloned());
        tools.extend(node.code_context.tools.iter().cloned());
        code_files.extend(node.code_context.filepaths.iter().cloned());
        code_functions.extend(node.code_context.functions.iter().cloned());
        capabilities.extend(node.code_context.capabilities.iter().cloned());
    }

    for edge in &edges {
        if edge.is_loop {
            let from_is_output = node_kinds.get(edge.from_node_id.as_str()) == Some(&NodeKind::Output);
            let to_is_output = node_kinds.get(edge.to_node_id.as_str()) == Some(&NodeKind::Output);
            if !from_is_output {
                loop_nodes.insert(edge.from_node_id.clone());
            }
            if !to_is_output {
                loop_nodes.insert(edge.to_node_id.clone());
            }
        }
    }

    let context = CodebaseContext {
        services: all_services.into_iter().collect(),
        entrypoints: entrypoints.into_iter().collect(),
        exits: exits.into_iter().collect(),
        models: models.into_iter().collect(),
        tools: tools.into_iter().collect(),
        code_files: code_files.into_iter().collect(),
        code_functions: code_functions.into_iter().collect(),
        capabilities: capabilities.into_iter().collect(),
        loop_nodes: loop_nodes.into_iter().collect(),
        total_traces: traces.len() as u64,
        total_spans,
        total_paths: paths.len() as u64,
        revision,
        last_amended_at_ns,
    };

    ExecutionGraph {
        nodes,
        edges,
        paths,
        context,
    }
}

fn aggregate_single_path(traces: &[ExtractedTrace]) -> GraphPath {
    let refs: Vec<&ExtractedTrace> = traces.iter().collect();
    aggregate_path_refs(&refs)
}

fn aggregate_path_refs(traces: &[&ExtractedTrace]) -> GraphPath {
    let first = traces[0];
    let trace_count = traces.len() as u64;
    let mut error_count = 0u64;
    let mut durations: Vec<f64> = Vec::with_capacity(traces.len());
    let mut total_tokens = 0u64;
    let mut total_cost_usd = 0.0f64;
    let mut llm_call_count = 0u64;
    let mut tool_call_count = 0u64;
    let mut eval_count = 0u64;
    let mut eval_score_sum = 0.0f64;
    let mut eval_score_count = 0u64;
    let mut first_seen_ns = i64::MAX;
    let mut last_seen_ns = i64::MIN;
    let mut services = BTreeSet::new();
    let mut edge_ids: Vec<String> = Vec::new();
    let mut edge_seen: HashSet<&str> = HashSet::new();
    let mut max_depth = first.max_depth;
    let mut has_loops = first.has_loops;
    let mut loop_count = first.loop_count;

    for trace in traces {
        if trace.status_code == 2 {
            error_count += 1;
        }
        durations.push(trace.duration_ms);
        total_tokens += trace.total_tokens;
        total_cost_usd += trace.total_cost_usd;
        llm_call_count += trace.llm_calls.len() as u64;
        tool_call_count += trace.tool_calls.len() as u64;
        eval_count += trace.evals.len() as u64;
        for ev in &trace.evals {
            if let Some(score) = ev.score {
                eval_score_sum += score;
                eval_score_count += 1;
            }
        }
        first_seen_ns = first_seen_ns.min(trace.start_time_ns);
        last_seen_ns = last_seen_ns.max(trace.start_time_ns);
        services.extend(trace.services.iter().cloned());
        max_depth = max_depth.max(trace.max_depth);
        has_loops |= trace.has_loops;
        loop_count = loop_count.max(trace.loop_count);
        for eid in &trace.edge_ids {
            if edge_seen.insert(eid.as_str()) {
                edge_ids.push(eid.clone());
            }
        }
    }

    let avg_duration_ms = if !durations.is_empty() {
        durations.iter().sum::<f64>() / durations.len() as f64
    } else {
        0.0
    };
    let p95_duration_ms = percentile_95(&mut durations);
    let avg_eval_score = if eval_score_count > 0 {
        Some(eval_score_sum / eval_score_count as f64)
    } else {
        None
    };

    GraphPath {
        path_id: first.path_id.clone(),
        signature: first.signature.clone(),
        collapsed_signature: first.collapsed_signature.clone(),
        steps: first.steps.clone(),
        node_ids: first.node_ids.clone(),
        edge_ids,
        has_loops,
        loop_count,
        max_depth,
        services: services.into_iter().collect(),
        trace_count,
        error_count,
        avg_duration_ms,
        p95_duration_ms,
        total_tokens,
        total_cost_usd: round_usd(total_cost_usd),
        llm_call_count,
        tool_call_count,
        eval_count,
        avg_eval_score,
        first_seen_ns: if first_seen_ns == i64::MAX {
            0
        } else {
            first_seen_ns
        },
        last_seen_ns: if last_seen_ns == i64::MIN {
            0
        } else {
            last_seen_ns
        },
    }
}

fn percentile_95(values: &mut [f64]) -> f64 {
    if values.is_empty() {
        return 0.0;
    }
    values.sort_by(f64::total_cmp);
    let idx = ((values.len() as f64 * 0.95).ceil() as usize)
        .saturating_sub(1)
        .min(values.len() - 1);
    values[idx]
}

#[derive(Default)]
struct LlmAgg {
    label: String,
    call_count: u64,
    error_count: u64,
    total_duration_ms: f64,
    input_sum: u64,
    input_count: u64,
    output_sum: u64,
    output_count: u64,
    total_cost_usd: f64,
    finish_reasons: BTreeSet<String>,
}

fn aggregate_path_llm_calls(traces: &[ExtractedTrace]) -> Vec<PathLlmCallSummary> {
    let mut map: BTreeMap<(String, Option<String>), LlmAgg> = BTreeMap::new();
    for trace in traces {
        for call in &trace.llm_calls {
            let agg = map
                .entry((call.node_id.clone(), call.model.clone()))
                .or_default();
            if agg.label.is_empty() {
                agg.label = call.label.clone();
            }
            agg.call_count += 1;
            if call.error {
                agg.error_count += 1;
            }
            agg.total_duration_ms += call.duration_ms;
            if let Some(inp) = call.input_tokens {
                agg.input_sum += inp;
                agg.input_count += 1;
            }
            if let Some(out) = call.output_tokens {
                agg.output_sum += out;
                agg.output_count += 1;
            }
            agg.total_cost_usd += call.cost_usd;
            agg.finish_reasons.extend(call.finish_reasons.iter().cloned());
        }
    }

    let mut list: Vec<PathLlmCallSummary> = map
        .into_iter()
        .map(|((node_id, model), agg)| PathLlmCallSummary {
            node_id,
            label: agg.label,
            model,
            call_count: agg.call_count,
            error_count: agg.error_count,
            avg_duration_ms: if agg.call_count > 0 {
                agg.total_duration_ms / agg.call_count as f64
            } else {
                0.0
            },
            avg_input_tokens: if agg.input_count > 0 {
                Some(agg.input_sum as f64 / agg.input_count as f64)
            } else {
                None
            },
            avg_output_tokens: if agg.output_count > 0 {
                Some(agg.output_sum as f64 / agg.output_count as f64)
            } else {
                None
            },
            total_cost_usd: round_usd(agg.total_cost_usd),
            finish_reasons: agg.finish_reasons.into_iter().collect(),
        })
        .collect();

    list.sort_by(|a, b| {
        b.call_count
            .cmp(&a.call_count)
            .then_with(|| a.node_id.cmp(&b.node_id))
            .then_with(|| a.model.cmp(&b.model))
    });
    list
}

#[derive(Default)]
struct ToolAgg {
    tool_name: String,
    call_count: u64,
    error_count: u64,
    total_duration_ms: f64,
}

fn aggregate_path_tool_calls(traces: &[ExtractedTrace]) -> Vec<PathToolCallSummary> {
    let mut map: BTreeMap<String, ToolAgg> = BTreeMap::new();
    for trace in traces {
        for call in &trace.tool_calls {
            let agg = map.entry(call.node_id.clone()).or_default();
            if agg.tool_name.is_empty() {
                agg.tool_name = call.tool_name.clone();
            }
            agg.call_count += 1;
            if call.error {
                agg.error_count += 1;
            }
            agg.total_duration_ms += call.duration_ms;
        }
    }

    let mut list: Vec<PathToolCallSummary> = map
        .into_iter()
        .map(|(node_id, agg)| PathToolCallSummary {
            node_id,
            tool_name: agg.tool_name,
            call_count: agg.call_count,
            error_count: agg.error_count,
            avg_duration_ms: if agg.call_count > 0 {
                agg.total_duration_ms / agg.call_count as f64
            } else {
                0.0
            },
        })
        .collect();

    list.sort_by(|a, b| {
        b.call_count
            .cmp(&a.call_count)
            .then_with(|| a.node_id.cmp(&b.node_id))
    });
    list
}

#[derive(Default)]
struct EvalAgg {
    count: u64,
    passed_count: u64,
    failed_count: u64,
    score_sum: f64,
    score_count: u64,
}

fn aggregate_path_evals(traces: &[ExtractedTrace]) -> Vec<PathEvalSummary> {
    let mut map: BTreeMap<(EvalKind, String), EvalAgg> = BTreeMap::new();
    for trace in traces {
        for ev in &trace.evals {
            let agg = map.entry((ev.kind, ev.name.clone())).or_default();
            agg.count += 1;
            match ev.passed {
                Some(true) => agg.passed_count += 1,
                Some(false) => agg.failed_count += 1,
                None => {}
            }
            if let Some(score) = ev.score {
                agg.score_sum += score;
                agg.score_count += 1;
            }
        }
    }

    let mut list: Vec<PathEvalSummary> = map
        .into_iter()
        .map(|((kind, name), agg)| PathEvalSummary {
            name,
            kind,
            count: agg.count,
            passed_count: agg.passed_count,
            failed_count: agg.failed_count,
            avg_score: if agg.score_count > 0 {
                Some(agg.score_sum / agg.score_count as f64)
            } else {
                None
            },
        })
        .collect();

    list.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(&b.name)));
    list
}

fn aggregate_path_code_context(traces: &[ExtractedTrace]) -> PathCodeContext {
    let mut services = BTreeSet::new();
    let mut files = BTreeSet::new();
    let mut functions = BTreeSet::new();
    let mut capabilities = BTreeSet::new();
    let mut models = BTreeSet::new();
    let mut tools = BTreeSet::new();

    for trace in traces {
        services.extend(trace.services.iter().cloned());
        for node in &trace.nodes {
            services.extend(node.services.iter().cloned());
            files.extend(node.code_context.filepaths.iter().cloned());
            functions.extend(node.code_context.functions.iter().cloned());
            capabilities.extend(node.code_context.capabilities.iter().cloned());
            models.extend(node.code_context.models.iter().cloned());
            tools.extend(node.code_context.tools.iter().cloned());
            if node.kind == NodeKind::Tool {
                tools.insert(node.label.clone());
            }
        }
    }

    PathCodeContext {
        services: services.into_iter().collect(),
        files: files.into_iter().collect(),
        functions: functions.into_iter().collect(),
        capabilities: capabilities.into_iter().collect(),
        models: models.into_iter().collect(),
        tools: tools.into_iter().collect(),
    }
}

fn build_trace_eval_summary(trace: &ExtractedTrace) -> Option<PathTraceEvalSummary> {
    if trace.evals.is_empty() {
        return None;
    }
    let mut passed_count = 0u64;
    let mut failed_count = 0u64;
    let mut score_sum = 0.0f64;
    let mut score_count = 0u64;

    for ev in &trace.evals {
        match ev.passed {
            Some(true) => passed_count += 1,
            Some(false) => failed_count += 1,
            None => {}
        }
        if let Some(score) = ev.score {
            score_sum += score;
            score_count += 1;
        }
    }

    Some(PathTraceEvalSummary {
        count: trace.evals.len() as u64,
        passed_count,
        failed_count,
        avg_score: if score_count > 0 {
            Some(score_sum / score_count as f64)
        } else {
            None
        },
    })
}

pub(crate) fn now_ns() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos() as i64)
        .unwrap_or_default()
}