ResearchHarness icon indicating copy to clipboard operation
ResearchHarness copied to clipboard

feat(trace_utils): RunTrendAnalyzer — cross-run success rate regression detection over FlatTraceWriter output

Open nanookclaw opened this issue 7 months ago • 1 comments

Problem

FlatTraceWriter writes per-event run_id, termination, error, and finish_reason to trace_{timestamp}_{run_id}.jsonl in trace_dir. Each run gets a unique trace file — richly structured, chronologically ordered by filename.

There is no mechanism to compute success rate across sequential runs. If termination=success drops from 91% to 78% to 64% across 20 runs, that signal is completely invisible.

The data exists. The analysis layer is absent.

Proposed: RunTrendAnalyzer

from dataclasses import dataclass
from pathlib import Path
import json
import statistics

TRACE_FIELD_NAMES = [
    "run_id", "event_index", "turn_index", "timestamp",
    "model_name", "workspace_root", "role", "text",
    "tool_call_ids", "tool_names", "tool_arguments",
    "finish_reason", "termination", "error", "image_paths",
]

@dataclass
class RunSummary:
    run_id: str
    timestamp: str
    total_events: int
    error_events: int
    tool_calls: int
    success: bool  # termination == "success" in final event

@dataclass
class MetricTrend:
    slope: float
    direction: str  # "improving" | "degrading" | "stable"
    first: float
    last: float
    window: int

@dataclass
class RunTrendReport:
    summaries: list[RunSummary]
    success_rate_trend: MetricTrend
    error_rate_trend: MetricTrend
    any_regression: bool

class RunTrendAnalyzer:
    def __init__(self, trace_dir: Path, window: int = 20):
        self.trace_dir = Path(trace_dir)
        self.window = window

    def _load_run(self, path: Path) -> RunSummary:
        events = []
        with open(path) as f:
            for line in f:
                line = line.strip()
                if line:
                    events.append(json.loads(line))
        if not events:
            return RunSummary(run_id=path.stem, timestamp="", total_events=0,
                              error_events=0, tool_calls=0, success=False)
        last = events[-1]
        return RunSummary(
            run_id=last.get("run_id", path.stem),
            timestamp=last.get("timestamp", ""),
            total_events=len(events),
            error_events=sum(1 for e in events if e.get("error")),
            tool_calls=sum(len(e.get("tool_names", [])) for e in events),
            success=last.get("termination") == "success",
        )

    def analyze(self) -> RunTrendReport:
        paths = sorted(self.trace_dir.glob("trace_*.jsonl"))[-self.window:]
        summaries = [self._load_run(p) for p in paths]

        def _trend(values):
            if len(values) < 2:
                return MetricTrend(slope=0.0, direction="stable",
                                   first=values[0] if values else 0.0,
                                   last=values[-1] if values else 0.0, window=len(values))
            xs = list(range(len(values)))
            slope, _ = statistics.linear_regression(xs, values)
            direction = "improving" if slope > 0.02 else "degrading" if slope < -0.02 else "stable"
            return MetricTrend(slope=slope, direction=direction,
                               first=values[0], last=values[-1], window=len(values))

        success_values = [float(s.success) for s in summaries]
        error_values = [s.error_events / max(s.total_events, 1) for s in summaries]

        success_trend = _trend(success_values)
        error_trend = _trend(error_values)
        return RunTrendReport(
            summaries=summaries,
            success_rate_trend=success_trend,
            error_rate_trend=error_trend,
            any_regression=success_trend.direction == "degrading" or error_trend.direction == "improving",
        )

CLI / test integration

# Analyze last 20 runs in trace directory
python -m agent_base.trend_utils --trace-dir traces/ --window 20

# CI gate
python -m agent_base.trend_utils --trace-dir traces/ --exit-on-regression

Implementation notes

  • Zero changes to FlatTraceWriter — reads existing output files
  • Natural home: agent_base/trend_utils.py (parallel to trace_utils.py)
  • trace_{timestamp}_{run_id}.jsonl filename sort order = chronological run order
  • Pure stdlib: statistics.linear_regression (Python 3.10+), pathlib, json
  • Reads TRACE_FIELD_NAMES fields already present in every trace row

Why this matters

FlatTraceWriter produces structured, per-run traces with termination and error fields. The data for cross-run behavioral slope is already there. A 91% -> 78% -> 64% success rate decline across 20 research-harness runs should not require manual trace file inspection to detect.


This gap has been confirmed in 108 independent agent evaluation and observability repositories. PDR: "Behavioral Reliability in Production AI Agents" — DOI: 10.5281/zenodo.19396555

nanookclaw avatar Apr 03 '26 07:04 nanookclaw

Thanks for the proposal. The underlying need is real, but this is not a good fit for ResearchHarness core. ResearchHarness is intended to stay focused on single-run execution, tracing, and benchmark-friendly agent runtime behavior, not cross-run analytics.

A few concrete reasons:

  • Success semantics are benchmark- and workflow-specific. termination == "success" is not a reliable cross-run success metric for all RH use cases.
  • This would add analysis-layer scope to agent_base, which pushes RH toward an observability platform rather than a lightweight harness.
  • Trend detection over mixed runs, models, prompts, and benchmarks is easy to misinterpret without stronger result contracts.

If we need this later, the better place is an optional external or benchmark-side analysis script that reads benchmark-specific result files, rather than a core agent_base feature. Closing for now to keep the runtime surface small and focused.

black-yt avatar Apr 27 '26 02:04 black-yt