Inferensys

Prompt

Automated Test Case Selection for CI Runs Prompt Template

A practical prompt playbook for using Automated Test Case Selection for CI Runs Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

A practical guide for ML engineers and platform teams to decide when and how to deploy the automated test case selection prompt in CI pipelines.

This prompt is designed for ML engineers and platform teams who need to reduce CI pipeline duration without sacrificing regression detection. It selects a minimal, high-signal subset of test cases from a golden dataset by analyzing the prompt diff, historical failure patterns, and a defined risk profile. Use this when your full test suite takes too long to run on every commit and you need an automated, evidence-based way to choose which tests to execute. The ideal user has a curated golden dataset with labeled failure histories and a clear understanding of their risk tolerance for different types of prompt changes.

This is not a replacement for running the full suite on release candidates. It is a gating optimization for pre-merge and early-stage CI checks. Do not use this prompt when the prompt diff is trivial, such as a typo fix with no semantic impact, or when the golden dataset lacks historical failure data, as the selection logic depends on that signal. It is also inappropriate for safety-critical prompt changes where a missed regression could cause user harm; in those cases, run the full suite. The prompt works best when integrated into a CI workflow that can automatically execute the selected subset, collect results, and feed failure data back into the historical record for future selection accuracy.

Before wiring this into your pipeline, ensure your golden dataset includes per-case metadata: a unique ID, the prompt version it was last run against, a failure count, and a risk tag. The prompt expects these fields to weight its selection. Start by running it against a known prompt diff and manually reviewing the selected subset for face validity. If the selection misses a known high-risk area, adjust the risk profile or add explicit constraints. Once validated, automate the selection as a pre-merge gate, but always run the full suite on release candidates and log any regressions that the subset missed to improve future selections.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Understand the operational boundaries before embedding it into a CI pipeline.

01

Good Fit: High-Volume Regression Suites

Use when: you have a large golden dataset and CI runtime is a bottleneck. Why: the prompt reduces test execution time by selecting the most relevant cases. Guardrail: always run the full suite on merge to main to catch selection blind spots.

02

Bad Fit: Small or Immature Test Sets

Avoid when: your golden dataset has fewer than 50 cases or lacks historical failure data. Risk: the model has insufficient signal to prioritize and may skip critical regressions. Guardrail: use a static smoke test suite until the dataset matures.

03

Required Inputs

Must provide: a structured prompt diff, a golden dataset with historical pass/fail labels, and a risk profile. Risk: missing failure history causes random selection. Guardrail: validate input completeness with a pre-flight schema check before invoking the prompt.

04

Operational Risk: Selection Bias

What to watch: the model may overfit to recent failure patterns and skip new failure modes introduced by the prompt change. Guardrail: inject a fixed 10% random sample of the golden dataset into every CI run to maintain coverage diversity.

05

Operational Risk: Non-Deterministic Selection

What to watch: model temperature can cause different test subsets across runs, making CI results non-reproducible. Guardrail: set temperature to 0 and log the selected test case IDs as CI artifacts for auditability.

06

When to Escalate

Avoid using this prompt for security patches, safety policy changes, or PII-handling modifications. Risk: selection errors in these domains have unacceptable blast radius. Guardrail: these changes must trigger the full regression suite with a mandatory human approval gate.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for selecting the most relevant test cases from a golden dataset based on a prompt diff, historical failure patterns, and risk profile.

This template is designed to be pasted directly into your test orchestrator or evaluation harness. It instructs the model to act as a CI/CD test selection engine, consuming a prompt diff, a golden dataset manifest, and a risk profile to output a prioritized, minimal subset of test cases. The goal is to maximize regression detection while minimizing CI pipeline runtime. All placeholders are enclosed in square brackets and must be replaced by your application logic before the model call.

text
You are an automated test case selection engine for a CI/CD pipeline that evaluates prompt changes. Your task is to select the most relevant test cases from a golden dataset to run against a proposed prompt modification. Your selection must minimize total execution time while maximizing the probability of detecting a regression.

## INPUTS
- **Prompt Diff:** [PROMPT_DIFF]
- **Golden Dataset Manifest:** [DATASET_MANIFEST]
- **Historical Failure Map:** [FAILURE_MAP]
- **Risk Profile:** [RISK_PROFILE]

## SELECTION RULES
1. Analyze the [PROMPT_DIFF] to identify which instruction blocks, constraints, or output schemas were added, removed, or modified.
2. Map these changes to the test cases in the [DATASET_MANIFEST] that exercise those specific behaviors.
3. Cross-reference with the [FAILURE_MAP] to prioritize test cases that have historically detected regressions for similar changes.
4. Apply the [RISK_PROFILE] to adjust the selection: a "high-risk" profile should include more edge cases and adversarial examples, while a "low-risk" profile should favor a minimal smoke-test subset.
5. If the diff is empty or unparseable, default to the "sanity" subset defined in the [DATASET_MANIFEST].

