Dev.to AI 🤖 Ai 👁 0 📖 10 min read

I Asked an LLM to Find Our Flaky Tests. The Final Version Runs on 80 Lines of Rules

The build is red. Again. Is it the change you merged an hour ago, or is it that test, the one that "sometimes fails"? Somebody re-runs the job. It goes green. Everybody moves on, a little less confident in the pipeline

The build is red. Again.

Is it the change you merged an hour ago, or is it that test, the one that "sometimes fails"? Somebody re-runs the job. It goes green. Everybody moves on, a little less confident in the pipeline than yesterday.

Multiply that by hundreds of end-to-end tests running against real Linux machines and you get the most expensive kind of noise in CI: people stop trusting red.

I wanted a dashboard that answers one question with data: which failures are real, and which are flaky? My first version handed the whole problem to an LLM. The version that is in the repository today doesn't call the model at all.

This post is the story of that tool, jenkins-flaky-tests-detector, and of why rules beat the model for this job.

TL;DR

  • Prometheus already knows your test history if you scrape Jenkins with an exporter. You only need to read it the right way.
  • A flaky test and a regression look identical in a failure counter. They look completely different as a time series.
  • I went from "LLM classifies everything" to "rules first, LLM for the doubtful cases" to "rules only, and flag the rest". About 80 lines of Python do the classification.
  • The output is a JSON file that Grafana reads through the Infinity data source. No database, no extra service.

The signal is already in Prometheus

We scraped Jenkins with a jenkins-exporter, which publishes a metric per test case:

jenkins_build_test_case_failure_age{jobname="...", suite="...", case="...", status="FAILED"}

The value is the failure age: how many consecutive builds that test has been failing. 0 (or no sample) means it passed. 1, 2, 3... means it has been red for that many builds in a row.

That single number carries the whole story once you look at it over time:

regression:  0 0 0 0 1 2 3 4 5 6 7 8 9 ...     (breaks once, stays broken)
flaky:       0 1 0 0 1 0 1 0 0 0 1 0 ...       (yo-yo without code changes)
infra/dead:  1 2 3 4 5 6 7 8 9 10 11 ...       (never passes in the window)

A dashboard that counts failures sees "8 failures" in both of the first two rows. The shape is what tells them apart.

Architecture

flowchart TD
    J[Jenkins] -->|test results| E[jenkins-exporter]
    E -->|scrape| P[(Prometheus)]
    P -->|PromQL range queries| D[flaky-detector]
    D -->|rules| C{Classify}
    C --> F[flaky_tests.json]
    F -->|HTTP :8080| G[Grafana<br/>Infinity data source]

The detector is a small Python process that runs in a loop inside a container:

  1. Harvest the history of every failing test from Prometheus.
  2. Reconstruct a dense time series from sparse samples.
  3. Classify each test with deterministic rules.
  4. Expose the result as a static JSON file for Grafana.

Step 1: harvest, and let Prometheus tell you which jobs exist

I didn't want to maintain a list of Jenkins jobs, so the detector discovers them:

query = 'count by (jobname) (max_over_time(jenkins_build_test_case_failure_age[30d]))'
result = self.prom.custom_query(query=query)
jobs = [x['metric']['jobname'] for x in result if 'jobname' in x['metric']]

Then, for each job, one range query brings back only the series that ever failed:

query = f'jenkins_build_test_case_failure_age{{jobname="{job_name}", status=~"FAILED|REGRESSION"}}'
result = self.prom.custom_query_range(query=query, start_time=start, end_time=end, step=step)

The default window is 15 days with a one-hour step. Tests that never failed never come back from the query, so the analysis only touches the tests that matter.

Step 2: rebuild the timeline (the part everyone gets wrong)

Here is the catch: because the query filters on failing statuses, a passing test produces no samples. Prometheus gives you islands of failures with nothing in between, and "nothing" does not mean "no data", it means "it passed".

So the detector rebuilds a continuous timeline with pandas, and imputes 0 (pass) wherever there is no sample:

full_time_index = pd.date_range(start=pd_start, end=pd_end, freq=f'{step}s')

df = pd.DataFrame(entry['values'], columns=['ds', 'y'])
df['ds'] = pd.to_datetime(df['ds'], unit='s')
df['y'] = pd.to_numeric(df['y'])
df = df.set_index('ds')

