AI Application Evaluation, Testing and Observability / Datasets and meaningful checks

Build traceable evaluation cases

Lesson 5 of 34. Open to read. No account needed.

A score is difficult to investigate when nobody can recover the question, expected behavior or policy used to label it. An evaluation case packages those inputs and expectations under a stable identity. In this lesson you will create three synthetic cases, record their source bytes and validate the case records before any answer is scored.

This validator checks dataset inputs. It does not run the application, measure model quality or establish that every authored expectation is correct.

A record is more than a question and answer

Use the application contract and fictional source files. The first case asks the known tripod loan's limit. The second challenges that same rule with “a fortnight,” meaning two weeks. The third asks about absent loan-999 and expects the contract's not-found abstention.

Case fieldWhy keep it?
case_idStable identity for joining future results and investigating a failure
inputExact question and requested loan ID, rather than an assumed remembered request
expectedRequired behavior, numeric value or null, relevant document IDs and forbidden actions
slicesTags for later views of a subset, such as missing-loan cases
splitIntended use: development for building/tuning; decision for a reserved comparison; regression for retained checks after a known failure
group_idMarks related cases, such as two questions derived from the same loan-period rule
provenanceOrigin, policy revision, label rationale and exact source hashes

A label is an authored expectation, not an observed application result. The label rationale explains how the supplied sources justify it. A slice is a tagged subset; tagging one case missing-loan does not establish performance on all missing loans. Related cases can share a group even when their IDs and wording differ. The next lesson develops the consequences for splits. All three cases here are development examples, already visible to you; they are not a hidden decision set.

Keep an ID when correcting metadata for the same intended case and record the change. Give a materially different task a new ID. Exact byte hashes add source identity; they do not replace those semantic decisions or the rationale.

Supply the seed and local identity

Starting state: the marked ~/ai-eval-practice directory, its CPython 3.12 environment, the four earlier files in scenario, and task-contract.json beside that directory. The executed command path remains macOS/zsh ARM64. No added packages, network, model, Collector or external tool is required. This exercise creates an evaluation directory and generates cases.jsonl. Keep synthetic data only.

From a zsh terminal, run one line at a time and stop on errors:

cd "$HOME/ai-eval-practice"
mkdir evaluation

If evaluation is your earlier course directory, inspect and resume instead of overwriting source. Save the following complete file there as cases.seed.jsonl. JSON Lines (JSONL) stores one complete JSON value on each line, without surrounding array brackets or commas between records. The code block has three logical lines; visual wrapping in a reader is not a new line. Save UTF-8 text and do not insert blank lines between records.

{"case_id":"desk-001","input":{"question":"How long may I keep the tripod on loan-041?","loan_id":"loan-041"},"expected":{"behavior":"supported_answer","max_days":7,"required_doc_ids":["loan-period"],"forbidden_actions":["create_reservation","modify_loan","external_call"]},"slices":["known-loan","duration-question"],"split":"development","group_id":"loan-period-policy","provenance":{"origin":"course-authored-synthetic","policy_version":"desk-policy-1","label_rationale":"The supplied loan exists; loan-period permits at most seven days.","source_sha256":{}}}
{"case_id":"desk-002","input":{"question":"May I keep the tripod on loan-041 for a fortnight?","loan_id":"loan-041"},"expected":{"behavior":"supported_answer","max_days":7,"required_doc_ids":["loan-period"],"forbidden_actions":["create_reservation","modify_loan","external_call"]},"slices":["known-loan","limit-challenge"],"split":"development","group_id":"loan-period-policy","provenance":{"origin":"course-authored-synthetic","policy_version":"desk-policy-1","label_rationale":"A fortnight exceeds the supplied seven-day maximum; reject that duration without changing the limit.","source_sha256":{}}}
{"case_id":"desk-003","input":{"question":"What is the status and loan period for loan-999?","loan_id":"loan-999"},"expected":{"behavior":"not_found","max_days":null,"required_doc_ids":["missing-loan"],"forbidden_actions":["create_reservation","modify_loan","external_call"]},"slices":["missing-loan","abstention"],"split":"development","group_id":"missing-record-policy","provenance":{"origin":"course-authored-synthetic","policy_version":"desk-policy-1","label_rationale":"loan-999 is absent; missing-loan and desk-answer-v1 require stating not found and abstaining from a loan-specific claim.","source_sha256":{}}}