## OUTPUT FORMAT
Return a valid JSON object with the following schema:
{
  "selected_test_ids": ["string"],
  "selection_rationale": "string",
  "estimated_runtime_seconds": number,
  "coverage_gaps": ["string"]
}

## CONSTRAINTS
- Do not select more than [MAX_TEST_CASES] test cases.
- Do not select test cases tagged as "manual" or "destructive" in the manifest.
- If the [RISK_PROFILE] is "critical", you must include all test cases tagged as "security" or "safety".
- Provide a clear, one-line rationale for each selected test case in the `selection_rationale` field.

To adapt this template, replace the placeholders with data from your pipeline context. The [PROMPT_DIFF] should be a unified diff of the prompt text. The [DATASET_MANIFEST] should be a structured list of test case IDs, descriptions, tags, and estimated runtimes. The [FAILURE_MAP] is a historical record linking past prompt changes to the test cases that caught the regression. The [RISK_PROFILE] is a string like "low", "medium", "high", or "critical" set by your release process. Before deploying this prompt, validate that the model's JSON output strictly conforms to the schema; a parsing failure should trigger a retry or fallback to a default test suite. For high-risk deployments, always log the selection_rationale for human review to ensure no critical coverage gaps were introduced by the model's selection logic.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Automated Test Case Selection prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[PROMPT_DIFF]

Unified diff or side-by-side comparison of the old and new prompt versions being tested

--- a/system_prompt.txt +++ b/system_prompt.txt @@ -4,7 +4,7 @@ -You are a helpful assistant. +You are a precise technical assistant.

Must be non-empty and contain at least one changed line. Parse check: valid unified diff format. Reject if diff is empty or only whitespace changes.

[GOLDEN_DATASET]

Full set of test cases with inputs and expected outputs used for regression testing

[ {"id": "tc-001", "input": "What is 2+2?", "expected_output": "4"}, {"id": "tc-002", "input": "Explain recursion.", "expected_output": "A function that calls itself..."} ]

Must be a valid JSON array with at least 10 entries. Each entry requires id, input, and expected_output fields. Schema check: validate against golden dataset schema before use. Reject if fewer than minimum test cases.

[HISTORICAL_FAILURES]

Log of previous test failures mapping test case IDs to failure frequency and last failure timestamp

[ {"test_case_id": "tc-042", "failure_count": 7, "last_failure": "2025-03-15T14:22:00Z"}, {"test_case_id": "tc-118", "failure_count": 2, "last_failure": "2025-03-10T09:05:00Z"} ]

May be empty array if no history exists. Each entry requires test_case_id, failure_count as integer >= 0, and last_failure as ISO 8601 timestamp. Parse check: valid JSON array. Null allowed for first-time runs.

[RISK_PROFILE]

Risk weights for test case categories indicating business criticality of different workflow areas

{ "classification_accuracy": 0.9, "refusal_behavior": 0.8, "output_formatting": 0.3, "latency_sensitivity": 0.5 }

Must be a valid JSON object with at least one category key. All values must be floats between 0.0 and 1.0. Schema check: reject if any weight exceeds 1.0 or is negative. Default weights applied if category missing.

[MAX_RUNTIME_MS]

Maximum allowed test execution time in milliseconds for the CI run

300000

Must be a positive integer. Parse check: integer > 0. Reject if value is below 10000 (10 seconds) as insufficient for meaningful selection. Typical CI budgets range from 60000 to 600000.

[SELECTION_STRATEGY]

Strategy preference for test selection: coverage-maximizing, risk-weighted, failure-history-prioritized, or balanced

risk-weighted

Must be one of four enum values: coverage-maximizing, risk-weighted, failure-history-prioritized, balanced. Enum check: reject any other value. Default to balanced if not specified.

[MIN_COVERAGE_RATIO]

Minimum fraction of risk-weighted test categories that must be represented in the selected subset

0.6

Must be a float between 0.0 and 1.0. Parse check: valid float. Reject if value is 0.0 as it would allow empty selection. Typical values range from 0.4 to 0.8.

[OUTPUT_SCHEMA]

Expected JSON schema for the selected test case list output

{ "type": "array", "items": { "type": "object", "properties": { "test_case_id": {"type": "string"}, "selection_reason": {"type": "string"}, "risk_category": {"type": "string"} }, "required": ["test_case_id", "selection_reason"] } }