df_resampled = df.resample(f'{step}s').max()                     # worst status in the bucket
df_reindexed = df_resampled.reindex(full_time_index).fillna(0)   # missing = pass
history = df_reindexed['y'].astype(int).tolist()

Two details matter here:

  • max() per bucket: if a job ran twice in the same hour, the worst result wins. A failure is never hidden by a later pass in the same bucket.
  • fillna(0): the whole classifier depends on this assumption. It is right for "the test ran and passed", and wrong for "the job didn't run at all". More on that at the end.

The result is, for every test, a list of about 360 integers (15 days of hourly buckets) that the rules can reason about.

Step 3: classify the shape

From each series the detector computes four numbers:

Metric Meaning
transitions How many times the test flipped between pass and fail
failure_rate Share of buckets where it was failing
max_streak Longest run of consecutive failures (the max failure age)
steps_since_fail How long it has been green since the last failure

And then applies the rules in order. This is the actual decision tree:

flowchart TD
    A[Test history] --> B{Failing in 100% of the window?}
    B -->|yes| ENV[ENVIRONMENTAL<br/>infra or dead test]
    B -->|no| C{3 or more pass/fail flips?}
    C -->|yes| FL1[FLAKY<br/>oscillation, score 1.0]
    C -->|no| D{Green now and failure rate under 30%?}
    D -->|yes| D2{Green for more than 48 buckets?}
    D2 -->|yes| FX1[FIXED<br/>healed]
    D2 -->|no| FL2[FLAKY<br/>sporadic, score 0.95]
    D -->|no| E{Green now and longest streak 6 or less?}
    E -->|yes| FL3[FLAKY or FIXED<br/>cluster]
    E -->|no| F{Green now?}
    F -->|yes| FX2[FIXED<br/>was a long regression]
    F -->|no| G{Failing for 3 or more builds now?}
    G -->|yes| REG[REGRESSION<br/>active, score 0.05]
    G -->|no| UNK[UNKNOWN<br/>too early to tell]

The oscillation rule is the heart of it. Counting flips is almost embarrassingly simple:

def _count_transitions(lst):
    flips = 0
    for i in range(1, len(lst)):
        if (lst[i-1] > 0) != (lst[i] > 0):
            flips += 1
    return flips

To check the behaviour, I fed some synthetic histories (about 360 hourly buckets each) to the real classification code. These are its actual outputs:

History Pattern (score) Reason
... 1 0 1 0 1 0 ... FLAKY (1.0) OSCILLATION: Flipped state 6 times.
one failure, 20 hours ago FLAKY (0.95) SPORADIC: Low failure rate (0.3%) but unstable.
one failure, 80 hours ago FIXED (0.0) HEALED: Sporadic failures (rate 0.3%) but passed last 80 runs.
failing for the last 5 builds REGRESSION (0.05) ACTIVE: Broken for 5 consecutive builds.
failing for the last 2 builds UNKNOWN (0.5) Complex pattern: [0, 0, 0, 1, 2]
failing for the whole window ENVIRONMENTAL (0.0) INFRA: Test has 100% failure rate.

Notice the score: it is not "probability of a bug". It is a flakiness score. Grafana sorts by it, so the yo-yo tests float to the top and the real regressions sink to the bottom, where the team should already be looking at them anyway.

The LLM journey: from "do everything" to "out of the loop"

This is the part I find most interesting, and it is all in the git history.

Version 1: the LLM classifies everything. The first draft sent batches of 30 time series to Gemini with a structured output schema (FLAKY, REGRESSION, ENVIRONMENTAL, UNKNOWN), temperature 0.2, and a long prompt explaining what each pattern looks like:

- Chaotic oscillation: `1, 0, 1, 0, 2, 0` (Randomly fails).
- CLUSTER FLAKES: A test fails for a short burst and then passes WITHOUT a long-term pattern.
- REGRESSION: Long, sustained failure blocks that require a fix. `0, 0, 1, 2, 3, 4, 5, 6, 7... 15`
- ENVIRONMENTAL: `25, 25, 25` (Metric is stuck/stale).

Read that prompt again. I was describing rules to the model in English, and paying tokens for it to apply them to every test.

Version 2: AI in the loop. Deterministic rules first; only the cases they couldn't decide went to Gemini, in batches of 20. The model went from classifying every failing test to looking only at the leftovers.

