All posts AI engineering, 12 min read

Designing a reward verifier for agent RL on tau-bench

A reward function is a specification of correctness. On tau-bench, my verifier took about 215 lines; the cost was 12 minutes of expert time per task.

I spent 2 weeks extending tau-bench into a new domain, food delivery, for reinforcement learning. The part that took the most design work was the verifier.

The verifier is the code that reads an agent's run and decides what reward to give it. I assumed it would be a thin wrapper around the benchmark's existing scorer.

Training against a checker like this is RLVR, reinforcement learning with verifiable rewards: the reward comes from code that checks the outcome.

The code came to about 215 lines and took a couple of days. The rest of the 2 weeks went into deciding, per task, what "correct" meant.

A reward function is a specification of correctness. If you write it like a loss function, you teach the policy the wrong thing. Writing it like a specification takes detailed knowledge of the domain, and getting that knowledge down on paper is the bigger cost.

The problem, from first principles

Strip RL training down and 3 facts remain:

  1. The learner is trained to make one number go up.
  2. That number comes from code, the verifier, reading what the agent did.
  3. So the verifier is the only description of the task the learner ever sees.

That gives 2 ways to fail:

  • The code accepts only one of several right answers. Training then pushes the policy away from right answers it found on its own.
  • The code misses a line that must never be crossed. Training is then indifferent to crossing it, and under pressure the policy will.

So before I ask "how far is this run from the target?", I ask 2 other questions:

  • What is the full set of runs I'd call correct?
  • Which runs must score zero whatever else they get right?

The answers are facts about the domain, so the cost of the verifier lands on whoever knows the domain. I'll work that idea through on my tau-bench project.

If you haven't done RL before, the next section builds it up from the parts. If you have, skip to what tau-bench gives you.

Reinforcement learning from first principles

The machine learning you've probably heard of is supervised. You show the model a labeled example, an image tagged "cat", and it learns to reproduce the label. There is a right answer for every input in the dataset, and training moves the model closer to those answers.

Reinforcement learning has no labeled answer for each step. There is a goal, a world the agent can act in, and a number that says, after the fact, how well things went.

The agent has to find out for itself which actions make that number go up. It learns from consequences.

Think of learning to ride a bike. Nobody gives you a table that says "at this lean angle, turn the wheel this many degrees." You push off, wobble, fall, and push off again.

After enough tries you develop a policy, a feel for what to do at each moment, that keeps you upright. The falls told you, again and again, when you got it wrong, and that shaped what you did next.

The formal parts of RL map straight onto this:

  • Agent. The learner and decision-maker. The cyclist. In my project, the model running a customer-service conversation.
  • Environment. Everything outside the agent that it acts on and that reacts. The bike, the road, gravity. For me, the customer-service domain: the database, the user simulator, and the tools the agent can call.
  • State. A snapshot of the situation now. Your current speed and lean. For me, the conversation so far plus the current database contents.
  • Action. A move the agent can make from a state. Steer, pedal, brake. For me, a tool call: issue a refund, dispatch a driver, ask the customer a question.
  • Reward. A single number that says how good an outcome was. Staying upright is positive, hitting the pavement is negative. For me, the score the verifier returns at the end of a conversation.
  • Policy. The agent's strategy: given this state, which action to take. The cyclist's balance. For the model, its learned tendency to pick certain actions in certain situations. Training means improving the policy.
  • Trajectory. One full run from start to finish: the sequence of states, actions and rewards. One ride from push-off to stop. For me, one complete conversation and its final score.

This cycle connects them:

The verifier sits inside the environment and produces the reward. Everything the agent learns arrives through that one number.

The agent observes the state and picks an action from its policy. The environment moves to a new state and returns a reward. The agent shifts its policy towards actions that earned reward and away from ones that didn't.

Run that cycle millions of times and a good policy emerges.

It's a feedback loop, like a thermostat or the way your body holds its temperature: an output is measured, compared against a target, and fed back to correct the next action. RL applies that idea to a learner that updates itself.