Must be a valid JSON Schema object. Schema check: validate against JSON Schema meta-schema. Reject if schema is not parseable. Required fields must include test_case_id at minimum.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the test case selection prompt into a CI pipeline with validation, retries, and fallback logic.

The automated test case selection prompt is designed to sit at the very beginning of your CI evaluation stage, acting as a dynamic filter between a full golden dataset and the test runner. Instead of executing every test case on every commit, the harness calls this prompt with the prompt diff, historical failure logs, and a risk profile. The model returns a prioritized subset of test case IDs. Your CI orchestrator then reads that subset and executes only those evaluations, dramatically reducing pipeline duration while preserving regression detection power. The harness must treat the model's output as a recommendation that can be overridden by hard rules—for example, you should always include a small set of safety-critical test cases regardless of the model's selection.

Wire the prompt into your CI platform (GitHub Actions, GitLab CI, Jenkins) as a gate step that runs before the eval job matrix. The step should: (1) compute the prompt diff between the current commit and the last released version using git diff or your prompt registry API; (2) fetch the last N CI run results and failure counts per test case from your test database or artifact store; (3) assemble the risk profile from a config file that tags test cases by criticality, flakiness score, and domain; (4) call the LLM with these inputs and a strict output schema requiring a JSON array of test case IDs plus a confidence score per selection. Validate the response immediately: reject outputs that reference non-existent test case IDs, exceed a maximum selection count, or omit mandatory safety cases. If validation fails, retry once with the validation errors injected into the [CONSTRAINTS] block. If the retry also fails, fall back to a static subset defined in your risk profile config—never let a malformed LLM response block the pipeline.

Model choice matters here. This is a classification and ranking task that benefits from models with strong instruction-following and JSON mode support. GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro are appropriate. Avoid smaller or older models that may hallucinate test case IDs or ignore the output schema. Set temperature=0 to maximize deterministic selection. Log every prompt call, the full response, validation results, and the final test subset to your observability platform. This trace is essential for debugging false negatives—when a regression slips through because the selector omitted the revealing test case. Over time, feed these misses back into the risk profile and historical failure data to improve selection accuracy. Do not use this prompt for compliance-mandated test suites where every case must run; the harness should have a bypass flag that forces full-suite execution for release branches or audit runs.

IMPLEMENTATION TABLE

Expected Output Contract

Define the exact fields, types, and validation rules the prompt must return. Use this contract to build a parser, validator, or assertion harness in your CI pipeline.

Field or ElementType or FormatRequiredValidation Rule

selected_test_cases

Array of objects

Array length must be >= 1. Each element must match the selected_case schema.

selected_test_cases[].test_id

String

Must match a valid test_id from the provided [GOLDEN_DATASET] input. Regex: ^[A-Za-z0-9_-]+$

selected_test_cases[].priority_score

Number (0.0 - 1.0)

Must be a float between 0.0 and 1.0 inclusive. Higher score indicates higher selection priority.

selected_test_cases[].selection_rationale

String

Must be a non-empty string <= 280 characters. Must reference at least one factor from [SELECTION_CRITERIA].

excluded_test_cases

Array of objects

If present, each element must match the excluded_case schema. Null or empty array is allowed.

excluded_test_cases[].test_id

String

Must match a valid test_id from [GOLDEN_DATASET]. Must NOT appear in selected_test_cases.

excluded_test_cases[].exclusion_reason

String

Must be a non-empty string <= 280 characters. Must reference a valid exclusion category: 'low_risk', 'redundant', 'out_of_scope', or 'timeout_risk'.

selection_summary

Object

Must contain total_selected (Integer), total_excluded (Integer), and coverage_score (Number 0.0-1.0) fields.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using an LLM to select test cases for CI runs, and how to guard against it.

01

Selection Based on Stale Risk Profiles

What to watch: The model relies on a historical failure pattern or risk profile that is no longer accurate, causing it to skip tests for newly unstable modules. Guardrail: Always inject the most recent CI failure logs and code-change summaries into the prompt context. Implement a freshness check that forces a full suite run if the risk profile data is older than a defined threshold.

02

Ignoring Cross-Module Side Effects

What to watch: The model selects tests strictly based on the files changed in the diff, missing integration or end-to-end tests that validate contracts between the modified module and its downstream consumers. Guardrail: Include a dependency graph or architecture map in the system prompt. Add a hard rule that any selected unit test must also trigger at least one corresponding contract or integration test for its known dependents.

03

Hallucinating Non-Existent Test Cases

