AI Failure Classifiers Stall on Missing Assertion Context
Many teams connect an AI classifier to their JUnit XML, watch it label a few failures as "environment" or "assertion", and assume it works. Then comes a week where it confidently mislabels half the failures, triage takes longer than before the model existed, and nobody can say why. Usually the model did not get worse. Its input did, and nobody noticed.
The failure mode is nearly always the same. The assertion context a human would use to reason about a failure, the expected value, the actual value, the object diff and the frame where the assertion fired, never reaches the text the model sees. Runners collapse multi-line diffs, ingestion schemas truncate, artifact pipelines drop long message bodies. The classifier is left with a test name and a line like AssertionError: false is not true. This article traces where context gets lost between runner and classifier, how to recover it, and how to stop it disappearing after the next runner upgrade.
Coding agents now write a large share of new tests, and they are a new source of thin assertions: bare assert result checks with no message and no values. Recovering context downstream helps, but the cheaper fix is making agent-written tests carry their context in the first place.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
What "Assertion Context" Actually Means to a Classifier
An AI failure classifier — whether it's a fine-tuned model or a prompt-wrapped call to a general-purpose LLM — operates as a text classifier at its core. It maps an input string to a label: flaky, environment, product-regression, test-code-defect. The quality of that label is bounded by the information density of the input. Assertion context is the highest-signal fragment in any test failure: it encodes what state the system was in, what state it was expected to be in, and implicitly, which code path produced the divergence.
In a well-instrumented pipeline, assertion context includes the full diff of expected vs. actual objects, the stack trace down to the assertion call site, any parameterized input values, and — ideally — a correlation ID linking the test execution to a distributed trace. Without those fields, the classifier is pattern-matching on test names and generic exception types, which is roughly as useful as classifying failures by file size. This is why confidence scoring for AI failure classifiers collapses when the underlying signal is thin: low-entropy inputs produce low-confidence outputs, and the model often defaults to the majority class in its training data.
Tracing the Signal Path from Runner to Classifier
Start at the JUnit XML spec. The <failure> element has a message attribute and a CDATA text body. Most runners write the one-liner to message and the full stack trace to the body — but some CI integrations, report summaries and home-grown ingestion scripts read only message when constructing the record they store or forward. Your classifier is almost certainly consuming the stored record, not the raw XML. Verify this:
# Pull a raw artifact and compare against what your DB stores
import xml.etree.ElementTree as ET, json, sys
tree = ET.parse("test-results.xml")
for tc in tree.iter("testcase"):
fail = tc.find("failure")
if fail is not None:
print(json.dumps({
"name": tc.attrib.get("name"),
"message": fail.attrib.get("message", "")[:120],
"body_len": len((fail.text or "").strip()),
}, indent=2))
If body_len is consistently above 200 characters but your classifier input table shows records under 80 characters, something in the ingestion path is truncating. Common culprits: a VARCHAR(255) column in a Postgres ingestion schema, a Datadog log pipeline with a truncate_at processor, or a Loki label cardinality guard that collapses the message field. Fix the schema first — alter the column to TEXT or JSONB and re-ingest from raw artifacts.
Once you have the full body, enrich it with OpenTelemetry trace correlation. If your test runner emits spans (a pytest OpenTelemetry plugin or hook, or a custom Playwright fixture), attach the trace ID to the JUnit XML <properties> block. Then, at classifier input-assembly time, join the failure record to the trace backend — Honeycomb, Jaeger, or Tempo — and pull the root span's attributes. OpenTelemetry trace analysis for failure correlation and root cause is the layer most teams skip, but it's what separates "the assertion fired" from "the assertion fired because the downstream payment service returned 503 on this specific tenant ID."
# Assemble classifier input with OTel trace context.
# fetch_spans(trace_id) -> list[dict] wraps your trace backend's API and
# returns spans flattened to dicts of attributes.
def fetch_trace_summary(trace_id: str, fetch_spans) -> dict:
spans = fetch_spans(trace_id)
root = next((s for s in spans if not s.get("parent_id")), {})
return {
"service": root.get("service.name"),
"status_code": root.get("http.status_code"),
"error_type": root.get("exception.type"),
"duration_ms": root.get("duration_ms"),
}
With this enrichment the classifier can distinguish an assertion failure caused by a slow external dependency (trace duration spike + 503 status) from one caused by a changed data contract (normal duration, unexpected field value in diff). The trace-driven root cause workflow in Honeycomb gives the practical setup for the span schema side of this.
Where Senior Engineers Still Drop the Context Ball
The most common mistake is treating artifact expiry as a storage concern rather than a signal-integrity concern. When a CI system expires artifacts after 30 days but the classifier's training pipeline re-ingests historical data monthly, it silently trains on truncated or missing records. The model degrades gradually — accuracy metrics look stable because the majority of recent failures are well-formed, but edge-case classification (the failures that actually matter) gets worse. Artifact expiry silently breaks historical failure trends in ways that are nearly invisible until you diff raw artifact counts against ingested record counts per week.
The second mistake is normalizing assertion messages at ingest time for deduplication. Stripping numeric values, UUIDs, and timestamps from messages to group similar failures is useful for dashboards but catastrophic for classifiers. The specific values are the signal — expected 404 got 200 and expected 200 got 404 are opposite failure modes that look identical after normalization. Keep two separate fields: a normalized key for grouping and a raw body for the classifier. Never feed the classifier the normalized version.
Making agent-written tests carry their own context
A classifier can only use assertion context that the test produced. Tests written by coding agents tend to be correct but terse: assert response.ok, assert len(items) == 3, expect(result).toBeTruthy(). When they fail, the message says almost nothing, and no amount of pipeline repair upstream of the classifier can recover values the test never reported.
Fix it at the source, in three places.
- Instructions. Put the rule in the repository's agent instruction file, such as
.github/copilot-instructions.mdor the equivalent for your agent: assertions compare a specific expected value with the actual one, include the identifiers involved (request ID, record ID, parameter values), and prefer assertion forms that print a diff. pytest's assertion rewriting already shows both sides of a plain==, soassert response.status_code == 201beatsassert response.ok. - Review. Treat a context-free assertion as a review comment, whoever wrote it. A test whose failure message would not help a stranger is not finished.
- A cheap check in CI. Flag new bare truthiness assertions in changed test files so reviewers see them:
import ast
import sys
def bare_asserts(path: str) -> list[int]:
"""Line numbers of `assert x` with no comparison and no message."""
tree = ast.parse(open(path).read())
return [
node.lineno
for node in ast.walk(tree)
if isinstance(node, ast.Assert)
and node.msg is None
and not isinstance(node.test, ast.Compare)
]
for path in sys.argv[1:]:
for line in bare_asserts(path):
print(f"{path}:{line}: assertion has no comparison or message")
Track the share of failures that reach the classifier with a usable expected/actual pair, split by whether the test was written by an agent or a person. It is a direct measure of input quality, and it usually moves before classifier accuracy does.
Myths That Keep Classifier Accuracy Stuck
Myth 1: More training data fixes low accuracy. If the training data is structurally context-poor, adding more of it reinforces the model's reliance on low-signal features like test name patterns. Fix the input pipeline first, then retrain on even a modest set of enriched records; a smaller set of high-context examples often beats a much larger truncated one. Myth 2: A high overall accuracy score means the classifier is working. If 80% of your failures are environment failures and the model labels everything as environment, you get 80% accuracy and zero utility. Evaluate per-class F1, specifically on product-regression and test-code-defect — those are the classes where AI failure classifiers misread cascading failures most often, and they're the ones that drive engineering decisions.
Myth 3: The classifier should handle flakiness detection. Flakiness is a temporal pattern — a test that fails intermittently across runs — not a property of a single failure record. A classifier operating on individual failure records has no visibility into run history. Flakiness detection belongs in a separate statistical layer that feeds a feature into the classifier (flake_probability: 0.73), not in the classifier's inference logic. Conflating the two produces a model that over-labels ambiguous failures as flaky because "flaky" is the safest default when context is thin.
The fix for a stalling AI failure classifier is almost never the model — it's the signal pipeline upstream of it. Audit what actually reaches the classifier input: compare raw JUnit XML body lengths against stored records, add OTel trace correlation at the test runner layer, and keep raw assertion text separate from normalized grouping keys. Once the context is intact, re-evaluate per-class F1 on product-regression before declaring the classifier production-ready. Start with the XML audit script above — run it against last week's artifacts and count how many failures lost their body text in transit.
Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.