Inferensys

Prompt

Test Failure Triage Prompt Template

A practical prompt playbook for using the Test Failure Triage Prompt Template in production CI/CD workflows to classify failures, detect flakiness, and route ownership.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, the operator, and the boundaries for automated test failure triage.

This prompt is designed for CI/CD pipeline operators and engineering teams who need to classify test failures by root cause category at scale. Instead of writing brittle rule-based classifiers or manually inspecting every failed job, you provide labeled examples of failure signatures—stack traces, error messages, and log snippets—and the model learns to categorize new failures into buckets like flaky test, environment issue, code regression, or dependency breakage. The primary job-to-be-done is reducing mean-time-to-diagnosis by routing failures to the right owner before a human opens the logs.

Use this prompt when you have a stream of test failures from automated pipelines and you need consistent, explainable triage decisions. It works best when you can supply 8–15 diverse examples covering your most common failure categories, including edge cases like timeout-induced flakes versus assertion-driven regressions. The prompt is not a replacement for flaky test detection algorithms or deterministic log parsers—it complements them by handling ambiguous failures where pattern matching alone fails. Do not use this prompt for real-time production incident response where latency is measured in seconds; it is designed for post-build triage workflows where a few seconds of inference time is acceptable.

Before deploying, you must validate the prompt against a golden set of 50–100 labeled failures to measure category-level precision and recall. Pay special attention to flakiness misclassification—the most common production failure mode is labeling a flaky infrastructure timeout as a code regression. If your pipeline produces failures that don't match any known category, the prompt should route them to an 'unclassified' bucket for human review, not force a wrong label. Wire the output into your alerting or ticketing system only after you've confirmed that ownership routing hints map to real teams and that the eval pass rate exceeds your organization's triage accuracy baseline.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Test Failure Triage Prompt Template delivers reliable classification and where you should reach for a different approach.

01

Good Fit: Stable CI/CD Pipelines

Use when: your test failures follow recurring patterns (flaky tests, environment timeouts, assertion errors) that can be captured in a few-shot example set. Guardrail: maintain a golden dataset of 20-30 labeled failure logs covering your top categories and update it when new failure signatures appear.

02

Bad Fit: Novel Failure Modes

Avoid when: your system generates entirely new failure types daily or the root cause requires deep architectural knowledge the model cannot infer from a log snippet. Guardrail: route unclassified failures to a human triage queue and use those cases to expand your example set before attempting automation.

03

Required Inputs

What you need: a test failure log with stack traces, the test name, and the environment context (branch, commit, runtime). Guardrail: strip secrets and internal hostnames before sending logs to external model APIs. Use a pre-processing step to redact PII and credentials.

04

Operational Risk: Example Drift

What to watch: your few-shot examples become stale as the codebase evolves, causing the model to misclassify new failure patterns into old categories. Guardrail: track classification confidence scores over time and trigger an example refresh when the rate of low-confidence predictions exceeds 15%.

05

Operational Risk: Ownership Routing Errors

What to watch: the model confidently assigns a failure to the wrong team, delaying incident response. Guardrail: require human confirmation for ownership assignments on P0 and P1 incidents. Log all routing decisions for weekly review against actual resolution paths.

06

When to Use Code Instead

Avoid when: you can deterministically classify failures using regex patterns on error messages or stack trace signatures. Guardrail: use the prompt template for ambiguous or multi-factor failures that require reasoning, and keep deterministic rules for clear-cut cases to reduce cost and latency.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for classifying CI/CD test failures by root cause using few-shot examples, including flakiness detection and ownership routing.

This prompt template is designed to be copied directly into your application or testing harness. It uses square-bracket placeholders for all dynamic inputs, allowing you to swap in the specific test failure log, your team's categories, and custom routing rules without rewriting the core instruction set. The template relies on a dense set of few-shot examples to teach the model the difference between an infrastructure flake, a product code regression, a test environment issue, and a genuine product bug, which is often more reliable than a long list of abstract rules.

code
You are a test failure triage specialist. Your task is to analyze a CI/CD test failure log and classify it into one of the predefined root cause categories. You must also assess the likelihood of flakiness and suggest the correct engineering owner. Use only the provided examples to guide your classification.

INPUT:
[TEST_FAILURE_LOG]

OUTPUT_SCHEMA:
{
  "classification": "[ROOT_CAUSE_CATEGORY]",
  "confidence": [CONFIDENCE_SCORE_BETWEEN_0_AND_1],
  "is_flaky": [TRUE_OR_FALSE],
  "flakiness_rationale": "[BRIEF_EVIDENCE_FROM_LOG]",
  "suggested_owner": "[TEAM_OR_INDIVIDUAL]",
  "key_evidence": "[QUOTED_LOG_LINE_OR_SUMMARY]"
}

CONSTRAINTS:
- Classification must be one of: [LIST_OF_CATEGORIES]
- If confidence is below [CONFIDENCE_THRESHOLD], set classification to "NEEDS_HUMAN_TRIAGE".
- Do not invent evidence. Quote directly from the log.

