Zum Inhalt springen
Plugins

observability Plugin

Test Insights

Syrus can ingest structured per-test results from a grader run and turn them into durable `TestInsights::TestRun`/`TestInsights::TestCase` history, grouped under one durable `TestInsights::TestIdentity` per `(repository, suite_name, name)` test. `TestInsights::TestIdentity` is the searchable/navigable object; `TestInsights::TestCase` is an individual execution row. Together they power per-test pass/fail timelines, duration history, and flaky test reporting. This ships as the `test_insights` plugin, which owns the storage, flakiness scoring, and UI. `test_result_parser` is a separate plugin *extension point* that lets a repository's test runner supply its own parsing logic.

test_insightsQuellcode

Test Insights (Flaky Tests)

Syrus can ingest structured per-test results from a grader run and turn them into durable TestInsights::TestRun/TestInsights::TestCase history, grouped under one durable TestInsights::TestIdentity per (repository, suite_name, name) test. TestInsights::TestIdentity is the searchable/navigable object; TestInsights::TestCase is an individual execution row. Together they power per-test pass/fail timelines, duration history, and flaky test reporting. This ships as the test_insights plugin, which owns the storage, flakiness scoring, and UI. test_result_parser is a separate plugin *extension point* that lets a repository's test runner supply its own parsing logic.

Enabling ingestion: junit_output

Add junit_output: to a grader entry in .syrus.yml, pointing at a file path (relative to the repo root) that the grader's command produces:

grade:
  - name: rspec
    run: bin/rspec --format progress --require rspec_junit_formatter --format RspecJunitFormatter --out .syrus/grade-output/rspec-junit.xml
    junit_output: .syrus/grade-output/rspec-junit.xml

After the grader command runs (pass or fail), Steps::Grader#announce_test_output! publishes the configured output path to Test Insights. The inline subscriber reads the file at that path and writes one TestInsights::TestRun, one TestInsights::TestCase row per parsed case, and links each case to its stable TestInsights::TestIdentity, tagged with the grader's name. A missing file is not an error — it logs "junit_output ... not found — skipping ingestion" and moves on, so a junit_output path that's only produced by one variant of a grader (see below) doesn't break the others. A parse failure is also non-fatal: it's logged as a warning and the grader's pass/fail outcome is unaffected either way — ingestion never blocks the workflow.

Oversized example names don't drop the whole batch

test_insight_cases/test_insight_identities' name, suite_name, and file_path columns are plain t.string (MySQL VARCHAR(255)), while failure_message, failure_backtrace, and output are MySQL TEXT columns. A full RSpec example description (nested context + it-string, sometimes interpolated) or matcher diff can exceed those storage limits. TestInsights::Ingester truncates those fields to fit before every bulk insert (TestInsights::TestCase.truncate_string_column / truncate_text_column), using the *untruncated* suite_name/name to compute TestIdentity.fingerprint_for first so a test's durable identity never shifts just because its display name got clipped. Case rows are still batched 500 at a time via insert_all! for throughput, but a batch that fails anyway (any other DB-level insert error) falls back to inserting row-by-row so one bad row is skipped and reported instead of silently discarding every sibling row in that batch — a single oversized name used to roll back the whole ingest transaction and leave that grader run with zero recorded history. Both the per-row and top-level ingestion failure paths report through OperationalLogging.ingest (source: "test_insights_ingester" / "test_insights_subscribers") in addition to the existing grader job-log warning line, so a recurring ingestion failure is discoverable without reading every grader's job log.

Only one file path is supported per grader Step; if your test command fans out across multiple parallel workers (see the caveat below), point junit_output at a single merged/aggregated results file, or leave it unset for that variant.

How the file gets parsed: the test_result_parser extension point

Test Insights gives standard JUnit XML to core's JunitXmlParser before trying plugin text parsers. Files with an .xml output path, or content that starts with a <testsuite>/<testsuites> root, are treated as JUnit XML so RSpec JUnit files cannot be claimed by Ruby::RspecParser just because a failure body contains RSpec's progress-output summary text.