2 more ideas before we get to the verifier:

  • Reward is sparse and delayed. You only learn the ride went well once you've stopped without falling. The agent took 15 actions and got one number at the end, and it has to work out which of the 15 deserved credit. This is the credit-assignment problem. Dense intermediate signal, covered later, makes it easier.
  • Exploration versus exploitation. The agent can repeat what already works, or try something new that might work better or might fail. Lean the way that kept you up last time, or try a sharper turn that could be faster. Too much exploitation leaves the agent stuck on its first habits that worked, and too much exploration stops it from settling on anything. What the reward rewards affects where that balance lands.

Everything the agent learns follows from the reward number. The policy chases whatever the reward measures, including parts you didn't intend. If the reward only checks that you eventually stopped, you learn to fall slowly.

So the reward function is the definition of the task, in the only form the agent reads. If it's wrong, a better model, more data and more training all push harder towards the wrong behavior.

The verifier is the code that computes the reward from a trajectory, so the design work sits there. A person has to state what good means precisely enough for a machine to optimize against it. I got that wrong at first, and the rest of this post is how I fixed it.

What tau-bench gives you, and where it stops

tau-bench is also where the pass^k reliability metric comes from, which I used from the buyer's side when testing a Zendesk AI agent.

tau-bench (Yao et al., NeurIPS 2024) and its successor tau2-bench are well-built agent benchmarks: customer-service domains, a user simulator, real tool calls, and a database the agent changes. The reward is strict and honest. This is its shape, from tau_bench/envs/base.py:

def calculate_reward(self) -> RewardResult:
    data_hash = self.get_data_hash()        # hash of agent's final DB state
    reward = 1.0

    self.data = self.data_load_func()        # fresh DB
    for action in self.task.actions:         # replay ground-truth actions
        if action.name not in self.terminate_tools:
            self.step(action)
    gt_data_hash = self.get_data_hash()

    if data_hash != gt_data_hash:
        reward = 0.0
    # ... plus a substring check on expected outputs
    return RewardResult(reward=reward, ...)

2 checks, both required:

  • The SHA-256 of the agent's final database equals the SHA-256 after replaying the ground-truth actions.
  • Each expected output string appears somewhere in the agent's replies.

Reward is 0.0 or 1.0. There's no partial credit, no concept of safety, and no tolerance for outcomes that are equivalent but not byte-identical.

For a leaderboard this is the right design, because ranking models needs a hard pass or fail. For RL training it's the wrong shape. Strict final-state equality says only the recorded ground-truth state is correct, and in a domain like food delivery several different states can be correct.

It breaks in 3 places:

  • Stochastic outcomes. I dispatch a replacement courier. The valid answer is "any available driver within 5 km." The recorded ground truth picked one, and the agent picks another, equally valid one. The database hash differs, so the reward is 0, and the policy gets punished for doing the right thing.
  • Several valid resolutions. A refund dispute can be settled with a card refund, wallet credit, a partial refund plus an apology credit, or a replacement order. Final-state equality accepts exactly one of those and scores the rest 0.
  • No safety floor. A good 10-step trajectory that suggests a peanut substitute to a customer with a peanut allergy scores the same as one that didn't, as long as the final state matches. There's no concept of an outcome you can never recover from.

For RL in a domain where money moves and safety rules apply, you need a different verifier.

flowchart TD
  O[Agent outcome] --> Q{"Is there one byte-exact<br/>correct final state?"}
  Q -->|yes| LB["Strict final-state equality<br/>good for a leaderboard"]
  Q -->|no, several valid forms| RL["RL needs a spec verifier"]
  RL --> EQ["Equivalence classes for<br/>stochastic choices"]
  RL --> INV["Conservation invariants for<br/>path-independent money"]
  RL --> GATE["Hard safety gates for<br/>irreversible mistakes"]

Treating the reward function as a specification

Loss functionSpecification
Question it asksHow far is the output from the target?Is the output correct, and how would I know?
What it isA distanceA definition
Several right answersOnly one sits at distance zeroAll of them pass
Lines you must never crossJust more distanceA hard zero

RL hands you a single number at the end, so it's easy to think the number is what you design. But the number is the output of a definition you have to write first.