EXAMPLES:
[FEW_SHOT_EXAMPLES]

---

Now, analyze the INPUT and return only the JSON object.

To adapt this template, start by replacing [LIST_OF_CATEGORIES] with your team's actual labels, such as INFRA_FLAKE, PRODUCT_REGRESSION, TEST_BUG, and ENVIRONMENT_MISCONFIG. The [FEW_SHOT_EXAMPLES] placeholder is critical; you should insert at least 3-5 contrasting examples that show the model how to distinguish a timeout caused by a network blip (a flake) from a timeout caused by a new database index (a regression). For high-risk deployments, add a [RISK_LEVEL] constraint that forces a human review if the failure occurs on a release branch. The final step is to validate the model's JSON output against the OUTPUT_SCHEMA before routing the result to your notification system.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Test Failure Triage Prompt Template. Populate these placeholders to ensure the model receives the necessary context for accurate root cause classification.

PlaceholderPurposeExampleValidation Notes

[TEST_FAILURE_LOG]

The raw stack trace, error message, and assertion failure output from the CI/CD pipeline.

java.lang.AssertionError: expected:<200> but was:<500> at com.api.UserTest.testLogin(UserTest.java:45)

Must be non-empty. Check for truncation if log exceeds model context window. Null not allowed.

[TEST_NAME]

The fully qualified name of the failing test case or suite.

com.api.UserTest.testLogin

Parse check: should match a standard test naming convention. Null not allowed.

[CODE_DIFF]

The unified diff of the code change that triggered the test run.

diff --git a/src/main/java/com/api/UserService.java b/src/main/java/com/api/UserService.java --- a/src/main/java/com/api/UserService.java +++ b/src/main/java/com/api/UserService.java @@ -12,7 +12,7 @@

  • code
       return client.getUser(id);
  • code
       return client.getUser(id, true);

Can be empty string if no code changes are associated. Validate diff format if provided.

[EXECUTION_ENVIRONMENT]

Details about the environment where the test failed (OS, language version, container image).

ubuntu-latest, Java 17, Docker image: openjdk:17-slim

Must be a non-empty string. Check for standard key-value pair formatting.

[RECENT_PASSING_LOG]

The log output from the most recent successful run of the same test for comparison.

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.234 sec

Null allowed if no history exists. If provided, must be a valid log string.

[FLAKINESS_HISTORY]

A boolean or structured string indicating if this specific test has a known history of flakiness.

Must be parseable as a boolean or a structured string like 'flaky: true'. Null defaults to false.

[SERVICE_OWNERSHIP_MAP]

A mapping of code paths or service names to responsible teams.

{"src/main/java/com/api/": "API Team", "src/main/java/com/db/": "DB Team"}

Must be valid JSON. Schema check: object with string keys and values. Null not allowed.

[OUTPUT_SCHEMA]

The exact JSON schema the model must use for its classification response.

{"root_cause": "string", "confidence": "float", "owner": "string", "evidence": ["string"]}

Must be a valid JSON schema definition. Parse check required before prompt assembly.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Test Failure Triage prompt into a CI/CD pipeline with validation, retries, and routing.

This prompt is designed to be called as a step in your CI/CD pipeline immediately after a test suite run produces a failure log. The harness should extract the raw failure output from your test runner (e.g., JUnit XML, pytest logs, or Go test output), truncate it to fit the model's context window, and inject it into the [FAILURE_LOG] placeholder. You must also provide a [TEST_ENVIRONMENT] string (e.g., 'staging', 'production', 'PR #452') to give the model operational context. The prompt returns a structured JSON classification, not free text, so your harness must parse this JSON to decide the next step: auto-assign an owner, open a ticket, or flag for manual review.

Validation and retries are critical because a malformed classification can silently drop a failure. Implement a JSON schema validator in your harness that checks for the required fields: root_cause_category, confidence_score, is_flaky, recommended_owner, and evidence_summary. If the model's output fails validation, retry once with the same prompt but append the validation error to the [FAILURE_LOG] as a prefix: 'Previous output was invalid. Ensure your response matches the required JSON schema.' If the second attempt also fails, log the raw output and escalate to the on-call channel with a 'Triage classification failed' alert. Do not silently fall back to a default category.

Model choice and latency matter here. Use a fast, low-latency model (e.g., GPT-4o-mini, Claude 3.5 Haiku, or a fine-tuned open-weight model) because this prompt runs on every test failure in your pipeline. The few-shot examples are tuned for instruction-following models; if you switch to a smaller model, validate that it still respects the confidence_score field and doesn't hallucinate categories not present in the examples. For high-risk deployment pipelines (e.g., production release gates), consider routing low-confidence classifications (confidence_score < 0.7) to a human triage queue rather than auto-assigning. Log every classification with the prompt version, model, failure signature, and assigned owner to build a feedback loop for example drift detection.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when triaging test failures with example-based prompts and how to guard against it.

01

Example Drift from New Failure Signatures

