When implementing non-trivial logic (token estimation, parsing, normalization, cap/policy decisions, diff/tree composition), first write down the exact semantics/invariants the algorithm must satisfy, then implement and test against “tricky shapes” that commonly break those semantics.
Practical checklist:
items, combinators like anyOf/oneOf/allOf), not just the top level.Example (token estimation invariant):
// Invariant: per-image cost is flat (independent of encoded base64 payload length)
const estimate = (data: string) => estimateRequestInputTokens({
messages: [{ role: "user", content: [{ type: "image", data, mediaType: "image/png" }] }],
});
const withoutImage = estimateRequestInputTokens({ messages: [{ role: "user", content: [] }] });
const perImage = estimate("A");
const perImageOnly = perImage - withoutImage;
expect(estimate("A".repeat(500_000)) - withoutImage).toBeCloseTo(perImageOnly, 50);
This standard reduces subtle correctness bugs by making the intended meaning explicit, implementing precisely to that meaning, and preventing regressions with targeted “shape/semantics” tests.