AI › AI Tools

Building a CI regression gate with Promptfoo assertions

Separate JSON schema checks from cross-field refund rules in Promptfoo 0.126.0, then control CI blocking with exit codes (0/100/1) and pass-rate thresholds.

Building a CI regression gate with Promptfoo assertions

An LLM can return valid JSON that still breaks business rules, such as assigning a non-zero refund to a denied order or exceeding the original payment amount. Using Promptfoo 0.126.0, you can separate is-json schema validation from cross-field JavaScript assertions and wire CLI exit codes (0, 100, 1) and pass-rate thresholds into a deterministic CI regression gate.

All commands, outputs, and captures below were verified locally on macOS (Apple Silicon) with Node.js v22.23.3, npm 10.9.9, and promptfoo@0.126.0 using echo provider fixtures with no external LLM calls. The GitHub Actions workflow YAML is a template based on Promptfoo’s official documentation; remote PR comment bots were not run in this local verification.

Why JSON schema checks alone miss business regressions

Structured output constraints eliminate most JSON syntax errors, yet production bugs still slip through when a response matches the schema types while violating domain invariants.

Consider an order refund decision endpoint that returns this JSON contract:

1
2
3
4
5
6
7
{
  "decision": "approve",
  "refund_amount": 30000,
  "currency": "KRW",
  "policy_id": "POL-REFUND-7D",
  "reason": "Cancelled within 7-day window before shipment."
}

A static JSON Schema can verify that decision is one of approve, deny, or escalate and that refund_amount is a non-negative number. It can’t easily express cross-field or input-dependent invariants tied to each test case:

  • If decision is "deny", refund_amount must be 0.
  • If decision is "approve", refund_amount must be greater than 0 and no higher than the test case’s vars.orderAmount.
  • policy_id must match the expected policy code (vars.expectedPolicyId) for that scenario.

Relying only on prompt instructions or delegating these checks to an LLM-as-a-judge (llm-rubric) adds latency, cost, and non-deterministic flakiness to pull requests. Keeping structural and domain invariants in deterministic assertions gives your CI gate a fast, repeatable first line of defense.

