Skip to content

The platform for continuously improving AI agents.

36.2 KB
Raw Blame
use std::{
    collections::{BTreeMap, HashMap},
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use anyhow::Result;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
use trace_types::{SpanRecord, SpanSource, group_key};

use crate::{
    custom::{
        CompiledCustomSignal, CustomSignalDef, CustomSignalSampleMatch, CustomSignalTestResult,
    },
    model::{SignalCatalogItem, SignalEvent, SignalSubscription},
    rules::{RuleContext, SignalRule, builtin_rules},
    store::{SignalStore, utc_date_from_ms},
};

pub const DEFAULT_WINDOW_DAYS: i64 = 30;
pub const DEFAULT_SPAN_LIMIT: usize = 20_000;
const MS_PER_DAY: i64 = 24 * 60 * 60 * 1000;
const MAX_TEST_SAMPLES: usize = 10;

pub struct SignalRunner {
    source: Arc<dyn SpanSource>,
    store: SignalStore,
    rules: Vec<Box<dyn SignalRule>>,
    window_ms: i64,
    span_limit: usize,
}

impl SignalRunner {
    pub fn new(source: Arc<dyn SpanSource>, store: SignalStore) -> Self {
        Self {
            source,
            store,
            rules: builtin_rules(),
            window_ms: DEFAULT_WINDOW_DAYS * MS_PER_DAY,
            span_limit: DEFAULT_SPAN_LIMIT,
        }
    }

    pub fn with_window_days(mut self, days: i64) -> Self {
        self.window_ms = days.max(1) * MS_PER_DAY;
        self
    }

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

    pub fn run_once(&self) -> Result<usize> {
        let since_ms = now_ms().saturating_sub(self.window_ms);
        let spans = self.source.recent_spans(since_ms, self.span_limit)?;
        if spans.is_empty() {
            return Ok(0);
        }

        let subs = self.store.list_subscriptions(None)?;
        let sub_map: HashMap<(String, String), SignalSubscription> = subs
            .into_iter()
            .map(|s| ((s.service_name.clone(), s.signal_type.clone()), s))
            .collect();

        let custom_defs = self.store.list_custom_signals()?;
        let mut compiled_custom = Vec::with_capacity(custom_defs.len());
        for def in custom_defs {
            match CompiledCustomSignal::compile(def) {
                Ok(c) => compiled_custom.push(c),
                Err(err) => {
                    tracing::warn!(?err, "skipping invalid stored custom signal");
                }
            }
        }

        let mut groups: BTreeMap<(String, String), Vec<&SpanRecord>> = BTreeMap::new();
        for span in &spans {
            let key = (span.service_name.clone(), group_key(span));
            groups.entry(key).or_default().push(span);
        }

        let mut created = 0;
        for ((service_name, gkey), group_spans) in &groups {
            let occurred_at_ms = latest_occurred_ms(group_spans);
            let date = utc_date_from_ms(occurred_at_ms);
            let conversation_id = gkey.strip_prefix("conversation:").map(ToString::to_string);

            // Built-in rules
            for rule in &self.rules {
                let item = rule.catalog_item();
                let (enabled, params) = resolve_config(&item, service_name, &sub_map);
                if !enabled {
                    continue;
                }

                let ctx = RuleContext {
                    service_name,
                    group_key: gkey,
                    spans: group_spans,
                    params: &params,
                };
                let Some(hit) = rule.evaluate(&ctx) else {
                    continue;
                };

                if self.persist_hit(
                    &item,
                    service_name,
                    gkey,
                    &date,
                    occurred_at_ms,
                    &conversation_id,
                    group_spans,
                    hit,
                )? {
                    created += 1;
                }
            }

            // Custom signals
            for custom in &compiled_custom {
                let item = custom.def.to_catalog_item();
                let (enabled, params) = resolve_config(&item, service_name, &sub_map);
                if !enabled {
                    continue;
                }

                let ctx = RuleContext {
                    service_name,
                    group_key: gkey,
                    spans: group_spans,
                    params: &params,
                };
                let Some(hit) = custom.evaluate(&ctx) else {
                    continue;
                };

                if self.persist_hit(
                    &item,
                    service_name,
                    gkey,
                    &date,
                    occurred_at_ms,
                    &conversation_id,
                    group_spans,
                    hit,
                )? {
                    created += 1;
                }
            }
        }

        Ok(created)
    }

    #[allow(clippy::too_many_arguments)]
    fn persist_hit(
        &self,
        item: &SignalCatalogItem,
        service_name: &str,
        gkey: &str,
        date: &str,
        occurred_at_ms: i64,
        conversation_id: &Option<String>,
        group_spans: &[&SpanRecord],
        hit: crate::rules::RuleHit,
    ) -> Result<bool> {
        let dedupe_key = sha256_hex(&format!(
            "{service_name}:{}:{gkey}:{date}",
            item.signal_type
        ));
        let id = format!("sig_{}", &dedupe_key[..24]);
        let trace_id = hit
            .details
            .trace_ids
            .first()
            .or_else(|| group_spans.first().map(|s| &s.trace_id))
            .cloned()
            .unwrap_or_default();

        let event = SignalEvent {
            id,
            signal_type: item.signal_type.clone(),
            severity: item.severity,
            service_name: service_name.to_string(),
            message: hit.message,
            details: hit.details,
            trace_id,
            conversation_id: conversation_id.clone(),
            dedupe_key,
            occurred_at_ms,
            seen_at_ms: None,
        };

        self.store.insert_event(&event)
    }

    /// Dry-run evaluates a custom signal definition against recent traces without persisting.
    pub fn test_custom_signal(
        &self,
        def: &CustomSignalDef,
        window_days: u32,
    ) -> Result<CustomSignalTestResult> {
        let compiled = CompiledCustomSignal::compile(def.clone())?;
        let days = if window_days == 0 {
            DEFAULT_WINDOW_DAYS
        } else {
            i64::from(window_days).clamp(1, 365)
        };
        let since_ms = now_ms().saturating_sub(days * MS_PER_DAY);
        let spans = self.source.recent_spans(since_ms, self.span_limit)?;

        let mut groups: BTreeMap<(String, String), Vec<&SpanRecord>> = BTreeMap::new();
        for span in &spans {
            let key = (span.service_name.clone(), group_key(span));
            groups.entry(key).or_default().push(span);
        }

        let scanned_groups = groups.len();
        let mut matches = Vec::new();
        let empty_params = Value::Object(Map::new());

        for ((service_name, gkey), group_spans) in &groups {
            let ctx = RuleContext {
                service_name,
                group_key: gkey,
                spans: group_spans,
                params: &empty_params,
            };
            let Some(hit) = compiled.evaluate(&ctx) else {
                continue;
            };
            let occurred_at_ms = latest_occurred_ms(group_spans);
            let trace_id = hit
                .details
                .trace_ids
                .first()
                .or_else(|| group_spans.first().map(|s| &s.trace_id))
                .cloned()
                .unwrap_or_default();
            matches.push(CustomSignalSampleMatch {
                trace_id,
                service_name: service_name.clone(),
                summary: hit.message,
                why: hit.details.why,
                evidence_count: hit.details.span_ids.len(),
                occurred_at_ns: occurred_at_ms * 1_000_000,
            });
        }

        matches.sort_by_key(|m| std::cmp::Reverse(m.occurred_at_ns));
        let matched_groups = matches.len();
        matches.truncate(MAX_TEST_SAMPLES);

        Ok(CustomSignalTestResult {
            matched_groups,
            scanned_groups,
            samples: matches,
        })
    }
}

pub fn spawn_worker(runner: Arc<SignalRunner>, interval: Duration) -> tokio::task::JoinHandle<()> {
    spawn_worker_with_delay(runner, Duration::ZERO, interval)
}

pub fn spawn_worker_with_delay(
    runner: Arc<SignalRunner>,
    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 r = Arc::clone(&runner);
            match tokio::task::spawn_blocking(move || r.run_once()).await {
                Ok(Ok(created)) => {
                    if created > 0 {
                        tracing::info!(created, "signals sweep created events");
                    } else {
                        tracing::debug!("signals sweep complete (0 new events)");
                    }
                }
                Ok(Err(error)) => tracing::error!(?error, "signals sweep failed"),
                Err(error) => tracing::error!(?error, "signals sweep task panicked"),
            }
        }
    })
}

