Skip to the page

Guides · Models & ML

Evals

Compare candidate checkpoints against your serving model on test cases in CI, score shadow traffic in the background and promote production misses into regression tests.

In the schema
ext::napalm::Job

What you’ll build#

You will verify that a candidate model version matches or beats the active serving version before promotion across four stages.

Golden set
Saved EvalCase rows holding exact input features and expected verdicts.
CI regression gate
A harness scores a candidate, records every EvalResult and fails the build on any lost case.
Shadow scoring
The candidate scores live requests beside the serving version without exposing candidate verdicts to users.
Growing coverage
Any misclassified production prediction promotes directly into EvalCase with the exact features sent.

Before you start#

This guide builds on Model serving, whose schema declares EvalCase, EvalResult and Prediction and whose handler records each prediction alongside its input features. You need the same service key and a script that calls a named model version.

StageExecutionSignal
Golden setCI scores every saved EvalCase with the candidate.SignalVerifies zero regressions on known edge cases.
ShadowA background job re-scores live predictions with the candidate.SignalMeasures agreement and latency on production inputs.
ServingPromoting updates Slot.serving to the candidate.SignalTags every live prediction with the active version.

Score the golden set#

Three deployed queries drive golden-set evaluation. First, evalCases loads every saved test case with its frozen input features and expected verdict:

dbschema/queries/evalCases.edgeql
select EvalCase { id, name, features, expected }order by .name

recordEvalResults replaces prior verdicts for that candidate in one atomic statement so interrupted runs never leave partial scores behind:

dbschema/queries/recordEvalResults.edgeql
for result in json_array_unpack(<json>$results) union (  insert EvalResult {    eval_case := <EvalCase><uuid>result['case'],    model := <str>$model,    verdict := <str>result['verdict'],    latency_ms := <int32>result['latency_ms'],  }  unless conflict on ((.eval_case, .model))  else (    update EvalResult set {      verdict := <str>result['verdict'],      latency_ms := <int32>result['latency_ms'],    }  ))

evalCompare joins both versions’ verdicts per case and lists every case where the serving model passed and the candidate regressed:

dbschema/queries/evalCompare.edgeql
with  mine := (select EvalResult filter .model = <str>$candidate),  theirs := (select EvalResult filter .model = <str>$serving),select {  total := count(mine),  passed := count(mine filter .passed),  serving_passed := count(theirs filter .passed),  mean_ms := (math::mean(mine.latency_ms) if count(mine) > 0 else 0.0),  regressions := (    select mine { name := .eval_case.name, verdict, expected := .eval_case.expected }    filter not .passed and .eval_case in (select theirs filter .passed).eval_case  ),}

Gate promotions in CI#

Static pass-rate thresholds let a candidate regress on critical edge cases whenever new wins mask old losses. Fail the CI gate whenever the candidate loses a case that serving passes, or drops in total pass count.

Pairwise regression gate

CI compares candidate verdicts case by case against the active serving version.

Run a short Python harness that scores every EvalCase, records the batch and exits non-zero on any regression:

evals/golden.py
# evals/golden.pyimport osimport sysimport time import httpx from model import score  # your model call: score(version, features) -> verdict candidate, serving = sys.argv[1], sys.argv[2]headers = {"Authorization": f"Bearer {os.environ['NAPALM_KEY']}"} with httpx.Client(base_url="https://notes.napalmdata.com", headers=headers, timeout=60) as napalm:    def call(name: str, **variables):        return napalm.post(f"/query/{name}", json={"variables": variables}).raise_for_status().json()["data"]     results = []    for case in call("evalCases"):        started = time.monotonic()        verdict = score(candidate, case["features"])        results.append({            "case": case["id"],            "verdict": verdict,            "latency_ms": round((time.monotonic() - started) * 1000),        })    call("recordEvalResults", model=candidate, results=results)     [compared] = call("evalCompare", candidate=candidate, serving=serving) for lost in compared["regressions"]:    print(f"lost {lost['name']}: said {lost['verdict']}, expected {lost['expected']}")print(f"{candidate}: {compared['passed']} of {compared['total']}, {serving}: {compared['serving_passed']}") # Fail on any regression against the serving version or a lower total pass count.sys.exit(1 if compared["regressions"] or compared["passed"] < compared["serving_passed"] else 0)

Invoke the harness in your workflow with a service key stored in CI secrets:

In CI
# .github/workflows/evals.yml- name: Score the golden set  env:    NAPALM_KEY: ${{ secrets.NAPALM_KEY }}  run: python evals/golden.py v5 v4

Shadow a candidate on live traffic#

A golden set covers only the cases you already anticipated. Setting a candidate on Slot.shadow queues a background job alongside every live prediction so the candidate scores real requests asynchronously without adding caller latency. The shadowScore gatekeeper query loads the served prediction’s frozen features alongside the active shadow version:

dbschema/queries/shadowScore.edgeql
select Prediction {  id,  features,  claim: { id },  candidate := <str>$model,}filter .id = <uuid>$prediction and not exists .shadow_of

Attach a shadowScore action handler that calls the candidate model and records the shadow verdict:

app/actions/[action]/route.ts
// app/actions/[action]/route.ts, beside scoreClaimasync shadowScore(call) {  type Served = { id: string; features: Record<string, unknown>; claim: { id: string }; candidate: string }  const [served] = call.rows as Served[]  const model = served.candidate   const scored = await fetch(`${process.env.MODEL_URL}/v1/predict`, {    method: 'POST',    headers: { Authorization: `Bearer ${process.env.MODEL_KEY}`, 'Content-Type': 'application/json' },    body: JSON.stringify({ model, features: served.features }),  })  if (!scored.ok) throw new Error(`The model answered ${scored.status}`)  const { score, verdict } = (await scored.json()) as { score: number; verdict: string }   const napalm = await call.db()  const recorded = await napalm.fetch('https://notes.napalmdata.com/query/recordShadow', {    method: 'POST',    headers: { 'Content-Type': 'application/json' },    body: JSON.stringify({      variables: { prediction: served.id, claim: served.claim.id, model, features: served.features, score, verdict },    }),  })  if (!recorded.ok) throw new Error(`The shadow answer wasn't recorded: ${recorded.status}`)  return { verdict }},

recordShadow inserts a linked Prediction row pointing back to the served prediction via shadow_of:

dbschema/queries/recordShadow.edgeql
insert Prediction {  claim := <Claim><uuid>$claim,  model := <str>$model,  status := PredictionStatus.Completed,  features := <json>$features,  score := <float64>$score,  verdict := <str>$verdict,  shadow_of := <Prediction><uuid>$prediction,}

Running shadow evaluation through background jobs and linked rows preserves three production invariants:

Zero caller latency
The shadow job runs after the caller receives the served answer, so a slow or failing candidate costs users nothing.
Hidden from callers
Each shadow Prediction links to the served prediction via shadow_of, and the claimant’s read policy excludes rows carrying that link.
Exact input parity
The candidate scores the frozen Prediction.features snapshot stored on the served prediction rather than re-reading mutable rows.

Once live traffic accumulates, compare candidate and serving verdicts with shadowAgreement:

dbschema/queries/shadowAgreement.edgeql
with shadows := (select Prediction filter .model = <str>$model and exists .shadow_of)select {  compared := count(shadows),  agreed := count(shadows filter .verdict ?= .shadow_of.verdict),}

When the two versions disagree, inspect the diverging predictions, since disagreement often highlights cases where the candidate improved over the serving model.

Promote misses to eval cases#

Whenever a served prediction proves wrong in production, promote it into EvalCase with the corrected verdict. Copying Prediction.features verbatim locks in the exact inputs the model saw:

dbschema/queries/addEvalCase.edgeql
insert EvalCase {  name := <str>$name,  features := assert_exists((select Prediction filter .id = <uuid>$prediction).features),  expected := <str>$expected,}

Static golden sets drift away from live traffic over time. Promote misclassified production predictions into EvalCase rows regularly, and retire cases whose expected business rules have changed.

Check the evals#

Your terminal
# 1. Compare the serving model against itself to confirm exit code 0.python evals/golden.py v4 v4; echo "exit $?" # 2. Run a candidate with a regression to confirm exit code 1 and the printed case name.python evals/golden.py v5 v4; echo "exit $?" # 3. Inspect agreement between the shadow candidate and serving predictions on live traffic.napalm call notes shadowAgreement --model v5

The baseline run exits 0, while a regressed candidate prints the lost case name and exits 1. Once shadowAgreement confirms parity or improvement on live traffic, promote the candidate.

Type a word or two to search every docs page.