What to watch: The model misclassifies a novel stack trace or error message because your few-shot examples only cover last month's failures. Guardrail: Implement a weekly review of unclassified or low-confidence outputs and add at least one new example for each emerging failure signature.

02

Flakiness Misclassification as Regression

What to watch: The model labels an intermittent timeout as a deterministic code regression, triggering an unnecessary full-scale investigation. Guardrail: Require the prompt to output a flakiness_score and include contrasting examples of transient infrastructure errors versus consistent assertion failures.

03

Ownership Routing to the Wrong Team

What to watch: A failure in shared library code is routed to the application team because the stack trace example focuses on the top-level test file. Guardrail: Include multi-owner examples in the prompt and add a post-processing rule that checks CODEOWNERS or service catalog mappings before final routing.

04

Ambiguous Failures with Low Confidence

What to watch: The model returns a high-confidence classification for a failure that spans multiple systems, masking the true root cause. Guardrail: Enforce a confidence threshold below which the triage is automatically escalated to a human with the raw logs attached, and include explicit 'ambiguous' examples in the prompt.

05

Overfitting to Log Format Variations

What to watch: A change in the CI runner's log formatting causes the model to fail to extract the core error, even though the failure is identical to a known example. Guardrail: Normalize logs by stripping timestamps and runner-specific prefixes before passing them to the prompt, and test the prompt against logs from different CI providers.

06

Ignoring the 'Root Cause' for the 'Symptom'

What to watch: The model correctly identifies a NullPointerException but routes it to the feature team instead of the platform team responsible for a recent API contract change. Guardrail: Structure the output schema to require separate symptom and root_cause_hypothesis fields, and use few-shot examples that demonstrate tracing a symptom back to an upstream dependency change.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a test failure triage prompt before deployment. Use these checks to ensure the prompt reliably classifies root causes, detects flakiness, and routes ownership correctly.

CriterionPass StandardFailure SignalTest Method

Root Cause Classification Accuracy

Correctly identifies the primary root cause category for 90% of test failures in a golden dataset of 50 labeled examples.

Output category does not match the ground-truth label; model confuses environment failures with code regressions.

Run prompt against a held-out set of 50 labeled test failure logs. Measure exact match accuracy and top-2 accuracy.

Flakiness Detection

Correctly flags flaky failures with a precision of at least 0.85 and a recall of at least 0.80.

Model labels a consistent, reproducible failure as flaky, or misses a known flaky pattern from historical data.

Use a dataset of 30 failures where 15 are confirmed flaky and 15 are deterministic. Calculate precision and recall.

Ownership Routing Hint Validity

Generates an ownership hint that maps to a real team or service for 85% of failures.

Ownership hint is empty, generic, or points to a team that does not exist in the provided service catalog.

Parse the [OWNERSHIP_HINT] field from 40 outputs. Cross-reference against a known service-to-team mapping. Measure valid match rate.

Evidence Extraction Completeness

Extracts the specific error message, stack trace snippet, and failed test name for 95% of inputs.

Output is missing one or more required evidence fields, or the extracted text is truncated or hallucinated.

Validate output schema for presence of [ERROR_MESSAGE], [STACK_TRACE_SNIPPET], and [TEST_NAME]. Check that values are substrings of the input.

Confidence Score Calibration

Confidence scores correlate with actual correctness: high-confidence predictions are correct at least 90% of the time.

Model assigns high confidence to incorrect classifications, or low confidence to correct ones.

Bin outputs by confidence score (0.0-0.5, 0.5-0.8, 0.8-1.0). Measure accuracy within each bin. High-confidence bin must exceed 90% accuracy.

Edge Case Handling

Handles empty logs, truncated inputs, and unknown error formats gracefully without hallucinating a category.

Model invents a specific root cause for an empty log, or crashes on a malformed input.

Pass inputs with empty [TEST_LOG], truncated text, and a novel error format not seen in few-shot examples. Check for a fallback category or an explicit uncertainty flag.

Few-Shot Example Adherence

Output format and classification logic match the pattern established by the few-shot examples.

Model ignores the example format and produces a different structure, or misapplies a category label from an unrelated example.

Compare the output schema and category label set against the provided examples. Check for format drift using a strict JSON schema validator.

Instruction vs. Example Conflict Resolution

When instructions and examples conflict, the model follows the examples for classification style and the instructions for output constraints.

Model follows a conflicting instruction literally and breaks the demonstrated classification pattern, or ignores a hard constraint like a required field.

Create a variant prompt where one instruction contradicts an example. Verify the output still contains all required fields and uses the example-based classification style.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and 5-10 hand-labeled failure examples covering your most common root cause categories (flake, infra, code regression, config, data). Use inline [INPUT] and [OUTPUT] pairs without schema enforcement. Run against a week of recent CI failures and spot-check 20 outputs manually.

Watch for

  • Model inventing root cause categories not in your example set
  • Over-classifying ambiguous failures as "flake" without retry evidence
  • Format inconsistency when confidence is low
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.