pub fn resolve_config(
    item: &SignalCatalogItem,
    service_name: &str,
    subs: &HashMap<(String, String), SignalSubscription>,
) -> (bool, Value) {
    let sub = if !service_name.is_empty() {
        subs.get(&(service_name.to_string(), item.signal_type.clone()))
            .or_else(|| subs.get(&(String::new(), item.signal_type.clone())))
    } else {
        subs.get(&(String::new(), item.signal_type.clone()))
    };

    match sub {
        Some(s) => (s.enabled, merge_objects(&item.default_params, &s.config)),
        None => (item.default_enabled, item.default_params.clone()),
    }
}

fn merge_objects(defaults: &Value, overrides: &Value) -> Value {
    let mut merged: Map<String, Value> = defaults.as_object().cloned().unwrap_or_default();
    if let Some(map) = overrides.as_object() {
        for (k, v) in map {
            merged.insert(k.clone(), v.clone());
        }
    }
    Value::Object(merged)
}

fn latest_occurred_ms(spans: &[&SpanRecord]) -> i64 {
    let max_start_ms = spans
        .iter()
        .map(|s| s.start_time_ns / 1_000_000)
        .filter(|ms| *ms > 0)
        .max();
    max_start_ms.unwrap_or_else(|| {
        spans
            .iter()
            .map(|s| s.received_at_ms)
            .max()
            .unwrap_or_else(now_ms)
    })
}