For non-JUnit output, Test Insights tries every registered test_result_parser plugin provider in registration order (Syrus::PluginRegistry.providers_for("test_insights:parser")), calling can_parse?(output_path:, format_hint:) on each; the first provider that returns true handles the file via call(output_path:, format_hint:). If no plugin claims the file, core falls back to JunitXmlParser, which parses standard JUnit XML (<testsuite>/<testsuites> with <testcase> elements, <failure>/<error>/<skipped> children).

A parser's call must return an object duck-typed to JunitXmlParser::ParsedRun: it responds to total_count, passed_count, failed_count, skipped_count, error_count, duration_ms, and cases, where each element of cases responds to name, suite_name, file_path, status, duration_ms, output, failure_message, failure_backtrace. See lib/syrus/plugin/test_result_parser.rb for the full contract and plugins/ruby/lib/ruby/rspec_parser.rb (Ruby::RspecParser) for a reference implementation.

format_hint is the configured output path's file extension, such as "xml" for .syrus/grade-output/rspec-junit.xml or "txt" for progress-output captures. Parsers should still inspect the file content when needed; the hint is only a lightweight routing clue, not a trusted format declaration.

Why this repo's own rspec grader uses JUnit XML, not Ruby::RspecParser's native format

Ruby::RspecParser can parse RSpec's plain progress/documentation output directly — no rspec_junit_formatter gem required — by content-sniffing for an N examples, N failures summary line. That's the right choice for a repo that hasn't configured a JUnit formatter. But RSpec's default output only lists *failing* examples individually (passing/pending examples aren't named in the text); Ruby::RspecParser therefore only ever creates TestCase rows with status: "failed". Since TestCase.top_flaky_tests (and TestCase.flakiness_score) require a test to have both a passed and a failed row within the lookback window to count as flaky, the native-text route can never actually detect a flaky test — it can only ever accumulate failures.

This repo's own .syrus.yml grader instead adds the rspec_junit_formatter gem (group :test in the Gemfile) and asks bin/rspec for a second, JUnit-formatted output stream alongside the normal progress output that appears in the grade log:

bin/rspec spec plugins --format progress --require rspec_junit_formatter --format RspecJunitFormatter --out .syrus/grade-output/rspec-junit.xml

Because JUnit XML enumerates every example (passed, failed, and skipped), JunitXmlParser (the core XML parser — Ruby::RspecParser.can_parse? declines JUnit XML content unless explicitly called with format_hint: "rspec") creates one TestCase row per example per grader Run, giving TestCase.top_flaky_tests real signal.

junit_output is attached to the grader entry that produced it, independent of phase. If a repository has separate landing and CI commands (for example rspec and rspec-ci), both entries should declare their own junit_output path so Syrus can ingest the results from either phase. Wrapper scripts that fan out across parallel_tests workers should merge their per-worker XML files before exiting.

Flakiness scoring

TestCase.flakiness_score (plugins/test_insights/app/models/test_insights/test_case.rb) looks at the most recent FLAKINESS_LOOKBACK (default 20) scored rows for a given (repository, suite_name, name) tuple, ordered by created_at descending. A test is flaky if that window contains at least one passed row and at least one failed/error row; the score is failed / total within the scored window.

Identity canonicalization prefers file_path plus the test name when a source path is available, so JUnit class names, native runner output, and renamed suite labels do not split one test's history. Deployment also merges existing suite-based identities that resolve to the same file and name, preserving their historical results under the canonical identity. Known-flaky adjudication also declines when the latest scored history ends in consecutive failures; that pattern is a persistent baseline regression, not an intermittent flake. A base-revision comparison that identifies an introduced failure takes precedence over this historical score and cannot be overridden by a known-flaky dismissal.

Scored history deliberately excludes a Job's own self-repaired WIP failures: when a failed/error TestCase came from a grader Step inside a workflow retry_until loop and a later grader Step in the same workflow, same loop, same grader name, and same TestIdentity recorded a pass, that failed/error row is treated as wip_repair_failure. It remains visible in execution history, but it is excluded from flakiness, failure-rate, recent failure-count, and last_failed_at calculations. Cross-workflow and cross-Job mixed pass/fail history still counts normally, so true nondeterministic flakes keep their flaky signal.

wip_repair_failure is a persisted test_insight_cases boolean column, not a read-time computation. The only writer is TestInsights::WipRepairFailureClassifier, called from TestInsights::Ingester right after a grader run is ingested: it looks at the cases that just passed and retroactively flags any earlier, still-scored, failed/error case in the same workflow/loop/grader/identity as superseded. TestCase.scored is then just where(wip_repair_failure: false) -- a plain indexed filter. This replaced an equivalent-but-far-more-expensive scored/wip_repair_failures scope that ran a correlated EXISTS across test_insight_cases/test_insight_runs/runs/steps on every read; MySQL 8's optimizer flattened that EXISTS into a semi-join across all four tables and picked a join order that ignored the test_identity_id index, so a query that should have touched a handful of rows for one TestIdentity instead examined millions of rows (production: 4,000+ calls/day averaging ~10M rows examined, up to 67s). TestInsights::WipRepairFailureBackfill, wrapped by the test_insights_wip_repair_failure_backfill maintenance task (MaintenanceTasks::Definitions::TestInsightsWipRepairFailureBackfill), replays the same classifier over a bounded historical set of test_insight_runs for rows ingested before the column existed. The backfill only treats grader-loop runs with durable test_insight_cases as pending work, skips zero-case runs, and records an upper_bound_test_run_id checkpoint when discovery creates or revives the task. Completed backfills do not tail newer live rows; normal ingestion handles those by calling the same classifier as each grader run arrives. It's idempotent (only ever flips false -> true) and safe to resume after a pause, cancellation, or retry because it keeps walking from after_id up to the original upper bound. MaintenanceTasks::Discovery surfaces it as a pending admin task automatically once there is bounded historical work to do -- start it from the Maintenance Tasks admin page (or the admin_maintenance_tasks MCP tool) if older history's flakiness/failure-rate numbers need to reflect it.

Every TestCase/TestIdentity/RecentStats query built on .scored is wrapped in PerformanceLogging.phase("test_insights.<name>", ...) (app/services/performance_logging.rb), the same slow-phase/slow-SQL instrumentation used elsewhere in Syrus. A regression that makes any of these queries slow again surfaces as a syrus.performance.slow_phase / syrus.performance.slow_sql event (Admin Performance UI, read_performance_diagnostics) instead of silently degrading.

TestCase.top_flaky_tests(repository:, lookback:, limit:) runs the same scored logic as a single SQL query (window functions) to rank the flakiest tests repository-wide. TestCase.batch_flakiness does the same scored lookup for an arbitrary set of test cases in one query, used to annotate a single Job's test results without an N+1.

Where it surfaces

  • Grade-loop repair prompts — TestInsights::GraderFailureSummarizer

provides core's :grader_failure_summarizer extension point. When a grader Step fails, Steps::GraderCollect asks it what failed, and it returns a compact list built from the TestRun/TestCase rows just ingested for that grader's run: a headline count, then failures grouped by file with each assertion's first line. Those lines are stored on the workflow's grade_log_manifest artifact and rendered at the top of the next repair agent's prompt, ahead of the archived grader log.

This exists because the grader log answers the question badly. The failures are scattered through tens of kilobytes of prose, and the excerpt core keeps inline is truncated by construction — one observed landing iteration recorded nine failing examples and showed the repair agent two of them, including hiding three failures in the file the agent then edited. These records are exact, so the summary is complete by construction.

It matches on grader_name so a react-tests summary never appears under an rspec failure, and returns nothing at all when the grader produced no test results or when everything passed.

  • Repository Tests tab — GET /api/v1/app/repositories/:repository_id/tests

(Api::V1::App::RepositoryTestsController#index) returns interesting recent failures by default and is filtered through the standard FilterBar component rather than a bespoke search box: the request carries the chip bar's usual q=<encoded filter tree> param, decoded server-side by TestInsights::TestsFilter (Filters::Ast/Filters::QueryParam, the same wire format every other FilterBar consumer uses) into a free-text query (name/suite/file), a single-select reason (failing/flaky/slow, replacing the old always-visible reason toggle chips), plus metadata filters for latest status, suite_name, and file_path. Any active chip routes the request through TestInsights::Query (category:/query:/filters:) instead of the default "interesting" listing; the response echoes back filter and filter_schema for FilterBar to render instead of the old query/limit fields. The table uses the shared data-table column primitives: all columns are sortable with the standard dashboard-style sort indicator, optional columns can be hidden or reordered in the column selector, and optional headers can be drag-reordered directly. Clicking a row opens GET /api/v1/app/repositories/:repository_id/tests/:id, which shows that TestIdentity's execution history, links to the individual Runs, and a duration-over-time graph. The history list is paginated (page/ per_page params, 20 per page by default, 100 max) and sorted newest to oldest; the duration graph independently plots up to the most recent TestIdentity::HISTORY_LIMIT (100) runs regardless of the history page.

  • Job test results — GET /api/v1/app/jobs/:job_id/test_results

(Api::V1::App::JobTestResultsController) returns each TestInsights::TestRun ingested for a Job's most recent Workflow that has test data. The default response contains grader summaries; pass grader_name and include_suites=true to load suite and case detail on demand. Case detail is capped at 20 cases per run by default (100 maximum through case_limit), with failures prioritized and omission counts in truncation. Failure message, backtrace, and output fields are each limited to 2 KiB. Returned cases are annotated with their current flakiness score via bounded, batched history lookups.

  • Flaky badge on failing test cases — app/frontend/routes/JobDetail.tsx

(around line 1251) renders an amber "flaky" badge with a failed/total sparkline next to a failing test case's name when its flakiness_score is between 0 and 1 (i.e., it has both passed and failed recently) — a 0 or 1.0 score means it's either never failed or never passed and isn't flagged as flaky.

  • Global search — test search results index TestIdentity, not

TestCase, so repeated executions of the same test collapse into one result. Search results link directly to the repository Tests tab history page for that identity.

MCP tools

Chat and workflow agents can inspect repository-level Test Insights through read-only MCP tools:

  • `list_repository_test_insights(repository:, repository_id:, filter:, sort:,

direction:, query:, grader_name:, limit:, lookback:, filters:) returns durable TestIdentity rows for a repository the caller can access. Workflow agents can omit repository/repository_id to default to their current Run's repository. filter accepts recently_seen, failing, flaky, and slow; category is accepted as an alias. sort accepts last_seen, last_failed, last_duration, failure_rate, avg_duration, p50_duration, and p95_duration. For quick slow-test investigations, use sort: "last_duration" with direction: "desc" so the list is ranked by each identity's latest recorded duration. For less noisy repository-wide runtime ranking, use sort: "p95_duration" or sort: "avg_duration"; those sorts read persisted test_identity_runtime_summaries rows for the bounded recent_100 window rather than aggregating raw test_cases` at request time. The response includes suite/name/file, last status and timestamps, last duration, recent pass/failure counts, failure rate, average duration, runtime summary p50/p95/avg/sample count when available, reasons, and latest run/workflow/job references.

  • read_test_insight(test_identity_id:, history_limit:, include_failures:)

returns one TestIdentity, recent execution history, duration points, related grader/run/job references, and bounded failure message/backtrace/output snippets. Each history row's test_case object includes classification: scored when the row contributes to flakiness and failure-rate aggregates, or wip_repair_failure when the row is a self-repaired grader-loop failure that is visible for auditability but excluded from those aggregates. Use the list tool first to discover a test_identity_id.

  • `read_job_test_results(job_id:, grader_name:, include_slow_cases:,

include_suites:, case_limit:) returns ingested results for the latest Workflow on that Job with test data, matching the app's Job Tests tab selection semantics. The default response is compact: one summary per TestRun with grader name, counts, duration, test run id, Run id, Workflow id, Job id, bounded failed/error cases, per-case flakiness annotations, and truncation metadata. Pass grader_name to inspect one grader, and opt into include_slow_cases or include_suites` only when that extra detail is needed.

  • `read_run_test_results(run_id:, grader_name:, include_slow_cases:,

include_suites:, case_limit:)` returns the same compact payload for a specific Run. This is the direct Run-level path for investigating one grader execution without reading transcript logs or using app endpoints.

  • `compare_test_runtime(repository:, repository_id:, test_identity_ids:,

query:, grader_name:, limit:, baseline_run_id:, comparison_run_id:, baseline_job_id:, comparison_job_id:, baseline_window:, comparison_window:) compares selected durable identities across exactly two bounded sources. Each side must be one Run id, one Job id, or one explicit time window with starts_at/ends_at (aliases from/to and start/end are accepted). Run sources compare only that Run's ingested test cases and include sanitized worker-health/command-span correlation from the existing read_run_worker_health` path. Job sources compare the Job's latest Workflow that has Test Insights data. Window sources compare only selected identities in the provided time bounds. The response includes sample count, avg, p50, p95, latest, min, max, observed bounds, and absolute/percent deltas.

These tools enforce repository visibility at the tool boundary. Workflow sidecars are restricted to the current Run's repository; chat sidecars use the same repository visibility rules as the app.

Safe query boundaries:

  • Repository-wide slow-test lists rank candidates from test_identities or

persisted test_identity_runtime_summaries; they must not aggregate all rows in test_cases during a request.

  • Per-identity history and comparison reads are bounded by selected

test_identity_id values, a specific Run/Job workflow, or explicit time windows. Keep limit small and prefer passing test_identity_ids discovered from list_repository_test_insights.

  • To answer "did this change make tests faster?", first compare the relevant

identities with compare_test_runtime across the before/after Runs or Jobs, then inspect worker_health in the same response for host pressure and command spans. If the run was under CPU/IO/memory pressure, treat runtime deltas as infrastructure-correlated until a clean rerun confirms them.

Admin API

Operators get the same data the MCP tools expose, reachable with a bearer token instead of a browser session or an agent run (docs/api.md has the general admin API auth model):

  • GET /api/v1/admin/repositories/:repository_id/tests — the admin twin of

list_repository_test_insights. Accepts state (alias category/filter) with the same recently_seen/failing/flaky/slow values, sort/ direction (including failure_rate and the runtime sorts), query, grader_name, limit, and a filters object for the summary/failure-rate bounds. It's the same TestInsights::Query service the MCP tool calls, so the two surfaces never drift onto different underlying data.

  • GET /api/v1/admin/repositories/:repository_id/tests/:id — the admin twin

of read_test_insight: one TestIdentity's history, duration points, and related refs, scoped to the given repository. Backed by TestInsights::Detail.

  • GET /api/v1/admin/jobs/:job_id/test_results — the admin twin of

read_job_test_results, backed by TestInsights::RunResults.for_job. Same compact-by-default shape: pass include_suites/include_slow_cases to opt into more detail, grader_name to scope to one grader, and case_limit to select up to 100 detailed cases per run.

All three are plugin-owned routes (plugins/test_insights/app/controllers/api/v1/admin/); with the plugin disabled they answer plugin_disabled like every other disableable plugin's admin routes.

A single malformed row (a TestIdentity, TestCase, or TestRun that fails to serialize -- typically a partially cleaned-up association) degrades to { id, type, error_serializing } in place rather than 500ing the whole response, the same posture Admin::JobStateSerializer uses for nested Job state. This applies to TestInsights::Query, TestInsights::Detail, and TestInsights::RunResults directly, so the MCP tools inherit the same resilience.

Configuring this for another repository

  1. Confirm the test runner can produce results in a format a registered

test_result_parser understands — JUnit XML for the bundled core parser, or RSpec's native progress/documentation output for Ruby::RspecParser (accepting that the native route can't detect flakiness, per above).

  1. Add whatever formatter/gem/flag the test runner needs to write that file

(e.g. rspec_junit_formatter, pytest --junitxml=..., jest --reporters default jest-junit).

  1. Set junit_output: <path> on every .syrus.yml grader entry that should

ingest results. If the landing and CI phases use separate graders, both entries need their own junit_output.

Search indexing runs on the home node

Test identities are indexed through IndexTestIdentitiesJob on the indexing queue, like every other search-index write.

Ingestion itself runs inside a grader step on the runs queue. On a split deployment that is a compute node, which by design has no access to the search database (config/queue.compute.yml). Writing test_identity_fts inline from TestRunIngester was the one path that broke that rule; the failure was swallowed as an enrichment warning, so search results simply went missing rather than anything erroring loudly.

A grader's test cases are stored before its Step finishes. The per-test summaries shown in test lists and the flakiest-tests ranking (last status, last pass and failure, recent counts and durations) are refreshed by a background job afterwards, so they can trail a just-finished grader by a few moments. Flakiness adjudication reads the stored test cases, not those summaries, and is unaffected.

Plugin ownership

Test Insights is the test_insights plugin. It owns the four primary tables (test_insight_runs, test_insight_cases, test_insight_identities, test_insight_runtime_summaries -- renamed from their unprefixed originals), the test_identity_fts search index, the query and comparison services, the five MCP tools, the repository Tests tab, and the Job detail Tests tab.

Core keeps four things:

  • JunitXmlParser, because ParsedRun is the contract of the

:test_result_parser extension point. A language plugin's framework-native parser returns one, and whichever plugin stores results consumes it; neither should have to depend on the other.

  • Steps::Grader, which no longer parses or stores anything. It publishes

step.grader.completed with the output path, inline, because that path is inside a workflow workspace that is torn down at terminal state.

  • MainBranchFailureClassifier, which asks :test_evidence providers

which tests failed rather than reading a model. With the plugin disabled the counts are zero and it falls back to its coarser pass/fail comparison -- exactly what a repository with no test data already got.

  • Adjudicators::KnownFlakyFailure, a rung-0 adjudicator (see

docs/engineering/conventions/plugins/authoring.md's adjudicator extension point) that asks :test_evidence providers for failing test cases and their flakiness scores rather than reading TestInsights::TestCase directly. With the plugin disabled there is no provider, so it always declines with no_flakiness_history -- the same "cannot tell" posture the ladder requires from a rung-0 check with no data.

  • Adjudicators::IsolatedReproDismissal, a second rung-0 adjudicator (see

landing_queue.md's isolated_repro_dismissal_enabled) that asks :test_evidence providers whether a failing test has an agent-recorded, same-SHA, pre-fix "did not reproduce in isolation" record, via the record_isolated_repro/isolated_repro_evidence capability this plugin implements against its own TestInsights::IsolatedReproAttempt table. With the plugin disabled there is no provider, so it always declines with no_isolated_repro_evidence.

  • App::JobDetailPayload, which asks :test_evidence providers for a

bounded failed-test summary (count, first-N names/locations/short messages) on each failed grade/grader Run, rendered inline on the workflows-tab run card (WorkflowGraph.tsx's TestFailureSummary) so an operator can see what broke without opening the raw grade log. With the plugin disabled, or when a grader's output wasn't test-shaped (no ingested TestCase rows for that run/grader pair -- e.g. the run crashed before producing output), the summary is nil and the run card falls back to its existing Grade log/Transcript buttons.

Disabling the plugin stops ingestion and hides the UI; recorded history stays.

Isolated repro attempts

test_insight_isolated_repro_attempts (TestInsights::IsolatedReproAttempt) is deliberately a separate table from test_insight_cases, not another row shape in it: an isolated repro attempt is a single, deliberate, agent-run action -- one exact command and its raw output, targeted at one failing example, recorded via the record_isolated_repro MCP tool -- not a grader execution. Mixing the two would dilute TestCase.flakiness_score's statistical scored pool with a fundamentally different kind of evidence. See landing_queue.md's isolated_repro_dismissal_enabled for the full recording/validation/adjudication flow.

Retention

test_insight_cases is by far the plugin's highest-volume table (one row per test example per grader run). Its policy in Admin Retention Settings controls how long the shared retention worker keeps raw cases and their parent run rows. It defaults to 90 days: active tests retain far more executions than the 20-case flakiness lookback needs, while the plugin's highest-volume table stays bounded. Set it to 0 for infinite retention. The job also deletes TestInsights::IsolatedReproAttempt::RETAIN_AFTER-old rows (30 days -- an isolated repro attempt is only ever useful in the immediate aftermath of the grading iteration it backs, unlike TestCase's statistical history) from test_insight_isolated_repro_attempts — all three are plain age cutoffs, no per-test_identity_id row-count cap. TestIdentity summary columns (last_status, recent_* counters) and search indexing are unaffected: they're rolled up from recent activity, not the raw rows themselves, so pruning old raw history doesn't erase live flakiness signal for a test that's still running.

The registry-driven sweep discovers this definition only while the plugin is enabled. Its plugin-owned executor removes empty parent runs and fixed-window isolated-repro attempts after the generic bounded case deletion. If eligible rows remain, the shared worker schedules one successor after a one-minute pause and continues until the backlog is drained. Disabling or removing the plugin removes the policy from discovery without leaving a plugin class named in core.