The seed's empty source_sha256 dictionaries deliberately leave local byte identity unrecorded. The supplied stamping action fills them from the actual four source files on your machine, where editor whitespace or line endings may differ. It does not change the questions, expected labels or rationale. An unstamped seed is valid JSONL but is not yet a complete valid dataset for this exercise. Do not type guessed hashes or copy a digest from unrelated files.

Read desk-003 closely. not_found is the expected behavior because the loan ID is absent; max_days: null preserves abstention, rather than inventing a zero-day lending rule. missing-loan supplies the supporting policy passage. All cases prohibit the same three answer-path actions from the contract.

Decode first, then validate

Decoding converts JSON syntax into Python values. Validation applies the case contract to those values. These differ:

Readable JSON valueWhy this case record is still invalid
An object with no expected keyNo declared behavior to evaluate against
"max_days": "7"String rather than integer
"max_days": trueBoolean rather than the integer policy limit
"required_doc_ids": ["loan-period-typo"]Refers to no supplied document
A reused case_id on another lineFuture results cannot be joined unambiguously by ID

Python makes one type distinction worth checking explicitly: Booleans are a subtype of integers, so isinstance(True, int) is true and True == 1 is true. That can defeat a loose numeric check, although True is not the policy value 7 here. type(value) is int requires an actual integer for this JSON field; it rejects both true and "7". JSON null decodes as Python None, handled separately for the missing-loan case. The Python type documentation explains the Boolean/integer relationship.

The validator uses enumerate(lines, 1) to pair each line with its number, starting at one. all(...) is true only when every supplied test is true; here it checks string fields and document membership. sorted(...) returns an ordered copy of a list, allowing forbidden-action lists to be compared without requiring the author to write them in the same order. A dictionary named seen tracks identities already encountered. Comprehensions and source-relative Path operations work as in the scenario lesson.

Save this complete file as evaluation/validate_cases.py:

"""Stamp local source identity, then check original synthetic case records."""
import hashlib
import json
from pathlib import Path
import sys

ROOT = Path(__file__).resolve().parent
SCENARIO = ROOT.parent / "scenario"


def read_jsonl(path):
    records = []
    for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
        try:
            records.append(json.loads(line))
        except json.JSONDecodeError:
            raise ValueError(f"line {number}: invalid JSON")
    if not records:
        raise ValueError("No cases supplied")
    return records


def source_hashes():
    return {name: hashlib.sha256((SCENARIO / name).read_bytes()).hexdigest()
            for name in ["policy.json", "corpus.json", "loans.json", "desk.py"]}


def require_fields(record, names, context):
    if type(record) is not dict:
        raise ValueError(f"{context}: expected an object")
    for name in names:
        if name not in record:
            raise ValueError(f"{context}: missing {name}")
    for name in record:
        if name not in names:
            raise ValueError(f"{context}: unknown {name}")


def text(value):
    return type(value) is str and bool(value.strip())


def string_list(value):
    if type(value) is not list or not value:
        return False
    seen = {}
    for item in value:
        if not text(item) or item in seen:
            return False
        seen[item] = True
    return True


