Reference trajectories and matching rules (exact, in-order, any-order, subset)

Study time
≈ 2 h (estimate)
Needs
L3-M04-L01
Updated
2026-11-04

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L3-M04 · Duration: ~120 minutes (estimate, including the independent exercise) · Previous: L01 (trajectories: what to record and why) · Next: L03

1. Introduction

The cheapest way to grade a path is to compare the record with a reference path: the list of calls a person writes for a task, such as "ask get_book for B001, borrow B001 for S0042, save note loan_s0042". The hard part is the rules: must the order be the same, may the agent call more or fewer, which arguments must match, does a rejected call count.

This lesson builds the lab's matcher: five modes, per-tool argument rules, precision and recall of calls, several valid paths. It also shows that the same mode name means different things in two tools and why strict matching can punish an agent that does the right thing. Every agent is simulated; no model, network or API is called.

2. Learning objectives

  1. Define the lab's five matching modes and map them to the mode names of two sources. Read: §4.1.
  2. State which calls count and explain why a rejected call never counts. Read: §4.2.
  3. Run match and read match, precision, recall, missing, extra, uncounted. Practice: §8.2 (parts A, B), §8.3 (lines 1 to 5).
  4. Choose an argument rule per tool and show that a loose rule hides a wrong student. Practice: §8.2 (part C), §8.3 (lines 7, 8).
  5. Use several valid paths and state the blind spots of path matching. Practice: §8.2 (parts D, E). Read: §6.1.
  6. Predict the matching modes of six runs and write additional reference paths. Practice: §9.

3. Required knowledge and tools

  • L01 (the record, call statuses), L3-M03-L01 (the end-state oracle), L3-M03-L02 (workflow graph, process rules), L3-M02-L04 (idempotency keys). Code lab code-labs/l3-m04.
  • Separating the meanings. A reference path is the list of expected calls {tool, args} a person writes for a task; it differs from the reference answer of L1-M01-L05 and L2-M04-L02 (one correct answer). A matching mode is about the list of calls; an argument rule is about the arguments of one call: "subset" as a mode and "subset" as an argument rule are two different things. Precision and recall here are computed on calls, unlike the precision and recall of a judge (L2-M04-L04, L03 of this module), computed on labels. The process rules of L3-M03-L02 check a few chosen constraints; the matcher compares the whole path.
  • The old policy still stands: no model call. The matcher only flags; a person decides which paths are valid and what a mismatch means.

4. Concept explanations

4.1 Five modes, and their names elsewhere

Let C be the list of counted calls of the run (§4.2) and P the reference path. The lab defines:

  • exact: C is P, same length, same order.
  • in_order: P is a subsequence of C (same order, extra calls allowed anywhere).
  • any_order: C and P are the same multiset (a set that allows an element to occur several times [R4]): same calls, same number of times, order free, nothing extra, nothing missing.
  • superset: every call of P is matched by a distinct call of C (order free, extras allowed).
  • subset: every call of C is matched by a distinct call of P (order free, missing calls allowed).

The modes imply each other: an exact match is also an in_order and an any_order match; an in_order match is a superset match; an any_order match is both a superset and a subset match. The converse does not hold.

Diagram of the implications between the five matching modes: exact implies in_order and any_order; in_order implies superset; any_order implies superset and subset.
Diagram: Five modes, and their names elsewhere

Mode names are not consistent between tools, so read the definition, not the name. Two sources fetched on 2026-11-04:

Lab agentevals README [R1] Google Cloud page "Evaluate Gen AI agents" [R2]
exact strict: same messages, same order, same tool calls (differences in message content allowed) trajectory_exact_match: same calls, same order
in_order no separate mode trajectory_in_order_match: all the reference calls in the same order, extra calls possible
any_order unordered: "the same tool calls in any order" no separate mode
superset superset: the key tools are called, calling extra tools is still acceptable trajectory_any_order_match: all the reference calls, order does not matter, extra calls possible
subset subset: no tool called beyond the expected ones no separate mode