Once I wrote the reward as a specification, the 4 things a domain like this needs followed directly. They run in a fixed order:

The gate is a veto and runs first. The outcome and invariant checks decide whether outcome is 0 or 1. Dense process signal goes on top in both cases.
  1. Equivalence classes. Any valid choice is correct, so the verifier compares classes of answers instead of single values.
  2. Irreversible safety constraints. Some violations can't be undone by good behavior later, so the verifier needs a hard zero that fires regardless of the outcome.
  3. Path-independent invariants. The verifier checks a conserved quantity, such as the money balancing, whatever path the agent took to get there.
  4. Dense intermediate signal. A sparse 0/1 at the end of an episode makes credit assignment hard, so the verifier also emits partial signal along the trajectory.

The first and third needed the most thought, and they're the 2 I show code for.

Example 1: equivalence-class hashing

The tool that exposed the problem is dispatch_replacement_courier. When an order's original driver drops out, it finds every available driver within range and assigns one. Which driver it picks varies across replays.

The fix went into the tool. When it assigns a driver, it also records the full candidate pool it chose from:

candidates = [
    d_id for d_id, d in data["drivers"].items()
    if d["status"] == "available"
    and len(d["active_orders"]) < d["max_concurrent_orders"]
    and _haversine_km(d["current_lat_lng"], rest_lat_lng) <= 5.0
]
chosen = sorted(candidates)[0]
order["assigned_driver_id"] = chosen
order["_driver_candidate_set"] = candidates   # for the verifier

The chosen ID is one valid answer, and every member of the candidate set is equally correct. So before hashing the final state, the verifier replaces each equivalence-classed field with its sorted candidate set:

def get_data_hash_canonical(self) -> str:
    canonical = copy.deepcopy(self.data)
    for ovr in self.task.reward_overrides.get("equivalence_class", []):
        candidates = _resolve_path(canonical, ovr["candidate_set_path"])
        if _resolve_path(canonical, ovr["field_path"]) in candidates:
            _set_path(canonical, ovr["field_path"], sorted(candidates))
    return consistent_hash(to_hashable(canonical))

If the agent's chosen driver is in the candidate set, the field becomes sorted(candidates), and any valid driver hashes to the same value. The ground-truth replay collapses to the same set, so the comparison passes for every correct choice instead of only the recorded one.

Canonicalizing before hashing turns "the recorded driver" into "any driver from the recorded candidate set". The tool records the set at runtime; the verifier only swaps it in.

The canonicalizer is about 10 lines. The cost was deciding, per task, which fields are equivalence-classed and what defines each class. That's a question about the domain:

  • For driver dispatch, the class is "available, in range, has capacity."
  • For a multi-stop delivery, it is "any visit order that respects the time windows."

I got this wrong the first time. I defined the equivalence class inside the verifier, as a rule, and that doesn't scale, because the class is different for every task.

So I had the tool record the candidate set at runtime and the verifier read it. The tool knows the domain and records the class, and the verifier only canonicalizes it.

Interactive: dispatch a replacement driver

An order's driver fell through. 4 drivers are all valid: available, in range, with spare capacity. The replay recorded one of them as ground truth. Pick the driver the agent dispatches, then switch the reward function and compare the scores.

Example 2: the monetary identity

Refunds showed the problem with final-state equality most clearly. One disputed charge has several correct resolutions:

  • A full refund to the original card.
  • The full amount as wallet credit.
  • A partial refund plus an apology credit that makes up the rest.
  • A replacement order whose value covers the dispute.

Final-state equality picks one ledger pattern and rejects the others. The business cares that the books balance: the customer is made whole, and no more than whole. That is a conservation law, so the verifier checks an identity instead of a state:

def _monetary_identity_holds(self) -> bool:
    inv = self.task.reward_overrides.get("monetary_identity")
    if inv is None:
        return True
    order = self.data["orders"][self.task.order_id]
    refunded = sum(r["amount"] for r in order.get("refunds", []))
    credited = sum(c["amount"] for c in order.get("credits", []))
    rep_val  = sum(_replacement_value(self, r_id)
                   for r_id in order.get("replacements", []))
    total = refunded + credited + rep_val
    return abs(total - inv["disputed_amount"]) <= inv.get("tolerance", 0.01)