Version 3: rules only. When I made the detector auto-discover and scan every Jenkins job, the model call came out of the loop. The leftovers are labelled UNKNOWN with their last five data points, so a human can glance at them.

flowchart TD
    V1["v1<br/>LLM classifies<br/>every failing test"] --> V2["v2<br/>rules first,<br/>LLM for leftovers"] --> V3["v3<br/>rules only,<br/>leftovers flagged UNKNOWN"]

Looking at what ends up in that bucket explains why. The ambiguous case is a test that started failing one or two builds ago. That is not a pattern problem, it is a missing-data problem: nobody, human or model, can tell yet whether it will recover on the next build or stay red. The next run of the detector, a few hours later, will usually classify it with no help at all.

The general lesson I took from it: keep the deterministic part deterministic, and spend a model only where it adds information you don't already have. When your prompt is a list of rules, write the rules.

The Gemini settings are still in the config template, so bringing the model back for the UNKNOWN bucket is a small change if it ever proves useful.

Step 4: expose it the boring way

The output is a flat JSON array:

{
  "job_name": "my-acceptance-job",
  "test_suite": "features/core",
  "test_case": "Register a client",
  "flakiness_score": 1.0,
  "failure_pattern": "FLAKY",
  "reasoning": "OSCILLATION: Flipped state 4 times."
}

(Field values here are illustrative.)

Serving it takes a 30-line http.server sidecar on port 8080. In Grafana, the Infinity data source reads the URL and a UQL query does the rest:

parse-json
| filter "job_name" == "${jobname}"
| project "test_suite", "test_case", "failure_pattern", "flakiness_score", "reasoning"
| order by "flakiness_score" desc

A jobname dashboard variable (built with parse-json | project "job_name" | distinct "job_name") gives a drop-down per test suite, and value mappings colour the pattern column: yellow for FLAKY, red for REGRESSION, blue for INFRA, purple for FIXED.

Running it

The container runs both processes from a tiny entrypoint: the web server in the background and the detector in a loop.

python3 serve_results.py --dir /data &

while true; do
    python3 flaky_detector.py --config /app/config.yaml || echo "Detector failed, retrying next interval."
    sleep ${CHECK_INTERVAL:-14400}   # every 4 hours by default
done

A GitHub Actions workflow builds and pushes the image to GHCR on every push to main (tagged latest, by version tag and by commit SHA). In the monitoring infrastructure where I ran it, a Salt state rendered the config from a Jinja template with the secrets taken from the pillar, and kept the container running:

jenkins-flaky-tests-detector:
  docker_container.running:
    - image: ghcr.io/srbarrios/jenkins-flaky-tests-detector:latest
    - binds:
      - /data/jenkins-flaky-tests-detector/config.yaml:/app/config.yaml:ro
      - /data/jenkins-flaky-tests-detector/output:/data
    - environment:
      - CHECK_INTERVAL: 14400
    - restart_policy: always
    - watch:
      - file: /data/jenkins-flaky-tests-detector/config.yaml

The watch means that changing the config in the pillar restarts the container with the new settings on the next highstate.

What I would change next

Writing this post made me run the rules against synthetic data, and that is a good way to find your own blind spots:

  1. Rule order matters more than thresholds. With about 360 buckets, almost any test has a failure rate under 30%, so the sporadic rule fires before the cluster rule ever gets a chance. A burst of four failures followed by green is reported as "sporadic" rather than "cluster". The verdict is still right, but the reason is less precise.
  2. Buckets are not builds. The "healed" threshold is 48 hourly buckets, not 48 runs. For a nightly job that is two runs; for a job that runs every 15 minutes it is close to 200. The threshold should be expressed in builds.
  3. "No sample" is not always "pass". If a job didn't run for a weekend, the timeline shows two green days. Joining with a "build ran" metric would remove that bias.
  4. Close the loop. The natural next step is to feed FLAKY tests back into the pipeline: quarantine them, re-run them automatically, or open an issue.

The repository is archived now and I'm not adding features, but the code is open source (GPL-3.0) and small enough to read in one sitting.

👉 Code: github.com/srbarrios/jenkins-flaky-tests-detector

How do you deal with flaky tests in your pipelines? Quarantine, automatic retries, or a dashboard like this one? I'd love to hear what has worked for you.

Originally published at oscarbarrios.tech.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.