@party-stack/tanstack-db-patches 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,631 @@
1
+ diff --git a/dist/cjs/query/compiler/order-by.cjs b/dist/cjs/query/compiler/order-by.cjs
2
+ index ae4a4162b4b2d998e07d41c4b0937507ccfce021..6d5c831df680bca915dd72190a5133a5fbe397a3 100644
3
+ --- a/dist/cjs/query/compiler/order-by.cjs
4
+ +++ b/dist/cjs/query/compiler/order-by.cjs
5
+ @@ -144,6 +144,7 @@ function processOrderBy(rawQuery, pipeline, orderByClause, selectClause, groupin
6
+ index,
7
+ orderBy: sourceOrderBy,
8
+ joinedFilterSourceIds: joinedFilterSourceId ? [joinedFilterSourceId] : void 0,
9
+ + exactOrderedWindow: false,
10
+ sourceHoldsAllRows: followRefResult.collection.config.syncMode !== `on-demand`,
11
+ requiresFullSource: sourceOrderBy.some(
12
+ ({ compareOptions }) => compareOptions.stringSort === `custom`
13
+ @@ -153,6 +154,51 @@ function processOrderBy(rawQuery, pipeline, orderByClause, selectClause, groupin
14
+ // root match may sit past the prefix.
15
+ (rawQuery.join?.some(({ type }) => type !== `left`) ?? false) || (rawQuery.where?.some(ir.isResidualWhere) ?? false) || hasCrossAliasWhere && joinedFilterSourceId === void 0 || (rawQuery.fnWhere?.length ?? 0) > 0 || rawQuery.groupBy !== void 0 || rawQuery.having !== void 0 || rawQuery.fnHaving !== void 0 || rawQuery.distinct === true
16
+ };
17
+ + // Core admits only a direct plan. The adapter additionally proves its
18
+ + // typed comparison domains, exact pushdown and unique final sort key.
19
+ + if (!info.requiresFullSource && !rawQuery.join?.length && (offset ?? 0) >= 0) {
20
+ + const predicates = (rawQuery.where ?? []).map((where) =>
21
+ + expressions.normalizeExpressionPaths(ir.getWhereExpression(where), orderByAlias),
22
+ + )
23
+ + const where =
24
+ + predicates.length === 0
25
+ + ? undefined
26
+ + : predicates.length === 1
27
+ + ? predicates[0]
28
+ + : new ir.Func(`and`, predicates)
29
+ + info.exactOrderedWindow =
30
+ + followRefResult.collection.config.sync.supportsOrderedWindow?.({
31
+ + where,
32
+ + orderBy: expressions.normalizeOrderByPaths(sourceOrderBy, orderByAlias),
33
+ + limit: (offset ?? 0) + limit,
34
+ + }) === true
35
+ + if (info.exactOrderedWindow) {
36
+ + const terms = sourceOrderBy.map((term) => ({
37
+ + extract: evaluators.compileExpression(
38
+ + new ir.PropRef(
39
+ + ir.followRef(rawQuery, term.expression, collection).path,
40
+ + ),
41
+ + true,
42
+ + ),
43
+ + compare: comparison.makeComparator(term.compareOptions),
44
+ + }))
45
+ + const sourceCollection = followRefResult.collection
46
+ + info.comparator = (a, b) => {
47
+ + for (const term of terms) {
48
+ + const compared = term.compare(
49
+ + a ? term.extract(a) : a,
50
+ + b ? term.extract(b) : b,
51
+ + )
52
+ + if (compared !== 0) return compared
53
+ + }
54
+ + // Rows that tie on every term order by key, as the query's result does,
55
+ + // so an ordering without its primary key is still a total order.
56
+ + return a && b
57
+ + ? dbIvm.compareKeys(sourceCollection.getKeyFromItem(a), sourceCollection.getKeyFromItem(b))
58
+ + : 0
59
+ + }
60
+ + }
61
+ + }
62
+ orderByOptimizationInfo = info;
63
+ const previous = optimizableOrderByCollections[orderBySourceId];
64
+ optimizableOrderByCollections[orderBySourceId] = previous ? {
65
+ @@ -172,19 +218,21 @@ function processOrderBy(rawQuery, pipeline, orderByClause, selectClause, groupin
66
+ info.offset + info.limit
67
+ ) - this.offset;
68
+ },
69
+ + exactOrderedWindow: previous.exactOrderedWindow && info.exactOrderedWindow && utils.deepEquals(previous.orderBy, info.orderBy),
70
+ + comparator: previous.exactOrderedWindow && info.exactOrderedWindow && utils.deepEquals(previous.orderBy, info.orderBy) ? info.comparator : compareSourceRows,
71
+ // Plan shape is fixed at compilation; only window bounds move.
72
+ - requiresFullSource: !utils.deepEquals(previous.orderBy, info.orderBy) || previous.requiresFullSource || info.requiresFullSource,
73
+ + requiresFullSource: previous.exactOrderedWindow !== info.exactOrderedWindow || !utils.deepEquals(previous.orderBy, info.orderBy) || previous.requiresFullSource || info.requiresFullSource,
74
+ dataNeeded: (boundary) => Math.max(
75
+ previous.dataNeeded?.(boundary) ?? 0,
76
+ info.dataNeeded?.(boundary) ?? 0
77
+ )
78
+ } : info;
79
+ const needsCount = joinedFilterSourceId !== void 0 && !info.sourceHoldsAllRows;
80
+ - if (index || needsCount) {
81
+ + if (index || needsCount || info.exactOrderedWindow) {
82
+ setSizeCallback = (getSize) => {
83
+ info.dataNeeded = (boundary) => {
84
+ const size = getSize(
85
+ - boundary && ((row) => compareSourceRows(
86
+ + boundary && ((row) => info.comparator(
87
+ row[orderByAlias],
88
+ boundary
89
+ ) <= 0)
90
+ @@ -235,4 +283,3 @@ function resolveCompareOptions(clause, defaults) {
91
+ }
92
+ exports.buildCompareOptions = buildCompareOptions;
93
+ exports.processOrderBy = processOrderBy;
94
+ -//# sourceMappingURL=order-by.cjs.map
95
+ diff --git a/dist/cjs/query/compiler/order-by.d.cts b/dist/cjs/query/compiler/order-by.d.cts
96
+ index aae21fc720238ddb5d3454e89ffe58c0da0bd8fa..5dea184e1f929438881f9af4e78de6c3332becb4 100644
97
+ --- a/dist/cjs/query/compiler/order-by.d.cts
98
+ +++ b/dist/cjs/query/compiler/order-by.d.cts
99
+ @@ -31,6 +31,8 @@ export type OrderByOptimizationInfo = {
100
+ requiresFullSource: boolean;
101
+ /** Whether the ordered source's installed rows are the whole source. */
102
+ sourceHoldsAllRows: boolean;
103
+ + /** Adapter-proven exact full-order prefixes; no leading-value tie is owed. */
104
+ + exactOrderedWindow?: boolean;
105
+ /** Sources whose lazy demand must settle before a joined-filter page. */
106
+ joinedFilterSourceIds?: ReadonlyArray<string>;
107
+ };
108
+ diff --git a/dist/cjs/query/live/ordered-source-loader.cjs b/dist/cjs/query/live/ordered-source-loader.cjs
109
+ index d6554e41a187de4e1bab84482a85d203b2640e98..5c8560433b58ee45843c6027eba8857d5fad676e 100644
110
+ --- a/dist/cjs/query/live/ordered-source-loader.cjs
111
+ +++ b/dist/cjs/query/live/ordered-source-loader.cjs
112
+ @@ -42,7 +42,7 @@ class OrderedSourceLoader {
113
+ this.cr = 0;
114
+ this.bG = false;
115
+ this.info.isRequesting = () => this.fT;
116
+ - this.gp = info.sourceHoldsAllRows && info.index !== void 0 && info.orderBy.length === 1 && !info.joinedFilterSourceIds?.length;
117
+ + this.gp = info.exactOrderedWindow || info.sourceHoldsAllRows && info.index !== void 0 && info.orderBy.length === 1 && !info.joinedFilterSourceIds?.length;
118
+ }
119
+ get ap() {
120
+ return this.gO !== `none`;
121
+ @@ -121,7 +121,7 @@ class OrderedSourceLoader {
122
+ this.loadFullSource();
123
+ return;
124
+ }
125
+ - if (!index) {
126
+ + if (this.info.exactOrderedWindow || !index) {
127
+ this.e$(offset + limit);
128
+ return;
129
+ }
130
+ @@ -172,15 +172,16 @@ class OrderedSourceLoader {
131
+ }
132
+ return this.pending;
133
+ }
134
+ - if (this.ap && !(continuesOrderedPrefixRepair && this.work.kind === `repair`) || this.info.requiresFullSource) {
135
+ - if (this.gO === `bounded` && !this.info.requiresFullSource) {
136
+ + const requiresFullSource = this.info.requiresFullSource || this.info.exactOrderedWindow && this.info.offset < 0;
137
+ + if (this.ap && !(continuesOrderedPrefixRepair && this.work.kind === `repair`) || requiresFullSource) {
138
+ + if (this.gO === `bounded` && !requiresFullSource) {
139
+ this.dw(windowOperationGeneration);
140
+ } else {
141
+ this.loadFullSource(windowOperationGeneration);
142
+ }
143
+ return this.pending;
144
+ }
145
+ - if (!this.info.index) {
146
+ + if (this.info.exactOrderedWindow || !this.info.index) {
147
+ const shouldLoad = windowOperationGeneration !== void 0 || this.F || (this.info.dataNeeded?.(this.ah) ?? 0) > 0 || this.bQ !== void 0 && this.bQ < this.info.offset + this.info.limit;
148
+ if (shouldLoad) {
149
+ this.F = false;
150
+ @@ -409,7 +410,7 @@ class OrderedSourceLoader {
151
+ revalidateLoadedCoverage() {
152
+ if (!this.aL) return;
153
+ const end = this.he();
154
+ - if (end !== void 0 && ((this.gI ?? 0) > this.info.offset + this.info.limit || Object.is(this.info.valueExtractorForRawRow(end), this.dl)))
155
+ + if (end !== void 0 && (this.info.exactOrderedWindow || (this.gI ?? 0) > this.info.offset + this.info.limit || Object.is(this.info.valueExtractorForRawRow(end), this.dl)))
156
+ return;
157
+ this.invalidateSourceOrdering();
158
+ }
159
+ @@ -580,6 +581,7 @@ class OrderedSourceLoader {
160
+ }
161
+ }
162
+ fJ(windowOperationGeneration, continuesOrderedPrefixRepair = false) {
163
+ + if (this.info.exactOrderedWindow) return this.loadMore(windowOperationGeneration, continuesOrderedPrefixRepair);
164
+ const biggest = this.ah;
165
+ if (biggest === void 0) {
166
+ return continuesOrderedPrefixRepair ? this.loadMore(windowOperationGeneration, true) : void 0;
167
+ @@ -917,4 +919,3 @@ class OrderedSourceLoader {
168
+ }
169
+ exports.OrderedLoaderInvariantError = OrderedLoaderInvariantError;
170
+ exports.OrderedSourceLoader = OrderedSourceLoader;
171
+ -//# sourceMappingURL=ordered-source-loader.cjs.map
172
+ diff --git a/dist/cjs/types.d.cts b/dist/cjs/types.d.cts
173
+ index c015a28632609ef577f63c19bbad124d27f9bb30..a276cb7a6032ef545f9e2f3cf514046ff093b2b7 100644
174
+ --- a/dist/cjs/types.d.cts
175
+ +++ b/dist/cjs/types.d.cts
176
+ @@ -354,6 +354,8 @@ export type SyncConfigRes = {
177
+ restartAfterScopedRecovery?: (cacheRotated: Promise<void>) => void | Promise<void>;
178
+ };
179
+ export interface SyncConfig<T extends object = Record<string, unknown>, TKey extends string | number = string | number> {
180
+ + /** Exact full-order prefix support for every finite window of this fixed normalized query. Not freshness. */
181
+ + supportsOrderedWindow?: (options: LoadSubsetOptions) => boolean;
182
+ sync: (params: {
183
+ collection: Collection<T, TKey, any, any, any>;
184
+ /**
185
+ diff --git a/dist/esm/query/compiler/order-by.d.ts b/dist/esm/query/compiler/order-by.d.ts
186
+ index 7aad9cbbd5a1241da433fdd366bc80a9fb7ddf53..04cfc7a977e9f67065b3043664e4f7b5dde6be3a 100644
187
+ --- a/dist/esm/query/compiler/order-by.d.ts
188
+ +++ b/dist/esm/query/compiler/order-by.d.ts
189
+ @@ -31,6 +31,8 @@ export type OrderByOptimizationInfo = {
190
+ requiresFullSource: boolean;
191
+ /** Whether the ordered source's installed rows are the whole source. */
192
+ sourceHoldsAllRows: boolean;
193
+ + /** Adapter-proven exact full-order prefixes; no leading-value tie is owed. */
194
+ + exactOrderedWindow?: boolean;
195
+ /** Sources whose lazy demand must settle before a joined-filter page. */
196
+ joinedFilterSourceIds?: ReadonlyArray<string>;
197
+ };
198
+ diff --git a/dist/esm/query/compiler/order-by.js b/dist/esm/query/compiler/order-by.js
199
+ index 9a0a188851a196728a27421c15df5f0239b34400..27025711a3ddccdbac5e9c8079c157c16a36f2c5 100644
200
+ --- a/dist/esm/query/compiler/order-by.js
201
+ +++ b/dist/esm/query/compiler/order-by.js
202
+ @@ -1,13 +1,13 @@
203
+ -import { groupedOrderByWithFractionalIndex, orderByWithFractionalIndex } from "@tanstack/db-ivm";
204
+ +import { compareKeys, groupedOrderByWithFractionalIndex, orderByWithFractionalIndex } from "@tanstack/db-ivm";
205
+ import { makeComparator, defaultComparator } from "../../utils/comparison.js";
206
+ -import { followRef, collectCollectionSources, PropRef, getWhereExpression, isResidualWhere } from "../ir.js";
207
+ +import { followRef, collectCollectionSources, Func, PropRef, getWhereExpression, isResidualWhere } from "../ir.js";
208
+ import { ensureIndexForField } from "../../indexes/auto-index.js";
209
+ import { findIndexForField, supportsOrderedRange, supportsOrderedIndexStructure } from "../../utils/index-optimization.js";
210
+ import { hasVirtualPropPath } from "../../virtual-props.js";
211
+ import { deepEquals } from "../../utils.js";
212
+ import { devBuild } from "../../error-message.js";
213
+ import { compileExpression } from "./evaluators.js";
214
+ -import { getSourceAliasesFromExpression } from "./expressions.js";
215
+ +import { getSourceAliasesFromExpression, normalizeExpressionPaths, normalizeOrderByPaths } from "./expressions.js";
216
+ function warnOrderIndexFallback(collection, path, options, index) {
217
+ if (devBuild() && process.env.NODE_ENV !== `production`) {
218
+ const field = path.join(`.`);
219
+ @@ -142,6 +142,7 @@ function processOrderBy(rawQuery, pipeline, orderByClause, selectClause, groupin
220
+ index,
221
+ orderBy: sourceOrderBy,
222
+ joinedFilterSourceIds: joinedFilterSourceId ? [joinedFilterSourceId] : void 0,
223
+ + exactOrderedWindow: false,
224
+ sourceHoldsAllRows: followRefResult.collection.config.syncMode !== `on-demand`,
225
+ requiresFullSource: sourceOrderBy.some(
226
+ ({ compareOptions }) => compareOptions.stringSort === `custom`
227
+ @@ -151,6 +152,51 @@ function processOrderBy(rawQuery, pipeline, orderByClause, selectClause, groupin
228
+ // root match may sit past the prefix.
229
+ (rawQuery.join?.some(({ type }) => type !== `left`) ?? false) || (rawQuery.where?.some(isResidualWhere) ?? false) || hasCrossAliasWhere && joinedFilterSourceId === void 0 || (rawQuery.fnWhere?.length ?? 0) > 0 || rawQuery.groupBy !== void 0 || rawQuery.having !== void 0 || rawQuery.fnHaving !== void 0 || rawQuery.distinct === true
230
+ };
231
+ + // Core admits only a direct plan. The adapter additionally proves its
232
+ + // typed comparison domains, exact pushdown and unique final sort key.
233
+ + if (!info.requiresFullSource && !rawQuery.join?.length && (offset ?? 0) >= 0) {
234
+ + const predicates = (rawQuery.where ?? []).map((where) =>
235
+ + normalizeExpressionPaths(getWhereExpression(where), orderByAlias),
236
+ + )
237
+ + const where =
238
+ + predicates.length === 0
239
+ + ? undefined
240
+ + : predicates.length === 1
241
+ + ? predicates[0]
242
+ + : new Func(`and`, predicates)
243
+ + info.exactOrderedWindow =
244
+ + followRefResult.collection.config.sync.supportsOrderedWindow?.({
245
+ + where,
246
+ + orderBy: normalizeOrderByPaths(sourceOrderBy, orderByAlias),
247
+ + limit: (offset ?? 0) + limit,
248
+ + }) === true
249
+ + if (info.exactOrderedWindow) {
250
+ + const terms = sourceOrderBy.map((term) => ({
251
+ + extract: compileExpression(
252
+ + new PropRef(
253
+ + followRef(rawQuery, term.expression, collection).path,
254
+ + ),
255
+ + true,
256
+ + ),
257
+ + compare: makeComparator(term.compareOptions),
258
+ + }))
259
+ + const sourceCollection = followRefResult.collection
260
+ + info.comparator = (a, b) => {
261
+ + for (const term of terms) {
262
+ + const compared = term.compare(
263
+ + a ? term.extract(a) : a,
264
+ + b ? term.extract(b) : b,
265
+ + )
266
+ + if (compared !== 0) return compared
267
+ + }
268
+ + // Rows that tie on every term order by key, as the query's result does,
269
+ + // so an ordering without its primary key is still a total order.
270
+ + return a && b
271
+ + ? compareKeys(sourceCollection.getKeyFromItem(a), sourceCollection.getKeyFromItem(b))
272
+ + : 0
273
+ + }
274
+ + }
275
+ + }
276
+ orderByOptimizationInfo = info;
277
+ const previous = optimizableOrderByCollections[orderBySourceId];
278
+ optimizableOrderByCollections[orderBySourceId] = previous ? {
279
+ @@ -170,19 +216,21 @@ function processOrderBy(rawQuery, pipeline, orderByClause, selectClause, groupin
280
+ info.offset + info.limit
281
+ ) - this.offset;
282
+ },
283
+ + exactOrderedWindow: previous.exactOrderedWindow && info.exactOrderedWindow && deepEquals(previous.orderBy, info.orderBy),
284
+ + comparator: previous.exactOrderedWindow && info.exactOrderedWindow && deepEquals(previous.orderBy, info.orderBy) ? info.comparator : compareSourceRows,
285
+ // Plan shape is fixed at compilation; only window bounds move.
286
+ - requiresFullSource: !deepEquals(previous.orderBy, info.orderBy) || previous.requiresFullSource || info.requiresFullSource,
287
+ + requiresFullSource: previous.exactOrderedWindow !== info.exactOrderedWindow || !deepEquals(previous.orderBy, info.orderBy) || previous.requiresFullSource || info.requiresFullSource,
288
+ dataNeeded: (boundary) => Math.max(
289
+ previous.dataNeeded?.(boundary) ?? 0,
290
+ info.dataNeeded?.(boundary) ?? 0
291
+ )
292
+ } : info;
293
+ const needsCount = joinedFilterSourceId !== void 0 && !info.sourceHoldsAllRows;
294
+ - if (index || needsCount) {
295
+ + if (index || needsCount || info.exactOrderedWindow) {
296
+ setSizeCallback = (getSize) => {
297
+ info.dataNeeded = (boundary) => {
298
+ const size = getSize(
299
+ - boundary && ((row) => compareSourceRows(
300
+ + boundary && ((row) => info.comparator(
301
+ row[orderByAlias],
302
+ boundary
303
+ ) <= 0)
304
+ @@ -235,4 +283,3 @@ export {
305
+ buildCompareOptions,
306
+ processOrderBy
307
+ };
308
+ -//# sourceMappingURL=order-by.js.map
309
+ diff --git a/dist/esm/query/live/ordered-source-loader.js b/dist/esm/query/live/ordered-source-loader.js
310
+ index b4052aa95734005096fe85550110bb1fce46f7bf..3f9139e7783679faa01c47c716e006e2191960f9 100644
311
+ --- a/dist/esm/query/live/ordered-source-loader.js
312
+ +++ b/dist/esm/query/live/ordered-source-loader.js
313
+ @@ -40,7 +40,7 @@ class OrderedSourceLoader {
314
+ this.cr = 0;
315
+ this.bG = false;
316
+ this.info.isRequesting = () => this.fT;
317
+ - this.gp = info.sourceHoldsAllRows && info.index !== void 0 && info.orderBy.length === 1 && !info.joinedFilterSourceIds?.length;
318
+ + this.gp = info.exactOrderedWindow || info.sourceHoldsAllRows && info.index !== void 0 && info.orderBy.length === 1 && !info.joinedFilterSourceIds?.length;
319
+ }
320
+ get ap() {
321
+ return this.gO !== `none`;
322
+ @@ -119,7 +119,7 @@ class OrderedSourceLoader {
323
+ this.loadFullSource();
324
+ return;
325
+ }
326
+ - if (!index) {
327
+ + if (this.info.exactOrderedWindow || !index) {
328
+ this.e$(offset + limit);
329
+ return;
330
+ }
331
+ @@ -170,15 +170,16 @@ class OrderedSourceLoader {
332
+ }
333
+ return this.pending;
334
+ }
335
+ - if (this.ap && !(continuesOrderedPrefixRepair && this.work.kind === `repair`) || this.info.requiresFullSource) {
336
+ - if (this.gO === `bounded` && !this.info.requiresFullSource) {
337
+ + const requiresFullSource = this.info.requiresFullSource || this.info.exactOrderedWindow && this.info.offset < 0;
338
+ + if (this.ap && !(continuesOrderedPrefixRepair && this.work.kind === `repair`) || requiresFullSource) {
339
+ + if (this.gO === `bounded` && !requiresFullSource) {
340
+ this.dw(windowOperationGeneration);
341
+ } else {
342
+ this.loadFullSource(windowOperationGeneration);
343
+ }
344
+ return this.pending;
345
+ }
346
+ - if (!this.info.index) {
347
+ + if (this.info.exactOrderedWindow || !this.info.index) {
348
+ const shouldLoad = windowOperationGeneration !== void 0 || this.F || (this.info.dataNeeded?.(this.ah) ?? 0) > 0 || this.bQ !== void 0 && this.bQ < this.info.offset + this.info.limit;
349
+ if (shouldLoad) {
350
+ this.F = false;
351
+ @@ -407,7 +408,7 @@ class OrderedSourceLoader {
352
+ revalidateLoadedCoverage() {
353
+ if (!this.aL) return;
354
+ const end = this.he();
355
+ - if (end !== void 0 && ((this.gI ?? 0) > this.info.offset + this.info.limit || Object.is(this.info.valueExtractorForRawRow(end), this.dl)))
356
+ + if (end !== void 0 && (this.info.exactOrderedWindow || (this.gI ?? 0) > this.info.offset + this.info.limit || Object.is(this.info.valueExtractorForRawRow(end), this.dl)))
357
+ return;
358
+ this.invalidateSourceOrdering();
359
+ }
360
+ @@ -578,6 +579,7 @@ class OrderedSourceLoader {
361
+ }
362
+ }
363
+ fJ(windowOperationGeneration, continuesOrderedPrefixRepair = false) {
364
+ + if (this.info.exactOrderedWindow) return this.loadMore(windowOperationGeneration, continuesOrderedPrefixRepair);
365
+ const biggest = this.ah;
366
+ if (biggest === void 0) {
367
+ return continuesOrderedPrefixRepair ? this.loadMore(windowOperationGeneration, true) : void 0;
368
+ @@ -917,4 +919,3 @@ export {
369
+ OrderedLoaderInvariantError,
370
+ OrderedSourceLoader
371
+ };
372
+ -//# sourceMappingURL=ordered-source-loader.js.map
373
+ diff --git a/dist/esm/types.d.ts b/dist/esm/types.d.ts
374
+ index 734ebd81f8aadd42a5872f759c7a42a2b830f620..795be3fc6fb6e36af9414f030b452312c1d500c5 100644
375
+ --- a/dist/esm/types.d.ts
376
+ +++ b/dist/esm/types.d.ts
377
+ @@ -351,6 +351,8 @@ export type SyncConfigRes = {
378
+ restartAfterScopedRecovery?: (cacheRotated: Promise<void>) => void | Promise<void>;
379
+ };
380
+ export interface SyncConfig<T extends object = Record<string, unknown>, TKey extends string | number = string | number> {
381
+ + /** Exact full-order prefix support for every finite window of this fixed normalized query. Not freshness. */
382
+ + supportsOrderedWindow?: (options: LoadSubsetOptions) => boolean;
383
+ sync: (params: {
384
+ collection: Collection<T, TKey, any, any, any>;
385
+ /**
386
+ diff --git a/src/query/compiler/order-by.ts b/src/query/compiler/order-by.ts
387
+ index 01c61fbf48116aa3b0e19cc1eea68290afd39e4c..e152c3f1f72b3d606c43dadc443f3270c06e228d 100644
388
+ --- a/src/query/compiler/order-by.ts
389
+ +++ b/src/query/compiler/order-by.ts
390
+ @@ -1,9 +1,11 @@
391
+ import {
392
+ + compareKeys,
393
+ groupedOrderByWithFractionalIndex,
394
+ orderByWithFractionalIndex,
395
+ } from '@tanstack/db-ivm'
396
+ import { defaultComparator, makeComparator } from '../../utils/comparison.js'
397
+ import {
398
+ + Func,
399
+ PropRef,
400
+ collectCollectionSources,
401
+ followRef,
402
+ @@ -20,7 +22,11 @@ import { hasVirtualPropPath } from '../../virtual-props.js'
403
+ import { deepEquals } from '../../utils.js'
404
+ import { devBuild } from '../../error-message.js'
405
+ import { compileExpression } from './evaluators.js'
406
+ -import { getSourceAliasesFromExpression } from './expressions.js'
407
+ +import {
408
+ + getSourceAliasesFromExpression,
409
+ + normalizeExpressionPaths,
410
+ + normalizeOrderByPaths,
411
+ +} from './expressions.js'
412
+ import type { CompareOptions } from '../builder/types.js'
413
+ import type { WindowOptions } from './types.js'
414
+ import type { Grouping } from './grouping.js'
415
+ @@ -67,6 +73,8 @@ export type OrderByOptimizationInfo = {
416
+ requiresFullSource: boolean
417
+ /** Whether the ordered source's installed rows are the whole source. */
418
+ sourceHoldsAllRows: boolean
419
+ + /** Adapter-proven exact full-order prefixes; no leading-value tie is owed. */
420
+ + exactOrderedWindow?: boolean
421
+ /** Sources whose lazy demand must settle before a joined-filter page. */
422
+ joinedFilterSourceIds?: ReadonlyArray<string>
423
+ }
424
+ @@ -297,6 +305,7 @@ export function processOrderBy(
425
+ joinedFilterSourceIds: joinedFilterSourceId
426
+ ? [joinedFilterSourceId]
427
+ : undefined,
428
+ + exactOrderedWindow: false,
429
+ sourceHoldsAllRows:
430
+ followRefResult.collection.config.syncMode !== `on-demand`,
431
+ requiresFullSource:
432
+ @@ -319,6 +328,51 @@ export function processOrderBy(
433
+ rawQuery.fnHaving !== undefined ||
434
+ rawQuery.distinct === true,
435
+ }
436
+ + // Core admits only a direct plan. The adapter additionally proves its
437
+ + // typed comparison domains, exact pushdown and unique final sort key.
438
+ + if (!info.requiresFullSource && !rawQuery.join?.length && (offset ?? 0) >= 0) {
439
+ + const predicates = (rawQuery.where ?? []).map((where) =>
440
+ + normalizeExpressionPaths(getWhereExpression(where), orderByAlias),
441
+ + )
442
+ + const where =
443
+ + predicates.length === 0
444
+ + ? undefined
445
+ + : predicates.length === 1
446
+ + ? predicates[0]
447
+ + : new Func<boolean>(`and`, predicates)
448
+ + info.exactOrderedWindow =
449
+ + followRefResult.collection.config.sync.supportsOrderedWindow?.({
450
+ + where,
451
+ + orderBy: normalizeOrderByPaths(sourceOrderBy, orderByAlias),
452
+ + limit: (offset ?? 0) + limit,
453
+ + }) === true
454
+ + if (info.exactOrderedWindow) {
455
+ + const terms = sourceOrderBy.map((term) => ({
456
+ + extract: compileExpression(
457
+ + new PropRef(
458
+ + followRef(rawQuery, term.expression as PropRef, collection)!.path,
459
+ + ),
460
+ + true,
461
+ + ) as CompiledSingleRowExpression,
462
+ + compare: makeComparator(term.compareOptions),
463
+ + }))
464
+ + const sourceCollection = followRefResult.collection
465
+ + info.comparator = (a, b) => {
466
+ + for (const term of terms) {
467
+ + const compared = term.compare(
468
+ + a ? term.extract(a) : a,
469
+ + b ? term.extract(b) : b,
470
+ + )
471
+ + if (compared !== 0) return compared
472
+ + }
473
+ + // Rows that tie on every term order by key, as the query's result does,
474
+ + // so an ordering without its primary key is still a total order.
475
+ + return a && b
476
+ + ? compareKeys(sourceCollection.getKeyFromItem(a), sourceCollection.getKeyFromItem(b))
477
+ + : 0
478
+ + }
479
+ + }
480
+ + }
481
+ orderByOptimizationInfo = info
482
+
483
+ // Ordered loading is owned by one lexical source. A collection can occur
484
+ @@ -349,8 +403,19 @@ export function processOrderBy(
485
+ ) - this.offset
486
+ )
487
+ },
488
+ + exactOrderedWindow:
489
+ + previous.exactOrderedWindow &&
490
+ + info.exactOrderedWindow &&
491
+ + deepEquals(previous.orderBy, info.orderBy),
492
+ + comparator:
493
+ + previous.exactOrderedWindow &&
494
+ + info.exactOrderedWindow &&
495
+ + deepEquals(previous.orderBy, info.orderBy)
496
+ + ? info.comparator
497
+ + : compareSourceRows,
498
+ // Plan shape is fixed at compilation; only window bounds move.
499
+ requiresFullSource:
500
+ + previous.exactOrderedWindow !== info.exactOrderedWindow ||
501
+ !deepEquals(previous.orderBy, info.orderBy) ||
502
+ previous.requiresFullSource ||
503
+ info.requiresFullSource,
504
+ @@ -366,7 +431,7 @@ export function processOrderBy(
505
+ // index, only an on-demand joined filter can leave the window short.
506
+ const needsCount =
507
+ joinedFilterSourceId !== undefined && !info.sourceHoldsAllRows
508
+ - if (index || needsCount) {
509
+ + if (index || needsCount || info.exactOrderedWindow) {
510
+ setSizeCallback = (getSize) => {
511
+ info.dataNeeded = (boundary) => {
512
+ // Window rows at or before the boundary are a leading run of
513
+ @@ -374,7 +439,7 @@ export function processOrderBy(
514
+ const size = getSize(
515
+ boundary &&
516
+ ((row) =>
517
+ - compareSourceRows(
518
+ + info.comparator(
519
+ (row as NamespacedRow)[orderByAlias],
520
+ boundary,
521
+ ) <= 0),
522
+ diff --git a/src/query/live/ordered-source-loader.ts b/src/query/live/ordered-source-loader.ts
523
+ index 405f06f05397d8c91fd71e75cf88e5e136a00241..7d9cf86b3d55f7e2a3973da68fcd20f7499c5024 100644
524
+ --- a/src/query/live/ordered-source-loader.ts
525
+ +++ b/src/query/live/ordered-source-loader.ts
526
+ @@ -163,10 +163,11 @@ export class OrderedSourceLoader {
527
+ // A joined filter drops rows after the source's limit, so a full window
528
+ // after a bounded read would not prove it holds the first eligible rows.
529
+ this.readsBoundedPrefix =
530
+ - info.sourceHoldsAllRows &&
531
+ - info.index !== undefined &&
532
+ - info.orderBy.length === 1 &&
533
+ - !info.joinedFilterSourceIds?.length
534
+ + info.exactOrderedWindow ||
535
+ + (info.sourceHoldsAllRows &&
536
+ + info.index !== undefined &&
537
+ + info.orderBy.length === 1 &&
538
+ + !info.joinedFilterSourceIds?.length)
539
+ }
540
+
541
+ private get needsOrderingRepair(): boolean {
542
+ @@ -292,7 +293,7 @@ export class OrderedSourceLoader {
543
+ this.loadFullSource()
544
+ return
545
+ }
546
+ - if (!index) {
547
+ + if (this.info.exactOrderedWindow || !index) {
548
+ this.loadPrefix(offset + limit)
549
+ return
550
+ }
551
+ @@ -381,19 +382,22 @@ export class OrderedSourceLoader {
552
+ }
553
+ return this.pending
554
+ }
555
+ + const requiresFullSource =
556
+ + this.info.requiresFullSource ||
557
+ + (this.info.exactOrderedWindow && this.info.offset < 0)
558
+ if (
559
+ (this.needsOrderingRepair &&
560
+ !(continuesOrderedPrefixRepair && this.work.kind === `repair`)) ||
561
+ - this.info.requiresFullSource
562
+ + requiresFullSource
563
+ ) {
564
+ - if (this.debt === `bounded` && !this.info.requiresFullSource) {
565
+ + if (this.debt === `bounded` && !requiresFullSource) {
566
+ this.loadOrderedPrefixRepair(windowOperationGeneration)
567
+ } else {
568
+ this.loadFullSource(windowOperationGeneration)
569
+ }
570
+ return this.pending
571
+ }
572
+ - if (!this.info.index) {
573
+ + if (this.info.exactOrderedWindow || !this.info.index) {
574
+ const shouldLoad =
575
+ windowOperationGeneration !== undefined ||
576
+ this.needsOptimisticRefill ||
577
+ @@ -713,7 +717,8 @@ export class OrderedSourceLoader {
578
+ // loader has started or will start a full-source read, which covers it.
579
+ if (
580
+ end !== undefined &&
581
+ - ((this.ownPrefixCount ?? 0) > this.info.offset + this.info.limit ||
582
+ + (this.info.exactOrderedWindow ||
583
+ + (this.ownPrefixCount ?? 0) > this.info.offset + this.info.limit ||
584
+ Object.is(this.info.valueExtractorForRawRow(end), this.lastBoundary))
585
+ )
586
+ return
587
+ @@ -959,6 +964,12 @@ export class OrderedSourceLoader {
588
+ windowOperationGeneration?: number,
589
+ continuesOrderedPrefixRepair = false,
590
+ ): Promise<void> | undefined {
591
+ + if (this.info.exactOrderedWindow) {
592
+ + return this.loadMore(
593
+ + windowOperationGeneration,
594
+ + continuesOrderedPrefixRepair,
595
+ + )
596
+ + }
597
+ const biggest = this.settledSourceBoundary
598
+ if (biggest === undefined) {
599
+ return continuesOrderedPrefixRepair
600
+ diff --git a/src/types.ts b/src/types.ts
601
+ index 8d17b2ae8ee9ce8b1f7ae46991578ddbc49f1fac..c62e0d984faa4e8461559aee00aa307bdb997ede 100644
602
+ --- a/src/types.ts
603
+ +++ b/src/types.ts
604
+ @@ -332,8 +332,9 @@ export type CursorExpressions = {
605
+ * the start of the order through its boundary, the leading order value of the
606
+ * last row the request returned, ties included. A request that returned no
607
+ * rows served no prefix. The ordered loader treats every row in a served
608
+ - * prefix as loaded. See `LoadSubsetFn` for what a sync adapter owes after it
609
+ - * refetches.
610
+ + * prefix as loaded. An adapter-declared exact ordered window instead proves
611
+ + * the complete ORDER BY boundary, including its unique final key; core need not
612
+ + * acquire the rest of the leading-value tie. See `LoadSubsetFn` for refetch.
613
+ */
614
+ export type LoadSubsetOptions = {
615
+ /**
616
+ @@ -447,6 +448,15 @@ export interface SyncConfig<
617
+ T extends object = Record<string, unknown>,
618
+ TKey extends string | number = string | number,
619
+ > {
620
+ + /**
621
+ + * Declares exact full-order prefix support for this normalized source query.
622
+ + * Core calls this pure function only for direct, fully pushed ordered plans.
623
+ + * Returning true promises matching comparison domains and a unique non-null
624
+ + * final key: every finite prefix of this fixed WHERE/ORDER is exact, including
625
+ + * after refetch, window changes and optimistic headroom. This is not readiness.
626
+ + * Absent or false preserves conservative leading-value tie acquisition.
627
+ + */
628
+ + supportsOrderedWindow?: (options: LoadSubsetOptions) => boolean
629
+ sync: (params: {
630
+ collection: Collection<T, TKey, any, any, any>
631
+ /**