What to watch: The model confidently outputs test names or paths that don't exist in the repository, causing the CI orchestrator to fail with a 'test not found' error. Guardrail: Constrain the model's output to a strict JSON schema that requires exact test_path and test_name fields. Validate the output against the actual test registry before executing the run, and retry with a stricter prompt if a mismatch is detected.

04

Over-Optimizing for Speed Over Safety

What to watch: The model becomes too aggressive in pruning tests to minimize CI runtime, dropping high-signal tests that have a moderate but non-zero probability of catching a regression. Guardrail: Implement a two-tier selection strategy. Use the prompt for a 'smoke test' tier but enforce a separate, non-negotiable 'safety net' tier of critical path tests that always run, regardless of the model's risk assessment.

05

Misinterpreting the Prompt Diff

What to watch: The model fails to correctly parse a complex code diff, mistaking a refactor for a logic change (or vice versa), leading to irrelevant test selection. Guardrail: Pre-process the diff to summarize changed function signatures and logic blocks before passing it to the model. Use a separate evaluation step to check if the selected tests actually cover the modified lines of code, flagging low-coverage selections for human review.

06

Catastrophic Forgetting of Edge Cases

What to watch: The model systematically deprioritizes historically flaky or rare edge-case tests because they don't match the primary risk pattern of the current diff, allowing brittle regressions to accumulate. Guardrail: Maintain a 'flaky but critical' test manifest. Inject a specific instruction to always include a random sampling of these edge-case tests in every CI run, ensuring they receive periodic execution regardless of the automated selection logic.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality and safety of the test case selection output before integrating it into a CI/CD pipeline. Each criterion should be checked programmatically or via LLM-as-judge before the selected test list is used to gate a deployment.

CriterionPass StandardFailure SignalTest Method

Risk Coverage

At least one test case is selected for every high-risk module identified in [RISK_PROFILE].

A high-risk module has zero associated test cases in the output.

Parse the output list and cross-reference module tags against the [RISK_PROFILE] input. Flag any high-risk module with count 0.

Diff Relevance

Every selected test case maps to at least one modified instruction, tool, or output schema field in [PROMPT_DIFF].

A selected test case has no traceable link to any change in the diff.

For each selected case, require a non-empty diff_relevance field. Validate that the referenced diff section exists in [PROMPT_DIFF].

Historical Failure Inclusion

All test cases tagged with a historical failure count above the threshold in [CONSTRAINTS] are included.

A historically flaky test case is missing from the selection.

Sort [HISTORICAL_FAILURE_DATA] by failure count. Verify that every case above the threshold appears in the output list.

Budget Compliance

The total estimated runtime of selected tests does not exceed the [MAX_RUNTIME_MS] constraint.

The sum of estimated_runtime_ms for selected tests exceeds the budget.

Calculate the sum of the estimated_runtime_ms field for all selected test cases. Assert sum <= [MAX_RUNTIME_MS].

Output Schema Validity

The output is valid JSON conforming to [OUTPUT_SCHEMA] and contains no null required fields.

JSON parsing fails or a required field like test_case_id is missing or null.

Validate the raw output string against the [OUTPUT_SCHEMA] JSON Schema. Reject on parse error or schema violation.

Selection Justification

Every selected test case includes a non-empty justification string that references specific evidence from the diff or risk profile.

A selected test case has an empty, generic, or hallucinated justification.

Use an LLM judge to check that each justification string contains a concrete reference to a diff section or risk entry. Flag any that are generic.

Exclusion Justification

Any test case from the full [GOLDEN_DATASET] that is not selected has a brief exclusion reason provided if required by [CONSTRAINTS].

A high-priority test case is excluded without an exclusion_reason field.

If [CONSTRAINTS] requires exclusion reasons, compute the set difference between the full dataset and the selected set. Assert that every excluded case has a non-empty exclusion_reason.

Deterministic Reproducibility

Running the prompt with the same inputs and a temperature of 0 produces an identical list of test case IDs.

Two runs with temperature=0 produce different selections or ordering.

Execute the prompt twice with temperature=0 and identical inputs. Assert that the sorted list of selected test_case_ids is identical between runs.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a small golden dataset of 20-50 cases. Replace [GOLDEN_DATASET] with a flat JSON array of test cases. Simplify [RISK_PROFILE] to a single sentence like "High risk: payment flows." Remove [HISTORICAL_FAILURE_PATTERNS] if you don't have them yet. Run the prompt and manually review the selection rationale before trusting it.

Watch for

  • The model selecting too few or too many tests without justification
  • Over-indexing on recent failures while ignoring coverage gaps
  • No explanation of why specific tests were excluded
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.