The identity holds within a tolerance ε:

∣∑refunds+∑credits+∑replacement value−disputed amount∣≤ε\left| \sum \text{refunds} + \sum \text{credits} + \sum \text{replacement value} - \text{disputed amount} \right| \le \varepsilon

Any resolution that satisfies it is correct. The check doesn't depend on the path the agent took, which matches how the business sees it.

I underestimated one thing here. The invariant is symmetric, so it doesn't notice when the agent pays out too much.

"Make the customer whole" and "do not over-refund" are separate constraints, and a policy under pressure from a simulated customer can learn to over-refund to end the conversation. So the same override carries a hard cap, checked as a safety gate that runs before anything else:

safety_passed = self._safety_gate_passed()   # e.g. total refund > authorized cap
if not safety_passed:
    return ShapedRewardResult(reward=0.0, outcome_reward=0.0,
                              process_reward=0.0, safety_passed=False)

The gate runs first, and if it trips, the episode's reward is zero and nothing the agent does afterwards changes that. 3 things trip it:

  • exceeding the authorized compensation cap
  • suggesting a substitute the customer is allergic to
  • acting on a flagged-fraud account without escalating

The verifier needs both the invariant (the books balance) and the gate (no irreversible line was crossed), and they run in a fixed order: gate, then canonical outcome, then invariant, then dense process reward on top.

def calculate_reward_shaped(self) -> ShapedRewardResult:
    if not self._safety_gate_passed():
        return ShapedRewardResult(reward=0.0, safety_passed=False, ...)
    outcome = 1.0 if self.get_data_hash_canonical() == self._gt_canonical_hash() else 0.0
    if not self._monetary_identity_holds():
        outcome = 0.0
    process = self._process_reward_score()
    return ShapedRewardResult(reward=outcome + 0.3 * process,
                              outcome_reward=outcome, process_reward=process, ...)

It stays backward compatible. A task with no overrides behaves exactly as before:

  • safety_passed=True
  • the invariant holds, because there's nothing to check
  • process reward is zero
  • the canonical hash equals the original hash

So existing leaderboard numbers don't move, and the new behavior only applies to tasks that declare it.

Dense signal, added last

A sparse reward at the end of an episode makes credit assignment hard. The agent did 15 things, and one number at the end says little about which of them mattered. So each task ships a few process checkpoints, small weighted checks over the trajectory:

[
  {"step": "fetched customer allergen profile before substitution", "weight": 0.15},
  {"step": "filtered substitutes by allergen", "weight": 0.15},
  {"step": "explicit customer confirmation captured", "weight": 0.10}
]

The process reward is the weighted sum over satisfied checkpoints, p = Σᵢ wᵢ · 1[checkpoint i satisfied]. The verifier returns it alongside the outcome, and the training client picks the blend:

  • outcome alone
  • the shaped form r = outcome + 0.3·p
  • outcome gated by safety, r = outcome · 1[safety passed]

I add this last on purpose. Dense shaping is the piece a policy can game most easily: reward the steps and the policy learns to perform the steps without reaching the result. Add it only after the outcome check, the equivalence handling and the safety gate underneath it are correct.

Spec work grows by about 12 minutes per task

The verifier upgrades, end to end:

UpgradeVerifier LOCPer-task spec time
Equivalence-class hashing~10~1 min (1 field)
Safety gates~30 (a small DSL)~3 min
Monetary-identity invariant~25~2 min
Process checkpoints~50~7 min
Grader regression suite~100one-off
Total~215~12 min/task

That's about 215 lines of code, plus about 12 minutes of domain-expert time per task to write down the equivalence class, the gate, the disputed amount and the checkpoints.1

The code is a fixed cost and the specification grows with the task set. At 12 minutes per task, every 1,000 tasks is 200 hours of specification work.

The code cost stays put as the task set grows. The specification cost is tasks times minutes per task, and it needs someone who knows the domain.