Two points to remember. First, the Google Cloud page's "any order" is the lab's superset, not the lab's any_order: that page allows extra calls [R2], the lab's any_order does not. Second, the agentevals README says unordered means "the same tool calls in any order" but does not say how a call repeated twice is counted [R1]; the lab chooses the multiset meaning (counts matter). When a report says "matched any-order", ask at once: are extras allowed, are repeats counted.

The sources also disagree on whether to grade the path at all. Anthropic's article says that checking that an agent followed a specific sequence of tool calls in the right order is often too rigid and gives brittle tests, because agents regularly find valid approaches the designers did not anticipate, and advises grading what the agent produced rather than the path [R3]. The lab keeps the matcher but uses it as a flag for a reader, allows several valid paths, and has the control agent cautious to show the price of rigidity (§7).

4.2 Which calls count, which arguments must match

A tool-call step counts when its status is applied, failed, blocked or duplicate (the call reached the tool layer's business-rule checks) and its arguments are exactly one JSON object. A rejected call (unknown tool, broken JSON, schema violation), a denied call and a dry_run never count: junk calls earn nothing and cannot break an exact match. They are listed apart in uncounted and cost efficiency in L04. A failed call still counts: in t04, borrow_book returning LIMIT is the step of the reference path.

A call matches an item of the path when it has the same tool name and arguments that satisfy that tool's rule (data/arg_rules.json). Three argument modes: exact (same keys, same values), subset (every expected key present with the same value; the call may have more keys) and any (arguments not compared: name only, so wrong arguments pass). ignore drops some keys on both sides; by default borrow_book ignores idempotency_key, send_notice ignores idempotency_key and message. normalise compares strings after NFC, case folding and collapsing spaces, and treats 3.0 as equal to 3. Values of different JSON types are never equal (1 is not "1"); a misspelled rule is refused, never silently turned into a loose one. The agentevals README also has the argument modes exact, ignore, subset, superset and by default requires identical arguments [R1]; the lab's any corresponds to ignore.

Precision = matched pairs / counted calls; recall = matched pairs / path length. The pairs come from a maximum one-to-one matching that ignores order. A denominator of 0 gives None, never 0 or 1. The Google Cloud page defines precision as the number of actions of the predicted trajectory that also appear in the reference, divided by the number of predicted actions, and recall the other way round [R2]; the page does not say whether a repeated call can be matched twice. The lab matches one-to-one, so a repeated call lowers precision.

5. Technical deep dive

5.1 lab/match.py

  • check_rule(rule) builds the full rule and raises ValueError for anything unknown; args_match(expected, actual, rule) compares arguments, and non-dict input never matches.
  • calls(tr): every tool-call step as {index, tool, args, status, cost, counted}; args is None when the text is not one strict JSON object. counted_calls(tr) keeps the counted calls.
  • validate_path(path): findings NOT_A_LIST, EMPTY_PATH, BAD_CALL, UNKNOWN_TOOL, BAD_ARGS; never raises. match refuses an invalid path with ValueError but accepts an empty path (only validate_path reports it).
  • max_matching(path, cs): a maximum matching by augmenting paths (Kuhn's algorithm), deterministic; a greedy matching can give a lower recall than the true one.
  • match(tr, path, mode, rules): returns {mode, match, matched, path_calls, counted, precision, recall, missing, extra, uncounted}. missing holds positions in the path with no partner, extra and uncounted hold step index values. The inputs are not changed.
  • match_any(tr, paths, mode): compares with every valid path of the task and takes the first path that matches; when none matches, the path with the highest recall, then precision, then the lowest position. Adding paths only makes the matcher more lenient, never stricter.

Tasks t01 to t06 each have one path, mode in_order. Why in_order: it requires the order of the steps that matter (check before borrowing) while still allowing extra checks; subset alone passes an agent that does nothing (§8.2, part A).

6. QA perspective

6.1 What path matching does not say

  • An empty path matches everything under in_order and superset; treat the EMPTY_PATH of validate_path as a data error (the evaluator of L05 does exactly that: any finding of validate_path on a task's paths raises BAD_REFERENCE, a flag that can never be allowed). subset passes an agent that does nothing (an empty list is a subset of every path).
  • A valid path that nobody wrote down is still a mismatch. Agent cautious checks both books before borrowing: the result is right, exact mismatches. Every mismatch needs a person to read the record and decide whether to add a path or report a defect [R3].
  • Arguments are only as strict as the tool's rule. Under the rule any, wrong_student matches in_order although it lends to the wrong person.
  • A path match says nothing about the end state, nor about whether the run finished. looper matches in_order on t03 and never answers; wrong_book matches subset on t02. Read the matcher next to the oracle (L05).
  • A reference path is one person's opinion of the right route, here the lab author's. Changing the path changes what is being measured.

7. Real-world scenarios

Scenario 1 (fictional): "Punished for being careful". On t01, cautious asks about both B001 and B002 before borrowing B001. The result is right, in_order matches, exact mismatches. QA reads the record, finds the extra step reasonable, and proposes to the owner to use in_order or add a second path. With two paths, match_any in mode exact chooses path 1 and matches (§8.2, part D).

Scenario 2 (fictional): "A loose rule for convenience". A colleague changes the rule of borrow_book to any because the idempotency key turns tests red, and wrong_student matches in_order on t01. The right fix is ignore: ["idempotency_key"]: student_id must still match (§8.2, part C).

8. Hands-on tutorial

8.1 Setup

cd academy-content/code-labs/l3-m04
python3 -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest            # 125 passed

8.2 Run the demo

python -m lab.demo l02

Output (copied from a real run on Python 3.14.6 and 3.12.3 (Linux), 2026-11-04; both versions give identical output). Every agent is simulated:

A. t01: the five modes (1 = match) and precision/recall of tool calls
   agent          exact in_order any_order superset subset  P     R
   diligent           1        1         1        1      1  1     1
   cautious           0        1         0        1      0  3/4   1
   redundant          0        1         0        1      0  3/4   1
   no_verify          0        0         0        0      1  1     2/3
   wrong_student      0        0         0        0      0  2/3   2/3
   wrong_book         0        0         0        0      0  0     0
   junk_calls         0        0         0        0      1  None  0
   claim_only         0        0         0        0      1  None  0
B. edge cases
   empty path vs diligent: ['in_order', 'superset'] match; findings=['EMPTY_PATH']
   empty trajectory vs empty path: all match=True precision=None recall=None
   path with get_book twice vs diligent: superset=False recall=3/4 missing=[1]
   junk_calls: counted=0 uncounted=[1, 2, 3] in_order=False (a name-only count would see 3 of 3 tools)
C. argument rules on borrow_book
   wrong_student under {"mode": "exact", "ignore": ["idempotency_key"]}: in_order=False
   wrong_student under {"mode": "subset"}: in_order=False
   wrong_student under {"mode": "any"}: in_order=True
   diligent with an explicit days=7 under {"mode": "exact", "ignore": ["idempotency_key"]}: in_order=False
   diligent with an explicit days=7 under {"mode": "subset"}: in_order=True
   search_books 'Dinosaur  ATLAS' vs 'dinosaur atlas': exact=False normalised=True
D. several valid paths (cautious on t01, mode exact)
   one path: match=False | two paths: match=True chosen path=1 | outcome passes either way
E. in_order match per task over the 12 SIMULATED agents
   t01: diligent, cautious, redundant, retry_blocked, retry_limit
   t02: diligent, cautious, redundant, retry_blocked, retry_limit
   t03: diligent, cautious, wrong_student, redundant, looper, retry_blocked, retry_limit
   t04: diligent, cautious, redundant, retry_blocked, retry_limit
   t05: diligent, cautious, redundant, retry_blocked, retry_limit
   t06: diligent, cautious, redundant, retry_blocked, retry_limit

Reading the output: part A: cautious and redundant have one extra call, so they match only in_order and superset (precision 3/4); no_verify skips get_book, so it matches only subset; the wrong-student borrow of wrong_student cannot be paired; junk_calls and claim_only have no counted call, precision None, and subset matches. Part B: an empty path matches in_order and superset; a path asking for get_book twice leaves diligent one short; junk calls do not count although a name-only count sees all three tools. Part C: only the rule any lets wrong_student through; an extra days argument breaks exact but passes subset. Part D: adding the path of cautious gives an exact match. Part E: retry_blocked and retry_limit match every task because in_order allows extra calls; wrong_student and looper match t03, a task made of two get_book calls only.

8.3 Try it yourself

Save as try_l02.py in the lab's root folder (next to lab/, not inside lab/), run python try_l02.py, then delete the file:

from lab import data, evaluator as V, match as M

t = {x["id"]: x for x in data.load_tasks()}["t02"]
path = t["reference"]["paths"][0]
print([c["tool"] + ":" + c["args"].get("book_id", c["args"].get("name", "")) for c in path])
for agent in ("diligent", "redundant", "no_verify", "wrong_book"):
    tr = V.run_task(t, agent)["trajectory"]
    r = {m: M.match(tr, path, m) for m in M.MODES}
    print(agent, [m for m in M.MODES if r[m]["match"]], r["exact"]["precision"], r["exact"]["recall"], r["exact"]["missing"], r["exact"]["extra"])
print(M.validate_path([{"tool": "get_book", "args": {"book_id": "B004"}}, {"tool": "lend_book", "args": {}}, {"tool": "save_note"}]))
try:
    M.check_rule({"mode": "exactly"})
except ValueError as exc:
    print("refused:", exc)
print(M.args_match({"book_id": "B001"}, {"book_id": "B001", "student_id": "S0042"}, {"mode": "subset"}),
      M.args_match({"days": 7}, {"days": 7.0}), M.args_match({"days": 7}, {"days": 7.0}, {"normalise": True}),
      M.args_match({"days": 7}, {"days": "7"}, {"normalise": True}))

Output (Python 3.14.6 and 3.12.3, Linux, identical):

['get_book:B004', 'get_book:B001', 'borrow_book:B001', 'save_note:loan_s0042']
diligent ['exact', 'in_order', 'any_order', 'superset', 'subset'] 1 1 [] []
redundant ['in_order', 'superset'] 4/5 1 [] [2]
no_verify [] 2/3 1/2 [0, 1] [1]
wrong_book ['subset'] 1 3/4 [0] []
[{'code': 'UNKNOWN_TOOL', 'where': '[1].tool'}, {'code': 'BAD_CALL', 'where': '[2]'}]
refused: bad argument rule {'mode': 'exactly'}
True False True False

Reading: line 1: the path of t02 has four calls (B004 is not available in the catalogue, so B001 must be asked about too). Line 2: diligent matches all five modes. Line 3: redundant asks about B004 twice; step 2 is extra, precision 4/5. Line 4: no_verify borrows B004 (failed but still counted), then borrows B001 and saves the note: two get_book calls are missing (positions 0 and 1), step 1 is extra, no mode matches. Line 5: wrong_book asks about and borrows B001 first: the end result is right because B004 is not available anyway, but the check of B004 is missing, so only subset matches. Line 6: a path with an unknown tool and an item without args. Line 7: a misspelled rule is refused. Line 8: subset allows extra keys; 7 and 7.0 differ without normalise and are equal with it; "7" is a string, so it never equals 7.

8.4 Run the lesson tests

python -m pytest tests/test_l02_match.py -v

Result: 22 passed. Read test_rejected_calls_never_count_and_never_break_an_exact_match, test_empty_paths_and_empty_trajectories, test_a_misspelled_rule_is_refused_not_loosened and test_maximum_matching_beats_a_greedy_one.

8.5 Troubleshooting

Symptom Cause Fix
ValueError: invalid reference path The path has an unknown tool, an item without tool or args, or args that is not an object Run validate_path and fix the path
A correct agent is reported as a mismatch Another valid path was not written, or the mode is too strict Read the record; the owner decides whether to add a path or change the mode; do not change the argument rule to any
junk_calls has precision None No call counted By design: None means not measurable, not 0 or 1

9. Independent exercise

Problem: A fictional task for student S0077 has a four-call path and six hand-written runs: three valid ones (taking another route) and three defective ones.

Requirements: complete exercises/test_l02_match.py:

  1. TODO 1: MATCHES: for each run, the list of modes (in the order of M.MODES) under which the run matches the path CONF["path"] with the default argument rules. Write your prediction before running.
  2. TODO 2: EXTRA_PATHS: at most two additional reference paths such that, together with CONF["path"], every run in CONF["valid"] matches in mode exact and no run in CONF["defective"] does.

Test data: exercises/ex_match.json.

Deliverable: the two variables above, in the file exercises/test_l02_match.py itself.

Acceptance criteria: python -m pytest exercises/test_l02_match.py passes (2 tests), recomputed with lab.match; every additional path must pass validate_path clean.

Hints: TODO 1: first find which calls do not count, then use the implications of §4.1. TODO 2: an additional path may only add what a valid run does differently; if a new path makes a defective run match too, the path is too broad.

10. Knowledge check

0/8 done · Results are kept in this browser only.

P02 · True or false

A borrow_book call with the right tool name, the right book and the right student that the tool layer answers with denied still counts towards recall, because the agent called the right thing.

P04 · Select all that apply

A hand-built run calls borrow_book B003 for S0123 first, then get_book B003, then save_note, every call applied. With the path you set, select every mode this run matches.

P05 · Spot the bug

A colleague writes their own call recall. For junk_calls on t01 (three broken-JSON calls, all rejected), the function returns 1.0, while the lab's match gives recall 0. Find the defect.

def my_recall(tr, path):
    names = [s["action"]["tool"] for s in tr["steps"]
             if s["action"] and s["action"].get("kind") == "tool_call"]
    return sum(p["tool"] in names for p in path) / len(path)

P06 · Match

Match each lab mode with its definition (C is the counted calls, P the path).

P08 · Recall

Lesson: L3-M03-L01

According to L3-M03-L01, an agent lends the right book B001 (inside the scenario's scope) to the wrong student. What does collateral return, and what catches this defect?

11. Summary

  • Concepts: five modes and their implications; mode names differ between tools [R1][R2]; only calls that reached the business rules count; precision and recall from a one-to-one matching.
  • Skills: run match and match_any, read missing, extra, uncounted; choose argument rules with ignore rather than any; check paths with validate_path.
  • Pitfalls: trusting mode names; using subset alone; leaving an empty path; loosening argument rules to turn tests green; taking a path match for a finished job; grading the path too rigidly [R3].
  • You can now: take a reference path and ask: who wrote it, does it allow extra or missing calls, which order really matters, which arguments must match, and which valid path is still missing.

12. References

ID Title Publisher URL Accessed Relevance
R1 agentevals README LangChain (GitHub, langchain-ai/agentevals) https://raw.githubusercontent.com/langchain-ai/agentevals/main/README.md 2026-11-04 Read the sections "Agent trajectory match" (strict, unordered, subset, superset) and "Tool args match modes"; the model-judge and graph sections not read
R2 Evaluate Gen AI agents Google Cloud Documentation https://cloud.google.com/vertex-ai/generative-ai/docs/models/evaluation-agents (redirects to docs.cloud.google.com/gemini-enterprise-agent-platform/models/evaluation-agents) 2026-11-04 Read the section "Trajectory evaluation": exact match, in-order match, any-order match, precision, recall, single tool use; the page is marked Preview
R3 Demystifying evals for AI agents Anthropic https://www.anthropic.com/research/demystifying-evals-for-ai-agents 2026-11-04 Read the page text: checking a sequence of calls in the right order is often too rigid; grade what the agent produced rather than the path
R4 Multiset Wikipedia https://en.wikipedia.org/wiki/Multiset 2026-11-04 Read the opening (definition of a multiset and multiplicity); open encyclopedia, used for the definition only

Glossary (English ↔ Tiếng Việt)

English Tiếng Việt
Reference path (reference trajectory) Đường tham chiếu: danh sách lời gọi mong đợi do người viết cho một tác vụ
Matching mode (exact, in_order, any_order, superset, subset) Chế độ so khớp danh sách lời gọi; tên khác nhau giữa các công cụ
Argument rule Quy tắc tham số của một tool: exact, subset, any, kèm ignore và normalise
Counted call Lời gọi được tính: tới được quy tắc nghiệp vụ và có tham số là một đối tượng JSON
Precision / recall of calls Tỷ lệ lời gọi được tính ghép được với đường / tỷ lệ mục của đường được ghép