Check layerPromptfoo assertion typeWhat it verifiesCost & repeatabilityBest fit
Structure contractis-json (+ JSON Schema)Required keys, types, enum, additionalProperties: falseZero cost · 100% deterministicSafe JSON parsing, blocking stray debug fields
Domain invariantsjavascript (file://*.cjs)Cross-field rules, dynamic limits from context.varsZero cost · 100% deterministicRefund caps, authorization rules, policy codes
Literal / patterncontains, regexRequired keywords or forbidden patternsZero cost · 100% deterministicQuick string and blocklist checks
Tone / prose qualityllm-rubric, model-graded-closedqaSummary faithfulness, tone, completenessModel call cost · can varyOpen-ended quality reviews (avoid as sole merge blocker)

Unit-testing schema and cross-field assertions with the echo provider

Before connecting a real model, verify that your assertion code catches the exact failures you care about. Promptfoo’s built-in echo provider returns the rendered prompt directly as output, letting you unit-test valid and broken fixtures in milliseconds with zero API cost.

Start with refund.schema.json. Setting additionalProperties: false catches regressions where extra debug keys leak into the payload.

1
2
3
4
5
6
7
8
9
10
11
12
13
// refund.schema.json
{
  "type": "object",
  "additionalProperties": false,
  "required": ["decision", "refund_amount", "currency", "policy_id", "reason"],
  "properties": {
    "decision": { "type": "string", "enum": ["approve", "deny", "escalate"] },
    "refund_amount": { "type": "number", "minimum": 0 },
    "currency": { "type": "string", "enum": ["KRW", "USD"] },
    "policy_id": { "type": "string", "minLength": 1 },
    "reason": { "type": "string", "minLength": 5 }
  }
}

Next, write an external JavaScript assertion in refund-rules.cjs that compares the parsed JSON against context.vars. Returning { pass, score, reason } records the exact failure message in both the web UI and the JSON report.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// refund-rules.cjs
module.exports = (output, context) => {
  let data;
  try {
    data = JSON.parse(output);
  } catch (err) {
    return { pass: false, score: 0, reason: `Invalid JSON: ${err.message}` };
  }

  const vars = context.vars || {};
  const orderAmount = Number(vars.orderAmount);
  const expectedPolicyId = vars.expectedPolicyId;
  const failures = [];

  if (data.decision === 'deny' && data.refund_amount !== 0) {
    failures.push(`denied decision must have refund_amount=0 (got ${data.refund_amount})`);
  }

  if (data.decision === 'approve') {
    if (data.refund_amount <= 0) {
      failures.push(`approved decision must have refund_amount > 0 (got ${data.refund_amount})`);
    }
    if (!Number.isNaN(orderAmount) && data.refund_amount > orderAmount) {
      failures.push(`refund_amount (${data.refund_amount}) exceeds orderAmount (${orderAmount})`);
    }
  }

  if (expectedPolicyId && data.policy_id !== expectedPolicyId) {
    failures.push(`policy_id=${JSON.stringify(data.policy_id)} (expected ${JSON.stringify(expectedPolicyId)})`);
  }

  if (failures.length > 0) {
    return { pass: false, score: 0, reason: failures.join('; ') };
  }

  return {
    pass: true,
    score: 1,
    reason: `Business invariants satisfied (${data.decision}, ${data.refund_amount} ${data.currency}, ${data.policy_id})`,
  };
};

Wire both assertions into defaultTest.assert inside promptfooconfig.yaml and assign distinct metric names (JSON schema and Refund rules). Separating metric names keeps schema breakage and business-rule failures cleanly split in the summary totals.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# promptfooconfig.yaml
description: "Order refund policy deterministic assertion gate (4 fixtures)"

prompts:
  - "{{rawOutput}}"

providers:
  - id: echo
    label: "echo-fixture"

defaultTest:
  assert:
    - type: is-json
      value: file://refund.schema.json
      metric: JSON schema
    - type: javascript
      value: file://refund-rules.cjs
      metric: Refund rules

tests:
  - description: "Valid approval"
    vars:
      orderAmount: 30000
      expectedPolicyId: "POL-REFUND-7D"
      rawOutput: '{"decision":"approve","refund_amount":30000,"currency":"KRW","policy_id":"POL-REFUND-7D","reason":"Cancelled within 7-day window before shipment."}'
  - description: "Extra field schema error"
    vars:
      orderAmount: 30000
      expectedPolicyId: "POL-REFUND-7D"
      rawOutput: '{"decision":"approve","refund_amount":30000,"currency":"KRW","policy_id":"POL-REFUND-7D","reason":"Cancelled within 7-day window.","internal_note":"debug-trace-123"}'
  - description: "Denied with non-zero refund"
    vars:
      orderAmount: 30000
      expectedPolicyId: "POL-DIGITAL-FINAL"
      rawOutput: '{"decision":"deny","refund_amount":15000,"currency":"KRW","policy_id":"POL-DIGITAL-FINAL","reason":"Digital license key already redeemed."}'
  - description: "Refund exceeds order total"
    vars:
      orderAmount: 30000
      expectedPolicyId: "POL-REFUND-7D"
      rawOutput: '{"decision":"approve","refund_amount":45000,"currency":"KRW","policy_id":"POL-REFUND-7D","reason":"Full refund plus compensation credit."}'

Running npx promptfoo eval -c promptfooconfig.yaml --no-cache -o results-c7.json and opening promptfoo view splits the four fixtures into exact per-metric outcomes:

FixtureJSON schemaRefund rulesRecorded reason (componentResults[].reason)
Valid approvalPASSPASSBusiness invariants satisfied (approve, 30000 KRW, POL-REFUND-7D)
Extra field schema errorFAILPASSJSON does not conform to the provided schema. Errors: data must NOT have additional properties
Denied with non-zero refundPASSFAILdenied decision must have refund_amount=0 (got 15000)
Refund exceeds order totalPASSFAILrefund_amount (45000) exceeds orderAmount (30000)

Promptfoo web UI showing four echo fixtures with separated JSON schema 75% and Refund rules 50% metric scores Figure 1. Local promptfoo view output for the four echo fixtures. The header aggregates JSON schema 75.00% (3.00/4.00) and Refund rules 50.00% (2.00/4.00) separately, while the visible rows isolate the extra-property schema error from the denied-refund business rule violation.

Extra field schema error fails only JSON schema because of internal_note while still passing Refund rules. The two business-rule fixtures pass JSON schema cleanly and fail only Refund rules with explicit diagnostics.

CLI exit codes (0, 100, 1) and componentResults JSON reports

Automated CI gates depend on predictable exit codes. Testing each path in local Bash with promptfoo@0.126.0 clarifies where exit code 1 stops and exit code 100 begins.

flowchart TD
    A["Run promptfoo eval"] --> B{"Config file loaded\nand parsed?"}
    B -->|"No (missing file / bad YAML)"| C["Exit code 1\n(eval never starts)"]
    B -->|"Yes"| D["Run tests & assertions\n(missing assertion file logs ERROR)"]
    D --> E{"Pass rate >= threshold\nor FAILED_TEST_EXIT_CODE=0?"}
    E -->|"Yes"| F["Exit code 0\n(CI passes)"]
    E -->|"No"| G["Exit code 100\n(CI blocks)"]

One detail stood out during testing. It’s easy to assume that referencing a missing JavaScript assertion file (file://does-not-exist.cjs) inside a test case will abort with exit code 1. In promptfoo@0.126.0, the evaluation has already started, so that case is recorded as a per-test [ERROR] (1 error (100%)) and the CLI exits with 100. Exit code 1 occurs when the CLI fails before evaluation starts, such as passing -c nonexistent-config.yaml or invalid YAML syntax.

Run condition (promptfoo@0.126.0)CLI summary outputExit code ($?)bash -e (set -e) behavior
--filter-pattern "Valid approval" (all pass)1 passed (100%) 0 failed (0%) 0 errors (0%)0Continues to next step
Full 4-fixture run (3 assertion failures)1 passed (25.00%) 3 failed (75.00%) 0 errors (0%)100Aborts immediately
Missing assertion file (file://does-not-exist.cjs)Per-test [ERROR], 1 error (100%)100Aborts immediately
Missing config file (-c nonexistent-config.yaml)Error: No configuration file found at nonexistent-config.yaml1Aborts immediately

Because both assertion regressions and missing assertion scripts return 100, CI alert scripts should inspect the -o results.json output alongside $?. Specifically, check prompts[].metrics.testErrorCount for runtime/file errors and gradingResult.componentResults for per-metric failures:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{
  "prompts": [
    {
      "provider": "echo-fixture",
      "metrics": {
        "testPassCount": 1,
        "testFailCount": 3,
        "testErrorCount": 0,
        "namedScores": { "JSON schema": 3, "Refund rules": 2 }
      }
    }
  ],
  "results": [
    {
      "success": true,
      "gradingResult": {
        "pass": true,
        "componentResults": [
          {
            "pass": true,
            "score": 1,
            "assertion": { "type": "is-json", "metric": "JSON schema" }
          },
          {
            "pass": true,
            "score": 1,
            "reason": "Business invariants satisfied (approve, 30000 KRW, POL-REFUND-7D)",
            "assertion": { "type": "javascript", "metric": "Refund rules" }
          }
        ]
      }
    }
  ]
}

Controlling CI blocking with pass-rate thresholds and advisory mode

Not every evaluation suite belongs behind a strict 100% merge blocker. Experimental prompt branches or nightly suites running non-deterministic models often need a minimum pass rate or a non-blocking advisory run that uploads a report without failing the job.

In promptfoo@0.126.0, two environment variables control this behavior:

  • PROMPTFOO_PASS_RATE_THRESHOLD: minimum passing percentage on a 0–100 scale (default 100). Pass 75, not 0.75.
  • PROMPTFOO_FAILED_TEST_EXIT_CODE: overrides the exit code when tests fail. Setting it to 0 runs the suite in advisory (non-blocking) mode while still recording every failure in the output file.

I verified both variables against a 4-fixture suite (promptfooconfig-75pct.yaml) where 3 cases pass and 1 fails (75.00% pass rate):

Environment variable (75.00% passing suite)Exit code ($?)Observed behavior
Default (unset)100Fails the step due to 1 failing case
PROMPTFOO_PASS_RATE_THRESHOLD=750Passes because 75.00% >= 75%
PROMPTFOO_PASS_RATE_THRESHOLD=80100Prints Pass rate 75.00% is below the threshold of 80% and blocks
PROMPTFOO_FAILED_TEST_EXIT_CODE=00Logs 1 failure in the report but exits 0 (advisory mode)

Terminal output showing Promptfoo 0.126.0 exit codes 0, 100, and 1 alongside pass-rate threshold 75, 80, and advisory mode runs Figure 2. Local Bash verification of promptfoo@0.126.0 exit codes (0, 100, 1) plus PROMPTFOO_PASS_RATE_THRESHOLD (75 → 0, 80 → 100) and PROMPTFOO_FAILED_TEST_EXIT_CODE=0 on the 75% passing suite.

Here is a GitHub Actions workflow template based on Promptfoo’s official CLI and CI documentation, using the exact commands verified locally:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# .github/workflows/prompt-regression-gate.yml (official docs template)
name: Prompt Regression Gate

on:
  pull_request:
    paths:
      - "prompts/**"
      - "evals/**"

jobs:
  deterministic-gate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: "22"

      - name: Install pinned Promptfoo
        working-directory: evals
        run: npm ci

      - name: Run deterministic refund policy gate
        working-directory: evals
        env:
          # Keep payment and refund invariants at 100%
          PROMPTFOO_PASS_RATE_THRESHOLD: "100"
        run: |
          set -euo pipefail
          npx promptfoo eval -c promptfooconfig.yaml --no-cache -o results.json

      - name: Upload evaluation report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: promptfoo-eval-results
          path: evals/results.json

Keep if: always() on the artifact upload step so failing PRs (exit code 100) still preserve results.json for inspection.

Production caveats and checklist

Never lower PROMPTFOO_PASS_RATE_THRESHOLD below 100 for suites that guard payment limits, refund policies, authorization checks, or PII rules. Thresholds like 75 or 80 fit large statistical quality benchmarks; mixing a critical invariant into a thresholded suite lets a single severe regression ship unnoticed as long as the aggregate percentage stays green.

In promptfoo@0.126.0, a broken assertion file path inside a test exits with 100 and increments testErrorCount, not exit code 1. Check testErrorCount > 0 in your CI post-processing so broken test wiring isn’t misread as a model regression.

Deterministic assertions also have a clear boundary: they validate payload shape and domain math quickly, but they don’t measure tone, clarity, or open-ended summarization quality. Split your pipeline into a fast deterministic PR gate (is-json + JS invariants at 100% threshold) and a separate scheduled quality evaluation suite.

Before enabling the gate on a repository, confirm these four items:

  • Pin the exact promptfoo version in package.json and pass --no-cache in CI so stale cache entries never mask regressions.
  • Assign separate metric names to is-json and javascript assertions so schema breakage and domain-rule violations stay distinct in reports.
  • Unit-test your assertions with the echo provider against valid, boundary, and broken fixtures before wiring a live model.
  • Preserve results.json with if: always() and inspect both testErrorCount and componentResults when a run fails.

References

Learn how to validate LLM outputs using deterministic logical tests including exact matching, regex patterns, JSON/XML validation, and text similarity metrics
Write JavaScript assertions to validate LLM outputs, return custom scores, and run asynchronous checks. Use inline expressions or scripts in your eval config.
Explore promptfoo CLI commands for LLM testing: run evals, generate datasets, scan models for vulnerabilities, and automate workflows from the terminal.
Automate LLM prompt testing in CI/CD with GitHub Actions integration. Compare prompt changes, view diffs, and analyze results directly in pull requests using promptfoo.
This post is licensed under CC BY 4.0 by the author.