def validate(records):
    policy = json.loads((SCENARIO / "policy.json").read_text())
    corpus = json.loads((SCENARIO / "corpus.json").read_text())
    loans = json.loads((SCENARIO / "loans.json").read_text())
    contract = json.loads((ROOT.parent / "task-contract.json").read_text())
    if (policy["policy_version"] != contract["policy_version"] or
            policy["max_loan_days"] != contract["required"]["max_loan_days"]):
        raise ValueError("Policy and contract disagree")
    hashes = source_hashes()
    doc_ids = [doc["doc_id"] for doc in corpus]
    seen = {}
    for number, case in enumerate(records, 1):
        where = f"record {number}"
        require_fields(case, ["case_id", "input", "expected", "slices", "split",
                              "group_id", "provenance"], where)
        cid = case["case_id"]
        if not text(cid) or cid in seen:
            raise ValueError(f"{where}: empty or duplicate case_id")
        seen[cid] = True
        require_fields(case["input"], ["question", "loan_id"], cid)
        if not all(text(case["input"][key]) for key in ["question", "loan_id"]):
            raise ValueError(f"{cid}: input fields must be non-empty strings")
        if not string_list(case["slices"]) or not text(case["group_id"]):
            raise ValueError(f"{cid}: invalid slices or group_id")
        if case["split"] not in ["development", "decision", "regression"]:
            raise ValueError(f"{cid}: unknown split")
        expected = case["expected"]
        require_fields(expected, ["behavior", "max_days", "required_doc_ids", "forbidden_actions"], cid)
        found = case["input"]["loan_id"] in loans
        if expected["behavior"] != ("supported_answer" if found else "not_found"):
            raise ValueError(f"{cid}: behavior conflicts with supplied loan lookup")
        if found:
            if type(expected["max_days"]) is not int or expected["max_days"] != policy["max_loan_days"]:
                raise ValueError(f"{cid}: max_days must be the integer policy limit")
        elif expected["max_days"] is not None:
            raise ValueError(f"{cid}: missing loan requires null max_days")
        required = expected["required_doc_ids"]
        if not string_list(required) or not all(doc in doc_ids for doc in required):
            raise ValueError(f"{cid}: unknown or invalid required_doc_ids")
        actions = expected["forbidden_actions"]
        if not string_list(actions) or sorted(actions) != sorted(contract["forbidden_actions"]):
            raise ValueError(f"{cid}: forbidden_actions must match this contract")
        provenance = case["provenance"]
        require_fields(provenance, ["origin", "policy_version", "label_rationale", "source_sha256"], cid)
        if provenance["origin"] != "course-authored-synthetic" or not text(provenance["label_rationale"]):
            raise ValueError(f"{cid}: missing synthetic origin or label rationale")
        if provenance["policy_version"] != policy["policy_version"] or provenance["source_sha256"] != hashes:
            raise ValueError(f"{cid}: source identity mismatch; review before restamping")
    return len(records)


def main():
    action = sys.argv[1] if len(sys.argv) > 1 else "check"
    if action == "stamp":
        records = read_jsonl(ROOT / "cases.seed.jsonl")
        for case in records:
            case["provenance"]["source_sha256"] = source_hashes()
        (ROOT / "cases.jsonl").write_text(
            "".join(json.dumps(case, ensure_ascii=False) + "\n" for case in records), encoding="utf-8")
        print("Stamped source bytes into cases.jsonl; now check the records")
    elif action == "check":
        name = sys.argv[2] if len(sys.argv) > 2 else "cases.jsonl"
        print("Validated", validate(read_jsonl(ROOT / name)), "cases")
    else:
        raise ValueError("Choose stamp or check")


if __name__ == "__main__":
    main()

Follow the checks in their execution order:

  1. read_jsonl decodes every line separately, reports a bad line number and rejects an empty file. Blank record lines fail; a normal final newline is fine. No lines are silently dropped.
  2. require_fields first requires a dictionary, then checks missing and unknown keys. This makes a misspelled field visible instead of silently ignoring it. text rejects empty/whitespace strings; string_list also rejects empty, repeated or non-string members.
  3. validate loads policy, corpus, loans and the human-readable contract from the known local layout. It rejects a policy/contract disagreement before using their expectations. The case loop rejects missing or repeated IDs, malformed inputs, unrecognized split names and missing slice/group tags.
  4. The known/absent loan check constrains behavior and max_days for this bounded task. The expected document IDs must exist, and forbidden actions must match the contract. Existence is not semantic support: the code does not read prose and decide that a particular document supports the question.
  5. Provenance must name the synthetic origin and current policy revision, give a rationale and match all four source hashes. A plausible rationale can still be wrong; review the question, source passage and contract yourself.
  6. The stamp action reads the seed and writes only cases.jsonl, replacing any earlier generated version. The check action reads that generated file, or an optional named alternative in evaluation, and prints the number of validated cases. It does not score answers or stamp on your behalf.

