Getting Started with TanStack Oracles: Guarding Specifications with Independent Models and Mutation Checks
TanStack Oracles defines specifications as laws and checks the real implementation against a simple independent model over the same action history. This article covers its design and hands-on use of oracleProperty, calibration, and oracle-gaps.
AI coding agents can now generate large amounts of code and tests in a short time, and the bottleneck in software development is shifting from "writing the implementation" to "verifying that the code does what was intended." Keeping up with an ever-growing stream of changes through human review alone is not realistic. We need a way to turn the specifications that developers decide on into something that tools and agents can verify automatically.
Traditional testing techniques have their own limits. Example-based tests, which list concrete input/output pairs, can only verify the cases someone already thought of. Property-based tests generate inputs automatically and check properties that must hold, which improves coverage. But for code whose state changes over a sequence of operations, two problems remain: how to compute the correct expected value, and whether the test's own checks are too lenient and let bugs slip through.
TanStack Oracles, announced as an early preview on December 3, 2026, is a framework aimed at this verification problem. It combines property-based testing, model-based testing, fuzzing, and mutation testing. You define the promises your software must keep as code, and the framework verifies both the implementation and the oracles themselves.
In this article, we first look at the design philosophy and building blocks of TanStack Oracles. Then we add @tanstack/oracles to a Vitest and fast-check project and try it out end to end: writing an oracle test with oracleProperty, verifying the check function with calibration, and running mutation checks with the oracle-gaps CLI.
This article is based on @tanstack/[email protected], the early preview available as of December 4, 2026. The API may change in future releases.
What Is TanStack Oracles?
TanStack Oracles is a verification framework that makes the promises about a piece of software's behavior explicit as a
law, then compares two results for automatically generated action histories: one from a simple independent model and one from the production code.
What sets it apart from existing testing techniques is the unit of verification and how the expected value is computed.
- Example-based tests (unit tests): The developer writes specific inputs and expected answers one at a time. For example, pass
[3, 1, 2]to a sort function and check that you get[1, 2, 3] - Property-based tests: Input generation is left to a generator, and the test checks properties such as invariants or ordering
- Oracle tests (TanStack Oracles): You provide a simple independent model (the oracle) that computes the correct expected value for any action history, apply the same history to both the model and the production code, and compare the results strictly at each point in time
In software testing, a "test oracle" is a term for the criterion or mechanism that tells you the correct expected result for any given input. The word comes from the Latin oraculum, a source of divine answers. It passed through Alan Turing's theory of computation (the oracle machine) and became established in software testing research in the 1970s and 80s.
Consider a task management app with a feature that "always lists the top 3 incomplete tasks by priority, breaking ties by ascending ID." Tasks are updated frequently through operations such as adding, completing, reopening, changing priority, and deleting.
In a production application or library, scanning and re-sorting every task on every operation gets expensive as the number of tasks grows, so you would likely add indexes, caches, or incremental updates to speed things up. However, the more branches you add for optimization, the easier it becomes for boundary bugs to sneak in, such as "a completed task stays in the list" or "the order breaks when tasks with the same priority swap places at the third slot."
That is why oracle testing deliberately keeps the test's "independent model" simple. The independent model holds every task in a plain Map and recomputes the top 3 from scratch with filter, sort, and slice on every operation. It gives up efficiency in exchange for simplicity, so that anyone can read it and tell whether it matches the specification, and then compares it with what the production code returns for the same action history.
The official blog calls this structure "One history, two answers." The key point is that the independent model does not reuse the production code's internal helpers or comparison logic. If they shared the same logic, the production code and the model would reproduce the same bug and agree on the wrong answer.
TanStack Oracles packages this verification cycle into a single registration function, oracleProperty, and splits it into five building blocks by responsibility. On top of that, it adds mechanisms that check the oracle itself for blind spots.
These are the five main elements that oracleProperty takes:
law: An object that records the promise the software keeps, its authority, and what this oracle does not guarantee. The current behavior of the production code may serve as evidence, but never as the authorityhistories: The definition of the action histories fed to the test. You can choose between an enumerated source that covers a finite range exhaustively and a generated source that uses afast-checkArbitrarymodel: A pure function that computes the expected result from an action history. It must not depend on the production codedriver: A function that applies the action history to the production code's public API and records public observations withobserve(checkpoint, value). It returns nothing and does not decide pass or failcheck: A function that compares the observation trace recorded by thedriverwith themodel's expected values and returnspassorviolation. Onlycheckcan report a violation
Recording the promise and its authority in law, right next to the code, is designed with AI coding agents in mind. Design decisions buried in specification documents or PR discussions are easy for an agent to miss when it later optimizes the code as part of a different task. When those decisions are executable as oracles, the test fails the moment an optimization breaks the order of equal-priority tasks, and the agent is shown the violated law, its authority (authority), and a minimal counterexample directly.
TanStack Oracles grew out of the work by its author, Kyle Mathews, to bring TanStack DB, a client-side data framework, to 1.0 RC1. According to TanStack DB 1.0 RC1: Going All In on Oracles, TanStack DB runs 211 oracle test files (roughly 420,000 lines) across 15 packages. @tanstack/oracles extracts that machinery into a general-purpose package, and the conditions an oracle must meet are summarized as ORC-001 to ORC-016 in the repository's Oracle checklist.
Three mechanisms that verify the oracle itself
Even when you combine an independent model with random generation, a fully passing test suite is not enough to feel safe. Two kinds of failure can still happen: "the tests never reached the state where the bug lives" and "they reached it, but the check function missed the problem."
The official blog shares a lesson learned during TanStack DB development. A test-side subscriber that verified a collection's change notifications handled both insert and update with JavaScript's Map.set. Even though the production code was sending an invalid message, an update for a row that did not exist, the final contents of the Map matched and the tests passed. When the check was made strict enough to reject an update for a missing row, 26 of the existing 378 cases failed at once without adding a single new history, exposing production bugs that had been hiding.
Based on this experience, TanStack Oracles builds three mechanisms into the framework, alongside the ones that verify production code, to question and confirm how well the oracle itself can detect problems.
constructed histories(reach check): Deliberately builds boundary conditions that random generation rarely produces, using a random history as a base. You declare the states that must be reached withstatesandenters, and the test itself fails if they are not reached at run timecalibration(checking that wrong answers are rejected): Picks a history that passes and feeds thecheckfunction data whose observation trace was deliberately corrupted by acorruptfunction (for example, swapping the order of equal-priority tasks from[a, b]to[b, a]). The test fails if the specifiedlawdoes not reliably reject itoracle-gapsCLI (gap detection through mutation): Automatically generates small mutations (mutants) in a copy of the production source declared inowns, such as changing<to<=or making anifcondition alwaystrue, and checks whether the registered oracles reject them. Every mutation that is not rejected is reported as a "gap"
Together, these let you continuously run a "design loop" that decides and revises the specification and an "enforcement loop" that closes the gaps in both the implementation and the oracles.
Setup and the Module Under Test
From here on, we run @tanstack/oracles in an actual TypeScript and Vitest project. Create a new directory and install the dependencies. fast-check is added for property-based testing.
npm init -y
npm install --save-dev @tanstack/[email protected] fast-check@^4.10.2 vitest@^4.1.12 typescript@^5.9.2Add package.json, tsconfig.json, and vitest.config.ts.
Configuration files
{
"name": "tanstack-oracles-example",
"private": true,
"type": "module",
"scripts": {
"test": "vitest run",
"gaps": "oracle-gaps --package . --source src/top-tasks.ts"
},
"devDependencies": {
"@tanstack/oracles": "0.0.1",
"fast-check": "^4.10.2",
"typescript": "^5.9.2",
"vitest": "^4.1.12"
}
}{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["src", "tests", "vitest.config.ts"]
}import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
},
})Next, implement the production module under test, src/top-tasks.ts. It receives upsert or remove actions and returns the IDs of the top 3 incomplete tasks, ordered by descending priority with ties broken by ascending ID.
Instead of re-sorting every task each time, it caches the top 3 in an array called cachedTop and rebuilds it only when it decides the change has an effect.
export interface Task {
readonly id: string
readonly priority: number
readonly completed: boolean
}
export type TaskAction =
| { readonly type: 'upsert'; readonly task: Task }
| { readonly type: 'remove'; readonly id: string }
function compareTasks(a: Task, b: Task): number {
if (b.priority !== a.priority) {
return b.priority - a.priority
}
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
}
export function createTopTasksBoard(limit = 3) {
const tasks = new Map<string, Task>()
let cachedTop: Array<Task> = []
const rebuildTop = () => {
const openTasks: Array<Task> = []
for (const task of tasks.values()) {
if (!task.completed) {
openTasks.push(task)
}
}
openTasks.sort(compareTasks)
cachedTop = openTasks.slice(0, limit)
}
// Decides whether the cache needs to be rebuilt
const affectsTop = (id: string, nextTask: Task | undefined): boolean => {
if (cachedTop.some((task) => task.id === id)) {
return true
}
if (!nextTask || nextTask.completed) {
return false
}
if (cachedTop.length < limit) {
return true
}
const last = cachedTop[cachedTop.length - 1]!
return compareTasks(nextTask, last) < 0
}
return {
apply(action: TaskAction): void {
if (action.type === 'remove') {
if (!tasks.has(action.id)) {
return
}
tasks.delete(action.id)
if (affectsTop(action.id, undefined)) {
rebuildTop()
}
return
}
const task = { ...action.task }
tasks.set(task.id, task)
if (affectsTop(task.id, task)) {
rebuildTop()
}
},
getTopIds(): Array<string> {
return cachedTop.map((task) => task.id)
},
}
}affectsTop is the logic that decides whether to update the cache. For example, it skips rebuildTop when "a completed task outside the cache is removed" or "the 3 slots are already full and the added task ranks below the last one." Incremental optimizations like this add branches where bugs can hide, which makes them a perfect subject for oracle testing.
Writing and Running an Oracle with oracleProperty
Oracle tests go in files whose names contain oracle. Here, create tests/top-tasks-oracle.property.test.ts.
First, define the rules for random action histories (a fast-check Arbitrary) and the model, driver, and check functions. Their roles are as follows:
- Action history rules: A definition that generates action histories made of 1 to 12 random
upsertandremoveoperations model(expectedSnapshots): An independent model that does not use the production cache and recomputes the expected list of IDs for each step from a plainMapevery timedriver(driveTopTasks): Applies the same action history to the productioncreateTopTasksBoardin order and recordsgetTopIds()for each step withobserve()check(checkTopTasks): Compares the observation trace recorded by thedriverwith themodel's expected values step by step, returningpassif everything matches andviolationif anything differs
import fc from 'fast-check'
import { differs, oracleProperty, pass } from '@tanstack/oracles'
import type { Observation } from '@tanstack/oracles'
import { createTopTasksBoard } from '../src/top-tasks.js'
import type { Task, TaskAction } from '../src/top-tasks.js'
const LIMIT = 3
const TASK_IDS = ['a', 'b', 'c', 'd', 'e', 'f'] as const
type History = {
readonly actions: ReadonlyArray<TaskAction>
}
const taskIdArb = fc.constantFrom<string>(...TASK_IDS)
const taskArb: fc.Arbitrary<Task> = fc.record({
id: taskIdArb,
priority: fc.integer({ min: 0, max: 5 }),
completed: fc.boolean(),
})
const actionArb: fc.Arbitrary<TaskAction> = fc.oneof(
fc.record({
type: fc.constant('upsert' as const),
task: taskArb,
}),
fc.record({
type: fc.constant('remove' as const),
id: taskIdArb,
}),
)
const historyArb: fc.Arbitrary<History> = fc.record({
actions: fc.array(actionArb, { minLength: 1, maxLength: 12 }),
})
// Independent model: skips the production cache and recomputes the expected values from the whole Map every time
function expectedSnapshots(history: History): Array<Array<string>> {
const tasks = new Map<string, Task>()
const snapshots: Array<Array<string>> = []
for (const action of history.actions) {
if (action.type === 'remove') {
tasks.delete(action.id)
} else {
tasks.set(action.task.id, {
id: action.task.id,
priority: action.task.priority,
completed: action.task.completed,
})
}
const topIds = [...tasks.values()]
.filter((task) => !task.completed)
.sort(
(left, right) =>
right.priority - left.priority ||
(left.id < right.id ? -1 : left.id > right.id ? 1 : 0),
)
.slice(0, LIMIT)
.map((task) => task.id)
snapshots.push(topIds)
}
return snapshots
}
function driveTopTasks(
history: History,
observe: (checkpoint: string, value: unknown) => void,
): void {
const board = createTopTasksBoard(LIMIT)
for (let index = 0; index < history.actions.length; index += 1) {
board.apply(history.actions[index]!)
observe(`step-${index}`, board.getTopIds())
}
}
function checkTopTasks(
_history: History,
observations: ReadonlyArray<Observation>,
expected: ReadonlyArray<ReadonlyArray<string>>,
) {
const count = Math.min(observations.length, expected.length)
for (let index = 0; index < count; index += 1) {
const stepMismatch = differs(
`step-${index}`,
'top-tasks-order',
observations[index]!.value,
expected[index],
)
if (stepMismatch) {
return stepMismatch
}
}
return (
differs(
'trace-length',
'top-tasks-order',
observations.length,
expected.length,
) ?? pass
)
}What if the independent model's own logic is wrong?
The independent model's logic can contain mistakes too. TanStack Oracles does not assume you will write a perfect model on the first try. Instead, it combines the following approaches to make the model itself more trustworthy.
- Keep it simple enough to doubt, and keep it independent: The model gives up efficiency and stays at a dozen or so lines of simple code, so humans and reviewers can spot mistakes by reading it. The official blog states explicitly that neither the model nor the production code is automatically treated as correct. Because the two are written independently, a bug in the model surfaces as a mismatch with production. When a mismatch appears, you diagnose it as one of three things: a production bug, a model bug, or an undecided specification (
law) - Hunt for holes with adversarial review and a checklist: Bring in a reviewer (an agent or a human) other than the one who wrote the oracle, and check whether the model and production share the same misunderstanding, or whether the model abstracts away so much state that it treats cases that should be distinguished as the same
- Add another formulation or an existing system: Where the model and production could share a common mistake, add a second calculation with a different structure, or a metamorphic relation. In areas where a homegrown model is prone to bugs, such as SQL queries or data synchronization, a proven existing system like Postgres can be used directly as the oracle
- Verify the model itself with formal methods: In areas with complex state transitions, such as conflicts between sync and optimistic updates, first verify the model's invariants and the absence of deadlocks with a formal method such as TLA+, then port that model to a TypeScript oracle
The observe and differs functions called in this code pass observations from the driver to check and report violations in a structured form.
observe(checkpoint, value): Records the result of the production code together with a name that identifies the step (such asstep-0). Only plain data can be passed; passing a class instance or aDatedirectly results in anOracleDataErrordiffers(checkpoint, lawName, actual, expected, difference?): Strictly compares the observed value with themodel's expected value and, only when they differ, creates aviolationobject that records which step violated whichlawalong with the difference. Because it returnspass/violationinstead of throwing directly withexpect, the framework can print the violatedlawand the replay command in a uniform format and keep the original reason for the violation during shrinking. It returnsundefinedwhen the values match, so you can append?? passto return a pass. The optional fifth argument,difference, takes a string describing the violation. If omitted, it defaults tothe observed value differs from the owed value, which is shown on theDifference:line of the failure report
There is a reason to go through observe to verify results. By keeping the production code's output in the framework as an observation trace, the following can be automated:
calibrationcan corrupt only the recorded data, without rewriting the production code, and verify in isolation whether thecheckfunction rejects wrong answers- A determinism test can run the same history twice and confirm that the recorded data sequences match exactly
- The
oracle-gapsCLI, covered later, can watch the observations and automatically tell whether, after a mutant was injected, the output changed but thecheckfunction missed it, or the output never changed in the first place
Finally, call oracleProperty. oracleProperty bundles the historyArb, model, driver, and check defined so far together with the law to uphold and additional test cases, and internally calls Vitest's describe / it to generate and run a full set of oracle tests.
Also define entersTieAtLimit, which determines whether an action history passes through the state where "tasks with the same priority compete for the third slot (the moment when the 3rd and 4th incomplete tasks have the same priority)." By passing it to the reached option of oracleProperty, you can count and verify on every run whether the random and constructed histories actually reached that boundary condition.
const TIE_AT_LIMIT = 'tie at limit boundary'
function entersTieAtLimit(history: History): boolean {
const tasks = new Map<string, Task>()
for (const action of history.actions) {
if (action.type === 'remove') {
tasks.delete(action.id)
} else {
tasks.set(action.task.id, action.task)
}
const open = [...tasks.values()]
.filter((task) => !task.completed)
.sort(
(left, right) =>
right.priority - left.priority ||
(left.id < right.id ? -1 : left.id > right.id ? 1 : 0),
)
if (
open.length > LIMIT &&
open[LIMIT - 1]!.priority === open[LIMIT]!.priority
) {
return true
}
}
return false
}
oracleProperty<History, Array<Array<string>>>({
id: 'top-tasks.order',
owns: ['src/top-tasks.ts'],
law: {
statement:
'For every sequence of upsert and remove actions, getTopIds() returns the top 3 incomplete tasks ordered by descending priority and ascending ID.',
authority: 'TopTasksBoard specification (limit=3, priority desc, id asc)',
limits:
'Covers synchronous single-board sequences up to 12 actions with limit=3 and IDs a..f.',
},
histories: {
arbitrary: historyArb,
runs: 100,
fixedSeeds: [20261204],
states: [TIE_AT_LIMIT],
fixed: [
{
name: 'equal-priority tie-break',
history: {
actions: [
{ type: 'upsert', task: { id: 'b', priority: 3, completed: false } },
{ type: 'upsert', task: { id: 'a', priority: 3, completed: false } },
],
},
},
],
constructed: [
{
name: 'tie at third slot',
enters: [TIE_AT_LIMIT],
build: (generated) => ({
actions: [
{ type: 'upsert', task: { id: 'e', priority: 5, completed: false } },
{ type: 'upsert', task: { id: 'f', priority: 4, completed: false } },
{ type: 'upsert', task: { id: 'b', priority: 2, completed: false } },
{ type: 'upsert', task: { id: 'a', priority: 2, completed: false } },
{ type: 'upsert', task: { id: 'a', priority: 2, completed: true } },
{ type: 'upsert', task: { id: 'a', priority: 2, completed: false } },
...generated.actions.slice(0, 6),
],
}),
},
],
},
model: expectedSnapshots,
reached: (history) => (entersTieAtLimit(history) ? [TIE_AT_LIMIT] : []),
driver: driveTopTasks,
check: checkTopTasks,
calibrations: [
{
name: 'swapped order for equal-priority tasks',
law: 'top-tasks-order',
history: { fixed: 'equal-priority tie-break' },
corrupt: (trace) => {
const lastIndex = trace.length - 1
const last = trace[lastIndex]
if (!last || !Array.isArray(last.value) || last.value.length < 2) {
return undefined
}
const swapped = [...last.value]
;[swapped[0], swapped[1]] = [swapped[1], swapped[0]]
return [
...trace.slice(0, lastIndex),
{ checkpoint: last.checkpoint, value: swapped },
]
},
},
],
})The main options of oracleProperty do the following:
owns: A literal array of the production source files this oracle is responsible for. Theoracle-gapsCLI, covered later, reads it through static analysis, so it must be passed as a literal array rather than a variablehistories.fixedSeeds: An array of fixed seeds that reproduce the same random sequence every time. In addition to one campaign per seed, a random campaign that explores with a different seed each run is registered automaticallyhistories.constructed: A way to assemble histories by combining handwritten operations with randomly generated ones, so that boundary conditions that random generation rarely produces are hit every time. In this example, the first half creates an equal-priority tie and the second half appends random operations. The test itself fails if the states declared inentersare not reachedcalibrations: A "test for the test" that confirms thecheckfunction is not letting wrong answers through. Without changing the production code, thecorruptfunction deliberately rewrites the final observation of the fixed historyequal-priority tie-break(['a', 'b']) to['b', 'a']and passes it to thecheckfunction. It passes if the specifiedlaw: 'top-tasks-order'reliably rejects it, and fails if the wrong answer slips through or fails for a different reason
Checking the Results in Vitest
The diagram below lets you follow how a single action history (step-0 to step-4) is processed at test time through histories → model → driver → check → reached, switching between the inputs and outputs of each stage.
When you actually run npm test, a single oracleProperty call automatically registers and runs 11 tests.
top-tasks.order fixed seed 20261204: tie at third slot reach {"tie at limit boundary":5}
top-tasks.order fixed seed 20261204: generated reach {"tie at limit boundary":1}
stdout | tests/top-tasks-oracle.property.test.ts > top-tasks.order > random seed: tie at third slot
ORACLE_SEED {"property":"top-tasks.order","seed":1175093126}
top-tasks.order random seed: tie at third slot reach {"tie at limit boundary":5}
top-tasks.order random seed: generated reach {"tie at limit boundary":0}
✓ tests/top-tasks-oracle.property.test.ts (11 tests) 29ms
✓ top-tasks.order (11)
✓ fixed seed 20261204: tie at third slot 5ms
✓ fixed seed 20261204: generated 13ms
✓ random seed: tie at third slot 2ms
✓ random seed: generated 6ms
✓ fixed history: equal-priority tie-break 0ms
✓ calibration: swapped order for equal-priority tasks 0ms
✓ determinism: fixed history: equal-priority tie-break 0ms
✓ determinism: constructed history: tie at third slot 0ms
✓ determinism: generated 0 1ms
✓ determinism: generated 1 0ms
✓ determinism: generated 2 0msThis output confirms two things:
- In the
generatedunits, which run 100 random trials, the equal-priority tie occurred only once with the fixed seed and zero times with the random seed. In contrast,constructedreached it in every case. This shows that boundary conditions can be built explicitly - Because the framework automatically runs the same history twice and verifies that the observation traces match exactly, it also guards against reproducibility being broken by things like the current time or random IDs leaking in
Detecting an Intentional Bug and Replaying It
Let's also check how the oracle behaves when a bug actually gets into the production code. Suppose the early return for completed or removed tasks in affectsTop in src/top-tasks.ts was written before the check for whether the task is in cachedTop.
const affectsTop = (id: string, nextTask: Task | undefined): boolean => {
if (!nextTask || nextTask.completed) {
return false
}
if (cachedTop.some((task) => task.id === id)) {
return true
}Running npm test in this state makes four campaign units fail, with reports like the following:
FAIL tests/top-tasks-oracle.property.test.ts > top-tasks.order > fixed seed 20261204: generated
Error: Property failed after 3 tests
{ seed: 20261204, path: "2:3:3:3:2:1:1", endOnFailure: true }
Counterexample: [{"actions":[{"type":"upsert","task":{"id":"a","priority":0,"completed":false}},{"type":"remove","id":"a"}]}]
Shrunk 6 time(s)
Replay: ORACLE_SEED=20261204 ORACLE_PATH=2:3:3:3:2:1:1 ORACLE_PROPERTY='top-tasks.order' ORACLE_UNIT='random seed: generated' vitest run -t '^top-tasks\.order(?: | > )random seed: generated$'
Caused by: OracleViolation: top-tasks.order violated at checkpoint "step-1" (law: top-tasks-order).
Law: For every sequence of upsert and remove actions, getTopIds() returns the top 3 incomplete tasks ordered by descending priority and ascending ID.
Difference: the observed value differs from the owed value
History: {"actions":[{"type":"upsert","task":{"id":"a","priority":0,"completed":false}},{"type":"remove","id":"a"}]}
Authority: TopTasksBoard specification (limit=3, priority desc, id asc)
Known limits: Covers synchronous single-board sequences up to 12 actions with limit=3 and IDs a..f.
- Expected
+ Received
- []
+ [
+ "a",
+ ]Six rounds of shrinking narrowed the failure down to a minimal two-action history, "add task a and then remove it immediately," and the violated Law, the Authority, the checkpoint (step-1), and the difference ([] versus ["a"]) are all shown together on one screen.
Running the printed Replay: line as is deterministically reproduces just this case. By specifying ORACLE_SEED and ORACLE_PATH, it replays only the branch of the randomly generated histories where the violation occurred.
Once you are done checking, restore affectsTop in src/top-tasks.ts to its original, correct order.
Finding Blind Spots with oracle-gaps
With all tests passing, run the oracle-gaps CLI next. This command automatically embeds mutants into a copy of src/top-tasks.ts and checks whether the oracle we just wrote can detect them.
npm run gapsIt checked 55 mutants in about one second and printed a report like this:
oracle-gaps: baseline pass tests/top-tasks-oracle.property.test.ts: 11 tests
oracle-gaps: baseline all 1 oracle file pass
oracle-gaps: progress unmutated: 11 tests in 0.2s and 0.1s; nondeterministic: 0
...
oracle-gaps: progress mutant phase: 55 mutants in 1.0s
oracle-gaps: summary 90092dd65ada: 55 mutants, 38 killed, 17 gaps, 0 unowned (warnings). 1 source files, 1 oracle files, 0 ordinary test files, 0 authored mutants, seed (none), pool threads.
oracle-gaps: function fn compareTasks (src/top-tasks.ts) (owners: tests/top-tasks-oracle.property.test.ts)
oracle-gaps: gap not-infected L15 top-tasks.ts:M6 ` < ` → ` <= `
oracle-gaps: gap not-infected L15 top-tasks.ts:M7 ` > ` → ` >= `
oracle-gaps: function fn rebuildTop (src/top-tasks.ts) (owners: tests/top-tasks-oracle.property.test.ts)
oracle-gaps: gap crashed L24 top-tasks.ts:M8 ` tasks.values() ` → ` undefined `
oracle-gaps: gap crashed L30 top-tasks.ts:M14 ` openTasks.slice(0, limit) ` → ` undefined `
oracle-gaps: function fn affectsTop (src/top-tasks.ts) (owners: tests/top-tasks-oracle.property.test.ts)
oracle-gaps: gap extra-work L35 top-tasks.ts:M15 ` cachedTop.some((task) => task.id === id) ` → ` true `
oracle-gaps: gap crashed L38 top-tasks.ts:M23 ` || ` → ` && `
...
oracle-gaps: done completed, 17 gaps, report .../summary.mdOf the 55 mutants, 38 were rejected (killed) by the top-tasks-order law, but 17 were reported as gaps. The breakdown is 6 crashed, 5 extra-work, 3 not-infected, 2 not-observed, and 1 not-distinguished. Two categories in particular differ from typical mutation testing tools:
crashed: Mutants such as replacingtasks.values()withundefined, where the production code throws aTypeErrorand thedriverstops partway through. Typical mutation testing counts a test that fails due to an exception as a successful detection, butoracle-gapsonly accepts a kill when thecheckfunction returns alawviolation. To resolve these, wrap thedriverintry / catch, record the exception withobserveas well, and have thecheckfunction explicitly reject it as alawviolationextra-work: Mutants that rewrite a condition inaffectsToptotrue, disabling the cache shortcut. The output does not change, but the CLI detects that the instrumented expressions were evaluated more times and suggests declaringwork: { ratio: ... }onoraclePropertyso that the mutant is rejected by an upper bound on work (work bound)
In addition, the not-infected gaps for a.id < b.id ? -1 : a.id > b.id ? 1 : 0 in compareTasks show that two tasks with the same ID are never compared, because Map keys are unique. This can also help you notice branches that cannot happen under the specification (dead code).
Applying the Gap Report and Rerunning
Following the report's guidance, make two improvements to tests/top-tasks-oracle.property.test.ts. First, record exceptions in driveTopTasks with observe('error', ...) and judge them as top-tasks-order violations in checkTopTasks. Second, add work: { ratio: 1.0 } to oracleProperty to reject the extra work caused by removing shortcuts.
function driveTopTasks(
history: History,
observe: (checkpoint: string, value: unknown) => void,
): void {
try {
const board = createTopTasksBoard(LIMIT)
for (let index = 0; index < history.actions.length; index += 1) {
board.apply(history.actions[index]!)
observe(`step-${index}`, { ok: true, ids: board.getTopIds() })
}
} catch (error) {
observe('error', {
ok: false,
message: error instanceof Error ? error.message : String(error),
})
}
}
function checkTopTasks(
_history: History,
observations: ReadonlyArray<Observation>,
expected: ReadonlyArray<ReadonlyArray<string>>,
) {
for (let index = 0; index < observations.length; index += 1) {
const observation = observations[index]!
if (observation.checkpoint === 'error') {
return differs(
'error',
'top-tasks-order',
observation.value,
{ ok: true },
'production threw while applying a valid action sequence',
)!
}
const expectedIds = expected[index]
const stepMismatch = differs(
`step-${index}`,
'top-tasks-order',
observation.value,
{ ok: true, ids: expectedIds },
)
if (stepMismatch) {
return stepMismatch
}
}
return (
differs(
'trace-length',
'top-tasks-order',
observations.length,
expected.length,
) ?? pass
)
}
oracleProperty<History, Array<Array<string>>>({
id: 'top-tasks.order',
owns: ['src/top-tasks.ts'],
work: { ratio: 1.0 },
// law, histories, model, reached, driver, and check are omitted...
calibrations: [
{
name: 'swapped order for equal-priority tasks',
law: 'top-tasks-order',
history: { fixed: 'equal-priority tie-break' },
corrupt: (trace) => {
const lastIndex = trace.length - 1
const last = trace[lastIndex]
const value = last?.value as { ok: true; ids: Array<string> } | undefined
if (!last || !value || !Array.isArray(value.ids) || value.ids.length < 2) {
return undefined
}
const swapped = [...value.ids]
;[swapped[0], swapped[1]] = [swapped[1], swapped[0]]
return [
...trace.slice(0, lastIndex),
{ checkpoint: last.checkpoint, value: { ok: true, ids: swapped } },
]
},
},
],
})In checkTopTasks, the checkpoint that recorded an exception passes 'production threw while applying a valid action sequence' as the fifth argument to differs. This lets the Difference: line of the failure report distinguish between "the values differed" and "the production code threw an exception."
work: { ratio: 1.0 } compares a deterministic count, the number of evaluations of the instrumented code, so it is not affected by machine load. After this change, running npm run gaps again changes the result as follows:
oracle-gaps: summary d5f6dd65d8b3: 55 mutants, 49 killed, 6 gaps, 0 unowned (warnings). 1 source files, 1 oracle files, 0 ordinary test files, 0 authored mutants, seed (none), pool threads.
oracle-gaps: legend not-distinguished: Add an owner history where the input that changes the value on line N gives a different result, and assert on the result.
oracle-gaps: legend not-infected: Add a history whose operands are equal, where `<operator>` and `<operator>` disagree. Operands seen: <a> and <b>.
oracle-gaps: legend not-observed: Observe the value this code changes in `<test>`, and assert on it. Where the mutated code computes the same result as the original, add a history where it computes something different.
...
oracle-gaps: done completed, 6 gaps, report .../summary.mdAll 6 crashed and 5 extra-work gaps were resolved, raising the number of killed mutants to 49 out of 55. For each of the remaining 6, the legend suggests which history or observation to add next.
Although it did not appear in this example, a mutant that only the random campaign could reject is also counted as a gap, under random-only-kill, because it was not killed through a reproducible route such as a fixed seed or fixed history. In this way, oracle-gaps refuses to count a lucky failure as a detection and steers you toward reproducible verification.
Working with AI Coding Agents
So far, we have written oracleProperty by hand, but the real home of TanStack Oracles is collaboration with AI coding agents. Writing the models, history generators, and gap investigations entirely by hand is expensive. By letting an agent handle the routine investigation and implementation while humans focus on deciding "what to promise as the specification (law)," the cost becomes practical.
The @tanstack/oracles package ships with Agent Skills such as oracles-explore, oracles-design, oracles-review, and oracles-setup. The official blog shows an easy way to try it: open a coding agent in your own repository and paste the following prompt.
Show me what oracle testing with @tanstack/oracles can find in this repository.
Download https://raw.githubusercontent.com/TanStack/oracles/main/packages/oracles/skills/oracles-explore/SKILL.md
Read it in full and follow it to explore this repository with Oracles.An agent following this skill does not start mass-producing test files. Instead, it works interactively in the following order:
- Read the target code, documentation, and existing tests, and run
probes (small scripts that call the code's public API to check its behavior) to gather facts - Report discrepancies in behavior and undefined boundary conditions it found, and propose candidate
laws (potential laws) - After the developer approves "bug or specification" and "which promises to adopt," create oracle files and proceed with bug fixes and with closing gaps reported by
oracle-gaps
On the official blog, the author reports applying this approach to more than 100 repositories, including popular npm packages, and finding bugs in every one of them. The post also touches on strengthening models with formal methods such as TLA+ and Lean. The repository's Roadmap lists porting the toolkit to languages beyond JavaScript / TypeScript as one of its top priorities.
Summary
- TanStack Oracles is a framework that integrates property-based testing, model-based testing, fuzzing, and mutation testing into a single approach, addressing the problem of verification becoming the bottleneck in the era of AI coding agents
oraclePropertyseparates responsibilities into five elements,law,histories,model,driver, andcheck, and compares the observations of the independent model and the production implementation step by step for the same action history- A single
oraclePropertyregistration automatically registers fixed-seed, random-seed, fixed-history,calibration, and determinism (determinism) tests, and on failure it prints the violatedlaw, a minimal counterexample, and a deterministicReplay:command - Boundary conditions that random generation tends to miss can be forced with
constructed historiesandstates, andcalibrationverifies that thecheckfunction rejects wrong answers - The
oracle-gapsCLI automatically injects mutants into the production code listed inownsand reports as gaps not only undetected mutations but also unjudged exceptions, extra work from removed shortcuts, and detections that are not reproducible - With the bundled Agent Skills, humans can focus on deciding "what to promise as the specification" while collaborating with agents to verify existing repositories and find bugs