The person doing it has to understand 3 things well enough to state a good outcome precisely enough to execute:

  • food-delivery refund policy
  • allergen liability
  • courier dispatch

That changes how I'd plan and staff a project like this:

  • Budget the specification as a separate line item. Estimate it as tasks times minutes per task.
  • Staff a domain expert. The verifier code needs an engineer for a few days, while the specification needs someone who knows the domain for the rest of the project.
  • Time the first 10 tasks before committing to an estimate for the rest.

The verifier also needs tests. If the grader passes a known-bad trajectory or fails a known-good one, every training example it scores carries the wrong label, and you only find out when training stalls on a signal that was wrong from the start.

I keep a regression suite of known-pass, known-fail and edge-case trajectories, and it gates every change to the verifier.

What I got wrong

  • I treated the verifier as plumbing and the data as the product. The verifier is the executable definition of the task, and the data is whatever that definition accepts. With a wrong definition, more data makes things worse, because it scales a wrong signal.
  • I defined equivalence classes inside the verifier. They belong in the tools that know the domain, recorded at runtime.
  • I assumed the money invariant was enough. It is symmetric and misses over-refunds, so it needed a safety gate with a hard cap.

Key takeaways

  • RL trains a policy against a reward, and the agent chases exactly what the reward measures, including parts you didn't intend. The reward is the task definition.
  • The verifier is the code that computes that reward from a trajectory. Domain knowledge gets written down there.
  • Strict final-state equality suits a leaderboard and mis-scores RL, because production domains have several correct outcomes.
  • Real domains need 4 properties: equivalence classes for stochastic choices, hard safety gates for irreversible mistakes, conservation invariants for path-independent correctness, and dense process signal for credit assignment.
  • Run them in a fixed order: gate first, then canonical outcome, then invariant, then process reward. Add dense shaping last because it's the easiest to game.
  • Give the verifier a regression suite. A silent grader bug mislabels every training example after it.
  • Budget for the specification. The code took a couple of days. At about 12 minutes per task, the specification is 200 hours per 1,000 tasks.

The full design study behind this post is on GitHub, including the domain spec, the reward and verifier design, the cost model, and a 12-slide deck: agent-eval-domain-extension.

Footnotes

  1. The 12 minutes is my average across this food-delivery domain, where I knew the refund and dispatch rules going in. Time the first 10 tasks in your domain before extrapolating: a domain you have to learn as you go, or one with more safety rules, takes longer per task. ↩

Common questions

Why is strict 0/1 final-state equality wrong for RL?↓

It is fine for a leaderboard, where you want a hard pass or fail. For RL it punishes outcomes that are correct but not identical to the recorded ground truth: a refund paid as wallet credit instead of to the card, a different but equally valid driver, a different valid visit order. The policy gets zero reward for being right, which teaches it the wrong thing.

What does a reward function specify?↓

Correctness. It is the executable definition of a good outcome in the domain. Real domains need 4 things that final-state equality misses: equivalence classes (any valid choice is correct), irreversible safety constraints, path-independent invariants (conserved quantities instead of one specific ledger), and dense intermediate signal.

If the verifier is only ~215 lines, where does the cost go?↓

Into per-task specification. About 12 minutes of domain-expert time per task to write down what correct means for that task: the equivalence class, the safety gate, the disputed amount, and the process checkpoints. The limit is how well someone understands the domain.

How do you reward an outcome that has several valid forms?↓

Canonicalize before you compare. For a stochastic driver assignment, hash the sorted candidate set instead of the chosen ID. For money, check a conservation identity (refunds plus credits plus replacement value equals the disputed amount within a tolerance) instead of matching one specific ledger pattern.

What is reinforcement learning, in one paragraph?↓

A learning setup where an agent acts in an environment, the environment returns a reward signal, and the agent improves its policy to earn more reward over time. There is no labeled answer per step as in supervised learning. The agent learns from consequences, the way you learn to ride a bike by wobbling and falling instead of from a manual. Because the policy chases whatever the reward measures, the reward function is the working definition of the task.

Keep reading

All posts Get in touch