An agent's tool call is a function call written by a model, and a model writes arguments the way a hurried colleague fills in a form: mostly right, occasionally "close enough". It sends "12.50" where you wanted an integer, true where you wanted a number, an order ID with a stray newline, or a nested object where a scalar belongs. Your validator is the only thing standing between those near-misses and a side effect.
Most teams test that validator with a handful of hand-picked cases: one good call, one missing field, one wrong type. Those cases come from the same imagination that wrote the validator, so they share its blind spots. This article shows a cheaper and harder-nosed alternative: state a few properties the validator must always satisfy, then let a property-based testing library generate hundreds of hostile inputs per run. The examples use Python and Hypothesis, but the idea transfers to any language with a property-testing library.
What you are actually testing
You are not testing the model, and you are not testing whether the refund is a good idea. You are testing one pure function: raw arguments in, either clean arguments or an error message out. Pure functions with a narrow contract are the best fit for property testing.
Three properties cover most of the value for a tool validator:
- It never raises. Whatever the model sends, the validator returns a verdict. An uncaught exception inside the validator typically surfaces as a generic server error, which the model cannot act on, so the agent retries blindly or gives up.
- Acceptance implies the invariants. If the validator says "ok", then every rule your downstream code relies on holds: the integer is really an integer, the ID really matches the format, the amount is in range. This is the property that protects the side effect.
- Rejection is short and useful. The error goes back into the model's context. It should be bounded in size and should not echo an arbitrarily large input back, or one bad call can bloat every following turn.
Notice that none of these properties needs an answer key. That is what makes them cheap to write.
A naive validator and the tests that break it
Here is a plausible first version for a create_refund tool. It looks careful: it checks types, coerces a digit string, and bounds the amount.
import re
MAX_CENTS = 50_000
def validate_refund(args):
order_id = args.get("order_id")
if not isinstance(order_id, str) or not re.match(r"^ORD-[0-9]{6}$", order_id):
return ("error", f"order_id must look like ORD-123456, got {order_id!r}")
amount = args.get("amount_cents")
if isinstance(amount, str) and amount.isdigit():
amount = int(amount)
if not isinstance(amount, int) or not (1 <= amount <= MAX_CENTS):
return ("error", f"amount_cents must be an integer from 1 to {MAX_CENTS}, got {amount!r}")
return ("ok", {"order_id": order_id, "amount_cents": amount,
"reason": str(args.get("reason", ""))[:200]})The test file generates arbitrary JSON-like values, plus a structured "near miss" dictionary for the two fields that matter, and asserts the three properties. The digitish strategy deserves a note: it draws characters from Unicode's decimal-digit and other-number categories, which is exactly the kind of input a plain st.text() almost never produces by chance.
from hypothesis import example, given, settings, strategies as st
from refund import MAX_CENTS, validate_refund
scalars = st.one_of(st.none(), st.booleans(), st.integers(), st.floats(), st.text())
values = st.recursive(
scalars,
lambda c: st.one_of(st.lists(c, max_size=3),
st.dictionaries(st.text(max_size=5), c, max_size=3)),
max_leaves=6,
)
digitish = st.text(alphabet=st.characters(categories=["Nd", "No"]),
min_size=1, max_size=6)
args_strategy = st.fixed_dictionaries(
{
"order_id": st.one_of(st.text(max_size=20),
st.from_regex(r"ORD-[0-9]{6}\n?", fullmatch=True)),
"amount_cents": st.one_of(values, st.integers(-10**12, 10**12), digitish),
},
optional={"reason": values},
)
@settings(max_examples=500)
@given(args=st.one_of(args_strategy, values))
def test_validator_properties(args):
status, out = validate_refund(args) # property 1: no exception
assert status in ("ok", "error")
if status == "ok": # property 2: invariants hold
assert type(out["amount_cents"]) is int and 1 <= out["amount_cents"] <= MAX_CENTS
assert out["order_id"].isascii() and len(out["order_id"]) == 10
else: # property 3: error is bounded
assert len(out) < 200Running this test, and slight variations of it, against the naive version produced failures that a hand-written suite would likely have missed (Hypothesis reports one failing property at a time, so I fixed and re-ran in turn):
- Non-object arguments crash it. If the model's arguments parse to
nullor a list,args.getraisesAttributeError. Property 1 flags it immediately; the fix is anisinstance(args, dict)check up front.
- A trailing newline is accepted.
{"order_id": "ORD-000000\n", "amount_cents": 1}passes. In Python,$matches at the end of the string or just before a newline at the end, so the pattern accepts an 11-character ID. The fix isre.fullmatchwith no anchors. - An error message was 200 characters long. A nested list in
amount_centswas echoed back in full through{amount!r}. Real inputs can be far bigger. The fix is to truncate whatever you echo. - `True` is accepted as an amount.
boolis a subclass ofintin Python, soisinstance(True, int)holds and the "amount" is 1 cent. A model that sends a boolean has misunderstood the schema, and silently coercing it hides that. The fix istype(amount) is int. - `"²"` crashes the validator.
str.isdigit()returns true for superscript digits, butint("²")raisesValueError. Property 1 catches this, but only when the generator produces such a character. My first run with a genericst.text()strategy did not find it within its example budget. The targeteddigitishstrategy found it immediately.
That last point is the honest limit of the technique: the library explores the space you describe, so the strategy is where your knowledge goes. Hypothesis shrinks each failure to a minimal example, which is why the reports above are short enough to read.
The fixed validator
import re
MAX_CENTS = 50_000
ORDER_ID = re.compile(r"ORD-[0-9]{6}")
ASCII_INT = re.compile(r"[0-9]{1,6}")
def _show(value):
return repr(str(value)[:40]) # bound what we echo back to the model
def validate_refund(args):
if not isinstance(args, dict):
return ("error", "arguments must be a JSON object")
order_id = args.get("order_id")
if not isinstance(order_id, str) or not ORDER_ID.fullmatch(order_id):
return ("error", f"order_id must look like ORD-123456, got {_show(order_id)}")
amount = args.get("amount_cents")
if isinstance(amount, str) and ASCII_INT.fullmatch(amount):
amount = int(amount)
if type(amount) is not int or not (1 <= amount <= MAX_CENTS):
return ("error", f"amount_cents must be an integer from 1 to {MAX_CENTS}, got {_show(amount)}")
return ("ok", {"order_id": order_id, "amount_cents": amount,
"reason": str(args.get("reason", ""))[:200]})Two design choices are worth defending. Coercion is limited to a short ASCII digit string, so "1250" is accepted but "12.50" and "٣" are not; a clear rejection teaches the model faster than a clever guess about its intent. And the digit regex caps length, which also keeps int() away from absurdly long strings.
Pin the failures and keep the run honest
Once a bug is found, record it as an explicit example so it runs on every build, not only when the random search stumbles on it again:
@example(args={"order_id": "ORD-000001\n", "amount_cents": 1})
@example(args={"order_id": "ORD-000001", "amount_cents": True})
@example(args={"order_id": "ORD-000001", "amount_cents": "²"})Hypothesis also saves failing inputs in a local example database and replays them, but its documentation describes that database as a cache rather than a guarantee, so @example is the right tool for inputs that must always be tested. Explicit examples run before random generation and are not shrunk.
A few trade-offs to keep in mind:
- Properties only cover what you can state. This approach cannot tell you whether refunding 40,000 cents is sensible. Authorization and business rules need example-based tests with real scenarios.
- Generators encode assumptions. If your strategy never produces a near-miss shape, the test passes while the hole remains. Revisit strategies when you see a new odd argument in production traces.
- Parse before you validate. Python's
json.loadsacceptsNaNandInfinityby default, even though they are outside the JSON spec. If your tool arguments arrive through that parser, either reject them withparse_constantor make sure the validator does, and includest.floats()with NaN in your strategy, as above. - Keep the test fast. The validator is pure, so hundreds of examples run in about a second. If a property needs a network or a model, it has stopped being a property test of the validator.
Checklist
- State three properties: never raises, acceptance implies invariants, rejection is short.
- Generate near-misses on purpose: wrong types, booleans as numbers, trailing whitespace, Unicode digits, nested values, NaN.
- Use
fullmatchinstead of anchoredmatch, and checktype(x) is intwhen booleans must not pass. - Truncate every value you echo into an error message.
- Pin each discovered bug with
@example. - Add a strategy whenever production traces show a new shape of bad argument.
Comments (0)
No comments yet — be the first.
Sign in to leave a comment.