fn sha256_hex(input: &str) -> String {
    let digest = Sha256::digest(input.as_bytes());
    let mut out = String::with_capacity(64);
    for b in digest {
        use std::fmt::Write as _;
        let _ = write!(&mut out, "{b:02x}");
    }
    out
}

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

pub fn now_ns() -> i64 {
    now_ms() * 1_000_000
}

#[cfg(test)]
mod tests {
    use serde_json::json;
    use trace_types::SpanUsage;

    use super::*;
    use crate::{
        custom::{
            ConditionOp, CustomCondition, CustomSignalError, CustomSignalFilters,
            CustomSignalScope, CustomSignalSpec, MatchMode, validate_custom_signal,
        },
        model::SignalSeverity,
        store::ListEventsFilter,
    };

    struct VecSource(Vec<SpanRecord>);

    impl SpanSource for VecSource {
        fn recent_spans(&self, since_received_ms: i64, limit: usize) -> Result<Vec<SpanRecord>> {
            Ok(self
                .0
                .iter()
                .filter(|s| s.received_at_ms >= since_received_ms)
                .take(limit)
                .cloned()
                .collect())
        }
    }

    struct SpanSpec<'a> {
        trace_id: &'a str,
        span_id: &'a str,
        name: &'a str,
        service: &'a str,
        start_ms: i64,
        dur_ms: i64,
        status_code: i32,
        status_message: &'a str,
        attrs: Value,
        events: Value,
    }

    fn mk_span(spec: SpanSpec<'_>) -> SpanRecord {
        let attrs_map = spec.attrs.as_object().cloned().unwrap_or_default();
        let usage = SpanUsage::from_attributes(&attrs_map);
        let normalized = trace_types::semconv::normalize_attributes(&attrs_map);
        SpanRecord {
            span_id: spec.span_id.into(),
            trace_id: spec.trace_id.into(),
            parent_span_id: None,
            name: spec.name.into(),
            kind: 1,
            start_time_ns: spec.start_ms * 1_000_000,
            end_time_ns: (spec.start_ms + spec.dur_ms) * 1_000_000,
            duration_ns: spec.dur_ms * 1_000_000,
            status_code: spec.status_code,
            status_message: spec.status_message.into(),
            service_name: spec.service.into(),
            resource_attrs: json!({ "service.name": spec.service }),
            scope_name: "agent".into(),
            scope_version: "1.0".into(),
            attributes: Value::Object(normalized),
            events: spec.events,
            links: json!([]),
            usage,
            received_at_ms: now_ms(),
        }
    }

    #[test]
    fn evaluates_all_sixteen_builtin_rules_and_deduplicates_on_rerun() {
        let now = now_ms();
        let mut spans = vec![
            // Trace 1: errors + slow_trace + high_cost + high_tokens + secret_leak + low_score + context_bloat + output_truncation
            mk_span(SpanSpec {
                trace_id: "trace-1",
                span_id: "s1",
                name: "llm.chat",
                service: "support-bot",
                start_ms: now - 10_000,
                dur_ms: 6_500,
                status_code: 2,
                status_message: "upstream 500 internal error",
                attrs: json!({
                    "gen_ai.operation.name": "chat",
                    "gen_ai.request.model": "openai/gpt-5-mini",
                    "gen_ai.usage.input_tokens": 15_000,
                    "gen_ai.usage.output_tokens": 5_000,
                    "gen_ai.usage.total_tokens": 20_000,
                    "gen_ai.response.finish_reasons": ["length"],
                    "overmind.cost": 0.12,
                    "overmind.input": "help me",
                    "overmind.output": "try key sk-live-secret12345678",
                    "overmind.score.helpfulness": 0.4,
                }),
                events: json!([]),
            }),
            // Trace 2: tool_loop (3 calls to search_kb) + tool_errors + rate_limit_or_timeout
            mk_span(SpanSpec {
                trace_id: "trace-2",
                span_id: "t1",
                name: "execute_tool",
                service: "support-bot",
                start_ms: now - 5_000,
                dur_ms: 100,
                status_code: 2,
                status_message: "504 search backend timeout",
                attrs: json!({ "gen_ai.tool.name": "search_kb" }),
                events: json!([]),
            }),
            mk_span(SpanSpec {
                trace_id: "trace-2",
                span_id: "t2",
                name: "execute_tool",
                service: "support-bot",
                start_ms: now - 4_500,
                dur_ms: 100,
                status_code: 1,
                status_message: "",
                attrs: json!({ "gen_ai.tool.name": "search_kb" }),
                events: json!([]),
            }),
            mk_span(SpanSpec {
                trace_id: "trace-2",
                span_id: "t3",
                name: "execute_tool",
                service: "support-bot",
                start_ms: now - 4_000,
                dur_ms: 100,
                status_code: 1,
                status_message: "",
                attrs: json!({ "gen_ai.tool.name": "search_kb" }),
                events: json!([]),
            }),
            // Trace 3: empty_output + low_score (event) + failed_expectations + negative_feedback (event + attr)
            mk_span(SpanSpec {
                trace_id: "trace-3",
                span_id: "e1",
                name: "llm.chat",
                service: "support-bot",
                start_ms: now - 3_000,
                dur_ms: 200,
                status_code: 1,
                status_message: "",
                attrs: json!({
                    "gen_ai.operation.name": "chat",
                    "gen_ai.request.model": "openai/gpt-5-mini",
                    "overmind.input": "summarize ticket",
                    "overmind.expectations": [
                        {"name": "mentions_refund", "passed": true},
                        {"name": "valid_json", "passed": false, "reason": "missing closing brace"}
                    ],
                    "overmind.feedback.rating": "thumbs_down",
                    "overmind.feedback.comment": "unhelpful answer"
                }),
                events: json!([
                    {
                        "name": "overmind.score",
                        "time_unix_nano": (now - 2_900) * 1_000_000,
                        "attributes": { "score": 0.5, "reason": "missing summary" }
                    },
                    {
                        "name": "overmind.feedback",
                        "time_unix_nano": (now - 2_800) * 1_000_000,
                        "attributes": { "score": 0.2, "reason": "wrong tone" }
                    }
                ]),
            }),
            // Trace 4: safety_or_refusal (OpenRouter Gemini SAFETY 403)
            mk_span(SpanSpec {
                trace_id: "trace-4",
                span_id: "sf1",
                name: "llm.chat",
                service: "support-bot",
                start_ms: now - 2_000,
                dur_ms: 150,
                status_code: 2,
                status_message: "403: Gemini blocked the request: SAFETY",
                attrs: json!({
                    "gen_ai.operation.name": "chat",
                    "gen_ai.request.model": "google/gemini-2.5-flash",
                    "gen_ai.response.finish_reasons": ["safety"],
                }),
                events: json!([]),
            }),
        ];

        // Trace 5: excessive_llm_calls (8 LLM spans)
        for i in 0..8 {
            spans.push(mk_span(SpanSpec {
                trace_id: "trace-5",
                span_id: &format!("llm-{i}"),
                name: "llm.chat",
                service: "support-bot",
                start_ms: now - 1_500 + (i as i64) * 50,
                dur_ms: 40,
                status_code: 1,
                status_message: "",
                attrs: json!({
                    "gen_ai.operation.name": "chat",
                    "gen_ai.request.model": "openai/gpt-5-mini",
                    "overmind.input": "step",
                    "overmind.output": "ok",
                }),
                events: json!([]),
            }));
        }

        let store = SignalStore::in_memory().unwrap();
        let runner = SignalRunner::new(Arc::new(VecSource(spans)), store.clone());

        let created = runner.run_once().unwrap();
        assert!(created >= 16);

        // Re-running is idempotent via dedupe_key.
        let created_again = runner.run_once().unwrap();
        assert_eq!(created_again, 0);

        let page = store
            .list_events(&ListEventsFilter::default(), 0, 100)
            .unwrap();
        let types: Vec<&str> = page.events.iter().map(|e| e.signal_type.as_str()).collect();
        for expected in [
            "errors",
            "tool_errors",
            "rate_limit_or_timeout",
            "tool_loop",
            "slow_trace",
            "excessive_llm_calls",
            "high_cost",
            "high_tokens",
            "context_bloat",
            "empty_output",
            "output_truncation",
            "low_score",
            "failed_expectations",
            "negative_feedback",
            "secret_leak",
            "safety_or_refusal",
        ] {
            assert!(types.contains(&expected), "missing rule {expected}");
        }

        // Secret leak evidence must redact the raw API key.
        let secret_ev = page
            .events
            .iter()
            .find(|e| e.signal_type == "secret_leak")
            .unwrap();
        let out = secret_ev.details.evidence[0].output.as_deref().unwrap();
        assert!(!out.contains("sk-live-secret12345678"));
        assert!(out.contains("[REDACTED]"));
    }

    #[test]
    fn clean_trace_triggers_zero_false_positives() {
        let now = now_ms();
        let spans = vec![mk_span(SpanSpec {
            trace_id: "trace-clean",
            span_id: "c1",
            name: "llm.chat",
            service: "support-bot",
            start_ms: now - 1_000,
            dur_ms: 400,
            status_code: 1,
            status_message: "",
            attrs: json!({
                "gen_ai.operation.name": "chat",
                "gen_ai.request.model": "openai/gpt-5-mini",
                "gen_ai.usage.input_tokens": 500,
                "gen_ai.usage.output_tokens": 200,
                "gen_ai.usage.total_tokens": 700,
                "gen_ai.response.finish_reasons": ["stop"],
                "overmind.cost": 0.001,
                "overmind.input": "Explain HTTP 504 timeout and safety filters",
                "overmind.output": "A 504 means gateway timeout and safety filters block harmful content.",
                "overmind.score.quality": 0.95,
                "overmind.expectations": [{"name": "helpful", "passed": true, "status": "passed"}],
                "overmind.feedback.rating": "thumbs_up",
                "overmind.feedback.score": 1.0,
                "overmind.feedback.user_id": "0"
            }),
            events: json!([]),
        })];

        let store = SignalStore::in_memory().unwrap();
        let runner = SignalRunner::new(Arc::new(VecSource(spans)), store);
        assert_eq!(runner.run_once().unwrap(), 0);
    }

    #[test]
    fn subscriptions_can_disable_or_override_thresholds() {
        let now = now_ms();
        let spans = vec![mk_span(SpanSpec {
            trace_id: "trace-slow",
            span_id: "s1",
            name: "agent.run",
            service: "svc-a",
            start_ms: now - 1_000,
            dur_ms: 2_500,
            status_code: 1,
            status_message: "",
            attrs: json!({}),
            events: json!([]),
        })];
        let store = SignalStore::in_memory().unwrap();

        // Lower slow_trace threshold to 2000ms globally.
        store
            .upsert_subscription(&SignalSubscription {
                service_name: String::new(),
                signal_type: "slow_trace".into(),
                enabled: true,
                config: json!({ "threshold_ms": 2000 }),
                updated_at_ms: now,
            })
            .unwrap();
        let runner = SignalRunner::new(Arc::new(VecSource(spans.clone())), store.clone());
        assert_eq!(runner.run_once().unwrap(), 1);

        // Disable slow_trace for svc-b and verify it does not fire on svc-b.
        let spans_b = vec![mk_span(SpanSpec {
            trace_id: "trace-slow-b",
            span_id: "s2",
            name: "agent.run",
            service: "svc-b",
            start_ms: now - 1_000,
            dur_ms: 9_000,
            status_code: 1,
            status_message: "",
            attrs: json!({}),
            events: json!([]),
        })];
        store
            .upsert_subscription(&SignalSubscription {
                service_name: "svc-b".into(),
                signal_type: "slow_trace".into(),
                enabled: false,
                config: json!({}),
                updated_at_ms: now,
            })
            .unwrap();
        let runner_b = SignalRunner::new(Arc::new(VecSource(spans_b)), store.clone());
        assert_eq!(runner_b.run_once().unwrap(), 0);
    }

    #[test]
    fn insights_compute_status_counts_and_mark_seen() {
        let now = now_ms();
        let spans = vec![
            mk_span(SpanSpec {
                trace_id: "trace-recent",
                span_id: "s1",
                name: "agent.run",
                service: "svc-a",
                start_ms: now - 60_000,
                dur_ms: 100,
                status_code: 2,
                status_message: "database failure",
                attrs: json!({ "error.type": "DbError" }),
                events: json!([]),
            }),
            mk_span(SpanSpec {
                trace_id: "trace-old",
                span_id: "s2",
                name: "agent.run",
                service: "svc-a",
                start_ms: now - 10 * MS_PER_DAY,
                dur_ms: 100,
                status_code: 2,
                status_message: "database failure",
                attrs: json!({ "error.type": "DbError" }),
                events: json!([]),
            }),
        ];
        let store = SignalStore::in_memory().unwrap();
        let runner = SignalRunner::new(Arc::new(VecSource(spans)), store.clone());
        assert_eq!(runner.run_once().unwrap(), 2);

        let summary = store.insights(14, None).unwrap();
        assert_eq!(summary.total_events, 2);
        assert_eq!(summary.total_unseen, 2);
        assert_eq!(summary.insights.len(), 1);
        let ins = &summary.insights[0];
        assert_eq!(ins.signal_type, "errors");
        assert_eq!(ins.severity, SignalSeverity::High);
        assert_eq!(ins.status, "ongoing");
        assert_eq!(ins.recent_count, 1);
        assert_eq!(ins.previous_count, 1);
        assert_eq!(ins.affected_traces, 2);
        assert_eq!(ins.daily_counts.len(), 14);

        let updated = store
            .mark_seen(&[], true, Some("svc-a"), Some("errors"), now)
            .unwrap();
        assert_eq!(updated, 2);
        let summary_after = store.insights(14, None).unwrap();
        assert_eq!(summary_after.total_unseen, 0);
    }

    fn sample_custom_def(slug: &str, spec: CustomSignalSpec) -> CustomSignalDef {
        let t = now_ns();
        CustomSignalDef {
            signal_type: slug.into(),
            title: "Custom Rule".into(),
            description: "Checks custom rule".into(),
            severity: SignalSeverity::Medium,
            remedy: "Check span".into(),
            enabled: true,
            spec,
            created_at_ns: t,
            updated_at_ns: t,
        }
    }

    #[test]
    fn validates_custom_signal_rules_strictly() {
        let valid_spec = CustomSignalSpec {
            scope: CustomSignalScope::Span,
            filters: CustomSignalFilters::default(),
            match_mode: MatchMode::All,
            conditions: vec![CustomCondition {
                field: "duration_ms".into(),
                op: ConditionOp::Gte,
                value: "1000".into(),
            }],
        };

        // Bad slug (uppercase / spaces)
        let bad_slug = sample_custom_def("Bad Slug!", valid_spec.clone());
        assert!(matches!(
            validate_custom_signal(&bad_slug),
            Err(CustomSignalError::Validation(_))
        ));

        // Reserved built-in slug
        let reserved = sample_custom_def("tool_errors", valid_spec.clone());
        assert!(matches!(
            validate_custom_signal(&reserved),
            Err(CustomSignalError::Validation(_))
        ));

        // Empty conditions
        let no_conds = sample_custom_def(
            "my_rule",
            CustomSignalSpec {
                scope: CustomSignalScope::Span,
                filters: CustomSignalFilters::default(),
                match_mode: MatchMode::All,
                conditions: vec![],
            },
        );
        assert!(validate_custom_signal(&no_conds).is_err());

        // Scope mismatch (trace field in span scope)
        let scope_mismatch = sample_custom_def(
            "my_rule",
            CustomSignalSpec {
                scope: CustomSignalScope::Span,
                filters: CustomSignalFilters::default(),
                match_mode: MatchMode::All,
                conditions: vec![CustomCondition {
                    field: "trace_cost_usd".into(),
                    op: ConditionOp::Gt,
                    value: "0.01".into(),
                }],
            },
        );
        assert!(validate_custom_signal(&scope_mismatch).is_err());

        // Non-numeric value on numeric operator
        let non_numeric = sample_custom_def(
            "my_rule",
            CustomSignalSpec {
                scope: CustomSignalScope::Span,
                filters: CustomSignalFilters::default(),
                match_mode: MatchMode::All,
                conditions: vec![CustomCondition {
                    field: "duration_ms".into(),
                    op: ConditionOp::Gt,
                    value: "fast".into(),
                }],
            },
        );
        assert!(validate_custom_signal(&non_numeric).is_err());

        // Invalid regex
        let bad_regex = sample_custom_def(
            "my_rule",
            CustomSignalSpec {
                scope: CustomSignalScope::Span,
                filters: CustomSignalFilters::default(),
                match_mode: MatchMode::All,
                conditions: vec![CustomCondition {
                    field: "output".into(),
                    op: ConditionOp::Regex,
                    value: "[unclosed".into(),
                }],
            },
        );
        assert!(validate_custom_signal(&bad_regex).is_err());

        // Numeric op on text field
        let text_gt = sample_custom_def(
            "my_rule",
            CustomSignalSpec {
                scope: CustomSignalScope::Span,
                filters: CustomSignalFilters::default(),
                match_mode: MatchMode::All,
                conditions: vec![CustomCondition {
                    field: "model".into(),
                    op: ConditionOp::Gt,
                    value: "5".into(),
                }],
            },
        );
        assert!(validate_custom_signal(&text_gt).is_err());
    }

    #[test]
    fn custom_signals_evaluate_span_trace_attr_regex_and_crud() {
        let now = now_ms();
        let spans = vec![
            mk_span(SpanSpec {
                trace_id: "trace-a",
                span_id: "sa1",
                name: "llm.chat",
                service: "billing-bot",
                start_ms: now - 3_000,
                dur_ms: 1_800,
                status_code: 1,
                status_message: "",
                attrs: json!({
                    "gen_ai.operation.name": "chat",
                    "gen_ai.request.model": "openai/gpt-5-mini",
                    "gen_ai.usage.input_tokens": 800,
                    "gen_ai.usage.output_tokens": 200,
                    "overmind.cost": 0.03,
                    "overmind.input": "refund please",
                    "overmind.output": "I cannot assist with refunds right now.",
                    "custom.tier": "enterprise",
                    "custom.retry_count": 4
                }),
                events: json!([]),
            }),
            mk_span(SpanSpec {
                trace_id: "trace-b",
                span_id: "sb1",
                name: "llm.chat",
                service: "docs-bot",
                start_ms: now - 2_000,
                dur_ms: 300,
                status_code: 1,
                status_message: "",
                attrs: json!({
                    "gen_ai.operation.name": "chat",
                    "gen_ai.request.model": "anthropic/claude-sonnet",
                    "overmind.input": "hello",
                    "overmind.output": "hi there",
                }),
                events: json!([]),
            }),
        ];

        let store = SignalStore::in_memory().unwrap();
        let runner = SignalRunner::new(Arc::new(VecSource(spans)), store.clone());

        // 1. Span scope with filters + regex + attr:* (AND)
        let span_rule = sample_custom_def(
            "enterprise_refusal",
            CustomSignalSpec {
                scope: CustomSignalScope::Span,
                filters: CustomSignalFilters {
                    service_name: "billing-bot".into(),
                    span_type: "llm".into(),
                    span_name_contains: "chat".into(),
                    model_contains: "gpt-5".into(),
                },
                match_mode: MatchMode::All,
                conditions: vec![
                    CustomCondition {
                        field: "output".into(),
                        op: ConditionOp::Regex,
                        value: "(?i)cannot assist".into(),
                    },
                    CustomCondition {
                        field: "attr:custom.tier".into(),
                        op: ConditionOp::Eq,
                        value: "enterprise".into(),
                    },
                    CustomCondition {
                        field: "attr:custom.retry_count".into(),
                        op: ConditionOp::Gte,
                        value: "3".into(),
                    },
                ],
            },
        );

        // Dry-run test BEFORE saving: must match 1 of 2 traces and persist 0 events.
        let preview = runner.test_custom_signal(&span_rule, 30).unwrap();
        assert_eq!(preview.scanned_groups, 2);
        assert_eq!(preview.matched_groups, 1);
        assert_eq!(preview.samples.len(), 1);
        assert_eq!(preview.samples[0].trace_id, "trace-a");
        assert_eq!(
            store
                .list_events(&ListEventsFilter::default(), 0, 10)
                .unwrap()
                .total_count,
            0
        );

        // Create and run
        store.create_custom_signal(&span_rule).unwrap();

        // 2. Trace scope with OR match_mode
        let trace_rule = sample_custom_def(
            "trace_cost_or_slow",
            CustomSignalSpec {
                scope: CustomSignalScope::Trace,
                filters: CustomSignalFilters::default(),
                match_mode: MatchMode::Any,
                conditions: vec![
                    CustomCondition {
                        field: "trace_cost_usd".into(),
                        op: ConditionOp::Gte,
                        value: "0.02".into(),
                    },
                    CustomCondition {
                        field: "llm_call_count".into(),
                        op: ConditionOp::Gte,
                        value: "5".into(),
                    },
                ],
            },
        );
        store.create_custom_signal(&trace_rule).unwrap();

        let created = runner.run_once().unwrap();
        assert_eq!(created, 2); // enterprise_refusal + trace_cost_or_slow on trace-a

        // Insights include custom signals with custom metadata.
        let summary = store.insights(14, None).unwrap();
        let custom_insight = summary
            .insights
            .iter()
            .find(|i| i.signal_type == "enterprise_refusal")
            .unwrap();
        assert!(custom_insight.is_custom);
        assert_eq!(custom_insight.category, "custom");

        // Updating spec clears stale events so re-run reflects the new logic.
        let mut stricter = span_rule.clone();
        stricter.spec.conditions[2].value = "99".into(); // retry_count >= 99 won't match
        let (_, spec_changed) = store.update_custom_signal(&stricter).unwrap();
        assert!(spec_changed);
        let events_after_update = store
            .list_events(
                &ListEventsFilter {
                    signal_type: Some("enterprise_refusal".into()),
                    ..Default::default()
                },
                0,
                10,
            )
            .unwrap();
        assert_eq!(events_after_update.total_count, 0);
        assert_eq!(runner.run_once().unwrap(), 0);

        // Deleting custom signal cleans up custom_signals, subscriptions, and signal_events.
        assert!(store.delete_custom_signal("trace_cost_or_slow").unwrap());
        let events_after_delete = store
            .list_events(
                &ListEventsFilter {
                    signal_type: Some("trace_cost_or_slow".into()),
                    ..Default::default()
                },
                0,
                10,
            )
            .unwrap();
        assert_eq!(events_after_delete.total_count, 0);
        assert!(store.get_custom_signal("trace_cost_or_slow").unwrap().is_none());
    }
}