AIO APEX
Claude Opus 5 (also works well with GPT-5.4 -- needs strong log-reading and causal reasoning, not ideal for smaller/faster models)You're a backend engineer and your team's CI pipeline has a test that fails about 1 in 15 runs with no code changes. Nobody wants to spend a sprint chasing it, so it's been ignored for three weeks -- and now two more tests in the same suite are starting to flake too.Developer Tools

El Diagnóstico de Test Flaky: Convierte Fallos Intermitentes de CI en Hipótesis de Causa Raíz Clasificadas

Compartir:
El Diagnóstico de Test Flaky: Convierte Fallos Intermitentes de CI en Hipótesis de Causa Raíz Clasificadas

Por qué importa este prompt

Flaky tests that get ignored quietly erode trust in the entire suite: engineers start re-running failed CI jobs by reflex instead of reading why they failed, which means a genuine regression can slip through disguised as 'oh, that test is just flaky.' Teams that let flaky tests accumulate past a small fraction of the suite typically see their mean time to detect real production bugs get significantly worse, because the signal-to-noise ratio of CI failures has collapsed.

Para qué lo usamos

You're a backend engineer and your team's CI pipeline has a test that fails about 1 in 15 runs with no code changes. Nobody wants to spend a sprint chasing it, so it's been ignored for three weeks -- and now two more tests in the same suite are starting to flake too.

Prompt

Act as a senior test infrastructure engineer who specializes in diagnosing intermittent, non-deterministic CI test failures ("flaky tests").

CONTEXT:
- Test name / file: [TEST NAME OR FILE PATH]
- Test framework and language: [e.g. "pytest, Python" or "Jest, TypeScript"]
- Failure frequency: [e.g. "1 in 15 runs" or "roughly once a week, no clear pattern"]
- Failure logs from 3-5 recent failed runs (paste full stack traces / error output, not summaries): [PASTE FAILURE LOGS HERE, SEPARATED BY RUN]
- Recent changes to the test or the code it covers, if known: [DESCRIBE OR PASTE RELEVANT DIFF, OR WRITE "NONE KNOWN"]
- What the test is actually verifying (in plain English): [ONE-SENTENCE DESCRIPTION OF TEST INTENT]

TASK:
Analyze the failure patterns across the provided logs and produce ranked root-cause hypotheses. Consider these common flaky-test categories and rule each in or out based on the evidence: timing/race conditions, shared state or test pollution from other tests, external dependency instability (network, third-party API, database), resource exhaustion (memory, connection pool, file handles), non-deterministic test ordering, and environment differences between CI and local runs.

CONSTRAINTS:
- Do not simply conclude "the test is flaky" without committing to at least 2 specific, falsifiable hypotheses ranked by likelihood
- Every hypothesis must cite specific evidence from the pasted logs -- if the logs don't support a hypothesis, don't include it
- Clearly distinguish between issues safe to quarantine now and investigate later, versus issues that likely mask a real production bug and must be fixed before quarantining
- If the provided logs don't contain enough information to diagnose confidently, say exactly that, and specify precisely what additional logging or instrumentation to add before the next failure

OUTPUT FORMAT:
1. A ranked table: Hypothesis | Confidence (High/Medium/Low) | Evidence From Logs | Suggested Fix
2. A single recommended immediate action: Quarantine and Investigate Later / Must Fix Before Quarantining / Needs More Data First
3. If "Needs More Data First": the exact logging statements or CI configuration change to add so the next failure captures what's missing

Resultado

Diagnosis: test_checkout_confirms_payment_status (pytest, Python)

Failure frequency: ~1 in 12 CI runs, no clear time-of-day pattern.

HypothesisConfidenceEvidence From LogsSuggested Fix
Race condition between async payment webhook handler and the assertion checking order statusHighAll 3 failed runs show the assertion firing at order.status == 'pending' rather than 'confirmed' -- the webhook handler logs show it completing 40-180ms AFTER the assertion ran in 2 of 3 failuresReplace the fixed 100ms sleep before the assertion with an explicit poll-until-status-or-timeout helper (max 2s), and add a log line at the exact moment the webhook handler acquires its DB lock
Shared test database state from a preceding test in the same suiteMediumOne failure log shows an order ID that doesn't match the expected sequence, suggesting a prior test's order wasn't cleaned up -- but this only appears in 1 of 3 logs, so it's a contributing factor, not the primary causeAdd explicit teardown assertion verifying zero leftover orders before this test starts; run this test in isolation for 20 iterations to confirm whether it still flakes without the suite context
Third-party payment sandbox API latency spikeLowNo log evidence of elevated response times from the payment sandbox in any of the 3 failures -- ruled out based on available dataN/A -- not supported by current evidence

Recommended Immediate Action: Must Fix Before Quarantining

This is not safe to quarantine. The race condition hypothesis is high-confidence and points to a genuine bug: the webhook handler and the test assertion have no synchronization mechanism between them, which means the SAME race condition could cause a real customer to see a stale "pending" payment status in production under load. Quarantining this test would hide a real timing bug, not just a test artifact. Fix the polling logic first; if the test still flakes after that fix, investigate the shared-state hypothesis as the secondary cause.

Cada equipo de ingeniería acumula test flaky, y cada equipo desarrolla el mismo mal hábito en respuesta: alguien pulsa re-run, el test pasa la segunda vez, y todos siguen adelante sin saber por qué falló la primera. Ese hábito es corrosivo. Una vez que un equipo empieza a tratar los fallos de CI como ruido por defecto, una regresión genuina termina ocultándose dentro de ese ruido y se despliega a producción.


Este prompt fuerza una disciplina diferente. En lugar de aceptar un vago diagnóstico de "es flaky", exige que el modelo lea los registros de fallos reales de múltiples ejecuciones y se comprometa con al menos dos hipótesis falsables específicas, clasificadas por confianza, cada una respaldada por una línea concreta de evidencia de los logs en lugar de una suposición genérica. Las causas raíz más comunes son condiciones de carrera (Race Conditions), estado compartido de tests, inestabilidad de dependencias externas, agotamiento de recursos y deriva del entorno entre CI y local; el prompt recorre cada una sistemáticamente en lugar de saltar a la que resulte más familiar.


La parte más útil del resultado es el veredicto que la mayoría de los equipos omiten por completo: ¿es seguro poner esto en cuarentena y revisarlo después, o la inestabilidad revela en realidad un bug real que podría afectar a producción bajo las mismas condiciones? Una condición de carrera entre un manejador de Webhook asíncrono y una comprobación de estado, por ejemplo, no es solo un problema de test: es el mismo bug que un cliente real podría encontrar bajo carga. Poner ese test en cuarentena ocultaría un problema de producción detrás de una marca verde. Acertar con esa distinción, cada vez, es lo que separa a los equipos con una señal de CI fiable de los equipos que han dejado silenciosamente de confiar en su propio suite de tests.

testingci-cddebuggingsoftware-qualityflaky-tests
Compartir: