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

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