diff --git a/.changeset/load-subset-relations.md b/.changeset/load-subset-relations.md new file mode 100644 index 0000000000..10ee8c9a37 --- /dev/null +++ b/.changeset/load-subset-relations.md @@ -0,0 +1,6 @@ +--- +'@tanstack/db': patch +'@tanstack/db-sqlite-persistence-core': patch +--- + +Forward a joined-filter window's filter to `loadSubset` as an optional `relations` hint, so an adapter can return only the root rows that pass. An adapter that applies the hint keeps its answer current as related rows change. No request sends the hint while a joined collection has a local write, and a window loaded with it reads its prefix again without it. SQLite persistence admits the hint and does not transport it. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index aa55120c43..a2cb26526c 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -767,7 +767,7 @@ that test identifiers must copy production's private data structures. | Drafts and native values | Complete | Native differential behavior, draft change tracking, detachment and its class-instance exception, adversarial keys, aliases, cycles, and Map/Set live iteration are literate. | | Query DB and observer | Complete | Query-scope row ownership, subset identity and cancellation, failure and recovery, and the per-listener eligibility ledger are literate. | | Query DB SSR dehydration | Fixed QueryClient/Seroval boundary | Successful on-demand entries with a compound predicate, a request signal, and an ordered cursor with a custom comparator retain their row and user metadata through Seroval's reconstructed stream payload and Query Core hydration; request options are absent from the stream, while query functions retain the original values. The TanStack Start router and browser Collection resume path still need a host witness. | -| Ordered acquisition | Complete | Exact demand identity, applied settlement, independent pagination recomputation, request work, lifecycle products, replay authority, source-generation readiness, and transaction-refinement abort boundaries are literate. An initial full-source ordered load shares the synchronous readiness cut ([historical review](oracle-reviews/initial-full-source-sync-readiness.md)). The ordered-lifecycle oracle covers an inexpressible-boundary fallback before first publication when every acquisition returns literal `true`. It also checks a later null-boundary fallback after the first joined window publishes, across literal, Promise, and held-receipt responses, including a held receipt after child demand settles ([review](oracle-reviews/issue-2152-initial-ordered-fallback.md)). The ordered loader state oracle also has a generated request-authority grammar (`ordered-loader.request-authority`, fixed and random campaigns). It drives the real loader over a fake subscription through settlements in any order, failures, deferred invalidation and report reactions, ordinary passes and window moves, and began with four laws from a TLA+ model (#2191): a successful repair keeps its acquisitions until a covering read succeeds; quiet loading holds nothing older than its last authoritative read; a superseded request's failure is recovered by a full-source read without an explicit retry; and once quiet, an invalidation and a pass issue a read unless a full-source read covers the source. Scenarios also throw from the first release callback, answer a repair synchronously from installed rows, and let a page's own delivery invalidate ordering; named fixed histories keep the traces they found, each of which failed on main (a throwing release that unwound a resumed repair, a synchronous repair waiting behind a superseded request, and a self-invalidating page whose tie was never retired). On main it found a superseded tie that failed after its repair finished and a newer invalidation's reaction was deferred, which left refills blocked; a named fixed history keeps that trace. A stale prefix that retires the repair's prefix fails the held law, and a stale request held after the repair finished fails the leak law. The grammar also crosses unexpressible boundaries, joined work that defers loading, truncate replay that succeeds or stays pending, optimistic departures, source deletes, the bounded backoff retry, window moves that shrink or widen, plans that read only the full source, and reports inside the loader's own first page. A replay owns the requests issued before its truncate, and when the subscription still holds a full-source lease the settled replay covers the source. These dimensions found three more defects, each kept as a named fixed history: a repair prefix that settled after a replay started its replacement took the replacement's chain tag and was never retired; a replay counted a full-source read as complete after an explicit retry had released it; and a failure from before a truncate dropped the next repair's staged step. Each of the seven defect replays fails on the loader at the branch's merge base with main. A later law, one request at a time, found that a replaced repair chain's prefix still counted as current and issued a tie beside the replacement's prefix; a chain is now superseded by any newer authority start. The failed-lease law also counts a covering replay, which a named fixed history reaches. Repeated random campaigns then found a repair request that settled after full-source coverage and stayed held; full coverage now retires it. The held law counts a later prefix that a successful replay reacquired while it was in flight. Four histories from TCP's known error classes followed: a request the provider never answers (a lost segment), a release callback that truncates synchronously (a reentrant reset), a window offset other than zero, and an at-most-once release law with no release while a replay owns the demand unless an explicit retry replaces it or a held full-source lease covers it. They found that the backoff retry's release pass kept releasing failed demands after a release started a truncate; every release pass now stops on a reentrant reset. The oracle now observes epoch moves as calls to `invalidateSourceOrdering()`, so it tells a replacement chain from a chain step exactly. The loader's work slot and debt now move only through a transition table that throws `OrderedLoaderInvariantError` on an illegal move or an incoherent work and debt pair; the oracle records any such error as a broken law, so its generated histories fuzz the table. A covering-lease law (a full-source lease whose read succeeded or whose demand a replay reacquired is never released) found that a full-source transport failing after a covering replay turned complete coverage into an own failure; the table then found that a repair request failing after a replay finished its chain did the same. Mutants that drop each new guard fail. A release callback that runs an ordinary pass synchronously, as a graph run does when the release delivers deletes outside a transaction, found that the pass issued a page while another request was settling, and that request then issued its tie; every release pass now blocks refinement until it unwinds. A dispose command and a release callback that disposes the loader check that a disposed loader issues and releases nothing; mutants that drop the loader's own `active` checks in the release pass and in failure handling survive because dispose resets the cursor, so those checks were removed. TLA+ run 3 (`LoaderTable.tla`) models the table with truncate and replay; its safe rules pass with 9,368,122 distinct states, and each of the four guards from this round, removed alone, produces a counterexample. Reverting any one fix fails its replay and a campaign. The generated histories also stack a second truncate on a pending replay and truncate after a failed replay, each with reach. A lease missing from its map during a release pass is now an invariant violation; no history reaches it. A second high review found that a covering replay did not retire a superseded failed lease from before its truncate, because the failed-lease law exempted every replay-owned request. The law now judges a superseded failure that was live (it failed in the incarnation it was issued in) once a covering replay settles after it, and the replay retires those leases. The subscriber now schedules the replay's graph run in a finally. The replay-refinement oracle is the receiving witness: its generated ordered section (`replay.ordered-window-faults`) drives a real on-demand Collection and an ordered live query through rank moves, held and failed loads, truncates, and unloads that throw without a truncate, while a replay starts, and while it settles. Its settled-window law found that a release throwing after a successful ordered load left the window on old rows, because the builder counted the rejected participant as a failed load (also on main); the loader now marks release errors and the builder publishes. It also fails without the subscriber's finally. The section now also crosses tied ranks (its law compares the window's rank sequence and each shown row's current rank), a peer live query on the same source, offset 1, descending order, and explicit window moves; a move that rejects after a failed source recovery leaves the window, and one rejected only by a release failure still moves. A reported-faults law accepts injected faults as rejected loads, thrown releases, rejected moves, or errors the subscription rethrows from a microtask, and rejects any other escaped error. These found that a window move whose load succeeded was recorded as failed when a release threw, so the window stayed private until another move. A throwing release is an adapter bug, so the loader now reports it uncaught from a microtask and changes nothing else; the reported-faults law rejects a move that a release failure rejects, and the request-authority oracle requires each throwing release to be reported uncaught exactly once (a mutant that swallows the error fails). It also crosses a joined marker source: a LEFT join that keeps marked or unmarked rows, and an inner join. The marker source is eager or on-demand, with marker loads that are held, fail, and truncate. This found that an on-demand joined source whose loads finished without delivering a row left the window on old rows, because nothing ran the graph that the pending joined work held; the subscriber now runs it when a joined source becomes ready. A truncate never aborts a window move: the move waits for any replay that holds publication and then applies (ARCHITECTURE.md), so a move that rejects with `AbortError` during a history is an escaped error. (An earlier version of this entry claimed a named fixed history reached an aborted-move branch; no history reached it, and the branch, which quietly accepted such a rejection, is gone.) Recovery truncates the marker source too, because a failed marker replay keeps the last complete publication until that source replays. A mutant-mutant pass over the loader's guards found guards that no ordered oracle kills. A differential instrument then ran 3,000 generated request-authority histories through the loader and each mutant and compared every request's shape, outcome, and release. Three guards the code makes redundant are deleted: the backoff timer guard, the explicit-move check in the retry callback, and the `requiresFullSource` check on a report. An ignored-report law now kills two of the mutants that changed public requests: a report issues no authoritative request before any request settled (a request in flight still owes an exact result for its own options) or while the window is inside the loader's own first prefix. Named replays reach both, and the random campaigns judge them in quiet histories. A random ordered-work campaign later found that the first-prefix check was unsound: it took the next installed row as the next source row, but a signalling refetch moved the page's end before the tie the loader had read, so that tie's row stood past the page while a row tied with the new end was never sent, and a later window move skipped it. The loader now accepts the row only when its page read it or when it read the tie of the page's current end. When the end moved, it repairs (see the later maintainer decision below); query-db's first-page witness requires bounded reads only, no full-source read, and an unchanged count of active Queries. The optimistic-window cases that allow but do not require a refill still bound any refill that occurs: an ordered read within the refill bound or a predicate read, never the full source (a mutant that made the growth read unbounded fails them). The ordered-work model now sorts `undefined` ranks with `null` ones, as the comparator does, and its histories generate both; nullish ranks tie in its window and in-flight comparisons. An `undefined` end also matches a loader that attempted no tie; a nullish end is never an expressible cursor, so the loader has started or will start a full-source read, which covers the source either way. A guard against that match survived the generated campaigns as an equivalent mutant and was removed. The ordered-work oracle keeps the trace as a named fixed history that fails on main, and the request-authority oracle has an unproven-report law (a report over a first page that no row it read proves starts a repair or reads the end's tie), whose replay and fixed campaign fail on main; the broad campaigns reach that law in about one history in 10,000, so an unproven-report campaign (`ordered-loader.unproven-report`, fixed and random) settles the first page, settles the read after it, and reports, over random case parameters and a random suffix, and declares its reach (about a third of 300 histories); `main`'s loader fails both runs. Its fake subscription now reads installed rows as the subscription does, applying a tie's equality, a cursor, and a limit; when its reads ignored the limit, the tie was always the last installed row's, so the first-prefix ignore branch was unreachable. The cost law's per-chain bound, three requests, was an artifact of that fake: it is now a prefix plus a tie and a page per installed row, and it also judges an unindexed window that still needs rows, which grows its prefix instead of reading the full source. The report campaign (`ordered-loader.unproven-report`, 1,000 runs; at 600 a random seed could miss the minimum) now starts each history with one of eight prefixes and declares reach for each report premise: a proven first page, a page that read past a window that shrank, a held full-source read, a head insert that moved the page's end, an owed repair, authoritative work in flight, a release of the older tie that truncates or disposes the loader, and a report to a disposed loader. The unproven-report law requires a bounded repair or the end's tie when every installed rank is expressible; a full-source read no longer satisfies it (a mutant that forced full debt after a report passed before). The cost law also rejects a repeated read: within one invalidation, no prefix, tie, or page repeats more often than the ordering epoch moved. Two laws are stronger: an ignored report, over a proven first page or a held full-source read, issues no request at all, where it used to forbid only authoritative ones; and a report while a repair is owed reads no tie or page before the repair. Deleting the moved-end early return in `revalidateLoadedCoverage`, or its past-window term, fails the first law, and deleting the owed-debt term in `loadMovedEndTie` fails the second; a deletion sweep had found all three surviving every oracle. With that reach, the report path's own `!active` checks were deleted: `dispose()` advances the generation that the stale-run check after the release reads, and a disposed loader issues nothing, which the dispose law judges. A head insert can carry a `-Infinity` rank, and two more laws judge every request: the loader never reads the tie of a rank no cursor can express, and the first finite request after a truncate has no cursor. The fake's `dataNeeded` now counts the window rows not at or before the boundary it is given, where it returned a constant. With those, the stale-run check after the older tie's release fails the reset law when a release truncates the loader and the window then grows (a prefix declares that reach), and removing `loadBoundary`'s own unexpressible-value check fails the unexpressible-tie law. The covered-source early return and the staged-continuation term were deleted: coverage that a full-source read completed holds the work slot, whose check then decides the report, and a staged finite continuation cannot coexist with a proven end, while a staged repair step owes a repair. The ignored-report law's full-source branch no longer needs a quiet history, since such coverage owes nothing, and a prefix reaches a paged loader whose repair fell back to a full-source read; removing the work-slot check then fails it. The unexpressible-end term in `loadMovedEndTie` stays: the unindexed-refetch random campaign found that without it an unindexed loader reads the full source through the boundary fallback where its bounded prefix repair would do, and a named fixed history of that trace fails without the term. Maintainer decision, later: a report whose page end moved now repairs instead of reading only the new end's tie, to cut shipped bytes; `loadMovedEndTie` and its guards are gone, so their mutants above no longer exist. The laws stay and judge the repair path: the ignored-report, owed-repair, unexpressible-tie, and reset laws all still run, and the unproven-report law accepts a repair. The report campaign drops its two prefixes whose release of the older tie truncated or disposed the loader, since a report no longer releases anything, and the query-db replay of an insert into a top-N list now expects the bounded repair's prefix and the new end's tie. Still open there: the `Object.is` term of the moved-end check. It skips work when the loader already read the end's tie, and it decides differently from its fallback only while other work is in flight, which the ignored-report law's quiet premise excludes. The ordered-work oracle owns that branch instead: peers over a refetching provider stay in its grammar for source filters (#2155 excludes only joined filters), and a proven-report law requires that a report which changes nothing the first query's own page and end tie prove, with the model's next row installed and no installed row deleted or reordered, starts no request for it and leaves it owing no `refetch: true` repair. A campaign fixed to that premise must reach it, and a loader that repairs every report fails both its fixed and random runs. A staged end tie that pending joined work defers is read by the pass after that work finishes; a request-authority named fixed history reaches it, and a loader that drops the staged tie fails it. The unproven-report law judges that later pass, and a truncate, failure, move, or disposal in between voids what the report owed. A history that starts during the initial preload found that a window move deferred behind a marker replay, which the source truncate then discarded, rejected with that replay's `AbortError`, so the older move's window won (also on main). A deferred move now waits for every replay that holds publication and applies unless one failed or cleanup ended the sync run; a named fixed history fails without the fix. The ordered-work refetch law also required no full-source read after a signalling refetch for an unindexed plan, which the architecture then let refill a short window from the full source; random seeds found it on main. Maintainer decision on this branch: an underfilled unindexed prefix never reads the full source, because that read is unbounded. It grows instead: each growth asks for twice the last prefix, and it stops once the last growth added no rows. A deletion sweep showed that the older condition's other term, a prefix that reads short, follows from that one. The refetch law now forbids a full-source read after a signalling refetch with no unindexed exception. The named fixed history of a short unindexed window and the fixed unindexed-refetch campaign (`ordered-work.eager-unindexed-refetch`, fixed and random, with reach on windows the prefix fills and windows it leaves short) failed on the full-source fallback and pass with growth; the full-source mutant still fails them. Growth made a new optimistic history possible: an unindexed one-row window behind a joined or anti-joined filter that installs only the prefix it grew to, whose departure leaves the replacement row missing. Sixteen fixed optimistic-window cases (update and delete, both consumers, acknowledge and rollback) cover it, with a refill bound of twice the installed prefix plus the overlaid row. A loader without the stop rule never reaches a fixed point; a loader that stops whenever the prefix reads short leaves those windows empty after settlement, because the pending departure hides a row from the count. The existing unindexed optimistic cases now allow, but do not require, a request behind a joined filter when the replacement row is installed: growth proves rows only up to its prefix, where the full-source fallback had proven every row (a maintainer-approved expectation change). The proven-report random campaign now declares its reach too. One mutant still changes requests without a law: dropping the optimistic-refill flag turns a refill into a refetching prefix. Six more are equivalent in the fake but stay, because the fake cannot reach their premise or they encode a documented rule: the own-first-page check behind a held sync transaction (the fake never holds one), a truncate moving complete coverage back to held, clearing the pending request when a full-source read starts (the fake never answers a full-source read synchronously), staging a joined `more` continuation, the staged-continuation guard before an unindexed prefix, and the drain re-entry guard (a long synchronous chain would otherwise recurse). An include dimension adds a `toArray` child that reads the marker source for each shown row, and an include-children law requires each shown row's markers to equal the model wherever the window law holds; a mutant that never loads newly demanded child keys fails it in an include-only scenario. A newest-move law requires a superseded window move to resolve only after the newest move settles (a superseded move that fails still rejects with its own error), and the model lets the newest move that resolved set the window; it found that a superseded move resolved as soon as its own load settled, so awaiting it showed neither window. The terminal-error law also allows `error` after a load fails while the query is still loading, the documented initial-load failure; a lazy join source is exempt. Limits: includes are one level deep. It also found that a release failure in lazy joined demand during a window move rejected the move, because the subscription reported it as a load error. A window law now lets the newest move win; it found that two moves deferred by a pending source recovery could resume in the opposite order, so the older request replaced the newer window. `setWindow()` now ignores a deferred call that a newer call superseded. A terminal-error law allows a final `error` only after a lazy join demand load, on either side, failed outside a truncate's recovery; named fixed histories reach that branch. A load belongs to a recovery when it asks again for a demand its source held before the truncate (the same request data), or when the graph starts it while the truncate commits. The first model read a flag set only during the commit, but subscriptions start replay loads in a later microtask, so it counted every replay load as new demand and allowed `error` after any failed replay load; a random campaign found the reverse case (#2224): a marker truncate privately moved the window, the include's new demand started outside any replay because releasing its old demand ended the subscription's replay, and its failure ended the query. The demand controller now starts new coverage before it releases retired coverage, a query subscription opens a replay at every truncate even without demand (a replay that starts no recovery work and reports no loading), and a demand failure that fails its subscription's replay keeps the last publication instead of ending the query once the query has first become ready. The section also generates histories that start during the initial preload, with an initial-readiness law (the preload has settled once loading is quiet), marker loads whose aborted requests reject with `AbortError` as the source contract asks, and settles of the newest held load. These found two older defects on main: an aborted lazy demand request that rejected after its truncate replay succeeded ended the query, and so did a superseded segment that the controller released; the controller now treats an aborted request as obsolete demand, which its replay or newer coverage decides. Named replays keep each trace; reverting each production change fails one of them, and a mutant whose replay rebuilds its request data fails the campaigns' replay-load reach witness. The ordered-lifecycle oracle owns the truncate-work witness: a zero-limit window issues no request and reports no loading at a truncate, while a one-row window reacquires. A retention law then judges law 9 at generated checkpoints: a truncate raises a publication barrier, every load its source starts while the barrier is up joins it, a participant's failure fails the replay while its logical demand is held, and while any barrier is up the query shows exactly the rows it showed when the first one rose. It runs after every command and once loading is quiet. A failed-replay campaign (`replay.ordered-failed-replay`, fixed and random) starts each history by holding loads, truncating a source, optionally starting demand, and failing a held load, with a branch that fails an include demand while its marker replay still loads; it declares four reach states in `oracleProperty`'s `histories.states` (a judged failed replay, a judged held replay, a demand started after the commit that fails while its replay loads, and the include form of that demand). A replay participant now also counts as recovery for the terminal-error law, so a demand that starts after the commit while its replay is open is judged in generated histories, not only by a named fixed history. A mutant whose failed replay releases the publication gate fails both failed-replay campaigns and the broad campaigns; a mutant that ends the query when such a demand fails fails both failed-replay campaigns; the branch's production files reverted to `main` fail both. A preload-recovery campaign (`replay.ordered-preload-recovery`, fixed and random) starts every history during the initial preload over on-demand markers and declares two more states: lazy demand in a replay that fails before the first ready, and a window move that waits behind a replay a newer truncate discards. A builder whose deferred move a discarded replay rejects, and one that keeps a failure before the first ready non-fatal, each failed only a named fixed history before; both now fail the fixed campaign, whose seed kills both (each dies in about half of 200-run seeds, so the random campaign kills each about half the time). Building the law found three model errors, each corrected from ARCHITECTURE.md: a failure is scoped to its logical demand, so a retired failed demand and the demand that replaces it publish when the replacement succeeds; a replay completes when its last participant's rows apply, so demand that a deferred window move starts afterwards does not join it; and an ordered tie request (a `where` on rank) is not lazy demand, which the terminal-error law had treated it as, so a failed tie request had excused a terminal error. A query's subscriptions to one collection now share one replay barrier (ARCHITECTURE.md, "Replay participants and failure"): a probe found that in a query that joins and includes the marker source, a marker truncate retired the include's only demand privately, its emptied replay closed while the join's replay still loaded, and include demand the graph then started failed outside every replay and ended the query. A sibling-demand branch of the failed-replay campaign declares that state; the branch's code before the fix fails the named fixed history and both campaigns at `convergence: terminal error`, and removing either sibling hold (at replay completion, or for an emptied replay) fails all three. The random failed-replay campaign then found the other half: one subscription's replay failed, the other's finished once it settled, and demand that a rank move then started on the finished subscription failed and ended the query, because the subscriber judged the failure by its own subscription. The subscriber now asks whether a replay of the source's collection failed; a named fixed history (`a demand that fails after the sibling subscription's replay failed`), a `failedSiblingDemandFailures` reach in the sibling branch (which now may move a row and fail the oldest held load), and both campaigns at 400 runs fail at `convergence: terminal error` on the per-subscription rule. A design that judged a failure against any failed replay of the query, across collections, used to survive, because the convergence check runs after an explicit window move, which retries a failed row demand. A strict terminal-error law now requires a failed lazy demand outside every recovery to end the query (ARCHITECTURE.md, error 228), skipping only failures the model cannot place: after a load threw, and, with a peer, a load that joined a replay. Merge with #2257: its review (CF01, [record](oracle-reviews/2026-10-26-pr-2257.md)) judged a new keyed request that a truncate commit starts as terminal, and called non-fatal recovery of that demand a future contract. This PR adopts that contract by maintainer decision. The merged owner keeps CF01's initiating-request receipt check as a second account of every terminal error, at each history cut and at convergence, plus its named fixed histories and the `replay.subscription-demand-origin` and `replay.keyed-request-failures` campaigns, with their two reach-state pairs measured on this owner's model. Both demand origins, new demand during a marker commit and a settled demand that the replay asks for again, must stay nonterminal after the first ready. An always-fatal `failDemand` mutant fails 15 tests, including both ported campaigns; a never-fatal mutant fails the strict law in 8. CF01's duplicate of the #2224 named fixed history is folded into this owner's existing one. Merge with #2168 (ARCHITECTURE.md law 16): after initial-query readiness no load failure ends a live query, and a failed lazy demand is a request error on the query's node. That supersedes the strict terminal-error law, the error-228 rule, and the always-fatal and never-fatal mutant results above for a query that has been ready. The replay owner now allows a terminal error only after a load failed while the query was still loading, judged at each history cut and at convergence, and it adopts #2168's request-error witness (`requestErrors`); the excusals for thrown and unplaced failures went with the strict law. #2168's design already starts new demand before it releases retired coverage, and it treats a synchronous `loadSubset` throw as a rejection whose owner's release unloads it (the subscription oracles fix that unload), so the adapter-release law now counts a thrown load as acquired. It lacked the shared barrier, the failure hold behind a sibling's failed replay, and the deferred window move's wait, which the merge ports onto it. Without the deferred-move loop, 8 tests fail, #2221 trace 2 among them; without `failReplacement`, the two-failures named fixed history fails; without the sibling wait, that replay and both failed-replay campaigns fail. A deferred move rejects when a reload ends the sync run of the query or of a source, which the source-health oracle requires. The window-request reset went: a move can no longer throw, and deleting it failed nothing. The replay that a truncate opened without demand went too: under law 16 its demand's failure no longer ends the query, and its named fixed history passes on #2168's subscription. Review of the merge (2026-10-28): the replay owner gained a request-error account. After initial-query readiness, each failed lazy demand load that is still owed must appear among the query node's open request failures, by its injected error object, at every history cut, and no request error may stay after recovery replays every source (authority: ARCHITECTURE.md law 16, law 17, and the glossary's request error). A failure is met when its demand retires, a later load of the source covers its keys, or a later replay of the source completes; a failure inside a replay owes nothing until every participant settled. A terminal error now needs a load that failed while that same query was loading, so a peer's initial failure no longer excuses `live`. A thrown load joins a replay that no participant joined yet, and the failed-sibling branch now generates a held retry. `requestErrorChecks` reaches the declared minimum of 5 in each failed-replay campaign. Mutants: demand outcomes that never report an error fail 9 tests at the per-cut check; a successful replay that keeps its request errors fails 22 at the stale-error check. Limits and open items: the account shares one replay across a query's subscriptions to a source, so it cannot judge one subscription's request error while another load of that source is held. The reviewer's finding that `failReplacement`'s replay, which has no recorded failure, completes when every demand that joined it settles is closed as a law revision by maintainer decision: the hold ends when every demand load that joins it loads, a later replay of the source succeeds, or the subscription's last demand retires (ARCHITECTURE.md, "Replay participants and failure"). The query retries the failed demand at once and that retry joins the hold, so the hold cannot publish without the failed demand's rows. The replay oracle judges each subscription's request-error verdict by the subscription that a load names, and its failed-replay campaigns declare the premise (a subscription's load succeeds while that subscription's failure is still owed; 30 fixed and 24 random histories at the normal budget). No live-query history violates the request-error or retention law there; a mutant that completes such a hold when any participant settles fails both failed-replay campaigns at the retention law. A subscription-level `it.fails` test that asserted the earlier, stricter wording (no joined demand may end the hold) was removed with the revision. Limit: the oracle drives the hold only through live-query histories, where the retry always joins; a direct `Collection.subscribeChanges` caller that never retries is outside the live-query contract. Which failure a deferred window move rejects with, when its replay has several, is not specified: `main` rejected with the replay's earliest failure, and this branch rejects with `lastSubsetError`; by maintainer decision the move rejects with its replay's earliest failure that still decides it (law 17 decides which count: a retired demand's, a retried request's, and a replaced demand's failures do not). An identity law now judges deferred moves that start before any failure of the replays they wait on; on the parent code both failed-replay campaigns and the named fixed history `a window move behind a replay with two failed loads` fail with "replay error identity", and the deferred-move loop that rethrows a non-abort replay error passes. The request-error account decides failures per key: a later load of the source that asks for some of a failure's keys decides them, and keys it no longer asks for left the demand. The held-retry branch then found, at three times the run budget, a marker change publishing over a window that the model retained after a failed marker replay (`hold, truncateMarkers, settle ok, settle ok, settle fail newest, mark 3 off`, ascending, offset 1, limit 1, includes over on-demand markers). It was a model defect: the query retries a failed demand at once, and when that retry loads the failed keys the failure no longer counts (ARCHITECTURE.md law 17), so the replay succeeds and publishes. The model now clears a replay failure when a later load of the replay loads its keys. The replay oracle passes at the normal budget and three times at three times it, and production without `failReplacement` still fails its named fixed history at the retention law. A move whose `setWindow` throws synchronously after the request generation increments is reachable only through invariant errors, which probes for a throwing subscriber, a crashed source, and a throwing `select` did not reach. An aborted request's rejection and the failure of a segment that newer coverage released are not failures. That design now fails both failed-replay campaigns. An independent oracle review then narrowed several judgments. The terminal-error excuse after a synchronous throw applies only to the thrown error itself, ending the query after the step that threw; the throw's own step, and every other failure, are judged strictly (a per-history flag had excused every later failure). A load that fails outside every barrier after a failed demand of its source retired is unplaced, because the failed replay may still hold through the subscription's other demands, which the adapter cannot attribute. Limit: with a peer, the strict law accepts either query ending, since the adapter boundary cannot tell which query's subscription issued a load; attributing each failure to its query's subscription would close that. The window check now also requires every shown row to be eligible and to appear once, so a tie cannot hide a row the join rejects. A synchronous-throw dimension (`markerThrows` arms the next marker load to throw while it starts) found that a load throwing inside an open replay ended the query: the subscription dropped the demand, so its failure did not fail the replay, and the subscriber treated the throw as fatal. The subscription now hands the replay a rejected participant for such a throw and keeps the demand, which a later replay retries; named fixed histories (`a replay load that throws while it starts`, `a demand whose load throws inside its open replay`), a `thrownReplayDemands` reach in a thrown-demand branch, and both failed-replay campaigns (now 600 runs) fail on the parent code, and a mutant that later unloads the never-acquired load fails the adapter-release check. Model corrections, each from the adapter-boundary rule that a thrown load acquires nothing: a thrown load joins a replay only if it still has a participant or a failure; an armed throw expires before the drain; and a thrown demand's retirement is invisible, so the retention law skips the marker barrier from a throw to the end of its episode (a later barrier in the episode inherits the ambiguity, which also corrects the existing release-throw case), and a failure that joins an already failed or ambiguous barrier may end the query. Maintainer decision: a synchronous throw inside an open replay fails that replay as a rejection does, so the subscription replay oracle's `new request throws` case and five `live-query-collection` cases, which expected a thrown new demand to roll back, now expect the rejection outcome. Limits: a design that dropped a thrown demand and let its replay succeed passes wherever only retention could see it; after a history command follows a throw, a terminal error is excused, because the model cannot see whether that command retired the thrown demand and with it its failed replay (a demand that waited on that replay then fails outside it). The named fixed histories judge the throw's own outcome strictly. The failed-replay random campaign at five times its run count then found a retention counterexample with no throw, on the parent code too: a join and an include of one marker source; one subscription's replay fails, the other's finishes, and a row move starts demand on it whose load fails, which the shared barrier kept from ending the query; a marker change then retired the first replay's failed demand, which discarded that replay and published an empty window, because the second failure held nothing. That failure now fails its own subscription's replacement, which holds until a later replay succeeds or the subscription's last demand retires. A named fixed history of the trace fails without the hold, and a `partialFailureRetirements` reach (a failed demand retires while another failure still holds the barrier) is declared in the failed-replay campaign; the campaigns themselves do not fail without the hold, so the named fixed history is the witness. A window move whose load throws while it starts counts as a settled, failed move in the model (it used to stay pending, so the newest-move law misjudged the older move), with a `thrownMoves` reach. The broad random campaign at five times its run count then found an older move whose settlement resolved with itself: the newer move threw after it bumped the request generation and before it replaced the latest request, so the older move's settlement returned its own promise, a chaining cycle that escaped as a TypeError. A call now clears the latest request when it bumps the generation, so no older move can wait on itself; a named fixed history fails without that. The same assignment covers a move deferred behind a replay, which had the same shape (an independent review found it can hang forever when a newer move throws between the replay settling and the deferred move resuming); that microtask limit is outside the grammar, which flushes between commands, so only the shared mechanism, not that path, has a witness. The ordered-work oracle also keeps the trace from #2221 as a named fixed history: before prefix growth the loader read the full source twice after a signalling refetch past a NaN boundary; with growth it reads none. Limits: the adapter boundary cannot tell which query issued a load, so the retention law and the participant rule skip histories with a peer. The retention law judges barriers that rise after the query first became ready; before that the initial-readiness law governs. It skips a barrier where a release threw while the replay started, which may fail that replay. Core now reports a throwing `unloadSubset` uncaught and fails nothing with it; the subscription lifecycle, replay, Effect disposal, includes-temporal, and subset-error oracles check the uncaught report, once, with the adapter's error. The request-authority oracle now also generates requests that throw while they start, the last history only TLA+ covered, with an error-identity law: a failed request's participant reports that request's own error. It found that a superseded failure whose recovery read threw at its start reported the start error instead (review finding 6). The state oracle compares every current failed request's participant reason with its own originating Error by identity. Release cleanup cannot replace that reason, even when the thrown value's message starts with “release ”. A bounded 16-case checker calibration crosses index availability, widths 1/2, actual throwing release absent/present, and ordinary/full-source plans. It feeds three wrong participant reasons into the same model/production-driver/comparison; the original prefix waiver and an actual-release-only waiver fail at that check. The existing fixed/random 10,000 authority histories declare and enforce current-request-error reach and actual cleanup-fault/current-request-error overlap. Scope ends at the loader participant and separate uncaught-cleanup observations; it adds no provider/framework or intermediate-publication promise. The state owner's shared error-identity calibration and paired generated campaigns enforce these checks. A cost law then checks, after loading is quiet and a bounded repair is available, that one invalidation reads no full source and issues at most one chain per ordering epoch move (in the fake, a prefix, a tie, and a refill); a mutant that always repairs with a full-source read fails it. The replay-refinement section's status law requires a quiet live query and its peer to stay ready when no load failed. Limits: whether a release runs the graph at once or defers it to a transaction belongs to the scheduler, and the oracle generates both forms without checking the scheduler's choice; the fake's rows do not move except for the unexpressible boundary; publication holds stay with other tests; the laws do not judge requests issued before a truncate; a hung authoritative request suspends the leak law for its unfinished chain; a recovery start that throws during a superseded failure is rare in the campaigns, so a named fixed history owns it. | +| Ordered acquisition | Complete | Exact demand identity, applied settlement, independent pagination recomputation, request work, lifecycle products, replay authority, source-generation readiness, and transaction-refinement abort boundaries are literate. An initial full-source ordered load shares the synchronous readiness cut ([historical review](oracle-reviews/initial-full-source-sync-readiness.md)). The ordered-lifecycle oracle covers an inexpressible-boundary fallback before first publication when every acquisition returns literal `true`. It also checks a later null-boundary fallback after the first joined window publishes, across literal, Promise, and held-receipt responses, including a held receipt after child demand settles ([review](oracle-reviews/issue-2152-initial-ordered-fallback.md)). `load-subset-relations.window`, `.demand-key`, `.shared-window` and `.subquery-root` check that a joined-filter window sends a relation hint only when it carries the whole joined filter and its root is the ordered collection itself, that applying or ignoring it publishes the same window, that it is part of demand identity, and (`.joined-change`) that a joined row's local write or synced change still publishes the window local evaluation gives, with no hint sent while a joined row has a local write. The ordered loader state oracle also has a generated request-authority grammar (`ordered-loader.request-authority`, fixed and random campaigns). It drives the real loader over a fake subscription through settlements in any order, failures, deferred invalidation and report reactions, ordinary passes and window moves, and began with four laws from a TLA+ model (#2191): a successful repair keeps its acquisitions until a covering read succeeds; quiet loading holds nothing older than its last authoritative read; a superseded request's failure is recovered by a full-source read without an explicit retry; and once quiet, an invalidation and a pass issue a read unless a full-source read covers the source. Scenarios also throw from the first release callback, answer a repair synchronously from installed rows, and let a page's own delivery invalidate ordering; named fixed histories keep the traces they found, each of which failed on main (a throwing release that unwound a resumed repair, a synchronous repair waiting behind a superseded request, and a self-invalidating page whose tie was never retired). On main it found a superseded tie that failed after its repair finished and a newer invalidation's reaction was deferred, which left refills blocked; a named fixed history keeps that trace. A stale prefix that retires the repair's prefix fails the held law, and a stale request held after the repair finished fails the leak law. The grammar also crosses unexpressible boundaries, joined work that defers loading, truncate replay that succeeds or stays pending, optimistic departures, source deletes, the bounded backoff retry, window moves that shrink or widen, plans that read only the full source, and reports inside the loader's own first page. A replay owns the requests issued before its truncate, and when the subscription still holds a full-source lease the settled replay covers the source. These dimensions found three more defects, each kept as a named fixed history: a repair prefix that settled after a replay started its replacement took the replacement's chain tag and was never retired; a replay counted a full-source read as complete after an explicit retry had released it; and a failure from before a truncate dropped the next repair's staged step. Each of the seven defect replays fails on the loader at the branch's merge base with main. A later law, one request at a time, found that a replaced repair chain's prefix still counted as current and issued a tie beside the replacement's prefix; a chain is now superseded by any newer authority start. The failed-lease law also counts a covering replay, which a named fixed history reaches. Repeated random campaigns then found a repair request that settled after full-source coverage and stayed held; full coverage now retires it. The held law counts a later prefix that a successful replay reacquired while it was in flight. Four histories from TCP's known error classes followed: a request the provider never answers (a lost segment), a release callback that truncates synchronously (a reentrant reset), a window offset other than zero, and an at-most-once release law with no release while a replay owns the demand unless an explicit retry replaces it or a held full-source lease covers it. They found that the backoff retry's release pass kept releasing failed demands after a release started a truncate; every release pass now stops on a reentrant reset. The oracle now observes epoch moves as calls to `invalidateSourceOrdering()`, so it tells a replacement chain from a chain step exactly. The loader's work slot and debt now move only through a transition table that throws `OrderedLoaderInvariantError` on an illegal move or an incoherent work and debt pair; the oracle records any such error as a broken law, so its generated histories fuzz the table. A covering-lease law (a full-source lease whose read succeeded or whose demand a replay reacquired is never released) found that a full-source transport failing after a covering replay turned complete coverage into an own failure; the table then found that a repair request failing after a replay finished its chain did the same. Mutants that drop each new guard fail. A release callback that runs an ordinary pass synchronously, as a graph run does when the release delivers deletes outside a transaction, found that the pass issued a page while another request was settling, and that request then issued its tie; every release pass now blocks refinement until it unwinds. A dispose command and a release callback that disposes the loader check that a disposed loader issues and releases nothing; mutants that drop the loader's own `active` checks in the release pass and in failure handling survive because dispose resets the cursor, so those checks were removed. TLA+ run 3 (`LoaderTable.tla`) models the table with truncate and replay; its safe rules pass with 9,368,122 distinct states, and each of the four guards from this round, removed alone, produces a counterexample. Reverting any one fix fails its replay and a campaign. The generated histories also stack a second truncate on a pending replay and truncate after a failed replay, each with reach. A lease missing from its map during a release pass is now an invariant violation; no history reaches it. A second high review found that a covering replay did not retire a superseded failed lease from before its truncate, because the failed-lease law exempted every replay-owned request. The law now judges a superseded failure that was live (it failed in the incarnation it was issued in) once a covering replay settles after it, and the replay retires those leases. The subscriber now schedules the replay's graph run in a finally. The replay-refinement oracle is the receiving witness: its generated ordered section (`replay.ordered-window-faults`) drives a real on-demand Collection and an ordered live query through rank moves, held and failed loads, truncates, and unloads that throw without a truncate, while a replay starts, and while it settles. Its settled-window law found that a release throwing after a successful ordered load left the window on old rows, because the builder counted the rejected participant as a failed load (also on main); the loader now marks release errors and the builder publishes. It also fails without the subscriber's finally. The section now also crosses tied ranks (its law compares the window's rank sequence and each shown row's current rank), a peer live query on the same source, offset 1, descending order, and explicit window moves; a move that rejects after a failed source recovery leaves the window, and one rejected only by a release failure still moves. A reported-faults law accepts injected faults as rejected loads, thrown releases, rejected moves, or errors the subscription rethrows from a microtask, and rejects any other escaped error. These found that a window move whose load succeeded was recorded as failed when a release threw, so the window stayed private until another move. A throwing release is an adapter bug, so the loader now reports it uncaught from a microtask and changes nothing else; the reported-faults law rejects a move that a release failure rejects, and the request-authority oracle requires each throwing release to be reported uncaught exactly once (a mutant that swallows the error fails). It also crosses a joined marker source: a LEFT join that keeps marked or unmarked rows, and an inner join. The marker source is eager or on-demand, with marker loads that are held, fail, and truncate. This found that an on-demand joined source whose loads finished without delivering a row left the window on old rows, because nothing ran the graph that the pending joined work held; the subscriber now runs it when a joined source becomes ready. A truncate never aborts a window move: the move waits for any replay that holds publication and then applies (ARCHITECTURE.md), so a move that rejects with `AbortError` during a history is an escaped error. (An earlier version of this entry claimed a named fixed history reached an aborted-move branch; no history reached it, and the branch, which quietly accepted such a rejection, is gone.) Recovery truncates the marker source too, because a failed marker replay keeps the last complete publication until that source replays. A mutant-mutant pass over the loader's guards found guards that no ordered oracle kills. A differential instrument then ran 3,000 generated request-authority histories through the loader and each mutant and compared every request's shape, outcome, and release. Three guards the code makes redundant are deleted: the backoff timer guard, the explicit-move check in the retry callback, and the `requiresFullSource` check on a report. An ignored-report law now kills two of the mutants that changed public requests: a report issues no authoritative request before any request settled (a request in flight still owes an exact result for its own options) or while the window is inside the loader's own first prefix. Named replays reach both, and the random campaigns judge them in quiet histories. A random ordered-work campaign later found that the first-prefix check was unsound: it took the next installed row as the next source row, but a signalling refetch moved the page's end before the tie the loader had read, so that tie's row stood past the page while a row tied with the new end was never sent, and a later window move skipped it. The loader now accepts the row only when its page read it or when it read the tie of the page's current end. When the end moved, it repairs (see the later maintainer decision below); query-db's first-page witness requires bounded reads only, no full-source read, and an unchanged count of active Queries. The optimistic-window cases that allow but do not require a refill still bound any refill that occurs: an ordered read within the refill bound or a predicate read, never the full source (a mutant that made the growth read unbounded fails them). The ordered-work model now sorts `undefined` ranks with `null` ones, as the comparator does, and its histories generate both; nullish ranks tie in its window and in-flight comparisons. An `undefined` end also matches a loader that attempted no tie; a nullish end is never an expressible cursor, so the loader has started or will start a full-source read, which covers the source either way. A guard against that match survived the generated campaigns as an equivalent mutant and was removed. The ordered-work oracle keeps the trace as a named fixed history that fails on main, and the request-authority oracle has an unproven-report law (a report over a first page that no row it read proves starts a repair or reads the end's tie), whose replay and fixed campaign fail on main; the broad campaigns reach that law in about one history in 10,000, so an unproven-report campaign (`ordered-loader.unproven-report`, fixed and random) settles the first page, settles the read after it, and reports, over random case parameters and a random suffix, and declares its reach (about a third of 300 histories); `main`'s loader fails both runs. Its fake subscription now reads installed rows as the subscription does, applying a tie's equality, a cursor, and a limit; when its reads ignored the limit, the tie was always the last installed row's, so the first-prefix ignore branch was unreachable. The cost law's per-chain bound, three requests, was an artifact of that fake: it is now a prefix plus a tie and a page per installed row, and it also judges an unindexed window that still needs rows, which grows its prefix instead of reading the full source. The report campaign (`ordered-loader.unproven-report`, 1,000 runs; at 600 a random seed could miss the minimum) now starts each history with one of eight prefixes and declares reach for each report premise: a proven first page, a page that read past a window that shrank, a held full-source read, a head insert that moved the page's end, an owed repair, authoritative work in flight, a release of the older tie that truncates or disposes the loader, and a report to a disposed loader. The unproven-report law requires a bounded repair or the end's tie when every installed rank is expressible; a full-source read no longer satisfies it (a mutant that forced full debt after a report passed before). The cost law also rejects a repeated read: within one invalidation, no prefix, tie, or page repeats more often than the ordering epoch moved. Two laws are stronger: an ignored report, over a proven first page or a held full-source read, issues no request at all, where it used to forbid only authoritative ones; and a report while a repair is owed reads no tie or page before the repair. Deleting the moved-end early return in `revalidateLoadedCoverage`, or its past-window term, fails the first law, and deleting the owed-debt term in `loadMovedEndTie` fails the second; a deletion sweep had found all three surviving every oracle. With that reach, the report path's own `!active` checks were deleted: `dispose()` advances the generation that the stale-run check after the release reads, and a disposed loader issues nothing, which the dispose law judges. A head insert can carry a `-Infinity` rank, and two more laws judge every request: the loader never reads the tie of a rank no cursor can express, and the first finite request after a truncate has no cursor. The fake's `dataNeeded` now counts the window rows not at or before the boundary it is given, where it returned a constant. With those, the stale-run check after the older tie's release fails the reset law when a release truncates the loader and the window then grows (a prefix declares that reach), and removing `loadBoundary`'s own unexpressible-value check fails the unexpressible-tie law. The covered-source early return and the staged-continuation term were deleted: coverage that a full-source read completed holds the work slot, whose check then decides the report, and a staged finite continuation cannot coexist with a proven end, while a staged repair step owes a repair. The ignored-report law's full-source branch no longer needs a quiet history, since such coverage owes nothing, and a prefix reaches a paged loader whose repair fell back to a full-source read; removing the work-slot check then fails it. The unexpressible-end term in `loadMovedEndTie` stays: the unindexed-refetch random campaign found that without it an unindexed loader reads the full source through the boundary fallback where its bounded prefix repair would do, and a named fixed history of that trace fails without the term. Maintainer decision, later: a report whose page end moved now repairs instead of reading only the new end's tie, to cut shipped bytes; `loadMovedEndTie` and its guards are gone, so their mutants above no longer exist. The laws stay and judge the repair path: the ignored-report, owed-repair, unexpressible-tie, and reset laws all still run, and the unproven-report law accepts a repair. The report campaign drops its two prefixes whose release of the older tie truncated or disposed the loader, since a report no longer releases anything, and the query-db replay of an insert into a top-N list now expects the bounded repair's prefix and the new end's tie. Still open there: the `Object.is` term of the moved-end check. It skips work when the loader already read the end's tie, and it decides differently from its fallback only while other work is in flight, which the ignored-report law's quiet premise excludes. The ordered-work oracle owns that branch instead: peers over a refetching provider stay in its grammar for source filters (#2155 excludes only joined filters), and a proven-report law requires that a report which changes nothing the first query's own page and end tie prove, with the model's next row installed and no installed row deleted or reordered, starts no request for it and leaves it owing no `refetch: true` repair. A campaign fixed to that premise must reach it, and a loader that repairs every report fails both its fixed and random runs. A staged end tie that pending joined work defers is read by the pass after that work finishes; a request-authority named fixed history reaches it, and a loader that drops the staged tie fails it. The unproven-report law judges that later pass, and a truncate, failure, move, or disposal in between voids what the report owed. A history that starts during the initial preload found that a window move deferred behind a marker replay, which the source truncate then discarded, rejected with that replay's `AbortError`, so the older move's window won (also on main). A deferred move now waits for every replay that holds publication and applies unless one failed or cleanup ended the sync run; a named fixed history fails without the fix. The ordered-work refetch law also required no full-source read after a signalling refetch for an unindexed plan, which the architecture then let refill a short window from the full source; random seeds found it on main. Maintainer decision on this branch: an underfilled unindexed prefix never reads the full source, because that read is unbounded. It grows instead: each growth asks for twice the last prefix, and it stops once the last growth added no rows. A deletion sweep showed that the older condition's other term, a prefix that reads short, follows from that one. The refetch law now forbids a full-source read after a signalling refetch with no unindexed exception. The named fixed history of a short unindexed window and the fixed unindexed-refetch campaign (`ordered-work.eager-unindexed-refetch`, fixed and random, with reach on windows the prefix fills and windows it leaves short) failed on the full-source fallback and pass with growth; the full-source mutant still fails them. Growth made a new optimistic history possible: an unindexed one-row window behind a joined or anti-joined filter that installs only the prefix it grew to, whose departure leaves the replacement row missing. Sixteen fixed optimistic-window cases (update and delete, both consumers, acknowledge and rollback) cover it, with a refill bound of twice the installed prefix plus the overlaid row. A loader without the stop rule never reaches a fixed point; a loader that stops whenever the prefix reads short leaves those windows empty after settlement, because the pending departure hides a row from the count. The existing unindexed optimistic cases now allow, but do not require, a request behind a joined filter when the replacement row is installed: growth proves rows only up to its prefix, where the full-source fallback had proven every row (a maintainer-approved expectation change). The proven-report random campaign now declares its reach too. One mutant still changes requests without a law: dropping the optimistic-refill flag turns a refill into a refetching prefix. Six more are equivalent in the fake but stay, because the fake cannot reach their premise or they encode a documented rule: the own-first-page check behind a held sync transaction (the fake never holds one), a truncate moving complete coverage back to held, clearing the pending request when a full-source read starts (the fake never answers a full-source read synchronously), staging a joined `more` continuation, the staged-continuation guard before an unindexed prefix, and the drain re-entry guard (a long synchronous chain would otherwise recurse). An include dimension adds a `toArray` child that reads the marker source for each shown row, and an include-children law requires each shown row's markers to equal the model wherever the window law holds; a mutant that never loads newly demanded child keys fails it in an include-only scenario. A newest-move law requires a superseded window move to resolve only after the newest move settles (a superseded move that fails still rejects with its own error), and the model lets the newest move that resolved set the window; it found that a superseded move resolved as soon as its own load settled, so awaiting it showed neither window. The terminal-error law also allows `error` after a load fails while the query is still loading, the documented initial-load failure; a lazy join source is exempt. Limits: includes are one level deep. It also found that a release failure in lazy joined demand during a window move rejected the move, because the subscription reported it as a load error. A window law now lets the newest move win; it found that two moves deferred by a pending source recovery could resume in the opposite order, so the older request replaced the newer window. `setWindow()` now ignores a deferred call that a newer call superseded. A terminal-error law allows a final `error` only after a lazy join demand load, on either side, failed outside a truncate's recovery; named fixed histories reach that branch. A load belongs to a recovery when it asks again for a demand its source held before the truncate (the same request data), or when the graph starts it while the truncate commits. The first model read a flag set only during the commit, but subscriptions start replay loads in a later microtask, so it counted every replay load as new demand and allowed `error` after any failed replay load; a random campaign found the reverse case (#2224): a marker truncate privately moved the window, the include's new demand started outside any replay because releasing its old demand ended the subscription's replay, and its failure ended the query. The demand controller now starts new coverage before it releases retired coverage, a query subscription opens a replay at every truncate even without demand (a replay that starts no recovery work and reports no loading), and a demand failure that fails its subscription's replay keeps the last publication instead of ending the query once the query has first become ready. The section also generates histories that start during the initial preload, with an initial-readiness law (the preload has settled once loading is quiet), marker loads whose aborted requests reject with `AbortError` as the source contract asks, and settles of the newest held load. These found two older defects on main: an aborted lazy demand request that rejected after its truncate replay succeeded ended the query, and so did a superseded segment that the controller released; the controller now treats an aborted request as obsolete demand, which its replay or newer coverage decides. Named replays keep each trace; reverting each production change fails one of them, and a mutant whose replay rebuilds its request data fails the campaigns' replay-load reach witness. The ordered-lifecycle oracle owns the truncate-work witness: a zero-limit window issues no request and reports no loading at a truncate, while a one-row window reacquires. A retention law then judges law 9 at generated checkpoints: a truncate raises a publication barrier, every load its source starts while the barrier is up joins it, a participant's failure fails the replay while its logical demand is held, and while any barrier is up the query shows exactly the rows it showed when the first one rose. It runs after every command and once loading is quiet. A failed-replay campaign (`replay.ordered-failed-replay`, fixed and random) starts each history by holding loads, truncating a source, optionally starting demand, and failing a held load, with a branch that fails an include demand while its marker replay still loads; it declares four reach states in `oracleProperty`'s `histories.states` (a judged failed replay, a judged held replay, a demand started after the commit that fails while its replay loads, and the include form of that demand). A replay participant now also counts as recovery for the terminal-error law, so a demand that starts after the commit while its replay is open is judged in generated histories, not only by a named fixed history. A mutant whose failed replay releases the publication gate fails both failed-replay campaigns and the broad campaigns; a mutant that ends the query when such a demand fails fails both failed-replay campaigns; the branch's production files reverted to `main` fail both. A preload-recovery campaign (`replay.ordered-preload-recovery`, fixed and random) starts every history during the initial preload over on-demand markers and declares two more states: lazy demand in a replay that fails before the first ready, and a window move that waits behind a replay a newer truncate discards. A builder whose deferred move a discarded replay rejects, and one that keeps a failure before the first ready non-fatal, each failed only a named fixed history before; both now fail the fixed campaign, whose seed kills both (each dies in about half of 200-run seeds, so the random campaign kills each about half the time). Building the law found three model errors, each corrected from ARCHITECTURE.md: a failure is scoped to its logical demand, so a retired failed demand and the demand that replaces it publish when the replacement succeeds; a replay completes when its last participant's rows apply, so demand that a deferred window move starts afterwards does not join it; and an ordered tie request (a `where` on rank) is not lazy demand, which the terminal-error law had treated it as, so a failed tie request had excused a terminal error. A query's subscriptions to one collection now share one replay barrier (ARCHITECTURE.md, "Replay participants and failure"): a probe found that in a query that joins and includes the marker source, a marker truncate retired the include's only demand privately, its emptied replay closed while the join's replay still loaded, and include demand the graph then started failed outside every replay and ended the query. A sibling-demand branch of the failed-replay campaign declares that state; the branch's code before the fix fails the named fixed history and both campaigns at `convergence: terminal error`, and removing either sibling hold (at replay completion, or for an emptied replay) fails all three. The random failed-replay campaign then found the other half: one subscription's replay failed, the other's finished once it settled, and demand that a rank move then started on the finished subscription failed and ended the query, because the subscriber judged the failure by its own subscription. The subscriber now asks whether a replay of the source's collection failed; a named fixed history (`a demand that fails after the sibling subscription's replay failed`), a `failedSiblingDemandFailures` reach in the sibling branch (which now may move a row and fail the oldest held load), and both campaigns at 400 runs fail at `convergence: terminal error` on the per-subscription rule. A design that judged a failure against any failed replay of the query, across collections, used to survive, because the convergence check runs after an explicit window move, which retries a failed row demand. A strict terminal-error law now requires a failed lazy demand outside every recovery to end the query (ARCHITECTURE.md, error 228), skipping only failures the model cannot place: after a load threw, and, with a peer, a load that joined a replay. Merge with #2257: its review (CF01, [record](oracle-reviews/2026-10-26-pr-2257.md)) judged a new keyed request that a truncate commit starts as terminal, and called non-fatal recovery of that demand a future contract. This PR adopts that contract by maintainer decision. The merged owner keeps CF01's initiating-request receipt check as a second account of every terminal error, at each history cut and at convergence, plus its named fixed histories and the `replay.subscription-demand-origin` and `replay.keyed-request-failures` campaigns, with their two reach-state pairs measured on this owner's model. Both demand origins, new demand during a marker commit and a settled demand that the replay asks for again, must stay nonterminal after the first ready. An always-fatal `failDemand` mutant fails 15 tests, including both ported campaigns; a never-fatal mutant fails the strict law in 8. CF01's duplicate of the #2224 named fixed history is folded into this owner's existing one. Merge with #2168 (ARCHITECTURE.md law 16): after initial-query readiness no load failure ends a live query, and a failed lazy demand is a request error on the query's node. That supersedes the strict terminal-error law, the error-228 rule, and the always-fatal and never-fatal mutant results above for a query that has been ready. The replay owner now allows a terminal error only after a load failed while the query was still loading, judged at each history cut and at convergence, and it adopts #2168's request-error witness (`requestErrors`); the excusals for thrown and unplaced failures went with the strict law. #2168's design already starts new demand before it releases retired coverage, and it treats a synchronous `loadSubset` throw as a rejection whose owner's release unloads it (the subscription oracles fix that unload), so the adapter-release law now counts a thrown load as acquired. It lacked the shared barrier, the failure hold behind a sibling's failed replay, and the deferred window move's wait, which the merge ports onto it. Without the deferred-move loop, 8 tests fail, #2221 trace 2 among them; without `failReplacement`, the two-failures named fixed history fails; without the sibling wait, that replay and both failed-replay campaigns fail. A deferred move rejects when a reload ends the sync run of the query or of a source, which the source-health oracle requires. The window-request reset went: a move can no longer throw, and deleting it failed nothing. The replay that a truncate opened without demand went too: under law 16 its demand's failure no longer ends the query, and its named fixed history passes on #2168's subscription. Review of the merge (2026-10-28): the replay owner gained a request-error account. After initial-query readiness, each failed lazy demand load that is still owed must appear among the query node's open request failures, by its injected error object, at every history cut, and no request error may stay after recovery replays every source (authority: ARCHITECTURE.md law 16, law 17, and the glossary's request error). A failure is met when its demand retires, a later load of the source covers its keys, or a later replay of the source completes; a failure inside a replay owes nothing until every participant settled. A terminal error now needs a load that failed while that same query was loading, so a peer's initial failure no longer excuses `live`. A thrown load joins a replay that no participant joined yet, and the failed-sibling branch now generates a held retry. `requestErrorChecks` reaches the declared minimum of 5 in each failed-replay campaign. Mutants: demand outcomes that never report an error fail 9 tests at the per-cut check; a successful replay that keeps its request errors fails 22 at the stale-error check. Limits and open items: the account shares one replay across a query's subscriptions to a source, so it cannot judge one subscription's request error while another load of that source is held. The reviewer's finding that `failReplacement`'s replay, which has no recorded failure, completes when every demand that joined it settles is closed as a law revision by maintainer decision: the hold ends when every demand load that joins it loads, a later replay of the source succeeds, or the subscription's last demand retires (ARCHITECTURE.md, "Replay participants and failure"). The query retries the failed demand at once and that retry joins the hold, so the hold cannot publish without the failed demand's rows. The replay oracle judges each subscription's request-error verdict by the subscription that a load names, and its failed-replay campaigns declare the premise (a subscription's load succeeds while that subscription's failure is still owed; 30 fixed and 24 random histories at the normal budget). No live-query history violates the request-error or retention law there; a mutant that completes such a hold when any participant settles fails both failed-replay campaigns at the retention law. A subscription-level `it.fails` test that asserted the earlier, stricter wording (no joined demand may end the hold) was removed with the revision. Limit: the oracle drives the hold only through live-query histories, where the retry always joins; a direct `Collection.subscribeChanges` caller that never retries is outside the live-query contract. Which failure a deferred window move rejects with, when its replay has several, is not specified: `main` rejected with the replay's earliest failure, and this branch rejects with `lastSubsetError`; by maintainer decision the move rejects with its replay's earliest failure that still decides it (law 17 decides which count: a retired demand's, a retried request's, and a replaced demand's failures do not). An identity law now judges deferred moves that start before any failure of the replays they wait on; on the parent code both failed-replay campaigns and the named fixed history `a window move behind a replay with two failed loads` fail with "replay error identity", and the deferred-move loop that rethrows a non-abort replay error passes. The request-error account decides failures per key: a later load of the source that asks for some of a failure's keys decides them, and keys it no longer asks for left the demand. The held-retry branch then found, at three times the run budget, a marker change publishing over a window that the model retained after a failed marker replay (`hold, truncateMarkers, settle ok, settle ok, settle fail newest, mark 3 off`, ascending, offset 1, limit 1, includes over on-demand markers). It was a model defect: the query retries a failed demand at once, and when that retry loads the failed keys the failure no longer counts (ARCHITECTURE.md law 17), so the replay succeeds and publishes. The model now clears a replay failure when a later load of the replay loads its keys. The replay oracle passes at the normal budget and three times at three times it, and production without `failReplacement` still fails its named fixed history at the retention law. A move whose `setWindow` throws synchronously after the request generation increments is reachable only through invariant errors, which probes for a throwing subscriber, a crashed source, and a throwing `select` did not reach. An aborted request's rejection and the failure of a segment that newer coverage released are not failures. That design now fails both failed-replay campaigns. An independent oracle review then narrowed several judgments. The terminal-error excuse after a synchronous throw applies only to the thrown error itself, ending the query after the step that threw; the throw's own step, and every other failure, are judged strictly (a per-history flag had excused every later failure). A load that fails outside every barrier after a failed demand of its source retired is unplaced, because the failed replay may still hold through the subscription's other demands, which the adapter cannot attribute. Limit: with a peer, the strict law accepts either query ending, since the adapter boundary cannot tell which query's subscription issued a load; attributing each failure to its query's subscription would close that. The window check now also requires every shown row to be eligible and to appear once, so a tie cannot hide a row the join rejects. A synchronous-throw dimension (`markerThrows` arms the next marker load to throw while it starts) found that a load throwing inside an open replay ended the query: the subscription dropped the demand, so its failure did not fail the replay, and the subscriber treated the throw as fatal. The subscription now hands the replay a rejected participant for such a throw and keeps the demand, which a later replay retries; named fixed histories (`a replay load that throws while it starts`, `a demand whose load throws inside its open replay`), a `thrownReplayDemands` reach in a thrown-demand branch, and both failed-replay campaigns (now 600 runs) fail on the parent code, and a mutant that later unloads the never-acquired load fails the adapter-release check. Model corrections, each from the adapter-boundary rule that a thrown load acquires nothing: a thrown load joins a replay only if it still has a participant or a failure; an armed throw expires before the drain; and a thrown demand's retirement is invisible, so the retention law skips the marker barrier from a throw to the end of its episode (a later barrier in the episode inherits the ambiguity, which also corrects the existing release-throw case), and a failure that joins an already failed or ambiguous barrier may end the query. Maintainer decision: a synchronous throw inside an open replay fails that replay as a rejection does, so the subscription replay oracle's `new request throws` case and five `live-query-collection` cases, which expected a thrown new demand to roll back, now expect the rejection outcome. Limits: a design that dropped a thrown demand and let its replay succeed passes wherever only retention could see it; after a history command follows a throw, a terminal error is excused, because the model cannot see whether that command retired the thrown demand and with it its failed replay (a demand that waited on that replay then fails outside it). The named fixed histories judge the throw's own outcome strictly. The failed-replay random campaign at five times its run count then found a retention counterexample with no throw, on the parent code too: a join and an include of one marker source; one subscription's replay fails, the other's finishes, and a row move starts demand on it whose load fails, which the shared barrier kept from ending the query; a marker change then retired the first replay's failed demand, which discarded that replay and published an empty window, because the second failure held nothing. That failure now fails its own subscription's replacement, which holds until a later replay succeeds or the subscription's last demand retires. A named fixed history of the trace fails without the hold, and a `partialFailureRetirements` reach (a failed demand retires while another failure still holds the barrier) is declared in the failed-replay campaign; the campaigns themselves do not fail without the hold, so the named fixed history is the witness. A window move whose load throws while it starts counts as a settled, failed move in the model (it used to stay pending, so the newest-move law misjudged the older move), with a `thrownMoves` reach. The broad random campaign at five times its run count then found an older move whose settlement resolved with itself: the newer move threw after it bumped the request generation and before it replaced the latest request, so the older move's settlement returned its own promise, a chaining cycle that escaped as a TypeError. A call now clears the latest request when it bumps the generation, so no older move can wait on itself; a named fixed history fails without that. The same assignment covers a move deferred behind a replay, which had the same shape (an independent review found it can hang forever when a newer move throws between the replay settling and the deferred move resuming); that microtask limit is outside the grammar, which flushes between commands, so only the shared mechanism, not that path, has a witness. The ordered-work oracle also keeps the trace from #2221 as a named fixed history: before prefix growth the loader read the full source twice after a signalling refetch past a NaN boundary; with growth it reads none. Limits: the adapter boundary cannot tell which query issued a load, so the retention law and the participant rule skip histories with a peer. The retention law judges barriers that rise after the query first became ready; before that the initial-readiness law governs. It skips a barrier where a release threw while the replay started, which may fail that replay. Core now reports a throwing `unloadSubset` uncaught and fails nothing with it; the subscription lifecycle, replay, Effect disposal, includes-temporal, and subset-error oracles check the uncaught report, once, with the adapter's error. The request-authority oracle now also generates requests that throw while they start, the last history only TLA+ covered, with an error-identity law: a failed request's participant reports that request's own error. It found that a superseded failure whose recovery read threw at its start reported the start error instead (review finding 6). The state oracle compares every current failed request's participant reason with its own originating Error by identity. Release cleanup cannot replace that reason, even when the thrown value's message starts with “release ”. A bounded 16-case checker calibration crosses index availability, widths 1/2, actual throwing release absent/present, and ordinary/full-source plans. It feeds three wrong participant reasons into the same model/production-driver/comparison; the original prefix waiver and an actual-release-only waiver fail at that check. The existing fixed/random 10,000 authority histories declare and enforce current-request-error reach and actual cleanup-fault/current-request-error overlap. Scope ends at the loader participant and separate uncaught-cleanup observations; it adds no provider/framework or intermediate-publication promise. The state owner's shared error-identity calibration and paired generated campaigns enforce these checks. A cost law then checks, after loading is quiet and a bounded repair is available, that one invalidation reads no full source and issues at most one chain per ordering epoch move (in the fake, a prefix, a tie, and a refill); a mutant that always repairs with a full-source read fails it. The replay-refinement section's status law requires a quiet live query and its peer to stay ready when no load failed. Limits: whether a release runs the graph at once or defers it to a transaction belongs to the scheduler, and the oracle generates both forms without checking the scheduler's choice; the fake's rows do not move except for the unexpressible boundary; publication holds stay with other tests; the laws do not judge requests issued before a truncate; a hung authoritative request suspends the leak law for its unfinished chain; a recovery start that throws during a superseded failure is rare in the campaigns, so a named fixed history owns it. | | Indexed predicate filtering | Complete for bounded dotted-path collision | An independent row filter checks direct predicates and public callback predicates for a dotted scalar field beside a nested path, with and without an index. Selected-field ordering checks the same distinction through `$selected`. | | WHERE predicate publication | Complete for bounded predicate and sync-transaction grammar | The contract, Kleene reference evaluator, snapshot and change-history grammar, three subscriber consumers plus direct snapshot, and per-commit key-set refinement check are literate. A fixed same-key update checks live-row and direct-subscriber payloads; a focused descriptor boundary checks stored-row prefilter safety. Generated cleanup and restart histories for filtered subscribers remain open. | diff --git a/packages/db-sqlite-persistence-core/src/remote-subset-wire.ts b/packages/db-sqlite-persistence-core/src/remote-subset-wire.ts index 590c94cde5..e3c474fbfc 100644 --- a/packages/db-sqlite-persistence-core/src/remote-subset-wire.ts +++ b/packages/db-sqlite-persistence-core/src/remote-subset-wire.ts @@ -161,6 +161,8 @@ function visitLoadSubsetOptions( `refetch`, `signal`, `subscription`, + // An optional hint: not transported, so the remote side returns a superset. + `relations`, ]) const state: ProjectionState = { diff --git a/packages/db-sqlite-persistence-core/tests/remote-subset-relations.test.ts b/packages/db-sqlite-persistence-core/tests/remote-subset-relations.test.ts new file mode 100644 index 0000000000..f7928a32f3 --- /dev/null +++ b/packages/db-sqlite-persistence-core/tests/remote-subset-relations.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { + toTransportedLoadSubsetOptions, + validateRemoteSubsetOptions, +} from '../src/remote-subset-wire' +import type { LoadSubsetOptions } from '@tanstack/db' + +describe(`remote subset relation hints`, () => { + const options = { + limit: 2, + relations: [ + { + quantifier: `some`, + collectionId: `owners`, + on: { parent: [`ownerId`], child: [`id`] }, + }, + ], + } as LoadSubsetOptions + + it(`admits a load with a hint, because an adapter may ignore it`, () => { + expect(() => validateRemoteSubsetOptions(options)).not.toThrow() + }) + + it(`leaves the optional hint out of the transported request`, () => { + expect(toTransportedLoadSubsetOptions(options)).toEqual({ limit: 2 }) + }) +}) diff --git a/packages/db/package.json b/packages/db/package.json index dc7503eebc..5235ddbff3 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -23,7 +23,7 @@ "test": "vitest --run", "test:dist": "vitest run --config vitest.dist.config.ts", "test:facade-retention": "node --expose-gc --import tsx tests/facade-retention.probe.ts", - "test:oracles": "vitest --run --coverage.enabled=false tests/oracle-campaign-units.test.ts tests/reverse-index-oracle.property.test.ts tests/query/compiler/in-evaluator-oracle.property.test.ts tests/query/compiler/group-by-pipeline-oracle.test.ts tests/cleanup-queue-oracle.property.test.ts tests/comparison-oracle.property.test.ts tests/duration-query-equality-oracle.test.ts tests/cursor-oracle.property.test.ts tests/index-update-oracle.property.test.ts tests/utils-oracle.property.test.ts tests/change-event-history-oracle.test.ts tests/index-suggestion-oracle.test.ts tests/btree-map-oracle.test.ts tests/paced-mutations-oracle.test.ts tests/db-client-hydration-authority-oracle.test.ts tests/local-storage-eager-reload-oracle.property.test.ts tests/local-only-direct-write-oracle.test.ts tests/local-storage-order-oracle.test.ts tests/local-storage-write-order-oracle.test.ts tests/local-storage-peers-oracle.test.ts tests/local-storage-value-fidelity-oracle.property.test.ts tests/collection-cleanup-restart-oracle.test.ts tests/collection-gc-transaction-oracle.property.test.ts tests/collection-gc-retention-oracle.property.test.ts tests/collection-gc-mutation-oracle.property.test.ts tests/effect-disposal-oracle.test.ts tests/optimistic-transaction-oracle.property.test.ts tests/transaction-ownership-oracle.property.test.ts tests/optimistic-history-oracle.property.test.ts tests/optimistic-history-publication-oracle.test.ts tests/optimistic-history-outcomes-oracle.test.ts tests/collection-metadata-publication-oracle.property.test.ts tests/collection-index-value-oracle.test.ts tests/collection-state-retention-oracle.property.test.ts tests/collection-subscription-lifecycle-history-oracle.property.test.ts tests/collection-subscription-lifecycle-oracle.test.ts tests/collection-subscription-reentrancy-oracle.test.ts tests/collection-subscription-lifecycle-publication-oracle.property.test.ts tests/collection-subscription-replay-oracle.property.test.ts tests/d2-source-reconciliation-oracle.property.test.ts tests/live-query-cache-options-oracle.test.ts tests/mutation-confirmation-calibration.test.ts tests/mutation-handler-types-oracle.test.ts tests/live-query-observer-history-oracle.property.test.ts tests/live-query-observer-hydration-oracle.property.test.ts tests/live-query-observer-snapshot-oracle.property.test.ts tests/query/cold-join-reconciliation-oracle.test.ts tests/query/identity-output-shape-oracle.test.ts tests/query/optimizer-semantics-oracle.test.ts tests/query/index-path-collision-oracle.test.ts tests/query/custom-index-order-selection-oracle.test.ts tests/query/mixed-index-order-oracle.test.ts tests/query/includes-collection-oracle.property.test.ts tests/query/includes-functional-projection-oracle.test.ts tests/query/includes-functional-input-boundary.test.ts tests/query/public-container-copy-oracle.test.ts tests/query/includes-context-transport-oracle.test.ts tests/query/includes-cross-formulation-oracle.property.test.ts tests/query/includes-optimistic-oracle.property.test.ts tests/query/includes-oracle.property.test.ts tests/query/includes-alias-shadowing-oracle.test.ts tests/query/includes-outer-join-route-work-oracle.test.ts tests/query/includes-publication-oracle.test.ts tests/query/includes-query-shape-oracle.test.ts tests/query/subquery-user-value-oracle.test.ts tests/query/includes-temporal-oracle.test.ts tests/query/includes-work-counter-oracle.test.ts tests/query/load-subset-oracle.property.test.ts tests/query/load-subset-replay-refinement-oracle.test.ts tests/query/load-subset-source-readiness-refinement-oracle.test.ts tests/query/load-subset-transaction-refinement-oracle.test.ts tests/query/ordered-source-loader-state-oracle.test.ts tests/query/ordered-demand-retirement.test.ts tests/query/ordered-default-work.test.ts tests/query/ordered-lifecycle-oracle.property.test.ts tests/query/ordered-work-oracle.property.test.ts tests/query/pagination-oracle.property.test.ts tests/query/includes-space-oracle.test.ts tests/query/virtual-row-fields-oracle.test.ts tests/query/virtual-row-fields-input-oracle.test.ts tests/query/virtual-row-fields-effect-oracle.test.ts tests/query/virtual-row-fields-types-oracle.test.ts tests/query/where-predicate-publication-oracle.property.test.ts tests/query/join-result-key-oracle.property.test.ts tests/query/pooled-live-query-oracle.property.test.ts tests/live-query-deferred-acquisition-oracle.test.ts tests/flat-change-tracking-oracle.property.test.ts tests/truncate-readiness-oracle.test.ts tests/proxy-detachment-contract-oracle.test.ts tests/production-error-messages-oracle.test.ts tests/query/bucket-facade-rollback-oracle.property.test.ts tests/query/aggregate-select-oracle.property.test.ts tests/query/load-subset-joint-replay-oracle.property.test.ts", + "test:oracles": "vitest --run --coverage.enabled=false tests/oracle-campaign-units.test.ts tests/query/load-subset-relations-oracle.test.ts tests/reverse-index-oracle.property.test.ts tests/query/compiler/in-evaluator-oracle.property.test.ts tests/query/compiler/group-by-pipeline-oracle.test.ts tests/cleanup-queue-oracle.property.test.ts tests/comparison-oracle.property.test.ts tests/duration-query-equality-oracle.test.ts tests/cursor-oracle.property.test.ts tests/index-update-oracle.property.test.ts tests/utils-oracle.property.test.ts tests/change-event-history-oracle.test.ts tests/index-suggestion-oracle.test.ts tests/btree-map-oracle.test.ts tests/paced-mutations-oracle.test.ts tests/db-client-hydration-authority-oracle.test.ts tests/local-storage-eager-reload-oracle.property.test.ts tests/local-only-direct-write-oracle.test.ts tests/local-storage-order-oracle.test.ts tests/local-storage-write-order-oracle.test.ts tests/local-storage-peers-oracle.test.ts tests/local-storage-value-fidelity-oracle.property.test.ts tests/collection-cleanup-restart-oracle.test.ts tests/collection-gc-transaction-oracle.property.test.ts tests/collection-gc-retention-oracle.property.test.ts tests/collection-gc-mutation-oracle.property.test.ts tests/effect-disposal-oracle.test.ts tests/optimistic-transaction-oracle.property.test.ts tests/transaction-ownership-oracle.property.test.ts tests/optimistic-history-oracle.property.test.ts tests/optimistic-history-publication-oracle.test.ts tests/optimistic-history-outcomes-oracle.test.ts tests/collection-metadata-publication-oracle.property.test.ts tests/collection-index-value-oracle.test.ts tests/collection-state-retention-oracle.property.test.ts tests/collection-subscription-lifecycle-history-oracle.property.test.ts tests/collection-subscription-lifecycle-oracle.test.ts tests/collection-subscription-reentrancy-oracle.test.ts tests/collection-subscription-lifecycle-publication-oracle.property.test.ts tests/collection-subscription-replay-oracle.property.test.ts tests/d2-source-reconciliation-oracle.property.test.ts tests/live-query-cache-options-oracle.test.ts tests/mutation-confirmation-calibration.test.ts tests/mutation-handler-types-oracle.test.ts tests/live-query-observer-history-oracle.property.test.ts tests/live-query-observer-hydration-oracle.property.test.ts tests/live-query-observer-snapshot-oracle.property.test.ts tests/query/cold-join-reconciliation-oracle.test.ts tests/query/identity-output-shape-oracle.test.ts tests/query/optimizer-semantics-oracle.test.ts tests/query/index-path-collision-oracle.test.ts tests/query/custom-index-order-selection-oracle.test.ts tests/query/mixed-index-order-oracle.test.ts tests/query/includes-collection-oracle.property.test.ts tests/query/includes-functional-projection-oracle.test.ts tests/query/includes-functional-input-boundary.test.ts tests/query/public-container-copy-oracle.test.ts tests/query/includes-context-transport-oracle.test.ts tests/query/includes-cross-formulation-oracle.property.test.ts tests/query/includes-optimistic-oracle.property.test.ts tests/query/includes-oracle.property.test.ts tests/query/includes-alias-shadowing-oracle.test.ts tests/query/includes-outer-join-route-work-oracle.test.ts tests/query/includes-publication-oracle.test.ts tests/query/includes-query-shape-oracle.test.ts tests/query/subquery-user-value-oracle.test.ts tests/query/includes-temporal-oracle.test.ts tests/query/includes-work-counter-oracle.test.ts tests/query/load-subset-oracle.property.test.ts tests/query/load-subset-replay-refinement-oracle.test.ts tests/query/load-subset-source-readiness-refinement-oracle.test.ts tests/query/load-subset-transaction-refinement-oracle.test.ts tests/query/ordered-source-loader-state-oracle.test.ts tests/query/ordered-demand-retirement.test.ts tests/query/ordered-default-work.test.ts tests/query/ordered-lifecycle-oracle.property.test.ts tests/query/ordered-work-oracle.property.test.ts tests/query/pagination-oracle.property.test.ts tests/query/includes-space-oracle.test.ts tests/query/virtual-row-fields-oracle.test.ts tests/query/virtual-row-fields-input-oracle.test.ts tests/query/virtual-row-fields-effect-oracle.test.ts tests/query/virtual-row-fields-types-oracle.test.ts tests/query/where-predicate-publication-oracle.property.test.ts tests/query/join-result-key-oracle.property.test.ts tests/query/pooled-live-query-oracle.property.test.ts tests/live-query-deferred-acquisition-oracle.test.ts tests/flat-change-tracking-oracle.property.test.ts tests/truncate-readiness-oracle.test.ts tests/proxy-detachment-contract-oracle.test.ts tests/production-error-messages-oracle.test.ts tests/query/bucket-facade-rollback-oracle.property.test.ts tests/query/aggregate-select-oracle.property.test.ts tests/query/load-subset-joint-replay-oracle.property.test.ts", "bench:nested-includes": "vitest bench tests/query/includes-performance.bench.ts --run --coverage.enabled=false --reporter=verbose", "test:indexed-db:package": "pnpm --filter @tanstack/db... build && vitest run --config vitest.indexed-db.package.config.ts", "test:local-stores:browser": "vitest run --config vitest.local-stores.config.ts --maxWorkers=1", diff --git a/packages/db/src/collection/subscription.ts b/packages/db/src/collection/subscription.ts index 2214d1601d..991819736f 100644 --- a/packages/db/src/collection/subscription.ts +++ b/packages/db/src/collection/subscription.ts @@ -21,6 +21,7 @@ import type { ChangeMessage, CollectionDependent, LoadSubsetOptions, + LoadSubsetRelation, LoadSubsetRequestResult, SubscribeChangesOptions, Subscription, @@ -76,6 +77,8 @@ type CollectionSubscriptionOptions = { includeInitialState?: boolean /** Pre-compiled expression for filtering changes */ whereExpression?: BasicExpression + /** Semi/anti-join filters for a loadSubset request, read per request */ + relations?: () => Array | undefined /** Callback to call when the subscription is unsubscribed */ onUnsubscribe?: (event: SubscriptionUnsubscribedEvent) => void /** Callback for subset-load failures scoped to this subscription. */ @@ -1375,11 +1378,17 @@ export class CollectionSubscription // Request the sync layer to load more data // don't await it, we will load the data into the collection when it comes in + // A full-source read stands for every row, so it sends no hint. + const relations = + opts?.limit !== undefined || opts?.where !== undefined + ? this.options.relations?.() + : undefined const loadOptions: LoadSubsetOptions = { ...(opts?.refetch ? { refetch: true } : {}), where: stateOpts.where, signal: opts?.signal, subscription: this, + ...(relations && { relations }), // Include orderBy and limit if provided so sync layer can optimize the query orderBy: opts?.orderBy, // A local optimistic row can hide one source row from a bounded prefix. @@ -1797,6 +1806,7 @@ export class CollectionSubscription // don't await it, we will load the data into the collection when it comes in // Note: `where` does NOT include cursor expressions - they are passed separately // The sync layer can choose to use cursor-based or offset-based pagination + const relations = this.options.relations?.() const loadOptions: LoadSubsetOptions = { ...(refetch ? { refetch: true } : {}), where, // Main filter only, no cursor @@ -1805,6 +1815,7 @@ export class CollectionSubscription cursor: cursorExpressions, // Cursor expressions passed separately offset: offset ?? 0, subscription: this, + ...(relations && { relations }), } const { diff --git a/packages/db/src/query/compiler/order-by.ts b/packages/db/src/query/compiler/order-by.ts index 01c61fbf48..3a4bd85634 100644 --- a/packages/db/src/query/compiler/order-by.ts +++ b/packages/db/src/query/compiler/order-by.ts @@ -4,6 +4,7 @@ import { } from '@tanstack/db-ivm' import { defaultComparator, makeComparator } from '../../utils/comparison.js' import { + Func, PropRef, collectCollectionSources, followRef, @@ -20,14 +21,25 @@ import { hasVirtualPropPath } from '../../virtual-props.js' import { deepEquals } from '../../utils.js' import { devBuild } from '../../error-message.js' import { compileExpression } from './evaluators.js' -import { getSourceAliasesFromExpression } from './expressions.js' +import { + getSourceAliasesFromExpression, + normalizeExpressionPaths, +} from './expressions.js' import type { CompareOptions } from '../builder/types.js' import type { WindowOptions } from './types.js' import type { Grouping } from './grouping.js' import type { CompiledSingleRowExpression } from './evaluators.js' -import type { OrderBy, OrderByClause, QueryIR, Select } from '../ir.js' +import type { + BasicExpression, + JoinClause, + OrderBy, + OrderByClause, + QueryIR, + Select, +} from '../ir.js' import type { CollectionLike, + LoadSubsetRelation, NamespacedAndKeyedStream, NamespacedRow, } from '../../types.js' @@ -69,6 +81,142 @@ export type OrderByOptimizationInfo = { sourceHoldsAllRows: boolean /** Sources whose lazy demand must settle before a joined-filter page. */ joinedFilterSourceIds?: ReadonlyArray + /** The joined filter as semi/anti-join hints for the source's loadSubset. */ + relations?: Array +} + +function flattenConjuncts( + expression: BasicExpression, + out: Array = [], +): Array { + if (expression.type === `func` && expression.name === `and`) { + for (const arg of expression.args) flattenConjuncts(arg, out) + } else { + out.push(expression) + } + return out +} + +// The join's `eq(root., joined.)` key paths, relative to each row. +function joinKeyOf( + join: JoinClause, + rootAlias: string, + joinedAlias: string, +): { parent: Array; child: Array } | undefined { + const on = join.on + if (on.type !== `func` || on.name !== `eq` || on.args.length !== 2) { + return undefined + } + const [a, b] = on.args + if (a?.type !== `ref` || b?.type !== `ref`) return undefined + const root = + a.path[0] === rootAlias && b.path[0] === joinedAlias + ? a.path + : b.path[0] === rootAlias && a.path[0] === joinedAlias + ? b.path + : undefined + if (!root) return undefined + const joined = root === a.path ? b.path : a.path + if (root.length < 2 || joined.length !== 2) return undefined + return { parent: root.slice(1), child: joined.slice(1) } +} + +function joinsOnKey(collection: CollectionLike, field: string) { + const probe = `__tanstack_db_key_probe__` + try { + return ( + (collection as Collection).config.getKey({ [field]: probe }) === probe + ) + } catch { + return false + } +} + +/** + * A conjunct over the joined alias as a relation on the root row: + * - `not(isUndefined(j.))` keeps a root row with a related row (some); + * `isUndefined(j.)` keeps one without (none). + * - Any other conjunct over the joined alias alone fails or passes on a + * missing related row. Failing, it keeps a root row only when a related row + * passes it: `some(conjunct)`. Passing, it drops a root row only when its + * related row fails it: `none(not conjunct)`, exact only when the join + * matches at most one row, so on the joined collection's key. + */ +function relationOf( + join: JoinClause, + rootAlias: string, + conjunct: BasicExpression, +): LoadSubsetRelation | undefined { + if (join.from.type !== `collectionRef`) return undefined + const joinedAlias = join.from.alias + const aliases = [...getSourceAliasesFromExpression(conjunct)] + if (aliases.length !== 1 || aliases[0] !== joinedAlias) return undefined + const key = joinKeyOf(join, rootAlias, joinedAlias) + if (!key) return undefined + const collection = join.from.collection + const collectionId = collection.id + + let quantifier: `some` | `none` = `none` + let check = conjunct + if ( + check.type === `func` && + check.name === `not` && + check.args.length === 1 + ) { + quantifier = `some` + check = check.args[0]! + } + if ( + check.type === `func` && + check.name === `isUndefined` && + check.args.length === 1 && + check.args[0]?.type === `ref` && + check.args[0].path.length === 2 && + check.args[0].path[1] === key.child[0] + ) { + return { quantifier, collectionId, on: key } + } + + let passesMissing: boolean + try { + passesMissing = Boolean(compileExpression(conjunct)({ [rootAlias]: {} })) + } catch { + return undefined + } + const where = normalizeExpressionPaths( + conjunct as BasicExpression, + joinedAlias, + ) + if (!passesMissing) + return { quantifier: `some`, collectionId, on: key, where } + if (!joinsOnKey(collection, key.child[0]!)) return undefined + return { + quantifier: `none`, + collectionId, + on: key, + where: new Func(`not`, [where]), + } +} + +// Every cross-alias conjunct of a joined-filter query as a relation, or none: +// a hint is exact only when it carries the whole joined filter. +function joinedFilterRelations( + rawQuery: QueryIR, + rootAlias: string, +): Array | undefined { + const join = rawQuery.join?.[0] + if (!join) return undefined + const relations: Array = [] + for (const where of rawQuery.where ?? []) { + for (const conjunct of flattenConjuncts(getWhereExpression(where))) { + const aliases = [...getSourceAliasesFromExpression(conjunct)] + if (aliases.every((alias) => alias === rootAlias)) continue + const relation = relationOf(join, rootAlias, conjunct) + if (!relation) return undefined + relations.push(relation) + } + } + return relations.length > 0 ? relations : undefined } function warnOrderIndexFallback( @@ -297,6 +445,13 @@ export function processOrderBy( joinedFilterSourceIds: joinedFilterSourceId ? [joinedFilterSourceId] : undefined, + // A subquery root can rename fields, so only a direct root's rows + // have the paths a hint names. + ...(joinedFilterSourceId !== undefined && + rawQuery.from.type === `collectionRef` && + rawQuery.from.sourceId === orderBySourceId && { + relations: joinedFilterRelations(rawQuery, orderByAlias), + }), sourceHoldsAllRows: followRefResult.collection.config.syncMode !== `on-demand`, requiresFullSource: @@ -338,6 +493,11 @@ export function processOrderBy( ...(info.joinedFilterSourceIds ?? []), ]), ], + // One subscription serves every window, so a hint holds only when + // each window asks for the same filter. + relations: deepEquals(previous.relations, info.relations) + ? info.relations + : undefined, get offset() { return Math.min(previous.offset, info.offset) }, diff --git a/packages/db/src/query/ir-stable-identity.ts b/packages/db/src/query/ir-stable-identity.ts index 94c2f05dca..2e6e134ad5 100644 --- a/packages/db/src/query/ir-stable-identity.ts +++ b/packages/db/src/query/ir-stable-identity.ts @@ -102,7 +102,8 @@ export function getLoadSubsetDemandKey( !options.orderBy?.length && options.limit === undefined && (options.offset === undefined || options.offset === 0) && - options.cursor === undefined + options.cursor === undefined && + !options.relations?.length ) { // Query-db uses its base query key for the one unconstrained demand. An // owner-only option must not create another cache entry for the same data. @@ -115,6 +116,33 @@ export function getLoadSubsetDemandKey( query: canonicalizeLoadSubsetQuery(options, `loadSubset`, seen), } + if (options.relations?.length) { + // A relation-filtered demand asks for fewer rows than the same demand + // without it: never the same key. + result.relations = options.relations.map((relation, index) => ({ + quantifier: relation.quantifier, + collectionId: relation.collectionId, + parent: canonicalizeRuntimeValue( + relation.on.parent, + `loadSubset.relations[${index}].on.parent`, + seen, + ), + child: canonicalizeRuntimeValue( + relation.on.child, + `loadSubset.relations[${index}].on.child`, + seen, + ), + ...(relation.where && { + where: canonicalizeExpression( + relation.where, + `loadSubset.relations[${index}].where`, + seen, + `exact-output`, + ), + }), + })) + } + if (options.limit !== undefined) { result.limit = canonicalizeRuntimeValue( options.limit, diff --git a/packages/db/src/query/live/ARCHITECTURE.md b/packages/db/src/query/live/ARCHITECTURE.md index eada4aeff7..f7a68aa1f8 100644 --- a/packages/db/src/query/live/ARCHITECTURE.md +++ b/packages/db/src/query/live/ARCHITECTURE.md @@ -1297,6 +1297,25 @@ row, so the joined source becoming ready schedules that run itself. Joined-side so a removed match can refill a short window. An empty joined replay still releases held Effect callbacks. +Such a window also forwards its joined filter on every `loadSubset` as +`relations`, a semi/anti-join hint, when every cross-alias conjunct maps to one. +An existence check is `some` or `none`. A conjunct that fails on a missing joined +row is `some(where)`. One that passes on a missing row is `none(not where)`, only +when the join is on the joined collection's key. A subquery root sends no hint, +since its projection can rename the paths a hint names. An adapter may apply the hint +or ignore it and return a superset, and it must not drop a row that passes. Local +evaluation stays authoritative. The hint is part of the demand key. Windows that +share a source send it only when they ask for the same joined filter. +An adapter that applies the hint keeps its answer current as related rows +change, as it does for rows that enter its `where`: it delivers a root row that +comes to pass. A local write on a joined row is not the provider's to see, so +no request sends the hint while a joined collection has one. A window that sent +it then reads its prefix again from the first row without the hint, once any +pending request settles, as many rows as its hinted reads settled plus what the +window still needs, and reads its boundary tie again. That is a finite +read, so it does not hold the optimistic publication. A full-source read stands +for every row, so it never sends the hint. + A finite indexed window is proven only up to the loader's settled boundary. Live root rows past the bounded prefix still enter the graph, so a window row after that boundary does not count toward a full window: an earlier eligible diff --git a/packages/db/src/query/live/collection-subscriber.ts b/packages/db/src/query/live/collection-subscriber.ts index e3d08e95c2..6b3dd13e55 100644 --- a/packages/db/src/query/live/collection-subscriber.ts +++ b/packages/db/src/query/live/collection-subscriber.ts @@ -360,9 +360,30 @@ export class CollectionSubscriber< this.sendChangesToPipeline(splittedChanges) } + // A local write on a joined row is not the provider's, so a hint could + // leave out a root row that the write makes pass. Requests send no hint + // while one is pending, and a window loaded with one reads its prefix again. + const relations = orderByInfo.relations + const joinedIds = new Set( + relations?.map(({ collectionId }) => collectionId), + ) + const joined = this.collectionConfigBuilder + .getSourceCollections() + .filter(({ id }) => joinedIds.has(id)) + const hasJoinedWrite = () => + joined.some((collection) => collection._optimisticOverlaySize() > 0) + let sentRelations = false + // Subscribe to changes with onStatusChange - listener is registered before any snapshot // values bigger than what we've sent don't need to be sent because they can't affect the topK const subscription = this.collection.subscribeChanges(sendChangesInRange, { + ...(relations && { + relations: () => { + if (hasJoinedWrite()) return undefined + sentRelations = true + return relations + }, + }), whereExpression, onStatusChange, onLoadSubsetError, @@ -460,6 +481,11 @@ export class CollectionSubscriber< orderByInfo.joinedFilterSourceIds?.some((sourceId) => this.collectionConfigBuilder.hasPendingJoinedWork(sourceId), ) ?? false, + () => { + const stale = sentRelations && hasJoinedWrite() + if (stale) sentRelations = false + return stale + }, ) this.orderedLoader.start() diff --git a/packages/db/src/query/live/ordered-source-loader.ts b/packages/db/src/query/live/ordered-source-loader.ts index 414a5f7882..d4badfb6d0 100644 --- a/packages/db/src/query/live/ordered-source-loader.ts +++ b/packages/db/src/query/live/ordered-source-loader.ts @@ -127,6 +127,8 @@ export class OrderedSourceLoader { private ownPrefixCount: number | undefined private lastBoundary: unknown private needsOptimisticRefill = false + // Settled rows that a prefix read without the relation hint covers again. + private prefixReread: number | undefined private retiringSupersededAcquisitions = false private repairRetries = 0 private repairTimer: ReturnType | undefined @@ -159,6 +161,7 @@ export class OrderedSourceLoader { private readonly canRetryRepair: () => boolean = () => false, private readonly getGraphInputRevision?: () => number, private readonly hasPendingJoinedWork: () => boolean = () => false, + private readonly relationHintIsStale: () => boolean = () => false, ) { this.info.isRequesting = () => this.requesting // A joined filter drops rows after the source's limit, so a full window @@ -309,6 +312,24 @@ export class OrderedSourceLoader { this.graphCheckedDuringRequest = this.getGraphInputRevision?.() } if (!this.active || this.info.limit === 0 || this.requesting) return + // A relation hint can have left out a root row that a local joined write + // now makes pass, so the window's prefix is read again without it, once + // a pending request settles. + if ( + this.hasSettledSourceRequest && + !this.pending && + this.relationHintIsStale() + ) { + // Read again as many rows as the hinted reads settled, so an adapter + // that ignored the hint answers with the same boundary. + this.prefixReread = + this.settledSourceBoundary === undefined + ? 0 + : this.countAcquiredRows(Infinity) + this.invalidateCursor() + // A hinted tie read can have left out tied rows too. + this.lastBoundary = undefined + } windowOperationGeneration ??= this.blockedLoadMore?.windowOperationGeneration continuesOrderedPrefixRepair ||= @@ -403,16 +424,18 @@ export class OrderedSourceLoader { const shouldLoad = windowOperationGeneration !== undefined || this.needsOptimisticRefill || + this.prefixReread !== undefined || (this.info.dataNeeded?.(this.settledSourceBoundary) ?? 0) > 0 || (this.lastPrefixCount !== undefined && this.lastPrefixCount < this.info.offset + this.info.limit) if (shouldLoad) { this.needsOptimisticRefill = false this.loadPrefix( - this.info.offset + this.info.limit, + this.info.offset + this.info.limit + (this.prefixReread ?? 0), windowOperationGeneration, continuesOrderedPrefixRepair, ) + this.prefixReread = undefined } else if (continuesOrderedPrefixRepair) { this.finishOrderedPrefixRepair(windowOperationGeneration) } @@ -435,9 +458,10 @@ export class OrderedSourceLoader { // A recorded failure always carries repair debt, so it cannot reach this // finite path; only the first request needs the whole prefix here. let count = Math.max( - this.info.dataNeeded(this.settledSourceBoundary), + this.info.dataNeeded(this.settledSourceBoundary) + + (this.prefixReread ?? 0), this.hasSettledSourceRequest ? 0 : this.info.offset + this.info.limit, - this.needsOptimisticRefill ? 1 : 0, + this.needsOptimisticRefill || this.prefixReread !== undefined ? 1 : 0, ) if ( windowOperationGeneration !== undefined && @@ -448,6 +472,10 @@ export class OrderedSourceLoader { } if (count > 0) { this.needsOptimisticRefill = false + // The reread starts at the source's first row. + if (this.prefixReread !== undefined) + this.settledSourceBoundary = undefined + this.prefixReread = undefined this.loadPage( count, windowOperationGeneration, @@ -844,11 +872,13 @@ export class OrderedSourceLoader { this.settledFiniteAcquisitions.clear() } - private countAcquiredRows(): number { + private countAcquiredRows( + limit = this.info.offset + this.info.limit, + ): number { return this.subscription .readOrderedSnapshot({ orderBy: normalizeOrderByPaths(this.info.orderBy, this.alias), - limit: this.info.offset + this.info.limit, + limit: Number.isFinite(limit) ? limit : undefined, }) .filter( ({ value }) => diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts index 6d58da9574..133406d550 100644 --- a/packages/db/src/types.ts +++ b/packages/db/src/types.ts @@ -376,6 +376,33 @@ export type LoadSubsetOptions = { * @optional Available when called from CollectionSubscription, may be undefined for direct calls */ subscription?: Subscription + /** + * Semi/anti-join filters on the returned rows (see LoadSubsetRelation). + * All must pass. Optional to apply: ignoring them returns a superset. + */ + relations?: Array +} + +/** + * A semi/anti-join filter on the rows a load returns: keep a row only if + * `some` (or `none`) of the rows of `collectionId` related to it + * (`row[on.parent] = related[on.child]`, paths relative to each row) match + * `where`. `every(p)` is `none(not p)`. + * + * A hint: live-query evaluation stays authoritative. A sync layer may apply it + * (return only the rows that pass) or ignore it (return a superset); it must + * never drop a row that passes. A relation-filtered request is exact for + * `limit`/`cursor` only when applied, so a sync layer that ignores it pages + * more. A sync layer that applies it keeps its answer current as related rows + * change: it delivers a row that comes to pass, as for rows entering `where`. + */ +export type LoadSubsetRelation = { + quantifier: `some` | `none` + /** The related collection's id. */ + collectionId: string + on: { parent: Array; child: Array } + /** Filter on the related rows, paths relative to the related row. */ + where?: BasicExpression } /** @internal Result returned by the collection's normalized subset boundary. */ @@ -1258,6 +1285,11 @@ export interface SubscribeChangesOptions< where?: (row: SingleRowRefProxy, TKey, true>) => any /** Pre-compiled expression for filtering changes */ whereExpression?: BasicExpression + /** + * Semi/anti-join filters for a loadSubset request, read per request. + * @internal + */ + relations?: () => Array | undefined /** * Whether this subscription defers provider work. It keeps the Collection * alive and reads its local rows, but starts no idle source sync run and no diff --git a/packages/db/tests/property-registry/db-query-ordered.ts b/packages/db/tests/property-registry/db-query-ordered.ts index 219c4374a1..e0e775ef48 100644 --- a/packages/db/tests/property-registry/db-query-ordered.ts +++ b/packages/db/tests/property-registry/db-query-ordered.ts @@ -122,6 +122,11 @@ const otherProperties: ReadonlyArray = [ `pooled-live-query.publication-fixed`, `pooled-live-query.release-timing`, `ordered-source-loader.staged-window`, + `load-subset-relations.window`, + `load-subset-relations.subquery-root`, + `load-subset-relations.demand-key`, + `load-subset-relations.shared-window`, + `load-subset-relations.joined-change`, `mixed-index-order.public-order`, `mixed-index-order.on-demand-window`, `derived-publication.queued-batches`, @@ -190,6 +195,11 @@ const otherOwners: ReadonlyArray = [ `ordered-source-loader`, `staged-window`, ], + [ + `db/tests/query/load-subset-relations-oracle.test.ts`, + `load-subset-relations`, + `window demand-key shared-window subquery-root joined-change`, + ], [ `db/tests/query/mixed-index-order-oracle.test.ts`, `mixed-index-order`, diff --git a/packages/db/tests/query/load-subset-relations-oracle.test.ts b/packages/db/tests/query/load-subset-relations-oracle.test.ts new file mode 100644 index 0000000000..e1d8dcf610 --- /dev/null +++ b/packages/db/tests/query/load-subset-relations-oracle.test.ts @@ -0,0 +1,803 @@ +/** + * # A joined-filter window forwards its filter as a relation hint + * + * ## Contract + * + * Issue #2124: `LoadSubsetOptions.relations` is an optional hint. An adapter + * may apply it and return only the root rows that pass, or ignore it and + * return a superset, and it must never drop a root row that passes. Local + * evaluation stays authoritative, so both choices publish the same window. A + * relation-filtered load never shares a demand key with the same load without + * the hint. + * + * A hint is sent only when it carries the whole joined filter. An existence + * check maps to `some` or `none`. A conjunct that fails on a missing joined + * row maps to `some(where)`. One that passes on a missing row maps to + * `none(not where)`, and only when the join is on the joined collection's key, + * because with several related rows `none(not p)` is not the same filter. + * + * An applying adapter keeps its answer current as related rows change. A local + * write on a joined row is not the provider's, so no load carries the hint + * while one is pending, and the window reads its prefix again without it. + * + * ## Limits + * + * The cells cross nine filter kinds with an adapter that applies or ignores the + * hint, over one window on direct LEFT joins to a collection. One changed + * owner moves a root row into or out of a window, by a local write before or + * after the load or a synced change. Joins through + * subqueries, `or` under a relation and unlimited queries are not hinted. + * + * ## Model + * + * `passes` evaluates each filter kind over plain fixture rows. `expectedHint` + * states the relation each kind must send. The adapter applies a hint with its + * own semi-join over the fixture. + * + * ## Production path and observation + * + * The driver runs a live query and observes its public rows, the options that + * reach the root collection's `loadSubset`, and how many root rows it wrote. + */ +import { describe, expect } from 'vitest' +import { D2 } from '@tanstack/db-ivm' +import { createCollection } from '../../src/collection/index.js' +import { BTreeIndex } from '../../src/indexes/btree-index.js' +import { + Query, + and, + compileQuery, + createLiveQueryCollection, + eq, + gte, + isUndefined, + not, + or, +} from '../../src/query/index.js' +import { compileSingleRowExpression } from '../../src/query/compiler/evaluators.js' +import { getQueryIR } from '../../src/query/builder/index.js' +import { Func, PropRef, Value } from '../../src/query/ir.js' +import { getLoadSubsetDemandKey } from '../../src/query/ir-stable-identity.js' +import { oracleProperty } from '../oracle-config.js' +import { + forwardAssertionJudgment, + recordAssertionJudgment, + recordedAssertionJudgment, +} from '../oracle-assertion-adapter.js' +import type { Collection } from '../../src/collection/index.js' +import type { InitialQueryBuilder } from '../../src/query/builder/index.js' +import type { OrderByOptimizationInfo } from '../../src/query/compiler/order-by.js' +import type { BasicExpression, QueryIR } from '../../src/query/ir.js' +import type { LoadSubsetOptions, SyncConfig } from '../../src/types.js' + +type Seek = { id: number; rank: number; ownerId: number } +type Owner = { id: number; ref: number; active: boolean; note?: string } +type Relation = { + quantifier: `some` | `none` + collectionId: string + on: { parent: Array; child: Array } + where?: BasicExpression +} +type OptionsWithRelations = LoadSubsetOptions & { relations?: Array } + +const seeks: Array = Array.from({ length: 36 }, (_, id) => ({ + id, + rank: 100 - id, + ownerId: id, +})) +const owners: Array = seeks + .filter(({ id }) => id % 3 !== 2) + .map(({ id }) => ({ + id, + ref: id, + active: id % 2 === 0, + ...(id % 4 === 0 ? { note: `kept` } : {}), + })) + +const kinds = [ + `exists`, + `missing`, + `match`, + `passes-missing`, + `passes-missing-off-key`, + `mixed`, + `partial`, + `with-root-filter`, + `field-undefined`, +] as const +const relationCases = kinds.flatMap((kind) => + [true, false].map((applied) => ({ kind, applied })), +) +type RelationCase = (typeof relationCases)[number] + +function passes(kind: RelationCase[`kind`], seek: Seek): boolean { + const owner = owners.find(({ id }) => id === seek.ownerId) + switch (kind) { + case `exists`: + return owner !== undefined + case `missing`: + return owner === undefined + case `match`: + return owner?.active === true + case `passes-missing`: + case `passes-missing-off-key`: + return owner === undefined || owner.active + case `mixed`: + return seek.id === 0 || owner?.active === true + case `partial`: + case `with-root-filter`: + return owner?.active === true + case `field-undefined`: + return owner === undefined || owner.note === undefined + } +} + +function expectedHint(kind: RelationCase[`kind`]) { + const on = { parent: [`ownerId`], child: [`id`] } + switch (kind) { + case `exists`: + return { quantifier: `some`, on, filtered: false } + case `missing`: + return { quantifier: `none`, on, filtered: false } + case `match`: + case `with-root-filter`: + return { quantifier: `some`, on, filtered: true } + case `passes-missing`: + case `field-undefined`: + return { quantifier: `none`, on, filtered: true } + default: + return undefined + } +} + +// The adapter's own semi-join: keeps a root row when the hint's related rows +// satisfy its quantifier. +function satisfies( + seek: Seek, + relation: Relation, + ownerRows: ReadonlyArray = owners, +): boolean { + const where = relation.where + ? compileSingleRowExpression(relation.where) + : undefined + const related = ownerRows.filter( + (owner) => + owner[relation.on.child[0] as keyof Owner] === + seek[relation.on.parent[0] as keyof Seek] && + (!where || where(owner) === true), + ) + return relation.quantifier === `some` + ? related.length > 0 + : related.length === 0 +} + +async function runRelationCell(cell: RelationCase): Promise { + const name = `load-subset-relations-${cell.kind}-${cell.applied}` + const loads: Array = [] + const delivered = new Set() + const root = createCollection({ + id: `${name}-root`, + getKey: (row) => row.id, + syncMode: `on-demand`, + startSync: true, + autoIndex: `eager`, + defaultIndexType: BTreeIndex, + sync: { + sync: ({ begin, write, commit, markReady }) => { + markReady() + return { + loadSubset: (options: OptionsWithRelations) => { + loads.push(options) + const where = options.where + ? compileSingleRowExpression(options.where) + : undefined + const from = options.cursor + ? compileSingleRowExpression(options.cursor.whereFrom) + : undefined + const hints = cell.applied ? (options.relations ?? []) : [] + const offset = from ? 0 : (options.offset ?? 0) + const answer = [...seeks] + .sort((a, b) => b.rank - a.rank) + .filter( + (row) => + (!where || where(row) === true) && + (!from || from(row) === true) && + hints.every((hint) => satisfies(row, hint)), + ) + .slice( + offset, + options.limit === undefined + ? undefined + : offset + options.limit, + ) + begin() + for (const row of answer) { + if (delivered.has(row.id)) continue + delivered.add(row.id) + write({ type: `insert`, value: { ...row } }) + } + const receipt = commit() + return receipt === true ? Promise.resolve() : receipt + }, + } + }, + }, + }) + const joined = createCollection({ + id: `${name}-owners`, + getKey: (row) => row.id, + syncMode: `on-demand`, + startSync: true, + autoIndex: `eager`, + defaultIndexType: BTreeIndex, + sync: { + sync: ({ begin, write, commit, markReady }) => { + const written = new Set() + markReady() + return { + loadSubset: (options: LoadSubsetOptions) => { + const where = options.where + ? compileSingleRowExpression(options.where) + : undefined + begin() + for (const row of owners) { + if ((where && where(row) !== true) || written.has(row.id)) + continue + written.add(row.id) + write({ type: `insert`, value: { ...row } }) + } + const receipt = commit() + return receipt === true ? Promise.resolve() : receipt + }, + } + }, + }, + }) + const live = createLiveQueryCollection({ + query: ((query: InitialQueryBuilder) => + query + .from({ seek: root }) + .leftJoin({ owner: joined }, ({ seek, owner }) => + cell.kind === `passes-missing-off-key` + ? eq(seek.ownerId, owner.ref) + : eq(seek.ownerId, owner.id), + ) + .where(({ seek, owner }) => { + switch (cell.kind) { + case `exists`: + return not(isUndefined(owner.id)) + case `missing`: + return isUndefined(owner.id) + case `match`: + return eq(owner.active, true) + case `mixed`: + return or(eq(seek.id, 0), eq(owner.active, true)) + case `partial`: + return and( + eq(owner.active, true), + or(eq(seek.id, 0), eq(owner.active, true)), + ) + case `with-root-filter`: + return and(eq(owner.active, true), gte(seek.rank, 0)) + case `field-undefined`: + return isUndefined(owner.note) + default: + return or(isUndefined(owner.active), eq(owner.active, true)) + } + }) + .orderBy(({ seek }) => seek.rank, `desc`) + .limit(4) + .select(({ seek }) => ({ id: seek.id }))) as never, + }) as unknown as Collection<{ id: number }> + try { + await live.preload() + await new Promise((resolve) => setTimeout(resolve, 5)) + expect( + Array.from(live.values(), ({ id }) => id), + `published window`, + ).toEqual( + seeks + .filter((seek) => passes(cell.kind, seek)) + .slice(0, 4) + .map(({ id }) => id), + ) + + const expected = expectedHint(cell.kind) + for (const load of loads) { + if (!expected) { + expect(load.relations, `no hint`).toBeUndefined() + continue + } + expect(load.relations, `one relation on every load`).toHaveLength(1) + const relation = load.relations![0]! + expect(relation.quantifier, `quantifier`).toBe(expected.quantifier) + expect(relation.collectionId, `related collection`).toBe(joined.id) + expect(relation.on, `join key`).toEqual(expected.on) + expect(relation.where !== undefined, `related filter`).toBe( + expected.filtered, + ) + const { relations: _relations, ...withoutHint } = load + expect( + getLoadSubsetDemandKey(load), + `the hint is part of the demand key`, + ).not.toEqual(getLoadSubsetDemandKey(withoutHint)) + } + if (expected && cell.applied) { + const passing = seeks.filter((seek) => passes(cell.kind, seek)) + expect( + [...delivered].every((id) => passing.some((seek) => seek.id === id)), + `an applied hint delivers only passing rows`, + ).toBe(true) + } + } finally { + await live.cleanup() + await root.cleanup() + await joined.cleanup() + } +} + +// A joined row changes after, or before, the window loads: a local write the +// provider has not seen, or a synced change that an applying adapter keeps its +// answer current with. The change moves a root row into or out of the window. +// A `tied` root ranks every row alike and has four sparse passing owners, so +// the window ends on a tie. A `held` root is unindexed, and its second load is +// still pending when the local write lands. +type JoinedChangeShape = `ranked` | `tied` | `held` +type JoinedWrite = `local write` | `local write before load` | `synced change` +const joinedChangeCases = ([`ranked`, `tied`, `held`] as const).flatMap( + (shape) => + (shape === `ranked` + ? ([`local write`, `local write before load`, `synced change`] as const) + : ([`local write`] as const) + ).flatMap((write: JoinedWrite) => + ([`enters`, `leaves`] as const).flatMap((move) => + [true, false].map((applied) => ({ + write, + move, + applied, + shape: shape as JoinedChangeShape, + })), + ), + ), +) +type JoinedChangeCase = (typeof joinedChangeCases)[number] +const tiedSeeks: Array = seeks.map((seek) => ({ ...seek, rank: 1 })) +const tiedOwners: Array = seeks.map(({ id }) => ({ + id, + ref: id, + active: id > 0 && id % 8 === 0, +})) + +async function runJoinedChangeCell(cell: JoinedChangeCase): Promise { + const name = `load-subset-relations-change-${cell.shape}-${cell.write}-${cell.move}-${cell.applied}` + const tied = cell.shape === `tied` + const rootRows = tied ? tiedSeeks : seeks + const ownerRows = tied ? tiedOwners : owners + // The change moves an inactive owner's seek into the window or an active + // owner's seek out of it. + const changed = + cell.move === `enters` + ? { id: tied ? 7 : 1, active: true } + : { id: tied ? 8 : 0, active: false } + const after = ownerRows.map((owner) => + owner.id === changed.id ? { ...owner, active: changed.active } : owner, + ) + let provided: ReadonlyArray = ownerRows + let pendingWrite = false + const hintedDuringWrite: Array = [] + const served: Array = [] + const delivered = new Set() + let releaseHeld: (() => void) | undefined + let rootSync!: Parameters[`sync`]>[0] + let ownerSync!: Parameters[`sync`]>[0] + const serve = (options: OptionsWithRelations) => { + const where = options.where + ? compileSingleRowExpression(options.where) + : undefined + const from = options.cursor + ? compileSingleRowExpression(options.cursor.whereFrom) + : undefined + const hints = cell.applied ? (options.relations ?? []) : [] + const offset = from ? 0 : (options.offset ?? 0) + const answer = [...rootRows] + .sort((a, b) => b.rank - a.rank) + .filter( + (row) => + (!where || where(row) === true) && + (!from || from(row) === true) && + hints.every((hint) => satisfies(row, hint, provided)), + ) + .slice( + offset, + options.limit === undefined ? undefined : offset + options.limit, + ) + for (const row of answer) { + if (delivered.has(row.id)) continue + delivered.add(row.id) + rootSync.write({ type: `insert`, value: { ...row } }) + } + } + const root = createCollection({ + id: `${name}-root`, + getKey: (row) => row.id, + syncMode: `on-demand`, + startSync: true, + autoIndex: cell.shape === `held` ? `off` : `eager`, + defaultIndexType: BTreeIndex, + sync: { + sync: (params) => { + rootSync = params + params.markReady() + return { + loadSubset: (options: OptionsWithRelations) => { + if (pendingWrite && options.relations) { + hintedDuringWrite.push(options) + } + served.push(options) + if (cell.shape === `held` && served.length === 2) { + return new Promise((resolve) => { + releaseHeld = () => { + params.begin() + serve(options) + params.commit() + resolve() + } + }) + } + params.begin() + serve(options) + const receipt = params.commit() + return receipt === true ? Promise.resolve() : receipt + }, + } + }, + }, + }) + const joined = createCollection({ + id: `${name}-owners`, + getKey: (row) => row.id, + startSync: true, + // The write stays pending, so the provider never sees it. + onUpdate: () => new Promise(() => {}), + sync: { + sync: (params) => { + ownerSync = params + params.begin() + for (const owner of ownerRows) { + params.write({ type: `insert`, value: { ...owner } }) + } + params.commit() + params.markReady() + }, + }, + }) + const change = () => { + if (cell.write === `synced change`) { + provided = after + ownerSync.begin() + ownerSync.write({ + type: `update`, + value: { ...after.find(({ id }) => id === changed.id)! }, + }) + ownerSync.commit() + // An applying adapter keeps its answer current with the related rows. + rootSync.begin() + for (const options of served) serve(options) + rootSync.commit() + } else { + pendingWrite = true + joined.update(changed.id, (draft) => { + draft.active = changed.active + }) + } + } + const live = createLiveQueryCollection({ + query: ((query: InitialQueryBuilder) => { + const ranked = query + .from({ seek: root }) + .leftJoin({ owner: joined }, ({ seek, owner }) => + eq(seek.ownerId, owner.id), + ) + .where(({ owner }) => eq(owner.active, true)) + .orderBy(({ seek }) => seek.rank, `desc`) + return (tied ? ranked.orderBy(({ seek }) => seek.id) : ranked) + .limit(4) + .select(({ seek }) => ({ id: seek.id })) + }) as never, + }) as unknown as Collection<{ id: number }> + try { + if (cell.write === `local write before load`) change() + const loading = live.preload() + if (cell.shape !== `held`) await loading + await new Promise((resolve) => setTimeout(resolve, 5)) + if (cell.write !== `local write before load`) change() + releaseHeld?.() + await loading + await new Promise((resolve) => setTimeout(resolve, 10)) + expect( + Array.from(live.values(), ({ id }) => id), + `published window`, + ).toEqual( + rootRows + .filter((seek) => + after.some((owner) => owner.id === seek.ownerId && owner.active), + ) + .slice(0, 4) + .map(({ id }) => id), + ) + expect( + hintedDuringWrite, + `no hint while a joined row has a local write`, + ).toEqual([]) + } finally { + await live.cleanup() + await root.cleanup() + await joined.cleanup() + } +} + +// A hint narrows a demand, so two demands that differ only in a hint, or in a +// hint's related filter, are different demands. +const relationOn = { parent: [`ownerId`], child: [`id`] } +const relatedWhere = (active: boolean) => + new Func(`eq`, [new PropRef([`active`]), new Value(active)]) +const identityCases = [ + { name: `a hint on an otherwise unconstrained load`, pair: `hint` }, + { name: `two hints that differ only in their related filter`, pair: `where` }, +] as const + +function demandPair( + pair: (typeof identityCases)[number][`pair`], +): [OptionsWithRelations, OptionsWithRelations] { + const relation = (where?: BasicExpression) => ({ + relations: [ + { + quantifier: `some` as const, + collectionId: `owners`, + on: relationOn, + ...(where ? { where } : {}), + }, + ], + }) + return pair === `hint` + ? [relation(), {}] + : [relation(relatedWhere(true)), relation(relatedWhere(false))] +} + +// One subscription serves every window compiled over a source, so a hint may +// narrow it only when every window asks for the same joined filter. +const sharedWindowCases = [ + { name: `the same joined filter`, same: true }, + { name: `different joined filters`, same: false }, +] + +function runSharedWindowCell({ same }: (typeof sharedWindowCases)[number]) { + const inert = { sync: { sync: () => {} } } + const root = createCollection({ + id: `load-subset-relations-shared-${same}-root`, + getKey: (row) => row.id, + syncMode: `on-demand`, + sync: { sync: () => ({ loadSubset: () => true }) }, + }) + const joined = createCollection({ + id: `load-subset-relations-shared-${same}-owners`, + getKey: (row) => row.id, + ...inert, + }) + const first = getQueryIR( + new Query() + .from({ seek: root }) + .leftJoin({ owner: joined }, ({ seek, owner }) => + eq(seek.ownerId, owner.id), + ) + .where(({ owner }) => eq(owner.active, true)) + .orderBy(({ seek }) => seek.rank) + .limit(2) + .select(({ seek }) => ({ id: seek.id })), + ) + const second: QueryIR = same + ? { ...first } + : { + ...first, + where: [ + new Func(`eq`, [new PropRef([`owner`, `active`]), new Value(false)]), + ], + } + const graph = new D2() + const inputs = { seek: graph.newInput(), owner: graph.newInput() } + const plans: Record = {} + for (const query of [first, second]) { + compileQuery( + query, + inputs as never, + { [root.id]: root, [joined.id]: joined } as never, + {}, + {}, + new Set(), + plans, + () => {}, + new WeakMap(), + ) + } + const plan = Object.values(plans)[0]! + expect(plan.relations !== undefined, `shared window hint`).toBe(same) +} + +// A root that is itself a subquery can rename the join key, so its fields are +// not the source's. It sends no hint, and its window is still right. +async function runSubqueryRootCell(): Promise { + const loads: Array = [] + const answer = (data: ReadonlyArray) => ({ + sync: { + sync: ({ begin, write, commit, markReady }: any) => { + begin() + for (const row of data) write({ type: `insert`, value: { ...row } }) + commit() + markReady() + return { + loadSubset: (options: OptionsWithRelations) => { + loads.push(options) + return true as const + }, + } + }, + }, + }) + const root = createCollection({ + id: `load-subset-relations-subquery-root`, + getKey: (row) => row.id, + syncMode: `on-demand`, + startSync: true, + ...answer(seeks), + }) + const joined = createCollection({ + id: `load-subset-relations-subquery-owners`, + getKey: (row) => row.id, + syncMode: `on-demand`, + startSync: true, + ...answer(owners), + }) + const renamed = new Query().from({ seek: root }).select(({ seek }) => ({ + id: seek.id, + rank: seek.rank, + renamedOwner: seek.ownerId, + })) + const live = createLiveQueryCollection({ + query: ((query: InitialQueryBuilder) => + query + .from({ seek: renamed }) + .leftJoin({ owner: joined }, ({ seek, owner }: any) => + eq(seek.renamedOwner, owner.id), + ) + .where(({ owner }: any) => eq(owner.active, true)) + .orderBy(({ seek }: any) => seek.rank, `desc`) + .limit(4) + .select(({ seek }: any) => ({ id: seek.id }))) as never, + }) as unknown as Collection<{ id: number }> + try { + await live.preload() + await new Promise((resolve) => setTimeout(resolve, 5)) + expect( + Array.from(live.values(), ({ id }) => id), + `published window`, + ).toEqual( + seeks + .filter((seek) => passes(`match`, seek)) + .slice(0, 4) + .map(({ id }) => id), + ) + expect( + loads.filter((load) => load.relations !== undefined), + `a subquery root sends no hint`, + ).toEqual([]) + } finally { + await live.cleanup() + await root.cleanup() + await joined.cleanup() + } +} + +describe(`loadSubset relation hints`, () => { + oracleProperty({ + id: `load-subset-relations.subquery-root`, + law: { + statement: `A window whose root is a subquery sends no relation hint and publishes the window local evaluation gives.`, + authority: `Issue #2124: an adapter must never drop a root row that passes.`, + limits: `One root subquery that renames the join key.`, + }, + owns: ['src/query/compiler/order-by.ts#processOrderBy'], + histories: [{ root: `renamed` }], + label: ({ root }) => `${root} subquery root`, + resolve: (cell) => ({ cell }), + model: recordedAssertionJudgment, + driver: (plan, observe) => + recordAssertionJudgment(`subquery root hint`, plan, observe, () => + runSubqueryRootCell(), + ), + check: forwardAssertionJudgment, + }) + + oracleProperty({ + id: `load-subset-relations.demand-key`, + law: { + statement: `A load with a relation hint never shares a demand key with a load whose hint is absent or has a different related filter.`, + authority: `Issue #2124.`, + limits: `Two pairs of demands at getLoadSubsetDemandKey.`, + }, + owns: ['src/query/ir-stable-identity.ts#getLoadSubsetDemandKey'], + histories: identityCases, + label: ({ name }) => name, + resolve: (cell) => ({ cell }), + model: recordedAssertionJudgment, + driver: (plan, observe) => + recordAssertionJudgment(`relation demand key`, plan, observe, () => { + const [left, right] = demandPair(plan.cell.pair) + expect(getLoadSubsetDemandKey(left)).not.toEqual( + getLoadSubsetDemandKey(right), + ) + }), + check: forwardAssertionJudgment, + }) + + oracleProperty({ + id: `load-subset-relations.shared-window`, + law: { + statement: `Windows compiled over one source send a relation hint only when they ask for the same joined filter.`, + authority: `Issue #2124: an adapter must never drop a root row that passes.`, + limits: `Two roots compiled over one source at the compiler boundary.`, + }, + owns: ['src/query/compiler/order-by.ts#processOrderBy'], + histories: sharedWindowCases, + label: ({ name }) => `compiled over ${name}`, + resolve: (cell) => ({ cell }), + model: recordedAssertionJudgment, + driver: (plan, observe) => + recordAssertionJudgment(`shared window hint`, plan, observe, () => + runSharedWindowCell(plan.cell), + ), + check: forwardAssertionJudgment, + }) + + oracleProperty({ + id: `load-subset-relations.joined-change`, + law: { + statement: `After a joined row changes, a joined-filter window publishes the window local evaluation gives, and no load sent while a joined row has a local write carries a relation hint.`, + authority: `Issue #2124: an adapter must never drop a root row that passes; query/live/ARCHITECTURE.md: Ordered requests, continuation, and recovery.`, + limits: `One changed owner that moves a root row into or out of one window, by a local write before or after the load or a synced change, with an applying or ignoring adapter. A local write also lands on a window that ends on a tie, and on an unindexed root while its second load is pending.`, + }, + owns: [ + 'src/query/live/collection-subscriber.ts#subscribeToOrderedChanges', + 'src/query/live/ordered-source-loader.ts#loadMore', + ], + histories: joinedChangeCases, + label: ({ shape, write, move, applied }) => + `a ${write} that a root row ${move} on a ${shape} root with the hint ${applied ? `applied` : `ignored`}`, + resolve: (cell) => ({ cell }), + model: recordedAssertionJudgment, + driver: (plan, observe) => + recordAssertionJudgment(`joined change window`, plan, observe, () => + runJoinedChangeCell(plan.cell), + ), + check: forwardAssertionJudgment, + }) + + oracleProperty({ + id: `load-subset-relations.window`, + law: { + statement: `A joined-filter window sends a relation hint only when it carries the whole joined filter, and publishes the same window whether the adapter applies or ignores it.`, + authority: `Issue #2124; query/live/ARCHITECTURE.md: Ordered requests, continuation, and recovery.`, + limits: `Nine filter kinds by an applying or ignoring adapter over one window on direct LEFT joins to a collection.`, + }, + owns: ['src/query/compiler/order-by.ts#processOrderBy'], + histories: relationCases, + label: ({ kind, applied }) => + `${kind} with the hint ${applied ? `applied` : `ignored`}`, + resolve: (cell) => ({ cell }), + model: recordedAssertionJudgment, + driver: (plan, observe) => + recordAssertionJudgment(`relation hint window`, plan, observe, () => + runRelationCell(plan.cell), + ), + check: forwardAssertionJudgment, + }) +}) diff --git a/packages/db/tests/query/ordered-work-oracle.property.test.ts b/packages/db/tests/query/ordered-work-oracle.property.test.ts index ed143f2192..11807aa3f5 100644 --- a/packages/db/tests/query/ordered-work-oracle.property.test.ts +++ b/packages/db/tests/query/ordered-work-oracle.property.test.ts @@ -3800,6 +3800,8 @@ async function checkOptimisticWindow( offset: options.offset, limit: options.limit, refetch: options.refetch, + // A relation hint is part of the demand. + relations: options.relations, }), newRows: 0, phase: settlementPhase, diff --git a/packages/db/tests/query/ordered-work-support.ts b/packages/db/tests/query/ordered-work-support.ts index 017f0ad6b6..e2165a5745 100644 --- a/packages/db/tests/query/ordered-work-support.ts +++ b/packages/db/tests/query/ordered-work-support.ts @@ -55,7 +55,14 @@ export function rowsForScenario(scenario: Scenario): Array { // them into an empty object. Signals/subscriptions are ownership, while // refetch controls the attempt; none of the three changes demand identity. export function requestFingerprint(options: LoadSubsetOptions): string { - const semantic = new Set([`where`, `orderBy`, `limit`, `offset`, `cursor`]) + const semantic = new Set([ + `where`, + `orderBy`, + `limit`, + `offset`, + `cursor`, + `relations`, + ]) for (const key of Reflect.ownKeys(options)) { if ( !semantic.has(String(key)) &&