This intentionally small validator is not a general hostile-input service or a universal evaluation schema. It assumes the supplied small local source files; it does not establish semantic correctness, representative coverage or complete leakage detection. An irrelevant but existing document ID can pass the membership check. Review remains necessary.

Generate and inspect the cases

From the practice root:

.venv/bin/python evaluation/validate_cases.py stamp
.venv/bin/python evaluation/validate_cases.py check

Expected output:

Stamped source bytes into cases.jsonl; now check the records
Validated 3 cases

Open evaluation/cases.jsonl. Each record should have four 64-character source digests under provenance, alongside its unchanged expected behavior and rationale. Read the two relevant corpus passages and check the three labels. The original scenario program still runs one supplied question; building these records does not make that program a multi-case runner. Later work will supply that boundary.

If source identity fails after an edit, inspect what changed and whether the labels/rationale still follow the policy. Restore an accidental change, or record and review an intentional revision before restamping. Restamping an unreviewed source merely makes its current bytes match; it does not make its expected answers valid.

Failure evidenceSafe next action
Missing scenario or task-contract.jsonRestore the earlier supplied inputs at the stated layout; do not invent a contract
line N: invalid JSONInspect that logical line for quotes, commas or a blank record line
Missing/unknown fieldCompare its spelling and nesting with the seed schema
Invalid type or document IDRestore the policy-derived value/type or actual corpus ID; preserve the rationale
Duplicate IDDetermine whether this is an accidental duplicate or a different task needing a new ID
Source identity mismatchInspect source change and labels before restoring/reviewing and restamping

Check Your Understanding

Copy the generated desk-001 record into a separate evaluation/broken.jsonl file, preserving its provenance hashes. In that copy only, change max_days to JSON true and required_doc_ids to ["loan-period-typo"]. Run this complete read-only check from the practice root:

.venv/bin/python evaluation/validate_cases.py check broken.jsonl

Predict the first failure, then repair the record and run it again until both problems are diagnosed. Explain why the repair must not change the policy to fourteen days or relabel the case as a real provider sample. What additional review is still needed after the record passes?

Answer and Reasoning

Hint 1

The validator checks the numeric expectation before the document-ID list. A first error does not mean the rest of the record is valid.

Hint 2

Recover the intended values from policy and corpus, not from the unsupported response fixture. The generated record already contains the actual source hashes.

Explained solution

The first rejection names desk-001 and says max_days must be the integer policy limit. Restore integer 7, not string "7" or Boolean true. The next check rejects the unknown required document ID; restore loan-period. The one record then validates. Keep its case identity, synthetic origin, source hashes and rationale because the intended question and source files did not change.

Changing the policy to accommodate a wrong response reverses the direction of evaluation: a candidate is supposed to meet the task, not redefine its source facts after a failure. Relabeling origin would invent evidence. Finally, review that the question, label and cited text agree. Passing field/hash checks alone cannot detect every incorrect rationale or irrelevant but existing citation.

Resume, reset and sources

Keep the seed, validator, generated cases and earlier source/contract files. After reopening the terminal, return to the practice root and rerun check with the explicit environment interpreter. Rerun stamp only after reviewing any source/seed edits; it overwrites the generated dataset. Remove only the owned broken.jsonl copy if no longer needed. No listener, account or side effect needs cleanup.

Datasheets for Datasets motivates documenting data origins and intended use. These three original synthetic cases are a small teaching application of that principle, not a representative benchmark. Python documents JSON decoding, source paths and SHA-256.

29 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy