Skip to content

The platform for continuously improving AI agents.

12.6 KB
Raw Blame
use std::sync::Arc;

use buffa::Message;
use connectrpc::{
    ConnectError, ErrorCode, RequestContext, Response, ServiceRequest, ServiceResult,
};
use graph::{
    CodebaseContext, GraphBuilder, GraphEdge, GraphNode, GraphPath, GraphStore, NodeCodeContext,
    PathCodeContext, PathEvalSummary, PathLlmCallSummary, PathStep, PathToolCallSummary,
    PathTraceEvalSummary, PathTraceRef,
};
use otel::{ReadCache, max_concurrent_reads_from_env, read_cache_ttl_from_env};
use tokio::sync::Semaphore;

use crate::pb::{
    CodebaseContext as PbCodebaseContext, GetGraphRequest, GetGraphResponse, GetPathDetailRequest,
    GetPathDetailResponse, GraphEdge as PbGraphEdge, GraphNode as PbGraphNode,
    GraphPath as PbGraphPath, GraphService, ListPathsRequest, ListPathsResponse,
    NodeCodeContext as PbNodeCodeContext, PathCodeContext as PbPathCodeContext,
    PathEvalSummary as PbPathEvalSummary, PathLlmCallSummary as PbPathLlmCallSummary,
    PathStep as PbPathStep, PathToolCallSummary as PbPathToolCallSummary,
    PathTraceEvalSummary as PbPathTraceEvalSummary, PathTraceRef as PbPathTraceRef,
    RebuildGraphRequest, RebuildGraphResponse,
};

const DEFAULT_PATH_LIMIT: usize = 200;
const MAX_PATH_LIMIT: usize = 1000;
const DEFAULT_TRACE_LIMIT: usize = 100;
const MAX_TRACE_LIMIT: usize = 500;

pub struct GraphServer {
    pub store: GraphStore,
    pub builder: Arc<GraphBuilder>,
    read_semaphore: Arc<Semaphore>,
    graph_cache: ReadCache<GetGraphResponse>,
}

impl GraphServer {
    pub fn new(store: GraphStore, builder: Arc<GraphBuilder>) -> Self {
        Self {
            store,
            builder,
            read_semaphore: Arc::new(Semaphore::new(max_concurrent_reads_from_env())),
            graph_cache: ReadCache::new(read_cache_ttl_from_env()),
        }
    }
}

#[allow(refining_impl_trait)]
impl GraphService for GraphServer {
    async fn get_graph(
        &self,
        _ctx: RequestContext,
        request: ServiceRequest<'_, GetGraphRequest>,
    ) -> ServiceResult<GetGraphResponse> {
        let req = request.to_owned_message();
        let key = req.encode_to_vec();
        let service_name = non_empty(req.service_name);
        let limit = clamp_limit(req.limit_paths, DEFAULT_PATH_LIMIT, MAX_PATH_LIMIT);
        let store = self.store.clone();
        let response = self
            .graph_cache
            .get_or_load(&self.read_semaphore, key, move || async move {
                let graph =
                    blocking(move || store.get_graph(service_name.as_deref(), limit)).await?;
                Ok::<_, ConnectError>(GetGraphResponse {
                    nodes: graph.nodes.into_iter().map(node_to_pb).collect(),
                    edges: graph.edges.into_iter().map(edge_to_pb).collect(),
                    paths: graph.paths.into_iter().map(path_to_pb).collect(),
                    context: Some(context_to_pb(graph.context)).into(),
                    ..Default::default()
                })
            })
            .await?;
        Response::ok(response)
    }

    async fn list_paths(
        &self,
        _ctx: RequestContext,
        request: ServiceRequest<'_, ListPathsRequest>,
    ) -> ServiceResult<ListPathsResponse> {
        let req = request.to_owned_message();
        let service_name = non_empty(req.service_name);
        let node_id = non_empty(req.node_id);
        let limit = clamp_limit(req.limit, DEFAULT_PATH_LIMIT, MAX_PATH_LIMIT);
        let store = self.store.clone();
        let paths =
            blocking(move || store.list_paths(service_name.as_deref(), node_id.as_deref(), limit))
                .await?;
        Response::ok(ListPathsResponse {
            paths: paths.into_iter().map(path_to_pb).collect(),
            ..Default::default()
        })
    }

    async fn get_path_detail(
        &self,
        _ctx: RequestContext,
        request: ServiceRequest<'_, GetPathDetailRequest>,
    ) -> ServiceResult<GetPathDetailResponse> {
        let req = request.to_owned_message();
        let path_id = req.path_id.trim().to_string();
        if path_id.is_empty() {
            return Err(ConnectError::new(
                ErrorCode::InvalidArgument,
                "path_id is required",
            ));
        }
        let trace_limit = clamp_limit(req.trace_limit, DEFAULT_TRACE_LIMIT, MAX_TRACE_LIMIT);
        let store = self.store.clone();
        let lookup_id = path_id.clone();
        let detail = blocking(move || store.get_path_detail(&lookup_id, trace_limit)).await?;
        let Some(detail) = detail else {
            return Err(ConnectError::new(
                ErrorCode::NotFound,
                format!("path `{path_id}` not found"),
            ));
        };
        Response::ok(GetPathDetailResponse {
            path: Some(path_to_pb(detail.path)).into(),
            share_of_traces: detail.share_of_traces,
            llm_calls: detail.llm_calls.into_iter().map(llm_call_to_pb).collect(),
            tool_calls: detail.tool_calls.into_iter().map(tool_call_to_pb).collect(),
            evals: detail.evals.into_iter().map(eval_to_pb).collect(),
            code_context: Some(path_code_context_to_pb(detail.code_context)).into(),
            traces: detail.traces.into_iter().map(trace_ref_to_pb).collect(),
            ..Default::default()
        })
    }

    async fn rebuild_graph(
        &self,
        _ctx: RequestContext,
        _request: ServiceRequest<'_, RebuildGraphRequest>,
    ) -> ServiceResult<RebuildGraphResponse> {
        let builder = Arc::clone(&self.builder);
        let report = blocking(move || builder.amend_once()).await?;
        self.graph_cache.clear();
        Response::ok(RebuildGraphResponse {
            scanned_traces: report.scanned_traces as u64,
            amended_traces: report.amended_traces as u64,
            skipped_traces: report.skipped_traces as u64,
            total_nodes: report.total_nodes as u64,
            total_edges: report.total_edges as u64,
            total_paths: report.total_paths as u64,
            revision: report.revision,
            ..Default::default()
        })
    }
}

fn non_empty(value: String) -> Option<String> {
    let trimmed = value.trim();
    (!trimmed.is_empty()).then(|| trimmed.to_string())
}

fn clamp_limit(requested: u32, default: usize, max: usize) -> usize {
    if requested == 0 {
        default
    } else {
        (requested as usize).min(max)
    }
}

async fn blocking<T: Send + 'static>(
    work: impl FnOnce() -> anyhow::Result<T> + Send + 'static,
) -> Result<T, ConnectError> {
    match tokio::task::spawn_blocking(work).await {
        Ok(Ok(value)) => Ok(value),
        Ok(Err(error)) => {
            tracing::error!(?error, "graph rpc failed");
            Err(ConnectError::new(ErrorCode::Internal, "internal error"))
        }
        Err(error) => {
            tracing::error!(?error, "graph rpc task panicked");
            Err(ConnectError::new(ErrorCode::Internal, "internal error"))
        }
    }
}

fn node_code_context_to_pb(ctx: NodeCodeContext) -> PbNodeCodeContext {
    PbNodeCodeContext {
        filepaths: ctx.filepaths,
        functions: ctx.functions,
        namespaces: ctx.namespaces,
        capabilities: ctx.capabilities,
        models: ctx.models,
        tools: ctx.tools,
        span_types: ctx.span_types,
        ..Default::default()
    }
}

fn node_to_pb(node: GraphNode) -> PbGraphNode {
    PbGraphNode {
        node_id: node.node_id,
        label: node.label,
        kind: node.kind.as_str().to_string(),
        services: node.services,
        span_count: node.span_count,
        trace_count: node.trace_count,
        error_count: node.error_count,
        avg_duration_ms: node.avg_duration_ms,
        total_tokens: node.total_tokens,
        total_cost_usd: node.total_cost_usd,
        is_entry: node.is_entry,
        is_exit: node.is_exit,
        has_self_loop: node.has_self_loop,
        code_context: Some(node_code_context_to_pb(node.code_context)).into(),
        ..Default::default()
    }
}

fn edge_to_pb(edge: GraphEdge) -> PbGraphEdge {
    PbGraphEdge {
        edge_id: edge.edge_id,
        from_node_id: edge.from_node_id,
        to_node_id: edge.to_node_id,
        kind: edge.kind.as_str().to_string(),
        transition_count: edge.transition_count,
        trace_count: edge.trace_count,
        is_loop: edge.is_loop,
        avg_gap_ms: edge.avg_gap_ms,
        ..Default::default()
    }
}

