Open History to see the last commit
1# Oracle Testing Rubric
2
3A test needs two things: something to try, and a way to tell whether it worked.
4
5In an ordinary example-based test, we supply both: these inputs should produce this result. That works well for individual cases. But as operations interact—insert, update, delete, retry, reconnect—the combinations grow beyond the examples we can reasonably write.
6
7**What if we could generate those combinations and still know the right answer?**
8
9That is the practical value of oracle-based testing. An oracle supplies the judgment independently of how we choose the test cases. It might be another implementation whose behavior should match, an executable specification, a simple reference that recomputes the answer, or a rule relating several executions.
10
11For an incremental query engine, production might maintain complex indexes while the reference simply filters and sorts an array. Or we might compare compatible queries against another database. Either way, we can explore many histories without hand-calculating every expected result.
12
13The payoff is broader bug detection and a stable check during refactoring. The challenge is making sure the reference, generated cases, and observations actually represent the behavior we promise.
14
15Start with [one small oracle](#build-one-small-oracle). Follow the later sections when your contract needs [richer state](#keep-only-state-that-can-matter), [controlled timing](#generate-histories-that-reach-the-problem), or [more observations](#observe-what-the-contract-promises). The [review card](#a-review-card) is a short way to apply the guide to an existing test. Historical cases and research are collected in the [companion notes](oracle-test-notes.md). Use the [project glossary](glossary.md) for terms shared with production code.
16
17For help discovering or challenging the law itself, use the repository's
18[oracle-authoring](https://github.com/TanStack/db/blob/main/.agents/skills/oracle-authoring/SKILL.md) or
19[oracle-review](https://github.com/TanStack/db/blob/main/.agents/skills/oracle-review/SKILL.md) skill and its
20[design instruments](instruments/index.md). These aids support inquiry; the
21numbered requirements below continue to define guide conformance.
22
23## How to interpret this guide
24
25The numbered requirements in this section are the complete checklist for an
26`oracle-rubric.md` conformance audit. Repository policies such as `AGENTS.md` and
27the coverage map apply separately. Later sections explain the requirements and
28give techniques and examples. They do not create additional requirements unless
29they cite one of these IDs.
30
31`MUST`, `SHOULD`, and `MAY` have their usual specification meanings:
32
33- `MUST` is required when the stated trigger applies.
34- `SHOULD` is expected when the trigger applies. A review may accept an
35 explicit, technically grounded reason for doing something else.
36- `MAY` is optional.
37
38Only these uppercase keywords inside numbered requirement blocks define guide
39conformance. Later prose may use lowercase contract terms such as `must` and
40`may`, but it does not create a new guide requirement unless it cites an ORC
41ID. Words such as “useful,” “ask,” and “consider” remain explanatory.
42
43An **important generated property** is a generated property used to protect a
44reusable product law, claim coverage beyond named examples, or demonstrate a
45bug-class repair. A fixed regression, bounded enumeration, or diagnostic stress
46probe is not an important generated property merely because it uses test data.
47
48The executable oracle MUST keep its contract, model, history grammar,
49production driver, and refinement check visible in the oracle file or in
50companion modules that the file names directly. Pull-request evidence and a
51versioned review record tied to the exact reviewed head may supplement those
52five responsibilities, but cannot replace them. Unless a requirement says
53otherwise, other conformance evidence MAY live in the executable test, an
54oracle-file comment, the pull-request description, or a versioned review record
55linked from the change. Reviewers MUST score the stated obligation, not the
56presence of a preferred heading, class, comment template, or helper.
57
58### ORC-001: Contract authority and limits
59
60- **Trigger:** A test computes or constrains an expected product result.
61- **Obligation:** The oracle MUST identify the promised law, its authority, and
62 the limits of the claimed result.
63- **Acceptance evidence:** A reviewer can trace the expected result to an
64 approved API, architecture document, established contract, or design
65 decision, and can identify what the oracle does not establish.
66- **Not required:** One particular comment format or a complete list of every
67 behavior outside the subsystem.
68
69### ORC-002: Independent judgment
70
71- **Trigger:** An oracle compares production with an expected result.
72- **Obligation:** The expected result MUST be derived independently of the
73 production semantic machinery whose behavior it judges.
74- **Acceptance evidence:** The model, alternate implementation, or relation
75 does not import or reproduce the relevant production classifier, transition,
76 comparator, or state machine without a separately justified trusted base.
77- **Not required:** Independence of the production driver. Exercising the real
78 production entry point is expected and does not violate this requirement.
79
80### ORC-003: Distinguishable oracle responsibilities
81
82- **Trigger:** Any oracle or generated-history test.
83- **Obligation:** The oracle MUST combine explanatory prose and executable code
84 as a literate program. Opening prose MUST state the promised law and its
85 limits before test mechanics. Prose beside the model MUST explain why its
86 independent rule predicts the promised result. The oracle MUST explain its
87 legal histories, production path, public observations, and comparison
88 checkpoint beside the relevant code. These explanations and the five
89 responsibilities MUST remain visible in the executable oracle or directly
90 named companion modules. The contract, model, history grammar, production
91 driver, and refinement check MUST remain distinguishable. Changes to the
92 executable law MUST update its prose in the same change.
93- **Acceptance evidence:** A reviewer can learn the subsystem contract by
94 reading the prose and code together. The explanations connect the law to the
95 model and the model to observations at the named checkpoint. A compact oracle
96 may use one opening comment and short explanations beside its code.
97- **Does not satisfy:** Code alone, five headings without explanations, or
98 explanations available only in a pull-request description or separate review
99 record.
100- **Not required:** Five headings, five classes, five files, one fixture per
101 law, a long essay, or a review card embedded in every oracle.
102
103### ORC-004: Generated-history grammar controls
104
105- **Trigger:** A generated property claims coverage of a legal history or input
106 grammar.
107- **Obligation:** The change MUST account for reconstruction, ablation, range,
108 and exclusion for that grammar.
109- **Acceptance evidence:** The evidence names every known valid witness within
110 the claimed scope and shows that each can be reconstructed; accounts for the
111 semantic contribution of each declared axis, rule, or overlap under ablation;
112 states the bounded domains and marginal cases; and names a nearby invalid
113 history or state the grammar rejects.
114- **Evidence location:** These controls MAY be executable calibration checks,
115 comments, pull-request evidence, or a versioned review record tied to the exact
116 reviewed head. Stable executable checks are preferred when the claim is cheap
117 to preserve.
118- **Not required:** One test per control, a Cartesian product of unrelated axes,
119 or a permanent source mutant.
120
121### ORC-005: Production path and observation
122
123- **Trigger:** Any oracle used as product evidence.
124- **Obligation:** The test MUST exercise the named production entry point and
125 MUST compare the promised public observation at the named checkpoint.
126- **Acceptance evidence:** A positive execution witness shows that the intended
127 path and comparison ran. The recorder can represent the violations relevant
128 to the law, including duplicates, omissions, order, or partial output when
129 those are contractual.
130- **Conditional information sufficiency:** When a concrete missing-input
131 hypothesis concerns a public result owed at the named checkpoint, the
132 evidence MUST show whether the production path receives the needed source
133 facts by then. If it does not, mark the claim unresolved. A green comparison
134 after later delivery MUST NOT be cited as proof of that earlier result.
135- **Not required:** Observation of internal facts that the contract does not
136 expose, or an exhaustive search for indistinguishable histories without a
137 concrete information-gap hypothesis. For ORC-012, evidence may record that no
138 concrete missing-information hypothesis was identified; this does not claim
139 an exhaustive search.
140
141### ORC-006: Checker calibration
142
143- **Trigger:** An important generated property or a claimed oracle repair.
144- **Obligation:** The evidence MUST name at least one plausible wrong answer or
145 design and demonstrate that the relevant comparison rejects it.
146- **Acceptance evidence:** A wrong-result control, hostile fixture, fault
147 injection, or production mutant reaches the intended checkpoint and preserves
148 the distinguishing failure.
149- **Not required:** Modifying production, checking in a mutant, or running a
150 production mutation campaign for every oracle.
151- **Conditional obligation:** When a mutant is run, the evidence MUST classify
152 its outcome as assertion failure, timeout, setup failure, runtime failure
153 after setup outside the intended comparison, an unreached path, survival, or
154 equivalence within the tested domain.
155
156### ORC-007: Fixed and random campaigns with direct replay
157
158- **Trigger:** An important generated property.
159- **Obligation:** The package's oracle campaign MUST execute the same property,
160 generators, observation recorder, refinement check, and run budget twice:
161 once with a documented fixed seed and once without a seed. A replay interface
162 MUST accept both the seed and shrink path and MUST run the requested replay
163 directly. When the property uses `fc.commands`, the interface MUST also accept
164 the commands arbitrary's reported `replayPath` and pass it back to
165 `fc.commands`.
166- **Acceptance evidence:** The normal test command reaches both campaigns, each
167 campaign records its execution, and a checked replay command reproduces a
168 captured seed-and-path failure, including the command replay path when the
169 property uses `fc.commands`.
170- **Does not satisfy:** Fixed examples do not replace the fixed-seed campaign.
171 Different generators, observation recorders, refinement checks, or budgets do
172 not establish campaign parity.
173- **Not required:** Running either normal campaign before an explicit replay.
174
175### ORC-008: Stateful-model minimality
176
177- **Trigger:** A change introduces, removes, combines, or splits state in a
178 stateful reference model.
179- **Obligation:** The change MUST explain whether a legal next action can
180 distinguish states the model proposes to treat as equal.
181- **Acceptance evidence:** A distinguishing history justifies retained state,
182 or a reasoned argument shows why removed state cannot change a promised
183 observation or action's legality.
184- **Not required:** An executable mutant for every model field or application of
185 this requirement to a stateless recomputation.
186
187### ORC-009: Vocabulary mapping
188
189- **Trigger:** A model combines or splits production concepts, or introduces a
190 model-only term that could be mistaken for a production concept.
191- **Obligation:** The oracle MUST map the differing concepts explicitly and MUST
192 use the project glossary's term for a shared concept.
193- **Acceptance evidence:** A reviewer can translate model actions, states, and
194 checkpoints to production boundaries without guessing.
195- **Not required:** A mapping entry for plainly local data holders whose meaning
196 and observation are already unambiguous.
197
198### ORC-010: Failure fidelity and cleanup
199
200- **Trigger:** Shrinking, capture, or cleanup can replace or erase an oracle
201 failure.
202- **Obligation:** The harness MUST preserve the original violated law and
203 checkpoint, retain distinguishable secondary cleanup diagnostics, and release
204 its resources.
205- **Acceptance evidence:** The failure report separates the primary mismatch
206 from each cleanup failure and says whether a reduction reproduced the same
207 violation.
208- **Not required:** Throwing cleanup failures as separate top-level exceptions.
209 An `AggregateError` satisfies this requirement when its `cause` and `errors`
210 preserve those distinctions.
211
212### ORC-011: Independent second formulation
213
214- **Trigger:** A reviewer names a plausible semantic fault that production and
215 the primary model could share, and a meaningfully different formulation could
216 distinguish it.
217- **Obligation:** The change SHOULD add that formulation. If it does not, the
218 evidence MUST state why it is impractical or out of scope and track the
219 remaining risk.
220- **Acceptance evidence:** The alternate path states its equivalence or
221 metamorphic relation, including relevant differences in ordering, projection,
222 duplicates, and empty results.
223- **Not required:** A second formulation without a named shared-fault
224 hypothesis.
225- **Does not satisfy:** Agreement between two structurally identical paths does
226 not establish independent evidence.
227
228### ORC-012: Review evidence
229
230- **Trigger:** A change claims that an oracle is new, repaired, or comprehensively
231 audited against this guide.
232- **Obligation:** The review evidence MUST record the outcome of every other
233 applicable numbered requirement and MUST identify the requirements that do
234 not apply.
235- **Acceptance evidence:** Each applicable requirement has concrete evidence or
236 an explicit unresolved gap. Each non-applicable requirement has a reason tied
237 to its trigger.
238- **Conditional bug-class closure:** When a change claims to eliminate a bug
239 class, the review evidence MUST name its contract × history × production-path
240 × observation boundary, identify the original and adjacent distinguishing
241 witnesses, show a relevant wrong design rejected at the intended checkpoint,
242 and list unresolved in-scope cells with their coverage-map owner. A known
243 reachable counterexample prevents a closure claim. One oracle need not own
244 every boundary.
245- **Evidence location:** At closeout, verdict-critical evidence outside the
246 executable oracle MUST live in a versioned review record tied to the exact
247 reviewed head. An editable pull-request description alone does not satisfy
248 this requirement.
249- **Not required:** Copying the layer-comparison questions or review card into
250 every test, answering them in their printed order, or placing the audit in the
251 oracle file.
252
253### ORC-013: Distinguishing witness for a reusable boundary law
254
255- **Trigger:** A fixed or generated oracle is cited as protecting a reusable
256 conditional, threshold, or range law beyond its named examples.
257- **Obligation:** The evidence MUST show a legal witness that reaches the law's
258 premise and a nearby in-domain witness whose observation at the claimed
259 checkpoint distinguishes the stated law from a plausible wrong boundary or
260 consequence. If those witnesses are unavailable, the claim MUST be limited
261 to the tested cases, and the reusable-law gap and its owner MUST be recorded.
262- **Acceptance evidence:** The test or review record names the wrong rule and
263 shows which existing case rejects it. For a numeric threshold, cases on
264 opposite sides are insufficient if a plausible misplaced threshold still
265 produces every expected result in the tested matrix.
266- **Not required:** Random generation, a permanent mutant, or exhaustive tests
267 of every adjacent value for a deliberately bounded example.
268
269### ORC-014: Controlled-premise handoff
270
271- **Trigger:** A controlled provider or host supplies a premise material to an
272 oracle result, and that result is cited as evidence for behavior with a real
273 provider or host.
274- **Obligation:** The evidence MUST identify that premise and either point to a
275 receiving witness in which the real provider or host supplies the same
276 premise, or mark the cross-boundary claim unresolved with an owner.
277- **Shared law:** When the controlled and real environments check the same
278 law, the receiving witness SHOULD be another production driver for the same
279 oracle. It
280 reuses the oracle's law, model, history grammar or examples, and comparison.
281 It supplies only its production entry point, premise control, and
282 observation recorder. If such a witness states its own expected results, it
283 MUST derive them from the oracle's model, or record why it cannot and the
284 drift risk that follows. An independent second model for the same law is an
285 ORC-011 formulation and needs that requirement's shared-fault hypothesis.
286- **Acceptance evidence:** A reviewer can trace the specific event shape,
287 ordering, error, or lifecycle condition from the controlled fixture to the
288 receiving witness. A real-provider test of an unrelated ordinary case does
289 not establish the handoff.
290- **Not required:** An end-to-end run inside every component oracle. An oracle
291 whose claim is explicitly limited to the controlled boundary does not need a
292 real-provider witness to satisfy this requirement.
293
294### ORC-015: Declared reach
295
296- **Trigger:** A pull request adds or changes an important generated property,
297 its history grammar, or its production driver, or cites one as evidence for a
298 bug-class repair.
299- **Obligation:** The property MUST declare the states that its changed or
300 cited laws depend on, and MUST fail when generated histories reach a declared
301 state fewer times than its stated minimum. Use
302 [`createOracleReach`](../../packages/db/tests/oracle-reach.ts) or an
303 equivalent counter that fails the property. A passing run count does not
304 satisfy this requirement.
305- **Acceptance evidence:** The pull request reports each declared state and how
306 many histories reached it in the normal test run. A state that only a larger
307 run budget reaches is reported as such.
308- **Not required:** A declared state for every modeled transition. Declare the
309 states that the cited laws need, so that reach stays honest about scope.
310
311## A quick start
312
313One way to supply that judgment is a small reference model. For a simple stateful test, choose a legal action, apply it to production and the reference, and compare the promised result at the agreed point. “After the action returns” may be the right point for one API; a callback during that action may matter for another.
314
315For example, suppose a query promises IDs in rank order. We expect `[1, 2]`; production returns `[2, 1]`. A length check passes. A membership check passes. An ordered comparison fails. We exercised the query in all three tests, but only one observed the difference we cared about.
316
317An **oracle** is the rule that judges that behavior. The **generator** chooses what to try. Keep those jobs separate: more executions cannot repair a comparison that ignores the promised order.
318
319Before writing the loop, answer six questions:
320
321| Question | What to write down |
322| -------------------------------- | ------------------------------------------------------------------------------------------------------ |
323| What is promised? | The rule, its source and its limits. |
324| What can happen? | Values, actions and relevant action orders. |
325| How will we know the answer? | A simpler reference, another implementation, or a relation that must hold. |
326| What are we actually exercising? | The production entry point and what the fixture supplies. |
327| What will we compare, and when? | Rows, order, events or other promised behavior, at a named checkpoint. |
328| Why should we trust this check? | Evidence the path ran, the comparison rejects the relevant wrong answer, and failures can be replayed. |
329
330These are responsibilities, not six required classes. A small property may answer them in a comment and twenty lines of code. A lifecycle suite may need a separate model and driver. Do not build a framework just to fill the table.
331
332An evidence card is an optional way to collect this information; it is not a
333required file format:
334
335```text
336Law and source:
337Domain and legal histories:
338Reference or relation:
339Production path and checkpoint:
340Observed result and known omissions:
341How to prove it ran and rejects a wrong answer; how to rerun:
342```
343
344An intentionally partial oracle is still useful. A rule that rejects duplicate completion cannot prove the rows are correct, but it can protect a real promise. A fixed regression can preserve a valuable history. Prefer an oracle that generalizes a bug's missing distinction where practical; keep the fixed witness when it adds clarity or reach. Randomness is not what makes either test trustworthy.
345
346Some concurrent contracts allow several results. In those cases, the reference must allow that freedom rather than invent one required order. We will return to that after establishing how to record an execution.
347
348## Write the oracle as executable subsystem documentation
349
350ORC-003 requires literate programming for every oracle and generated-history
351test. Prose and executable code together teach humans and agents the subsystem
352contract. State what the system promises and explain why each observable result
353follows from the model. The guidance below explains this requirement.
354
355This does not make the model the source of product policy. Derive the contract
356from an approved API, architecture document, established behavior, or design
357decision. The file then keeps that contract, its model, and its production
358evidence together.
359
360Two small examples show the form:
361
362- [`load-subset-transaction-refinement-oracle.test.ts`](https://github.com/TanStack/db/blob/main/packages/db/tests/query/load-subset-transaction-refinement-oracle.test.ts)
363 explains when an abort can still cancel an on-demand load.
364- [`fifo-retry-oracle.property.test.ts`](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/fifo-retry-oracle.property.test.ts)
365 explains why a ready transaction waits behind a delayed FIFO head.
366
367### Name oracle files consistently
368
369Use `oracle` in filenames that own an independent expected-result computation,
370state model, differential or metamorphic comparison, or reusable law checker.
371A separate module that defines that model, checker, or its history grammar also
372qualifies. Identify the mechanism in the code before applying the name. A mixed
373test file can qualify through a specific oracle inside it; its other tests do
374not thereby become separate oracles.
375
376An ordinary example or regression does not need this suffix merely because it
377asserts a contract. The same applies to concrete type assertions, fixtures,
378registration wrappers, and generic runner utilities. A driver that only invokes
379production or records observations remains support. Coverage-map inclusion,
380parameterization, and contract prose alone do not establish oracle ownership.
381
382Count owners, model/checker definitions, drivers, and other support separately.
383Several files may execute one shared oracle, and one file may contain several
384oracle mechanisms. A filename is a discovery aid, not evidence of guide
385conformance. Preserve runner suffixes such as `.property.test.ts`, `.test-d.ts`,
386and `.spec.ts`. Update imports, test commands, replay selectors, and current
387coverage links whenever an oracle file moves.
388
389### Keep five responsibilities distinguishable
390
391ORC-003 requires these responsibilities to remain distinguishable even when
392they share one file:
393
394| Layer | What it must answer |
395| --- | --- |
396| Contract | What does the subsystem promise, and where is the boundary? |
397| Model | What is the smallest independent rule that predicts public results? |
398| History grammar | Which values, actions, relationships, and schedules can occur? |
399| Production driver | Which real entry point and event boundary does the test exercise? |
400| Refinement check | Which public observations must agree with the model, and when? |
401
402Do not create five classes merely to match this table. A short file can use one
403opening comment, one pure model function, a generated input, a production
404fixture, and assertions. A large state machine can split these layers into
405separate modules when that makes each layer easier to review.
406
407### Lead with the law
408
409Under ORC-003, state the contract and its limits before introducing test
410mechanics. Start with a question or a direct statement of the problem. Explain
411why a normal example can miss the failure.
412
413Put the central law beside the model too. The opening comment supplies context.
414The local comment lets a reader check the model without searching the file.
415These comments are not duplicates when they serve those separate jobs.
416
417For example:
418
419```ts
420// Publication is the boundary. An abort before publication rejects the load
421// and discards the row. An abort after publication starts resolves the load
422// and keeps the row visible.
423function expectedOutcome(phase: AbortPhase): ExpectedOutcome {
424 // ...
425}
426```
427
428### Make the model easy to distrust
429
430Prefer a pure function or a small state transition. Keep production queues,
431caches, classifiers, and helpers out of the expected result. A reader should be
432able to challenge the model without first learning the implementation.
433
434Name partial models honestly. If a model predicts rows but not callback counts,
435say so. If several outcomes are legal, return the permitted set or relation. Do
436not hide policy in scattered assertions outside the model.
437
438Check every modeled public fact at each relevant boundary. During the FIFO
439rewrite, prose exposed that the first draft modeled calls but checked outbox
440ownership only at the end. Moving both observations into one state model made
441the test and the documentation agree.
442
443### Decompose the model by law
444
445A reference model can become as hard to trust as production. Do not keep adding
446state until it becomes a second implementation of the subsystem.
447
448Treat the oracle as a small graph when the contract has independent laws:
449
450- A node owns one coherent rule and the least state needed to predict it.
451- An edge records a real dependency between two rules.
452- The production driver can feed the same action to several nodes.
453- The refinement check composes their observations at the named checkpoint.
454
455For example, demand generations, facade identity, and callback coherence can
456use separate models. They share actions, but they do not need one controller
457that reproduces every production queue and cache. A failure then names the law
458that diverged. A reviewer can also inspect each rule without learning the rest
459of the subsystem.
460
461Do not split state that a legal next action can observe only as a whole. Use the
462distinguishing-history test: if two states look equal to the proposed nodes,
463can one legal next action produce different promised results? If yes, add the
464missing edge or keep that state in one model.
465
466Decomposition does not mean one model per assertion. Group facts that form one
467state machine. Keep independent policies separate. When an integrated promise
468spans several nodes, add a relational check across their outputs instead of
469merging their internal machinery.
470
471This graph is a reasoning tool, not a required test framework. Plain functions
472and Maps are often enough.
473
474### Treat the input domain as a grammar
475
476Before choosing arbitraries, describe the language of legal cases. A useful
477grammar separates three kinds of fact:
478
479- **Dynamics:** actions and transformations that move the system.
480- **Constraints:** invariants, interfaces, and forbidden combinations.
481- **Boundary conditions:** starting state, scale, provider behavior, and value
482 domains that limit where the rules apply.
483
484Freeze the contract first. Mark which rules come from an API or architecture
485document and which rules the test author inferred. Then map containment,
486overlap, and dependency. Do not force overlapping concerns into a tree merely
487to make the generator neat.
488
489ORC-004 requires four controls before a generated property claims grammar
490coverage:
491
4921. **Reconstruction:** Can the grammar rebuild every known valid witness?
4932. **Ablation:** Does removing each axis, rule, or overlap lose a promised case
494 or admit a forbidden one?
4953. **Range:** Does an independent marginal case require only new parameter
496 values, or does it expose a missing rule?
4974. **Exclusion:** Can the grammar reject a nearby invalid history or state?
498
499Generate adjacent valid forms from this grammar. Do not take a flat Cartesian
500product of unrelated axes merely because the tool makes that easy. When the
501contract does require a product, add a calibration assertion that proves every
502declared cell appears once.
503
504This approach exposes two common false greens. A grammar that cannot reconstruct
505a known bug omits a path. A grammar that generates valid and invalid histories
506without distinction makes skips and classifiers carry hidden policy.
507
508### Use controlled technical English
509
510Write prose that another agent can parse without asking what a term means:
511
512- Use active voice and short sentences.
513- Give one state or event one name. Do not rotate synonyms.
514- Define necessary domain terms when they first appear.
515- Keep lowercase `must`, `may`, and `does not` exact when they describe a
516 product contract. Only the uppercase keywords in the numbered ORC blocks
517 define guide conformance.
518- Use a list for three or more phases, actions, or conditions.
519- Avoid metaphors when a boundary or transition has a precise name.
520- Explain laws, causes, omissions, and checkpoints. Do not narrate clear code.
521
522Aim for no more than 25 words in a descriptive sentence. Keep a longer sentence
523when splitting it would lose a condition or change its force. Clarity is the
524goal. A low word count is not.
525
526### Use production vocabulary
527
528The model and production code must use the same term for the same concept. Read
529the [project glossary](glossary.md) and the subsystem architecture before naming
530model states, actions, or observations.
531
532Shared vocabulary does not weaken model independence. Reuse a production term,
533not its queue, cache, transition helper, or semantic implementation. If the
534model deliberately combines or splits production concepts, declare that mapping
535beside the model. Never give a model-only convenience the name of a stronger
536production concept.
537
538Check the causal grammar as well as the nouns. Demand starts an acquisition
539attempt. Adapter acceptance establishes a physical acquisition and its lease.
540Committing source writes produces an applied receipt. Publication exposes one
541coherent public snapshot. Adapter acceptance, promise settlement, applied
542settlement, and publication are different boundaries even when one synchronous
543execution crosses all four.
544
545Avoid unqualified words that hide those distinctions. Name a `sync run`,
546`public snapshot`, `logical subset owner`, or `window-operation generation`
547rather than a generic session, state, owner, or generation. When production
548renames a concept, update its glossary entry and the models that represent it in
549the same change.
550
551### Audit prose, model, driver, and observations together
552
553Treat the layers as separate claims. Compare each pair during review:
554
5551. Does every promise in the prose have a model rule?
5562. Does the model retain every distinction that a legal next action can expose?
5573. Can the history grammar reach each modeled transition?
5584. Does the driver exercise the named production path and event boundary?
5595. Does each modeled output reach an assertion at the promised checkpoint?
5606. Can the recorder represent duplicate, missing, reordered, or partial output?
5617. Does any assertion impose behavior that the contract and model do not state?
5628. Do prose, model, driver, and production use the glossary's canonical term
563 and transition grammar for each shared concept?
5649. Does every model-only term declare how it maps to production, or that it has
565 no production counterpart?
566
567This comparison is a useful audit instrument. ORC-012 requires outcomes for the
568applicable numbered requirements, not these questions or their answers in the
569test file. If the prose cannot explain an assertion through the model, the model
570may be incomplete. If the model predicts a fact that the test never observes,
571the test may be false green. If the driver cannot create a named phase, the
572prose claims more reach than the test has.
573
574### Keep the prose proportional
575
576ORC-003 requires explanatory prose and five visible responsibilities in every
577oracle and generated-history test. A focused regression that is not an oracle
578can remain short when its name and setup already state the whole contract,
579but it does not replace applicable oracle coverage.
580
581Mandatory structure does not mean five classes or a long essay. A compact
582oracle can state its contract and limits in one opening comment, keep a pure
583model beside it, define a small grammar, drive the production entry point, and
584compare the promised observations at a named checkpoint.
585
586As a starting budget, add only prose that helps a reader answer one of the five
587layer questions. After the first draft, remove comments that only translate the
588next line of code into English. Run the test after the rewrite. A documentation
589edit that weakens the executable law changes behavior.
590
591## Build one small oracle
592
593We'll build a small reference model as one example of the approach. The following is an **illustrative contract**, not a specification for every TanStack query:
594
595- Rows have unique integer `id` values and finite numeric `rank` values.
596- Rows sort by ascending rank, then ascending ID.
597- A nonnegative integer width chooses the first rows; width zero returns none.
598- Each action inserts an absent ID, changes the rank of a present ID, or deletes a present ID.
599- After an action has been applied, the ordered visible IDs must match a full recomputation.
600
601Here is the completed card for this example:
602
603```text
604Law: sort by rank then ID; return the first width IDs after each action.
605Source: the illustrative contract above.
606Domain: finite numeric ranks, unique integer IDs, legal insert/update/delete.
607Reference: independent Map, fully sorted after every action.
608Production path: the ordered-query entry point, after each action is applied.
609Observe: the complete ordered IDs; not row values or callback counts.
610Prove it ran: record applied actions and executed comparisons.
611Challenge: the comparison must reject [2, 1] when [1, 2] is required.
612Replay: retain the action list and width, plus the harness's replay inputs.
613```
614
615The production path still needs its concrete API name when this card becomes a real integration test. The example does not establish row-value, notification, locale or asynchronous-loading behavior.
616
617### Start with agreement, then the model
618
619Our expected answer is an ordered list of IDs. We may ignore internal tree nodes. We may not sort the actual IDs before comparison: doing so would erase the ordering bug.
620
621The reference can store all rows in a `Map` and sort from scratch. It does not need production's tree, incremental caches or rank maintenance:
622
623```js
624function expectedIds(rows, width) {
625 return [...rows.values()]
626 .sort((a, b) => a.rank - b.rank || a.id - b.id)
627 .slice(0, width)
628 .map((row) => row.id);
629}
630```
631
632Keep the reference's records separate from production's records. If production mutates a shared object and thereby changes the expected answer too, the two sides can agree for the wrong reason. Here, copying the two numeric fields is enough. Richer values need a copying or identity policy suited to their contract—not an automatic appeal to JSON serialization.
633
634Independent code also needs independent reasoning. Calling production's comparator from this reference would make comparator defects invisible to this particular comparison. Reuse mundane test mechanics when useful, but name any semantic helper both sides trust. A small model is easier to inspect; it is not correct merely because it is small.
635
636### Turn examples into histories
637
638Take two rows: `(id: 1, rank: 2)` and `(id: 2, rank: 1)`, with width two. The expected IDs are `[2, 1]`. Change row 1's rank to zero and they become `[1, 2]`. Delete row 1 and the answer becomes `[2]`.
639
640That is a history: a starting state followed by actions. The generator can produce many such histories while the same reference computes each answer.
641
642The integration loop below is pseudocode; the named driver operations are not TanStack APIs:
643
644```text
645create independent model and production fixture
646for each generated action:
647 require action to be legal in the model
648 apply action through the production driver
649 apply action to the model
650 reach the contract's applied checkpoint
651 compare production's visible IDs with expectedIds(model, width)
652finally:
653 clean up the fixture without hiding the original failure
654```
655
656For this settled-result law, no intermediate publication claim follows. If atomic publication is also promised, record callbacks during the action; a read afterward cannot recover a transient tear.
657
658For this example, choose only actions that are legal now:
659
660| Current model | Available choices |
661| -------------------- | ---------------------------------------------------------------- |
662| Empty | Insert an unused ID. |
663| Contains ID 1 | Insert another ID; update 1; delete 1. |
664| Contains IDs 1 and 2 | Insert another ID; update either live ID; delete either live ID. |
665
666After choosing an action kind, choose its key from the applicable set. This is constructive generation: build a legal case rather than repeatedly discard illegal ones. Another valid approach generates commands with applicability checks and skips those that cannot run. Either way, count executed actions; a long list of skipped commands may do little work.
667
668Shrinking means reducing a failing input or action list while keeping its failure. Design action dependencies so the smaller histories remain meaningful; don't disable shrinking merely because the test is stateful. The [fast-check model guide](https://fast-check.dev/docs/advanced/model-based-testing/) describes commands and replay; check the installed version before copying an API recipe.
669
670Pin the structural cases that matter: no rows, width zero, a boundary tie, and repeated changes to one key. Exhaust a small domain where that is cheap. Then randomize values and longer legal histories. Fixed cases, bounded enumeration and random exploration do different jobs; overlap between them is not a defect.
671
672### Run fixed and random campaigns with direct replay
673
674A fixed fast-check seed always generates the same cases. This makes a useful
675history stable, but it does not explore new histories on later runs. Do not
676describe a fixed-seed property as random coverage.
677
678Under ORC-007, every important generated property runs in two campaigns:
679
6801. Run a fixed seed that preserves a known useful campaign.
6812. Run without a seed so fast-check chooses a new seed.
682
683When the random campaign fails, retain the reported seed and shrink path. Give the
684suite environment variables or another checked replay interface. The replay
685input must select both the seed and the path. A seed alone reruns the
686campaign but might not stop at the same reduced counterexample.
687
688`fc.commands` reports another value named `replayPath`. It records which
689generated commands were eligible as the model changed. Capture that command
690replay path separately from `fc.assert`'s shrink path and pass it back through
691the `replayPath` option of `fc.commands`; the assert seed and path alone do not
692fully specify a command-model replay.
693
694When replay inputs are present, run only the requested replay. Do not spend
695time on the fixed campaign before reaching the failure the developer asked to
696reproduce.
697
698The fixed and random campaigns must use the same property, generators,
699observation recorder, refinement check, and run budget. Only their seed source
700may differ. This keeps a random failure eligible for promotion into a pinned
701example or fixed campaign.
702
703[`fifo-retry-oracle.property.test.ts`](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/fifo-retry-oracle.property.test.ts)
704shows this shape. Its fixed run preserves one scheduler campaign. Its second
705campaign uses a random seed by default and accepts `OFFLINE_ORACLE_SEED` with
706`OFFLINE_ORACLE_PATH` for replay.
707
708Do not use a larger random run count as a substitute for structural reach.
709Pinned examples force rare boundaries. Bounded enumeration proves small finite
710domains. A stress job increases sampling depth. Record each form separately.
711
712### Make the comparison prove its usefulness
713
714Suppose the update test only asserts that the result changed. Returning `[]` passes that assertion. Keep the update—it is a useful cause—but compare against `[1, 2]`.
715
716Now test the check against a known bad _actual_ answer:
717
718```js
719function sameOrderedIds(actual, expected) {
720 return (
721 actual.length === expected.length &&
722 expected.every((id, index) => actual[index] === id)
723 );
724}
725
726sameOrderedIds([1, 2], [1, 2]); // true: the allowed answer
727sameOrderedIds([2, 1], [1, 2]); // false: correct members, wrong order
728sameOrderedIds([], [1, 2]); // false: an arbitrary changed answer
729```
730
731In the test harness, assert those outcomes rather than merely calling the function. This calibrates the comparison; a production mutant that reverses results would test whether the whole fixture carries that fault to the assertion. Separately, confirm that the integration test reached the production boundary it names. Checker sensitivity and path reach are different claims: a perfect comparison on an unused code path protects nothing there.
732
733When production fails, keep the original history and the first mismatching checkpoint. Reduce the history while requiring that same violation, then retain the small witness with the broader property. That gives us both a readable explanation and more ways to encounter the class of failure.
734
735### When a full reference is not the best fit
736
737The `Map` works because the answer is cheap to compute independently. Other promises support other judgments:
738
739| Method | Useful judgment | Important limit |
740| ------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------- |
741| Simple model | Recompute the allowed result or step a small abstract state. | The model can omit a meaningful distinction or encode the wrong rule. |
742| Differential comparison | Run equivalent work through another implementation or formulation. | Both paths can share a bug; their semantics must actually agree. |
743| Metamorphic relation | Transform an execution and check a relation between the answers. | The transformation's premises must hold. |
744| Partial invariant | Check a specific promise such as no duplicate completion. | Passing says nothing about unobserved properties. |
745| Recorded regression or snapshot | Preserve a known execution and expected result. | The stored result needs justification; recording it does not make it right. |
746
747Choose the smallest authority that answers the question. Combining complementary checks can help; making every test compute every possible observation usually does not.
748
749## Keep only state that can matter
750
751A reference becomes suspicious when it starts to look like production. But removing fields until it looks simple is not a sound design method either. Which distinctions can we safely discard?
752
753Consider this **illustrative support model**. An acquisition handle supports a row. Replacing handle `a` with `b` transfers that support. Releasing a retired handle is a legal no-op. We observe support, not whether a provider physically deletes a source row.
754
755| History | Current supported rows | Live support count |
756| ---------------------------------------------------- | ---------------------- | ------------------ |
757| Acquire `a` supporting `x` | `{x}` | 1 |
758| Acquire `a`, then replace it with `b` supporting `x` | `{x}` | 1 |
759
760The rows and count look identical. Now release `a`. The first history loses support for `x`; the second retains it through `b`. A model containing only rows and counts cannot answer both correctly.
761
762This gives the reasoning required by ORC-008: **find two states the model treats
763as equal, then try a legal next action that could distinguish them.** If their
764promised observations diverge—or an action is legal in only one—the model erased
765something relevant. The evidence may be an argument or a preserved witness; a
766separate executable test for every state field is not required.
767
768The witness tells us to retain the ownership distinction here. It does not prove the revised model handles every retry, pending completion or replacement race. Nor does it require every real API to accept retired handles: if the actual contract rejects them, model that rule instead.
769
770### Know where the expected answer comes from
771
772There are two questions behind “the model says so.” Who established the behavior? And which state determines the observable?
773
774An example from the archive makes the risk concrete: a finite model represented scores only up to three, turning `score > 3` into an empty predicate. The model had lost permitted values; that was not a reason to change production semantics. A separate ordering correction concerned which state owned the position: the model used locally edited values where the relevant contract used source state. The case notes retain that distinction; neither historical correction defines today's operator contract. See the [case notes](oracle-test-notes.md#historical-cases).
775
776Before changing production to satisfy a red test, check the contract, representation and comparison. A genuinely unresolved product choice belongs with its owner. A missing value in a finite model belongs in the model. References—including newly written specifications—can be wrong.
777
778Review the accusation and suggested fix separately. In one recorded adapter episode, returning a Promise created an acquisition lease even when it later rejected. Clearing ownership on rejection looked like cleanup but reportedly leaked that release obligation. The concern was useful; that repair did not follow from it. Other adapters may use different acquisition rules.
779
780Projection deserves the same care. Removing internal metadata from a public-value comparison can be valid. Removing a contractual virtual field because it is called “metadata” cannot. Write down one difference the comparison may ignore and one it must retain.
781
782## Generate histories that reach the problem
783
784Once the reference can distinguish relevant states, the generator must put production into them. Random payloads alone do not create ownership reuse, failed startup or work after recovery.
785
786Look for relationships and transitions: same key versus fresh key; one owner versus a surviving sibling; reject before versus after acquisition; release before versus after completion; recover, then perform another operation. Keep healthy peers alive where isolation is part of the promise. A test that ends at “recovery succeeded” may never reveal broken next-use state.
787
788Fresh disjoint rows can simplify a fixture while excluding the retired-key interaction it needs. Repeated `true` leadership reports do not cover `true → false → true` while earlier work is pending. These are different histories, not merely different random values.
789
790### Control the event, not just its returned Promise
791
792Async operations can have several boundaries:
793
794```text
795request invoked → response delivered → writes applied → view published
796 ↘ returned Promise settles
797```
798
799That diagram names possible events, not a universal required order. The API contract must say which events precede which others. The test must control and observe the ones its claim depends on.
800
801If `setWindow` applies work eagerly, delaying its returned Promise does not delay that work. In an earlier harness, an unconditional `await` let a queued microtask repair a same-turn mismatch before the assertion ran. A test that reads only settled state could not expose the earlier observation. Likewise, an equal initial window change can repair startup before startup is checked.
802
803Put an explicit hold or release at the event you need to control. For example, a fixture testing visibility before application can arrange this illustrative sequence:
804
805```text
806production requests data
807fixture receives the response but holds delivery of its writes
808test records the visible state while that delivery is held
809test releases write delivery and lets production apply it
810test records the visible state at the promised applied checkpoint
811```
812
813The fixture must really hold write delivery. If it delivers the writes and only delays returning from its load function, it controls a different event. Whether the returned Promise settles before or after application is a separate contract question. Record publications during the held interval if the promise concerns what users can see then. A scheduler is helpful only within the boundaries it controls; a seed cannot schedule arbitrary external I/O. The [fast-check scheduler documentation](https://fast-check.dev/docs/advanced/race-conditions/) explains the distinction between an operation's lifecycle and delivery of its result.
814
815### Treat driver timing helpers as premises
816
817A production driver often needs helpers such as "wait until the request is
818blocked" or "let the message reach the worker". Each helper establishes a
819premise. If a helper does less than its name says, every production driver
820that uses it can go green without reaching the history.
821
822In one [recorded case](oracle-reviews/pr-2213-opfs-close.md), a driver loop
823shared by the Node and Chromium production drivers gave back a lock in the same
824turn in which it submitted close. The close message was still crossing a task
825boundary, so the earlier request finished first. Close never ran during the
826wait, and both worker mutants passed both production drivers. The loop had a
827premise check for "a request waits for the lock", but it had none for "close
828arrives during that wait".
829
830For each timing helper, do one of these:
831
832- Assert the premise at its checkpoint, for example from a lock inventory or a
833 delivery counter.
834- Show that the history rejects a mutant that it can distinguish only when
835 the premise holds. This is calibration under
836 [ORC-006](#orc-006-checker-calibration).
837
838A helper that waits a fixed time does not prove delivery. It still needs one
839of the two checks above. State its time bound beside the helper.
840
841### One matrix can need two schedules
842
843The historical four-receipt settlement fixture shows why enumerating more positions is not enough. A receipt here is a completion obligation for a portion of applied work. The tested contract required success to await the relevant receipts and failure not to wait for unrelated later work.
844
845For each selected receipt, two schedules asked different questions:
846
847| Question | Hold and release pattern | Observation |
848| ----------------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
849| Can settlement ignore this receipt? | Keep it pending; apply every peer. | The request must still await this obligation. |
850| Does its rejection wait for a later peer? | Apply earlier receipts; leave later ones pending; reject this one. | Observe the exact rejection while later work remains pending, and compare the intact partial rows with the expected applied prefix. |
851
852Number the four receipts `r0` through `r3` and select `r1`. In the omission branch, apply `r0`, `r2` and `r3`, hold `r1`, and check that the request remains pending. In the rejection branch, apply only `r0`; hold `r2` and `r3`; reject `r1` with error E. Before releasing either later receipt, check rejection with E and the exact rows from the applied prefix. The fixture's application action must control applied work, not merely rename a Promise resolution.
853
854Resolving every peer first isolates omission but removes the pending sibling needed to expose delayed rejection. At the terminal receipt there is no later peer, so that cell cannot distinguish this delay. An empty expected prefix at the first receipt is valid; do not require nonempty rows just to prove the test ran.
855
856The archive reports that an `allSettled` mutant failed by timeout in this fixture. That is evidence about delayed rejection, not proof that every row or error assertion rejected a wrong value. Keep the two claims separate.
857
858Widening a generator can lose reach in two ways. A rewrite may remove a previously possible complete history, even while adding a dimension. Or a larger domain may make a useful history rarer at the same run budget. Neither means a true superset contains fewer cases; it means possibility and sampling frequency need separate checks.
859
860### Make the fixture respect the responsibility boundary
861
862A test provider can accidentally fix the consumer. One reported pagination fixture removed already-delivered rows before applying the requested limit. That supplied progress the consumer had not requested and hid repeated-page behavior.
863
864Contrast a provider whose job is to gather several backend pages to satisfy one requested offset and limit. Its internal draining loop may be legitimate. The location of code in a test helper does not decide which case it is. State what the request asks, what the provider promises, and which progress production must arrange.
865
866The same discipline applies to reentry. If a callback conditionally triggers the second operation, assert that the callback and trigger occurred. “If reached, check it” is a useful conditional claim, but it is not evidence that reentry was tested.
867
868ORC-013 asks a different question from whether the fixture ran: would the
869tested cases reject a plausible wrong interpretation of the reusable law? A
870conditional assertion needs a legal case where its premise is true. A finite
871threshold matrix needs a case close enough to the boundary to distinguish the
872promised cut from a plausible displaced cut. The claim can instead remain about
873the named cases; record the broader law as open rather than stretching the
874matrix's result.
875
876ORC-014 applies only when evidence crosses from a controlled premise to a
877real-provider or host claim. Name the exact premise being transferred. For
878example, a controlled callback can judge a component's response to an event;
879claiming that a real provider emits that same event under the relevant
880conditions needs a receiving witness. A declared controlled-boundary limit is
881an honest scope, not a failed component oracle.
882
883An oracle covers a design space, and each environment supplies one production
884driver for it. When Node and a browser must satisfy the same law, put the law,
885model, histories, and comparison in one module. Then give each environment a
886production driver for its entry point, premise control, and observations. The
887production drivers may run in different test runners, but they do not each
888restate the expected results.
889
890The OPFS request-order oracle shows the layout.
891[`opfs-request-order-oracle.ts`](https://github.com/TanStack/db/blob/main/packages/browser-db-sqlite-persistence/tests/opfs-request-order-oracle.ts)
892owns the law, the model, the fixed examples, the driver loop, and the
893comparison. The
894[Node driver](https://github.com/TanStack/db/blob/main/packages/browser-db-sqlite-persistence/tests/opfs-request-order-oracle.test.ts)
895and the
896[Chromium page driver](https://github.com/TanStack/db/blob/main/packages/browser-db-sqlite-persistence/e2e/opfs-request-order.opfs.ts)
897supply the entry point, access-handle control, database names, and result
898reporting. The Node driver also generates random histories from the same
899grammar. Neither driver states expected results, and both feed the same
900comparison. The
901[Chromium spec](https://github.com/TanStack/db/blob/main/packages/browser-db-sqlite-persistence/e2e/opfs-request-order-oracle.opfs.spec.ts)
902checks for page errors, a completed run, one result per example, and no
903violations. It states no expected results either. A witness
904that restates expected results needs the record that ORC-014 describes.
905
906## Observe what the contract promises
907
908Reaching the right state still leaves a choice: what evidence survives the test harness?
909
910Select observations from the actual promise. Membership, values, order, multiplicity, callback boundaries, downstream views, error identity, settlement timing, durable storage and resource ownership are not interchangeable. No suite needs all of them merely because they exist.
911
912If an unprojected sort field changes, compare the expected new ordering, not just whether the array changed. If a callback count matters, assert the count before looping through callbacks; a loop over no callbacks checks nothing. If a failed write must not reach storage later, reconstruct persisted data after a later successful operation. The assertion should separate the specific wrong behavior from the allowed one.
913
914### Let the recorder represent violations
915
916It is useful to make generated inputs legal. It is dangerous to make recorded outputs incapable of being illegal.
917
918Suppose production completes the same request twice. A request-keyed map that stores only the last completion collapses the violation. Record both events, then assert the promised count. Keeping the raw list alone is not enough if the final report folds it back into a map and loses the duplicate.
919
920Similarly, do not reset a delta tracker before checking unchanged anchors, discard negative weights merely because the final relation should be nonnegative, or normalize away contractual order. Normalize only what the chosen comparison permits.
921
922### Check incremental results and publication separately
923
924This section and the next are deeper branches for incremental-query and cross-formulation tests. If you are building an ordinary collection test, continue with [testing the test](#test-the-testand-keep-the-same-failure) and return when these comparisons become useful.
925
926An incremental engine emits changes. A reference often computes a whole result. Compare compatible objects: accumulate the changes, then compare that state with full recomputation at the promised logical point. Inspect individual batches too when the contract makes their boundaries visible.
927
928DBSP formalizes the computational relation as `QΔ = D ◦ Q ◦ I`: accumulate input changes, run the ordinary query, then take output differences. Equivalently, accumulating the incremental output should agree with querying the accumulated input. This is a useful source of laws for db-ivm. It does not choose whether a client may see a partial publication, when readiness changes, or what cancellation means. [DBSP paper](https://www.vldb.org/pvldb/vol16/p1601-budiu.pdf).
929
930A final correct snapshot cannot establish that every earlier callback was coherent. The recorded graph-history case used asymmetric changes to expose an old-left/new-right publication that a later settled check would miss. Choose observation points that can distinguish the promised failure, rather than adding delays until the result is stable.
931
932When scheduling legitimately allows several results, check for **one permitted explanation of the observed history**. Do not approve each field against a different allowed execution: those individually permitted pieces may never coexist. In specification terms, refinement means implementation-visible behaviors are permitted by the specification. A bounded test checks sampled histories; it is not a refinement proof. Nor can an accepted finite prefix prove eventual completion. [Refinement mappings](https://lamport.azurewebsites.net/pubs/abadi-existence.pdf).
933
934### Compare formulations when a model might share the bug
935
936Even a plain reference can copy an incorrect semantic assumption. A second formulation gives another way to disagree.
937
938This is the conditional requirement in ORC-011, not a universal requirement for
939every oracle. It applies after a plausible shared semantic fault and a
940meaningfully different formulation have been identified.
941
942For a suitably scoped includes query, compare nested results with per-parent standalone queries or a flat join regrouped by parent. First state how empty parents, duplicates, ordering and projection match. A transformation that changes the answer is not an oracle for equivalence.
943
944SQLancer names ternary logic partitioning, or TLP, as one such strategy: compare a query with recomposed predicate partitions. Here is a simple illustration of the partition relation, not a verified TanStack recipe: give every occurrence in an input exactly one label—true, false or unknown—according to the same predicate. Recombining all three groups, retaining every occurrence once, recovers that input. NULL behavior, aggregation and ordering need explicit treatment before turning this into a library recipe. It is not a license to split an arbitrary limited query into independently limited pieces. [SQLancer's oracle inventory](https://github.com/sqlancer/sqlancer).
945
946Metamorphic testing is the broader idea: transform an execution and check a known relation between the answers. Incremental-versus-recompute checks and legal history transformations can serve similar roles. They need not know one answer in advance, but they still need a justified relation.
947
948Agreement across two paths is not proof of independence. NoREC's database experiments report shared operator faults and a copied join path that concealed a bug; count comparison can also miss wrong rows with the right count. Use differing formulations for the faults they can separate, not as an automatic second vote. [NoREC paper](https://arxiv.org/pdf/2007.08292).
949
950## Test the test—and keep the same failure
951
952“The suite passed” compresses several claims. Was the property selected? Did it run? Did it reach the intended path? Did its comparison execute? Would that comparison reject the fault under discussion?
953
954Treat those as separate evidence. A replay registry can contain a property nobody invokes. A multiplier can be parsed without changing the run count. A no-op assertion can leave a campaign green. Use a positive execution witness and a deliberate wrong-result control where those claims matter.
955
956Mutation testing changes production code deliberately to challenge tests. Record what happened, not just whether a mutant was “killed”:
957
958- A value assertion rejected the intended wrong answer.
959- A timeout exposed a missing progress obligation.
960- Setup failed before reaching the comparison.
961- Execution failed outside the intended comparison after setup, such as a crash.
962- The changed code never ran.
963- The mutant survived, or the change was equivalent within the tested domain.
964
965These results call for different conclusions. If deleting one clause leaves the same obligation enforced elsewhere, survival does not show the obligation unnecessary. If the test kills a compound change, it may not distinguish each part. Research on mutation testing does not supply a conversion from a score to the probability that this library is correct; the [reading notes](oracle-test-notes.md#research-and-further-reading) preserve those limits.
966
967### Preserve the violation, not merely a red exit
968
969Shrinking makes failures explainable by removing irrelevant values and actions. A smaller legal history that fails during setup is not a reproduction of an original torn publication. Require the original failure predicate: the violated law, the relevant observation point, and the distinguishing evidence.
970
971Keep the original trace beside the reduction. Record which property ran and which checkpoint replay reached. “Ran, but did not reproduce the original mismatch” and “failed before reaching the comparison” are useful outcomes; neither should be labeled successful reproduction.
972
973Capture evidence before cleanup can change it. The historical publication fix copied the batch list before rollback; that preserved the needed local evidence, not universal deep immutability. An outer copy may still hold mutable values. A serializer may lose object identity or reorder arrays. Choose capture rules for the law and retain an original representation when normalization would erase the disputed distinction.
974
975Cleanup also has three separate jobs: preserve the primary failure, retain
976secondary cleanup diagnostics, and release resources. Reporting the first error
977does not prove the other two happened. Avoid letting a cleanup exception replace
978the mismatch that started the investigation. “Separate” means distinguishable
979in the report; an `AggregateError` may preserve the primary error as its cause
980and each cleanup diagnostic in its errors.
981
982A useful failure report contains:
983
984```text
985Law and source; requested property and actually executed target/path
986Code/dependency version; relevant environment
987Seed/path and explicit action or schedule trace
988Reached checkpoint; expected versus actual observation
989Original trace; reduced trace; reproduction result
990Primary failure; separate cleanup diagnostics
991```
992
993Check replay commands against the installed tool. A seed is not a recording of the network, operating system or every Promise. If a challenge influenced the design, keep it as a regression or tuning case; it is no longer a held-out test of that design.
994
995## Review and maintain the portfolio
996
997When a reviewer finds a bug beside a green oracle, ask why the test missed it before adding another isolated example. Was the expected answer wrong? Was the history absent? Did the fixture drive another path or supply the missing work? Did the observation admit the wrong answer? Did capture or replay erase the failure?
998
999These categories overlap. They are prompts for a concrete explanation, not an exhaustive taxonomy or a grade.
1000
1001Begin a portfolio audit with known product promises as well as existing test claims. Otherwise ten honest settled-row tests can hide that nobody claimed startup rejection in the first place. Credit a witness at **contract × history × production path × observation**. A green component tested under a mock assumption does not establish that its real provider satisfies that assumption.
1002
1003The historical React tie-group test illustrates precise credit. It exercised a real QueryClient/Query DB path with a finite test provider and checked visible prefixes and exhaustion. That could fill a portfolio-level gap without improving another test's weak assertion. It did not establish page-array contents, every framework or arbitrary server ordering. Preserve useful partial tests without lending them their neighbors' scope.
1004
1005### Borrow behavioral questions from another project
1006
1007A donor regression gives one case; a property gives a relation; a model and
1008generator give a way to investigate further cases. None makes the donor's
1009policy a TanStack DB contract. Before porting a test, record the donor's version
1010or revision and motivating counterexample. Identify the recipient's contract
1011authority and map the donor's actions and observations to its public boundary.
1012State which donor assumptions still hold, which change, and which interaction
1013with existing recipient laws needs a new witness. Try a nearby donor case that
1014should **not** transfer, such as an automatic-reopen policy for an adapter whose
1015approved contract requires a new descriptor. This checks whether the mapping
1016selects behavior or indiscriminately copies a suite. The [IndexedDB donor
1017survey](oracle-reviews/2026-10-06-indexeddb-donor-survey.md) records both
1018receiving witnesses and rejected transfers.
1019
1020### Simplify machinery without changing the question
1021
1022Before removing or combining tests, identify the valid history, expected outcome, production path and observation that will remain. Name the receiving test. “Retry the parent” becoming “delete the parent” changes the behavior, even if the replacement is shorter and green. The archive records exactly that kind of loss during reduction.
1023
1024Other reductions are legitimate: an expectation can contradict the adapter contract, or two branches can enforce the same established law. Removing a redundant branch need not remove its law. Keep valuable fixtures and semantic assertions even when their old helper or duplicate implementation goes away.
1025
1026Share stable mechanics such as replay parsing or resource cleanup where they are genuinely interchangeable. Keep domain truth small and separately reviewable. Several independent models should not grow into a universal miniature implementation merely to reduce duplication.
1027
1028### Vary machinery and premises separately
1029
1030When comparing implementation candidates, hold the accepted behavioral law,
1031legal histories, and observation cuts fixed. An index or cache may be removable
1032without changing public results; measure its resource cost under a stated
1033workload separately. If instead a premise changes—delivery may duplicate,
1034ordering may tie, or the client may see only part of the source—derive which
1035guarantees still follow. A failure under a changed premise may call for more
1036provider data or a contract decision rather than another algorithm.
1037
1038### Report evidence and open work separately
1039
1040Sometimes the right correction is to narrow a claim. A reachable-object count is not a construction count: traversal may itself construct objects, and discarded objects are unseen. The historical repair both renamed that metric and checked source delivery before and after traversal. Renaming alone would omit part of the repair.
1041
1042Narrowing evidence does not retire the larger promise. Keep two lines when necessary:
1043
1044```text
1045Observed: 100 irrelevant payload reads versus zero in the recorded probe.
1046Open: elapsed slowdown is unverified; the extra-work finding remains open
1047 in that historical ledger.
1048```
1049
1050Likewise, “assertions passed; process exited nonzero” is neither a clean green run nor an absence of passing assertions. An observed compatibility failure and an unresolved support policy can coexist. State both rather than squeezing them into one status.
1051
1052A weak observer, a missing protocol signal, and a measurement not yet taken are different limits. None alone grants permission to drop a valid product obligation. The guide does not prescribe a universal run count, fault rate or stopping score.
1053
1054### A review card
1055
1056This card is an optional presentation for the ORC-012 evidence. For a new oracle
1057or a claimed repair, ask:
1058
10591. What exact promise authorizes this expected result?
10602. If a concrete missing-input hypothesis arises, what source facts does the
1061 production path receive by the promised checkpoint (ORC-005)?
10623. Which legal history distinguishes the proposed model from a weaker one?
10634. Does the fixture make production do the work being tested?
10645. Which concrete wrong answer can the comparison reject—and which can it miss?
10656. What proves the path and assertion ran? What did the mutant or fault injection actually show?
10667. Can capture, cleanup or shrinking turn this into a different failure?
10678. Which larger promises remain outside this test, and where are they tracked?
10689. If a reusable boundary law is claimed, which case rejects a nearby wrong
1069 boundary? If a controlled premise supports a real-provider claim, where is
1070 that exact premise received, and does that production driver share the
1071 oracle's model
1072 and comparison?
107310. If the result exposes a problem, which [repair location](instruments/adversarial-review.md#locate-the-repair)
1074 does the evidence support?
1075
1076### Reusable boundary-law checklist
1077
1078Adapter and lifecycle oracles should consider these laws when the contract has
1079the corresponding boundary. They are prompts, not universal requirements. State
1080why an inapplicable law does not belong to the owner instead of adding a vacuous
1081case.
1082
1083- **Real-provider conformance:** freeze representative values from each
1084 supported provider version. Prove the fixture accepts those values before it
1085 stands in for that provider.
1086- **Minimal ambiguity:** include the smallest valid input for every classifier
1087 branch. Rich values that carry several redundant signals do not cover a
1088 one-field collision.
1089- **Name invariance:** changing a user-controlled name or SQL alias must not
1090 change envelope classification unless the public contract assigns that name
1091 structural meaning.
1092- **Representation symmetry:** equivalent array/object forms and coexisting
1093 carriers must produce the same public result or the same documented error.
1094- **Await-boundary transitions:** hold each relevant `await`, change ownership,
1095 leadership, generation, abort, cleanup, or restart state, then release it.
1096 Compare the result with the contract for that transition.
1097- **Local/transport refinement:** immutable transported data must have the same
1098 meaning on local and remote paths. Live local references must remain local,
1099 and cleanup must receive the exact lifecycle object delivered locally.
1100- **Partial-construction cleanup:** fail each construction step after it acquires
1101 a resource. Preserve the primary error and prove every acquired resource is
1102 released exactly once.
1103- **Value-and-work refinement:** when bounded work is promised, check the exact
1104 result and a deterministic work/cardinality measure. Correct rows alone do
1105 not establish the work law.
1106
1107Every owner should also state its known omissions beside the contract. The
1108coverage map tracks open reusable laws; an unchecked item is not evidence that
1109the neighboring laws are absent.
1110
1111The payoff is not a bigger test framework. It is a smaller distance between “this test is green” and a precise account of what that green result protects.