Engineering managers and platform teams use this prompt to stop flaky tests from being a diffuse, unmanaged drag on delivery velocity. The prompt ingests failure logs, test code, and CI metadata to classify each flaky failure into a defined category (environmental, timing, data, concurrency, infrastructure) and assign a severity score based on failure frequency, blast radius, and release impact. The output is a structured triage report that feeds directly into a remediation backlog, replacing ad-hoc Slack threads and spreadsheets with a repeatable, evidence-backed prioritization process.
Prompt
Flaky Test Classification and Severity Triage Prompt

When to Use This Prompt
A practical guide for engineering managers and platform teams to decide when batch triage of flaky tests is the right intervention.
Use this prompt when you have a growing list of flaky tests and need to decide which ones to fix first, quarantine, or monitor. It is designed for batch triage of known flaky failures where you have accumulated failure logs, test code, and CI metadata across multiple runs. The prompt works best when you can provide at least 10-20 failure instances per test to establish reliable frequency patterns. For each test under review, you should supply the test file path, failure stack traces from recent CI runs, the test's pass/fail history over the last 30 days, and any known blast radius metadata such as which services or release pipelines depend on this test passing. The severity scoring logic weighs three factors: failure frequency (how often it fails relative to total runs), blast radius (how many teams, pipelines, or releases are blocked when it fails), and release impact (whether failures have historically correlated with production regressions). Tests that fail frequently, block critical release paths, and correlate with past incidents receive the highest severity scores and should be fixed or quarantined first.
Do not use this prompt for real-time incident response or for diagnosing a single test failure in isolation. It is not designed for root cause analysis of a novel failure mode; for that, use the Flaky Test Failure Log Analysis Prompt or Race Condition Hypothesis Generation Prompt. This prompt also assumes you have already identified which tests are flaky—it does not detect flakiness from raw CI data. If you need to identify flaky tests first, pair this with a test suite stability regression detection workflow. Finally, the severity scores are recommendations, not automated decisions. Always review high-severity classifications with the owning team before quarantining tests or blocking releases, especially for tests covering security-critical or compliance-relevant code paths.
Use Case Fit
Where the Flaky Test Classification and Severity Triage Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your workflow before integrating it into your CI pipeline or triage queue.
Good Fit: High-Volume CI Pipelines with Known Flakiness
Use when: your CI pipeline produces more flaky test failures than your team can manually triage each sprint. The prompt scales classification and severity assignment across hundreds of failures, giving platform teams a prioritized remediation backlog without manual labeling. Guardrail: feed the prompt structured failure logs, not raw console output. Pre-process logs to extract test name, stack trace, duration, and execution environment before calling the model.
Bad Fit: Single Failure Deep Forensics
Avoid when: you need root cause analysis for one specific flaky test with full repository context. This prompt classifies and prioritizes; it does not trace race conditions through source code or propose concrete fixes. Guardrail: route single-test deep-dive requests to the Flaky Test Failure Log Analysis Prompt or Race Condition Hypothesis Generation Prompt instead. Use this prompt for batch triage, not individual investigation.
Required Inputs: Structured Failure Records
What to watch: the prompt depends on structured input fields—test name, failure message, stack trace, execution duration, environment metadata, and recent pass/fail history. Missing or unstructured input degrades classification accuracy and severity scoring. Guardrail: validate input completeness before calling the prompt. If failure records lack stack traces or environment data, route to a log enrichment step first. Do not expect the model to infer missing evidence.
Operational Risk: Severity Inflation Without Human Calibration
What to watch: the model may over-assign high severity when failure frequency or blast radius signals are ambiguous, leading to alert fatigue and wasted remediation effort on low-impact flaky tests. Guardrail: implement a human review threshold for severity scores above a defined cutoff. Track severity distribution over time and recalibrate the prompt if high-severity assignments exceed 20% of classified failures without corresponding release impact evidence.
Operational Risk: Category Drift Across Model Versions
What to watch: classification categories (environmental, timing, data, concurrency) may shift meaning or boundary when the underlying model is updated, causing inconsistent taxonomy across triage cycles. Guardrail: maintain a golden dataset of 20-30 labeled flaky test failures with known categories and severities. Run this dataset through the prompt after any model change and flag category agreement below 85% for investigation before trusting production output.
Integration Point: Downstream Routing and Quarantine Decisions
What to watch: classification and severity output must feed into actionable workflows—team routing, quarantine rules, or fix prioritization backlogs. If the output sits in a dashboard without triggering action, the prompt adds cost without reducing flakiness. Guardrail: wire prompt output to your ticketing system or test quarantine tool. Map severity levels to SLA targets and category labels to owning teams. Measure time-to-remediation, not just classification accuracy.
Copy-Ready Prompt Template
Paste this prompt into your AI harness to classify flaky test failures and assign severity scores for remediation prioritization.
This prompt template is designed to be copied directly into your AI orchestration layer, test harness, or CI/CD pipeline. It expects structured input data about flaky test failures and returns a classification with severity triage. All square-bracket placeholders must be replaced with real data before execution. The prompt enforces a strict output schema so downstream systems can parse the classification deterministically.
textYou are a test reliability engineer analyzing flaky test failures. Your task is to classify each flaky test failure by its root cause category and assign a severity score based on failure frequency, blast radius, and release impact. ## INPUT [FAILURE_REPORTS] ## CLASSIFICATION TAXONOMY Classify each failure into exactly one of these categories: - `environmental`: Infrastructure, network, CI worker, disk, or external service issues outside the test code. - `timing`: Race conditions, fixed waits, missing await conditions, or timeout-induced failures. - `data`: Database state contamination, missing cleanup, implicit data ordering, or seed-dependent data. - `concurrency`: Parallel execution conflicts, shared mutable state, port conflicts, or test worker interference. - `assertion`: Non-deterministic assertions on random seeds, UUIDs, timestamps, unordered collections, or floating-point precision. - `infrastructure`: CI configuration drift, missing environment variables, or resource exhaustion. - `external_dependency`: Mock/stub mismatch, third-party service flakiness, or API contract drift. ## SEVERITY SCORING RULES Assign a severity score from 1 (lowest) to 5 (highest) using these criteria: - **Frequency**: How often does this test fail? (1: <1% of runs, 3: 1-5%, 5: >5%) - **Blast Radius**: How many other tests or pipelines are blocked? (1: isolated, 3: blocks a test suite, 5: blocks multiple pipelines or release) - **Release Impact**: Does this failure block production releases? (1: no impact, 3: delays release, 5: blocks release entirely) - **Investigation Cost**: Average developer hours wasted per failure investigation. (1: <15 min, 3: 1-4 hours, 5: >4 hours) Calculate the final severity as: `round((frequency + blast_radius + release_impact + investigation_cost) / 4)` ## OUTPUT_SCHEMA Return a valid JSON object with this exact structure: { "classifications": [ { "test_name": "string", "test_file": "string", "category": "environmental|timing|data|concurrency|assertion|infrastructure|external_dependency", "confidence": 0.0-1.0, "evidence_summary": "string (max 200 chars, cite specific log lines or stack trace elements)", "severity": { "score": 1-5, "frequency": 1-5, "blast_radius": 1-5, "release_impact": 1-5, "investigation_cost": 1-5, "rationale": "string (max 150 chars)" }, "recommended_action": "quarantine|immediate_fix|monitor|investigate_further", "action_rationale": "string (max 150 chars)" } ], "summary": { "total_failures": "integer", "category_distribution": {"category": "count"}, "average_severity": "float", "tests_recommended_for_quarantine": ["test_name"], "tests_requiring_immediate_fix": ["test_name"] } } ## CONSTRAINTS - Do not invent failure data. Only classify failures present in [FAILURE_REPORTS]. - If a failure cannot be confidently classified, set confidence below 0.5 and use category `unknown`. - Do not recommend quarantine for tests covering critical path code (authentication, payment, data integrity) without flagging the risk. - If severity score is 5, recommended_action must be `immediate_fix` or `quarantine`. - Cite specific evidence from logs or stack traces in evidence_summary. Do not speculate. ## EXAMPLES [FEW_SHOT_EXAMPLES] ## RISK_LEVEL [HIGH] - Classification errors can cause incorrect quarantine decisions or mask real regressions. Human review is required before applying quarantine actions to critical-path tests.
Adaptation guidance: Replace [FAILURE_REPORTS] with structured failure data including test names, log excerpts, stack traces, execution duration, and CI context. Replace [FEW_SHOT_EXAMPLES] with 2-3 annotated examples showing correct classification and severity scoring for your test suite's common failure patterns. The output schema is designed for direct ingestion into test management systems or quarantine automation. Always validate the JSON response against the schema before acting on quarantine or fix recommendations. For critical-path tests, route the classification to a human reviewer before automated action.
Prompt Variables
Required and optional inputs for the Flaky Test Classification and Severity Triage Prompt. Each variable must be populated before the prompt is sent. Missing or malformed inputs degrade classification accuracy and severity scoring.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TEST_NAME] | Unique identifier for the flaky test | UserAuthIntegrationTest.testConcurrentSessionRefresh | Must be non-empty string. Used for deduplication and tracking across runs. |
[FAILURE_LOG] | Raw test failure output including stack trace, assertion errors, and log lines | AssertionError: Expected 200, got 503 at line 142 in test_login_flow.py | Must contain at least one stack frame or error message. Null allowed if only [EXECUTION_HISTORY] is provided. |
[EXECUTION_HISTORY] | Recent pass/fail records with timestamps, branch, and CI worker ID | [{run_id: 8421, status: FAIL, branch: main, worker: ci-node-7, timestamp: 2025-03-15T14:22:01Z}] | Must be valid JSON array with at least 5 entries. Each entry requires status, timestamp, and worker fields. Null allowed if only [FAILURE_LOG] is provided. |
[TEST_CODE] | Source code of the flaky test method or function | def test_concurrent_session_refresh(): client = TestClient(app) response = client.post('/auth/refresh') | Must be non-empty string. Required for concurrency, assertion, and data category classification. Omission reduces classification confidence. |
[DEPENDENCY_MAP] | External services, databases, queues, or APIs the test touches | {"services": ["redis-sessions", "postgres-auth"], "mocks": ["email-gateway"]} | Must be valid JSON object. Used to detect environmental and infrastructure flakiness. Null allowed if test has no external dependencies. |
[CI_ENVIRONMENT] | CI platform, runner OS, resource limits, and environment variables for the failing run | {"platform": "GitHub Actions", "os": "ubuntu-22.04", "cpu": 2, "memory_mb": 7168} | Must be valid JSON object. Required for environmental category detection. Include resource limits when available. |
[FREQUENCY_THRESHOLD] | Team-defined flakiness budget as percentage of recent runs | 5.0 | Must be float between 0.0 and 100.0. Used to determine if severity should escalate. Default to 3.0 if not provided. |
[RELEASE_CONTEXT] | Whether a release is in progress, blocked, or imminent | {"release_active": true, "release_blocked": false, "target_branch": "release/v2.9"} | Must be valid JSON object with release_active boolean. Required for blast radius and release impact severity scoring. Null allowed during non-release periods. |
Implementation Harness Notes
How to wire the Flaky Test Classification and Severity Triage Prompt into a CI pipeline or triage application.
This prompt is designed to be called programmatically after a test failure event, not as a one-off chat interaction. The implementation harness should collect the required inputs—failure logs, test code, execution context, and historical failure data—from your CI system (e.g., GitHub Actions, Jenkins, CircleCI) and assemble them into the structured [INPUT] block before invoking the model. The output is a JSON classification and severity object, which your harness must validate against the expected [OUTPUT_SCHEMA] before routing the result to an issue tracker, a quarantine system, or a team notification channel.
Wire the prompt into a post-failure hook in your CI pipeline. When a test fails with a flaky signature (e.g., it passed on retry, or its failure history shows intermittent patterns), the harness should: (1) fetch the last N failure logs and stack traces from your test reporting tool; (2) retrieve the test source code from the repository at the relevant commit; (3) query your test history database for failure frequency, quarantine status, and affected code paths; (4) assemble these into the [INPUT] block with clear section delimiters; (5) call the model with a moderate temperature (0.1–0.2) to balance consistency with nuanced classification; (6) validate the returned JSON against the expected schema, checking that category is one of the allowed enum values and severity is an integer between 1 and 5; (7) on validation failure, retry once with the error message appended to the prompt as a correction hint; (8) log the full prompt, response, and validation result for auditability. For high-severity classifications (4–5), route to a human triage queue rather than auto-quarantining.
Avoid calling this prompt on every test failure—only trigger it when the failure matches a flaky pattern (intermittent, passes on retry, or flagged by your flakiness detection system). Do not use this prompt's output to automatically skip or delete tests without human review for severity levels 3 and above. Store the classification results in your test health database to build a historical record that improves future triage accuracy and feeds into your Flaky Test Budget and Threshold Enforcement dashboards. The next step after classification is to route the result: low-severity environmental failures may go to a platform team backlog, while high-severity concurrency failures should trigger an immediate developer alert with the generated hypothesis and suggested remediation path.
Expected Output Contract
Defines the exact fields, types, and validation rules for the model's JSON response. Use this contract to build a post-processing validator before the classification result enters your triage queue or dashboard.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
classification.primary_category | enum string | Must be one of: environmental, timing, data, concurrency, infrastructure, assertion, unknown. Reject any other value. | |
classification.secondary_categories | array of enum strings | If present, each element must be a valid primary_category value. Array must not contain duplicates. Null allowed. | |
classification.confidence | number (0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Values below 0.6 should trigger a human-review flag in the application layer. | |
severity.score | integer (1-5) | Must be an integer from 1 (lowest) to 5 (highest). Reject non-integer or out-of-range values. | |
severity.rationale | string | Must be 1-3 sentences explaining the score. Must reference at least one of: failure_frequency, blast_radius, or release_impact from the input context. | |
evidence.failure_signature | string | Must contain a quoted excerpt from [FAILURE_LOG] or [STACK_TRACE] that supports the primary_category. Empty string is invalid. | |
evidence.frequency_context | string | Must summarize the failure rate using data from [FAILURE_HISTORY]. If no history provided, must state 'No historical frequency data provided.' | |
remediation.suggested_action | string | Must be a concrete, actionable step aligned with the primary_category. Generic advice like 'fix the test' is invalid. Must reference a specific pattern (e.g., 'Replace fixed wait with await condition on element visibility'). |
Common Failure Modes
What breaks first when classifying flaky tests and how to guard against it.
Overfitting to a Single Failure Signature
What to watch: The model latches onto a keyword like 'timeout' or 'connection refused' and classifies every failure as the same category, ignoring contradictory evidence in the stack trace or test body. Guardrail: Require the prompt to list contradictory evidence before finalizing a classification. Add a 'confidence' field that drops when multiple categories are plausible.
Severity Inflation for High-Frequency, Low-Impact Tests
What to watch: A flaky unit test that fails 20% of the time but covers a non-critical utility function gets marked as 'critical' simply because of its failure rate. Guardrail: Include blast radius as a required input variable. The prompt must weigh 'affected code paths' and 'release impact' alongside failure frequency before assigning severity.
Ignoring Cross-Test Contamination Signals
What to watch: The model classifies a failure as 'data-related' without checking if the test passes in isolation but fails only after a specific predecessor. This misses test order dependencies. Guardrail: If execution order logs are provided, add a pre-processing step that flags tests with different pass/fail rates in randomized vs. sequential runs before classification.
Misclassifying Infrastructure Flakiness as Code Flakiness
What to watch: CI worker disk pressure or network blips cause failures that look like timeouts or resource issues in the test code. The model blames the test rather than the environment. Guardrail: Require CI worker metadata and resource metrics as optional inputs. When present, the prompt must rule out infrastructure causes before assigning a code-level category.
Vague or Unactionable Severity Justifications
What to watch: The model outputs 'severity: high' with a generic reason like 'fails often,' giving the remediation team no basis to prioritize or challenge the decision. Guardrail: The output schema must include a structured 'evidence' field that cites specific failure frequency, affected services, and release blockage count. Validate that the evidence field is non-empty and specific.
Category Drift Across Repeated Runs
What to watch: The same test failure log, when submitted multiple times, gets classified as 'environmental' in one run and 'concurrency' in another due to model non-determinism. Guardrail: Set a low temperature (0.0–0.1) for classification tasks. Add a consistency eval that re-runs the prompt on a golden set and flags any test with >10% category disagreement across runs.
Evaluation Rubric
Criteria for evaluating the quality and safety of the Flaky Test Classification and Severity Triage output before integrating it into a CI/CD pipeline or ticketing system.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Category Assignment Accuracy | Failure category matches the root cause evidence in [FAILURE_LOG] and [TEST_CODE] for 90% of test cases. | Category is 'Unknown' or 'Other' for >20% of samples; category contradicts stack trace evidence (e.g., 'Concurrency' assigned to a null pointer exception). | Run 50 labeled historical flaky tests through the prompt. Compare predicted category to ground-truth label. Calculate precision and recall per category. |
Severity Score Calibration | Severity score correlates with actual business impact: 'Critical' tests have blocked releases; 'Low' tests have no historical release impact. | A test with 0 historical release blocks is scored 'Critical'; a test blocking every release for a week is scored 'Low'. | Backtest on 6 months of CI data. Check if severity score predicts actual release blockage count and developer time wasted. |
Evidence Grounding | Every classification cites a specific line from [FAILURE_LOG], [STACK_TRACE], or [TEST_CODE] as justification. | Justification contains hallucinated log lines, references code that does not exist in [TEST_CODE], or uses only generic reasoning. | Automated check: extract cited strings from output and verify they exist verbatim in the input context. Flag any citation with <100% match. |
Output Schema Compliance | Output is valid JSON matching the [OUTPUT_SCHEMA] exactly. All required fields present. Enum values match allowed lists. | JSON parse error; missing 'severity_score' field; 'category' value not in allowed enum list. | Schema validator applied to output. Check for parse errors, missing required fields, wrong types, and invalid enum values. |
Blast Radius Assessment | Blast radius correctly identifies affected services, teams, or code paths from [CODEOWNERS] and [TEST_METADATA]. | Blast radius is empty when [CODEOWNERS] is provided; blast radius lists services not present in the repository. | Verify that every service listed in blast radius appears in the provided [CODEOWNERS] file or test path metadata. |
Remediation Actionability | Suggested remediation steps are specific to the failure category and test framework in use. | Remediation is generic ('fix the test') or suggests a tool not present in the project's language or framework. | Manual review by a senior QA engineer: do the suggested steps provide a concrete starting point for a developer? |
Confidence Score Honesty | Confidence score is low (<0.7) when evidence is ambiguous or contradictory; high (>0.9) only when evidence is clear and singular. | Confidence is always >0.95 regardless of input quality; confidence is high when [FAILURE_LOG] is empty or corrupted. | Inject ambiguous failure logs with multiple possible causes. Verify confidence score drops below 0.7. Inject clear, single-cause failures and verify score exceeds 0.9. |
Frequency Calculation Correctness | Failure frequency is correctly calculated from [HISTORICAL_RUNS] data: failures / total runs. | Frequency is 1.0 when historical data shows 3 failures in 100 runs; frequency is null when historical data is provided. | Unit test the frequency calculation logic. Provide known [HISTORICAL_RUNS] inputs and assert the output frequency value. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base classification and severity prompt. Remove strict output schema requirements. Use a simpler severity scale (Low/Medium/High) instead of the full matrix. Accept free-text classification rationales rather than structured evidence fields.
codeClassify this flaky test failure into one category: Environmental, Timing, Data, or Concurrency. Assign severity: Low, Medium, or High. Explain your reasoning in 2-3 sentences. Test name: [TEST_NAME] Failure log: [FAILURE_LOG] Recent pass rate: [PASS_RATE]
Watch for
- Inconsistent category assignment across similar failures
- Severity inflation when pass rate context is missing
- Vague rationales that don't cite specific log evidence
- No distinction between first-time and recurring flakiness

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us