fn step_to_pb(step: PathStep) -> PbPathStep {
    PbPathStep {
        step_index: step.step_index,
        node_id: step.node_id,
        label: step.label,
        kind: step.kind.as_str().to_string(),
        depth: step.depth,
        is_loop_back: step.is_loop_back,
        ..Default::default()
    }
}

fn path_to_pb(path: GraphPath) -> PbGraphPath {
    PbGraphPath {
        path_id: path.path_id,
        signature: path.signature,
        collapsed_signature: path.collapsed_signature,
        steps: path.steps.into_iter().map(step_to_pb).collect(),
        node_ids: path.node_ids,
        edge_ids: path.edge_ids,
        has_loops: path.has_loops,
        loop_count: path.loop_count,
        max_depth: path.max_depth,
        services: path.services,
        trace_count: path.trace_count,
        error_count: path.error_count,
        avg_duration_ms: path.avg_duration_ms,
        p95_duration_ms: path.p95_duration_ms,
        total_tokens: path.total_tokens,
        total_cost_usd: path.total_cost_usd,
        llm_call_count: path.llm_call_count,
        tool_call_count: path.tool_call_count,
        eval_count: path.eval_count,
        avg_eval_score: path.avg_eval_score,
        first_seen_ns: path.first_seen_ns,
        last_seen_ns: path.last_seen_ns,
        ..Default::default()
    }
}

fn context_to_pb(ctx: CodebaseContext) -> PbCodebaseContext {
    PbCodebaseContext {
        services: ctx.services,
        entrypoints: ctx.entrypoints,
        exits: ctx.exits,
        models: ctx.models,
        tools: ctx.tools,
        code_files: ctx.code_files,
        code_functions: ctx.code_functions,
        capabilities: ctx.capabilities,
        loop_nodes: ctx.loop_nodes,
        total_traces: ctx.total_traces,
        total_spans: ctx.total_spans,
        total_paths: ctx.total_paths,
        revision: ctx.revision,
        last_amended_at_ns: ctx.last_amended_at_ns,
        ..Default::default()
    }
}

fn llm_call_to_pb(call: PathLlmCallSummary) -> PbPathLlmCallSummary {
    PbPathLlmCallSummary {
        node_id: call.node_id,
        label: call.label,
        model: call.model,
        call_count: call.call_count,
        error_count: call.error_count,
        avg_duration_ms: call.avg_duration_ms,
        avg_input_tokens: call.avg_input_tokens,
        avg_output_tokens: call.avg_output_tokens,
        total_cost_usd: call.total_cost_usd,
        finish_reasons: call.finish_reasons,
        ..Default::default()
    }
}

fn tool_call_to_pb(call: PathToolCallSummary) -> PbPathToolCallSummary {
    PbPathToolCallSummary {
        node_id: call.node_id,
        tool_name: call.tool_name,
        call_count: call.call_count,
        error_count: call.error_count,
        avg_duration_ms: call.avg_duration_ms,
        ..Default::default()
    }
}

fn eval_to_pb(eval: PathEvalSummary) -> PbPathEvalSummary {
    PbPathEvalSummary {
        name: eval.name,
        kind: eval.kind.as_str().to_string(),
        count: eval.count,
        passed_count: eval.passed_count,
        failed_count: eval.failed_count,
        avg_score: eval.avg_score,
        ..Default::default()
    }
}

fn path_code_context_to_pb(ctx: PathCodeContext) -> PbPathCodeContext {
    PbPathCodeContext {
        services: ctx.services,
        files: ctx.files,
        functions: ctx.functions,
        capabilities: ctx.capabilities,
        models: ctx.models,
        tools: ctx.tools,
        ..Default::default()
    }
}

fn trace_eval_summary_to_pb(summary: PathTraceEvalSummary) -> PbPathTraceEvalSummary {
    PbPathTraceEvalSummary {
        count: summary.count,
        passed_count: summary.passed_count,
        failed_count: summary.failed_count,
        avg_score: summary.avg_score,
        ..Default::default()
    }
}

fn trace_ref_to_pb(trace: PathTraceRef) -> PbPathTraceRef {
    PbPathTraceRef {
        trace_id: trace.trace_id,
        service_name: trace.service_name,
        root_span_name: trace.root_span_name,
        start_time_ns: trace.start_time_ns,
        duration_ms: trace.duration_ms,
        status_code: trace.status_code,
        span_count: trace.span_count,
        llm_calls: trace.llm_calls,
        tool_calls: trace.tool_calls,
        total_tokens: trace.total_tokens,
        cost_usd: trace.cost_usd,
        eval_summary: trace.eval_summary.map(trace_eval_summary_to_pb).into(),
        output_label: trace.output_label,
        ..Default::default()
    }
}