@rocicorp/zero 1.13.0-canary.2 → 1.13.0-canary.4

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.
Files changed (86) hide show
  1. package/out/z2s/src/compiler.d.ts.map +1 -1
  2. package/out/z2s/src/compiler.js +6 -6
  3. package/out/z2s/src/compiler.js.map +1 -1
  4. package/out/zero/package.js +1 -1
  5. package/out/zero/package.js.map +1 -1
  6. package/out/zero-cache/src/server/replicator.js +3 -3
  7. package/out/zero-cache/src/server/replicator.js.map +1 -1
  8. package/out/zero-cache/src/services/change-source/pg/change-source-init.js +14 -4
  9. package/out/zero-cache/src/services/change-source/pg/change-source-init.js.map +1 -1
  10. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +9 -0
  11. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  12. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +23 -1
  13. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  14. package/out/zero-cache/src/services/replicator/write-worker-client.js +17 -3
  15. package/out/zero-cache/src/services/replicator/write-worker-client.js.map +1 -1
  16. package/out/zero-cache/src/services/replicator/write-worker.js +11 -2
  17. package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
  18. package/out/zero-cache/src/services/view-syncer/view-syncer.js +13 -15
  19. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  20. package/out/zero-client/src/client/custom.js +1 -1
  21. package/out/zero-client/src/client/mutation-tracker.js +1 -1
  22. package/out/zero-client/src/client/version.js +1 -1
  23. package/out/zero-client/src/client/zero.js +1 -1
  24. package/out/zero-protocol/src/ast.d.ts +2 -2
  25. package/out/zero-protocol/src/ast.js +2 -2
  26. package/out/zero-protocol/src/ast.js.map +1 -1
  27. package/out/zero-protocol/src/down.d.ts +27 -27
  28. package/out/zero-protocol/src/inspect-down.d.ts +81 -81
  29. package/out/zql/src/ivm/aggregate.js +5 -4
  30. package/out/zql/src/ivm/aggregate.js.map +1 -1
  31. package/out/zql/src/ivm/cap.d.ts.map +1 -1
  32. package/out/zql/src/ivm/cap.js +116 -63
  33. package/out/zql/src/ivm/cap.js.map +1 -1
  34. package/out/zql/src/ivm/deferred-input.js +1 -1
  35. package/out/zql/src/ivm/exists.d.ts.map +1 -1
  36. package/out/zql/src/ivm/exists.js +136 -73
  37. package/out/zql/src/ivm/exists.js.map +1 -1
  38. package/out/zql/src/ivm/fan-in.d.ts.map +1 -1
  39. package/out/zql/src/ivm/fan-in.js +3 -3
  40. package/out/zql/src/ivm/fan-in.js.map +1 -1
  41. package/out/zql/src/ivm/fan-out.d.ts +2 -2
  42. package/out/zql/src/ivm/fan-out.d.ts.map +1 -1
  43. package/out/zql/src/ivm/fan-out.js +47 -12
  44. package/out/zql/src/ivm/fan-out.js.map +1 -1
  45. package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
  46. package/out/zql/src/ivm/filter-operators.js +98 -13
  47. package/out/zql/src/ivm/filter-operators.js.map +1 -1
  48. package/out/zql/src/ivm/filter-push.d.ts.map +1 -1
  49. package/out/zql/src/ivm/filter-push.js +5 -13
  50. package/out/zql/src/ivm/filter-push.js.map +1 -1
  51. package/out/zql/src/ivm/filter.d.ts.map +1 -1
  52. package/out/zql/src/ivm/filter.js +3 -2
  53. package/out/zql/src/ivm/filter.js.map +1 -1
  54. package/out/zql/src/ivm/flipped-join.js +1 -0
  55. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  56. package/out/zql/src/ivm/group-by.js +1 -1
  57. package/out/zql/src/ivm/join-index-tap.d.ts +1 -1
  58. package/out/zql/src/ivm/join-index-tap.d.ts.map +1 -1
  59. package/out/zql/src/ivm/join-index-tap.js +9 -7
  60. package/out/zql/src/ivm/join-index-tap.js.map +1 -1
  61. package/out/zql/src/ivm/join.d.ts.map +1 -1
  62. package/out/zql/src/ivm/join.js +72 -67
  63. package/out/zql/src/ivm/join.js.map +1 -1
  64. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  65. package/out/zql/src/ivm/memory-source.js +163 -57
  66. package/out/zql/src/ivm/memory-source.js.map +1 -1
  67. package/out/zql/src/ivm/push-accumulated.d.ts +1 -1
  68. package/out/zql/src/ivm/push-accumulated.d.ts.map +1 -1
  69. package/out/zql/src/ivm/push-accumulated.js +23 -28
  70. package/out/zql/src/ivm/push-accumulated.js.map +1 -1
  71. package/out/zql/src/ivm/skip.d.ts.map +1 -1
  72. package/out/zql/src/ivm/skip.js +6 -9
  73. package/out/zql/src/ivm/skip.js.map +1 -1
  74. package/out/zql/src/ivm/stream.d.ts +58 -0
  75. package/out/zql/src/ivm/stream.d.ts.map +1 -1
  76. package/out/zql/src/ivm/stream.js +256 -1
  77. package/out/zql/src/ivm/stream.js.map +1 -1
  78. package/out/zql/src/ivm/take-gate.d.ts +1 -1
  79. package/out/zql/src/ivm/take-gate.d.ts.map +1 -1
  80. package/out/zql/src/ivm/take-gate.js +11 -21
  81. package/out/zql/src/ivm/take-gate.js.map +1 -1
  82. package/out/zql/src/ivm/take.d.ts.map +1 -1
  83. package/out/zql/src/ivm/take.js +243 -217
  84. package/out/zql/src/ivm/take.js.map +1 -1
  85. package/out/zql/src/query/query.d.ts +4 -4
  86. package/package.json +1 -1
@@ -6,7 +6,8 @@ import { must } from "../../../shared/src/must.js";
6
6
  import { makeAddChange, makeEditChange, makeRemoveChange } from "./change.js";
7
7
  import { compareValues, makeComparator, valuesEqual } from "./data.js";
8
8
  import { skipYields } from "./skip-yields.js";
9
- import { consume } from "./stream.js";
9
+ import { emptyArray } from "../../../shared/src/sentinels.js";
10
+ import { andFinally, andThen, consume, doneResult, eachStream } from "./stream.js";
10
11
  import { assertOrderingIncludesPK } from "../query/complete-ordering.js";
11
12
  import { filterPush } from "./filter-push.js";
12
13
  import { constraintMatchesPrimaryKey, constraintMatchesRow, primaryKeyConstraintFromFilters } from "./constraint.js";
@@ -175,11 +176,8 @@ var MemorySource = class MemorySource {
175
176
  getIndexKeys() {
176
177
  return [...this.#indexes.keys()];
177
178
  }
178
- *#fetch(req, conn) {
179
- if (req.multiConstraints && req.multiConstraints.some((mc) => mc.length > 0)) {
180
- yield* this.#fetchMulti(req, conn);
181
- return;
182
- }
179
+ #fetch(req, conn) {
180
+ if (req.multiConstraints && req.multiConstraints.some((mc) => mc.length > 0)) return this.#fetchMulti(req, conn);
183
181
  const requestedSort = must(conn.sort);
184
182
  const { compareRows } = conn;
185
183
  const connectionComparator = req.reverse ? (r1, r2) => compareRows(r2, r1) : compareRows;
@@ -206,21 +204,10 @@ var MemorySource = class MemorySource {
206
204
  else assignProperty(scanStart, key, dir === "asc" ? minValue : maxValue);
207
205
  } else scanStart = startAt;
208
206
  const rowsIterable = generateRows(data, scanStart, req.reverse);
209
- if (!(this.#overlay && conn.lastPushedEpoch >= this.#overlay.epoch) && !req.start && !pkConstraint) {
210
- const { constraint } = req;
211
- for (const row of rowsIterable) {
212
- if (constraint && !constraintMatchesRow(constraint, row)) break;
213
- if (mergedFilterPredicate && !mergedFilterPredicate(row)) continue;
214
- yield {
215
- row,
216
- relationships: {}
217
- };
218
- }
219
- return;
220
- }
207
+ if (!(this.#overlay && conn.lastPushedEpoch >= this.#overlay.epoch) && !req.start && !pkConstraint) return new SourceNodes(rowsIterable, req.constraint, mergedFilterPredicate);
221
208
  const withOverlay = generateWithOverlay(startAt, pkConstraint ? once(rowsIterable) : rowsIterable, req.constraint, this.#overlay, conn.lastPushedEpoch, indexComparator, connectionComparator, mergedFilterPredicate);
222
209
  const withConstraint = generateWithConstraint(skipYields(generateWithStart(withOverlay, req.start, connectionComparator)), req.constraint);
223
- yield* mergedFilterPredicate ? generateWithFilter(withConstraint, mergedFilterPredicate) : withConstraint;
210
+ return mergedFilterPredicate ? generateWithFilter(withConstraint, mergedFilterPredicate) : withConstraint;
224
211
  }
225
212
  *#fetchMulti(req, conn) {
226
213
  const multis = must(req.multiConstraints).filter((mc) => mc.length > 0);
@@ -283,8 +270,12 @@ var MemorySource = class MemorySource {
283
270
  const sorted = isAscending(rows, comparator) ? rows : sortedByStringKey(rows, this.#primaryKey) ?? rows.sort(comparator);
284
271
  index.data = BTreeSet.fromSorted(comparator, sorted);
285
272
  }
286
- *push(change) {
287
- for (const result of this.genPush(change)) if (result === "yield") yield result;
273
+ push(change) {
274
+ const { data } = this.#getPrimaryIndex();
275
+ const exists = (row) => data.has(row);
276
+ const setOverlay = (o) => this.#overlay = o;
277
+ const writeChange = (c) => this.#writeChange(c);
278
+ return pushAndWriteWithSplitEdit(this.#connections, change, exists, setOverlay, writeChange, () => ++this.#pushEpoch);
288
279
  }
289
280
  genPush(change) {
290
281
  const { data } = this.#getPrimaryIndex();
@@ -321,6 +312,62 @@ function mergePredicates(connPredicate, reqFilter) {
321
312
  if (!connPredicate) return reqPredicate;
322
313
  return (row) => connPredicate(row) && reqPredicate(row);
323
314
  }
315
+ /**
316
+ * The fast path of `#fetch`: walks rows from the scan start, stops once the
317
+ * constraint no longer matches, drops the rows the filter rejects and wraps
318
+ * the rest as Nodes. An iterator rather than a generator, see `mapNodes` in
319
+ * stream.ts.
320
+ */
321
+ var SourceNodes = class {
322
+ #rows;
323
+ #constraint;
324
+ #predicate;
325
+ #done = false;
326
+ constructor(rows, constraint, predicate) {
327
+ this.#rows = rows;
328
+ this.#constraint = constraint;
329
+ this.#predicate = predicate;
330
+ }
331
+ [Symbol.iterator]() {
332
+ return this;
333
+ }
334
+ next() {
335
+ if (this.#done) return doneResult;
336
+ const constraint = this.#constraint;
337
+ const predicate = this.#predicate;
338
+ for (;;) {
339
+ let row;
340
+ let matches;
341
+ try {
342
+ const r = this.#rows.next();
343
+ if (r.done) {
344
+ this.#done = true;
345
+ return doneResult;
346
+ }
347
+ row = r.value;
348
+ if (constraint && !constraintMatchesRow(constraint, row)) {
349
+ this.#done = true;
350
+ return doneResult;
351
+ }
352
+ matches = !predicate || predicate(row);
353
+ } catch (e) {
354
+ this.#done = true;
355
+ throw e;
356
+ }
357
+ if (matches) return {
358
+ value: {
359
+ row,
360
+ relationships: {}
361
+ },
362
+ done: false
363
+ };
364
+ }
365
+ }
366
+ return() {
367
+ this.#done = true;
368
+ return doneResult;
369
+ }
370
+ };
324
371
  function* generateWithConstraint(it, constraint) {
325
372
  for (const node of it) {
326
373
  if (constraint && !constraintMatchesRow(constraint, node.row)) break;
@@ -331,16 +378,7 @@ function* generateWithFilter(it, filter) {
331
378
  for (const node of it) if (filter(node.row)) yield node;
332
379
  }
333
380
  function* genPushAndWriteWithSplitEdit(connections, change, exists, setOverlay, writeChange, getNextEpoch) {
334
- let shouldSplitEdit = false;
335
- if (change[0] === 2) {
336
- for (const { splitEditKeys } of connections) if (splitEditKeys) {
337
- for (const key of splitEditKeys) if (!valuesEqual(change[1][key], change[2][key])) {
338
- shouldSplitEdit = true;
339
- break;
340
- }
341
- }
342
- }
343
- if (change[0] === 2 && shouldSplitEdit) {
381
+ if (mustSplitEdit(connections, change)) {
344
382
  yield* genPushAndWrite(connections, makeSourceChangeRemove(change[2]), exists, setOverlay, writeChange, getNextEpoch());
345
383
  yield* genPushAndWrite(connections, makeSourceChangeAdd(change[1]), exists, setOverlay, writeChange, getNextEpoch());
346
384
  } else yield* genPushAndWrite(connections, change, exists, setOverlay, writeChange, getNextEpoch());
@@ -350,18 +388,7 @@ function* genPushAndWrite(connections, change, exists, setOverlay, writeChange,
350
388
  writeChange(change);
351
389
  }
352
390
  function* genPush(connections, change, exists, setOverlay, pushEpoch) {
353
- if (exists) switch (change[0]) {
354
- case 0:
355
- assert(!exists(change[1]), () => `Row already exists ${stringify(change)}`);
356
- break;
357
- case 1:
358
- assert(exists(change[1]), () => `Row not found ${stringify(change)}`);
359
- break;
360
- case 2:
361
- assert(exists(change[2]), () => `Row not found ${stringify(change)}`);
362
- break;
363
- default: unreachable(change);
364
- }
391
+ assertCanPush(change, exists);
365
392
  setOverlay({
366
393
  epoch: pushEpoch,
367
394
  change
@@ -371,20 +398,7 @@ function* genPush(connections, change, exists, setOverlay, pushEpoch) {
371
398
  const { output, filters, input } = conn;
372
399
  if (output) {
373
400
  conn.lastPushedEpoch = pushEpoch;
374
- const outputChange = change[0] === 2 ? makeEditChange({
375
- row: change[1],
376
- relationships: {}
377
- }, {
378
- row: change[2],
379
- relationships: {}
380
- }) : change[0] === 0 ? makeAddChange({
381
- row: change[1],
382
- relationships: {}
383
- }) : makeRemoveChange({
384
- row: change[1],
385
- relationships: {}
386
- });
387
- yield* filterPush(outputChange, output, input, filters?.predicate);
401
+ yield* filterPush(toOutputChange(change), output, input, filters?.predicate);
388
402
  yield void 0;
389
403
  }
390
404
  }
@@ -399,6 +413,98 @@ function* genPush(connections, change, exists, setOverlay, pushEpoch) {
399
413
  setOverlay(void 0);
400
414
  }
401
415
  }
416
+ /**
417
+ * Whether `change` is an edit of a column that one of the connections splits
418
+ * edits on, and so is pushed as a remove and an add.
419
+ */
420
+ function mustSplitEdit(connections, change) {
421
+ if (change[0] !== 2) return false;
422
+ for (const { splitEditKeys } of connections) if (splitEditKeys) {
423
+ for (const key of splitEditKeys) if (!valuesEqual(change[1][key], change[2][key])) return true;
424
+ }
425
+ return false;
426
+ }
427
+ function assertCanPush(change, exists) {
428
+ if (!exists) return;
429
+ switch (change[0]) {
430
+ case 0:
431
+ assert(!exists(change[1]), () => `Row already exists ${stringify(change)}`);
432
+ break;
433
+ case 1:
434
+ assert(exists(change[1]), () => `Row not found ${stringify(change)}`);
435
+ break;
436
+ case 2:
437
+ assert(exists(change[2]), () => `Row not found ${stringify(change)}`);
438
+ break;
439
+ default: unreachable(change);
440
+ }
441
+ }
442
+ /** The change a connection's output gets for a change to the source. */
443
+ function toOutputChange(change) {
444
+ return change[0] === 2 ? makeEditChange({
445
+ row: change[1],
446
+ relationships: {}
447
+ }, {
448
+ row: change[2],
449
+ relationships: {}
450
+ }) : change[0] === 0 ? makeAddChange({
451
+ row: change[1],
452
+ relationships: {}
453
+ }) : makeRemoveChange({
454
+ row: change[1],
455
+ relationships: {}
456
+ });
457
+ }
458
+ function pushAndWriteWithSplitEdit(connections, change, exists, setOverlay, writeChange, getNextEpoch) {
459
+ if (mustSplitEdit(connections, change)) return andThen(pushAndWrite(connections, makeSourceChangeRemove(change[2]), exists, setOverlay, writeChange, getNextEpoch()), () => pushAndWrite(connections, makeSourceChangeAdd(change[1]), exists, setOverlay, writeChange, getNextEpoch()));
460
+ return pushAndWrite(connections, change, exists, setOverlay, writeChange, getNextEpoch());
461
+ }
462
+ function pushAndWrite(connections, change, exists, setOverlay, writeChange, pushEpoch) {
463
+ assertCanPush(change, exists);
464
+ setOverlay({
465
+ epoch: pushEpoch,
466
+ change
467
+ });
468
+ let s;
469
+ try {
470
+ s = pushToConnections(connections, change, pushEpoch);
471
+ } catch (e) {
472
+ setOverlay(void 0);
473
+ throw e;
474
+ }
475
+ if (s === emptyArray) {
476
+ setOverlay(void 0);
477
+ writeChange(change);
478
+ return emptyArray;
479
+ }
480
+ return andThen(andFinally(s, () => setOverlay(void 0)), () => {
481
+ writeChange(change);
482
+ return emptyArray;
483
+ });
484
+ }
485
+ /** Pushes `change` to each connection, then reconciles each. */
486
+ function pushToConnections(connections, change, pushEpoch) {
487
+ let i = 0;
488
+ let reconciling = false;
489
+ return eachStream(() => {
490
+ if (!reconciling) {
491
+ while (i < connections.length) {
492
+ const conn = connections[i++];
493
+ const { output, filters, input } = conn;
494
+ if (output) {
495
+ conn.lastPushedEpoch = pushEpoch;
496
+ return filterPush(toOutputChange(change), output, input, filters?.predicate);
497
+ }
498
+ }
499
+ reconciling = true;
500
+ i = 0;
501
+ }
502
+ while (i < connections.length) {
503
+ const { output, input } = connections[i++];
504
+ if (output?.reconcile) return output.reconcile(input);
505
+ }
506
+ });
507
+ }
402
508
  function* generateWithStart(nodes, start, compare) {
403
509
  if (!start) {
404
510
  yield* nodes;
@@ -1 +1 @@
1
- {"version":3,"file":"memory-source.js","names":[],"sources":["../../../../../zql/src/ivm/memory-source.ts"],"sourcesContent":["import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {BTreeSet} from '../../../shared/src/btree-set.ts';\nimport {hasOwn} from '../../../shared/src/has-own.ts';\nimport {once} from '../../../shared/src/iterables.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {\n nativeSortIsAdaptive,\n sortByNaturalRuns,\n} from '../../../shared/src/natural-runs.ts';\nimport {assignProperty} from '../../../shared/src/objects.ts';\nimport type {\n Condition,\n Ordering,\n OrderPart,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport type {SchemaValue} from '../../../zero-types/src/schema-value.ts';\nimport type {DebugDelegate} from '../builder/debug-delegate.ts';\nimport {\n createPredicate,\n transformFilters,\n type NoSubqueryCondition,\n} from '../builder/filter.ts';\nimport {assertOrderingIncludesPK} from '../query/complete-ordering.ts';\nimport {ChangeType} from './change-type.ts';\nimport type {Change} from './change.ts';\nimport {makeAddChange, makeEditChange, makeRemoveChange} from './change.ts';\nimport {\n constraintMatchesPrimaryKey,\n constraintMatchesRow,\n primaryKeyConstraintFromFilters,\n type Constraint,\n} from './constraint.ts';\nimport {\n compareValues,\n makeComparator,\n valuesEqual,\n type Comparator,\n type Node,\n} from './data.ts';\nimport {filterPush} from './filter-push.ts';\nimport {\n skipYields,\n type FetchRequest,\n type Input,\n type MultiConstraint,\n type Output,\n type Start,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {SourceChangeIndex} from './source-change-index.ts';\nimport type {\n Source,\n SourceChange,\n SourceChangeAdd,\n SourceChangeEdit,\n SourceChangeRemove,\n SourceInput,\n} from './source.ts';\nimport {makeSourceChangeAdd, makeSourceChangeRemove} from './source.ts';\nimport {consume, type Stream} from './stream.ts';\n\nexport type Overlay = {\n epoch: number;\n change: SourceChange;\n};\n\nexport type Overlays = {\n add: Row | undefined;\n remove: Row | undefined;\n};\n\ntype Index = {\n comparator: Comparator;\n data: BTreeSet<Row>;\n};\n\nexport type Connection = {\n input: Input;\n output: Output | undefined;\n sort?: Ordering | undefined;\n splitEditKeys: Set<string> | undefined;\n compareRows: Comparator;\n filters:\n | {\n condition: NoSubqueryCondition;\n predicate: (row: Row) => boolean;\n }\n | undefined;\n readonly debug?: DebugDelegate | undefined;\n lastPushedEpoch: number;\n};\n\n/**\n * A `MemorySource` is a source that provides data to the pipeline from an\n * in-memory data source.\n *\n * This data is kept in sorted order as downstream pipelines will always expect\n * the data they receive from `pull` to be in sorted order.\n */\nexport class MemorySource implements Source {\n readonly #tableName: string;\n readonly #columns: Record<string, SchemaValue>;\n readonly #primaryKey: PrimaryKey;\n readonly #primaryIndexSort: Ordering;\n readonly #indexes: Map<string, Index> = new Map();\n readonly #connections: Connection[] = [];\n\n #overlay: Overlay | undefined;\n #pushEpoch = 0;\n\n constructor(\n tableName: string,\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n primaryIndexData?: BTreeSet<Row>,\n ) {\n this.#tableName = tableName;\n this.#columns = columns;\n this.#primaryKey = primaryKey;\n this.#primaryIndexSort = primaryKey.map(k => [k, 'asc']);\n const comparator = makeBoundComparator(this.#primaryIndexSort);\n this.#indexes.set(JSON.stringify(this.#primaryIndexSort), {\n comparator,\n data: primaryIndexData ?? new BTreeSet<Row>(comparator),\n });\n }\n\n get tableSchema() {\n return {\n name: this.#tableName,\n columns: this.#columns,\n primaryKey: this.#primaryKey,\n };\n }\n\n fork() {\n const primaryIndex = this.#getPrimaryIndex();\n return new MemorySource(\n this.#tableName,\n this.#columns,\n this.#primaryKey,\n primaryIndex.data.clone(),\n );\n }\n\n get data(): BTreeSet<Row> {\n return this.#getPrimaryIndex().data;\n }\n\n /** Whether any input is connected to this source. */\n get connected(): boolean {\n return this.#connections.length > 0;\n }\n\n #getSchema(connection: Connection, unordered: boolean): SourceSchema {\n return {\n tableName: this.#tableName,\n columns: this.#columns,\n primaryKey: this.#primaryKey,\n sort: unordered ? undefined : connection.sort,\n system: 'client',\n relationships: {},\n isHidden: false,\n compareRows: connection.compareRows,\n };\n }\n\n connect(\n sort: Ordering | undefined,\n filters?: Condition,\n splitEditKeys?: Set<string>,\n ): SourceInput {\n const transformedFilters = transformFilters(filters);\n const unordered = sort === undefined;\n const internalSort = sort ?? this.#primaryIndexSort;\n\n const input: SourceInput = {\n getSchema: () => schema,\n fetch: req => this.#fetch(req, connection),\n setOutput: output => {\n connection.output = output;\n },\n destroy: () => {\n this.#disconnect(input);\n },\n fullyAppliedFilters: !transformedFilters.conditionsRemoved,\n };\n\n const connection: Connection = {\n input,\n output: undefined,\n sort: internalSort,\n splitEditKeys,\n compareRows: makeComparator(internalSort),\n filters: transformedFilters.filters\n ? {\n condition: transformedFilters.filters,\n predicate: createPredicate(transformedFilters.filters),\n }\n : undefined,\n lastPushedEpoch: 0,\n };\n const schema = this.#getSchema(connection, unordered);\n if (!unordered) {\n assertOrderingIncludesPK(internalSort, this.#primaryKey);\n }\n this.#connections.push(connection);\n return input;\n }\n\n #disconnect(input: Input): void {\n const idx = this.#connections.findIndex(c => c.input === input);\n assert(idx !== -1, 'Connection not found');\n this.#connections.splice(idx, 1);\n\n // Indexes deliberately hold no reference back to the connections that use\n // them. They used to, to support deleting an index once its last user went\n // away. That deletion is gone (see below) but the `usedBy` set outlived it,\n // so an index kept every `Connection` — and through its `input` and\n // `output`, the whole torn-down pipeline — reachable for as long as the\n // source lived.\n //\n // TODO: We used to delete unused indexes here. But in common cases like\n // navigating into issue detail pages it caused a ton of constantly\n // building and destroying indexes.\n //\n // Perhaps some intelligent LRU or something is needed here but for now,\n // the opposite extreme of keeping all indexes for the lifetime of the\n // page seems better.\n }\n\n #getPrimaryIndex(): Index {\n const index = this.#indexes.get(JSON.stringify(this.#primaryIndexSort));\n assert(index, 'Primary index not found');\n return index;\n }\n\n #getOrCreateIndex(sort: Ordering): Index {\n const key = JSON.stringify(sort);\n const index = this.#indexes.get(key);\n // Future optimization could use existing index if it's the same just sorted\n // in reverse of needed.\n if (index) {\n return index;\n }\n\n const comparator = makeBoundComparator(sort);\n\n // When creating these synchronously becomes a problem, a few options:\n // 1. Allow users to specify needed indexes up front\n // 2. Create indexes in a different thread asynchronously (this would require\n // modifying the BTree to be able to be passed over structured-clone, or using\n // a different library.)\n // 3. We could even theoretically do (2) on multiple threads and then merge the\n // results!\n // `toArray` rather than spreading the tree: the iterator costs about\n // 0.5us/row on Hermes, and this materialization is what is left in this\n // function now that the sort is often skipped outright. The array is ours,\n // so the paths below may reorder it in place.\n const rows = this.#getPrimaryIndex().data.toArray();\n\n // Three ways to get the rows into the new index's order, cheapest first.\n //\n // Natural-run merging leads where it can win at all -- which is only where\n // the engine's own sort is not adaptive, since on V8 it already walks\n // ordered input in one pass and a JS pass over the same rows is strictly\n // worse. It is the only one of the three that can be O(N),\n // and because it hits more often than it looks: rows arrive here in\n // primary-key order, and a secondary sort key is usually a timestamp or\n // sequence number that moves with insertion order, so the input is often\n // already sorted, exactly reversed, or a few ordered batches. It declines\n // cheaply -- bounded by `maxRuns` comparisons -- and leaves `rows`\n // untouched when it does.\n //\n // The numeric path is next: it cannot reach O(N), but it beats a general\n // comparator sort on the shape it covers. The plain sort is the floor.\n const sorted =\n (nativeSortIsAdaptive()\n ? undefined\n : sortByNaturalRuns(rows, comparator)) ??\n this.#sortedByLeadingNumberColumn(sort, rows) ??\n rows.sort(comparator);\n const data = BTreeSet.fromSorted(comparator, sorted);\n\n const newIndex = {comparator, data};\n this.#indexes.set(key, newIndex);\n return newIndex;\n }\n\n /**\n * The rows for a new index, sorted without calling a row comparator once, for\n * the shape that dominates: one numeric column followed by the primary key.\n *\n * `#getOrCreateIndex` otherwise sorts every row through\n * `makeBoundComparator`, which reads its columns through variable keys and\n * compares two of them. On Hermes that one sort was 38ms of a 91ms cold-start\n * hydration -- 77% of the index build -- because an interpreter pays for the\n * dynamic property reads and the closure indirection that V8's JIT removes.\n *\n * Two observations collapse it. First, the trailing primary key never needs to\n * be compared: the input is the primary index, so it already arrives in\n * primary-key order, and `Array.prototype.sort` has been stable since ES2019,\n * so ties keep that order -- which is exactly what comparing the ascending\n * primary key would produce. Second, with only one key left, the sort can\n * decorate: extract the column once per row and sort an index array on\n * primitive subtraction, trading N*logN property reads for N.\n *\n * Measured over a 20,000-row cold start: the sort goes from 38.2ms to 17.0ms\n * on Hermes (2.25x) and 1.14x on V8, taking the whole hydration of one\n * `where` + `orderBy` query from 91ms to 70ms on Hermes. Returns `undefined`\n * when the shape does not apply, and the caller falls back to the general\n * sort.\n */\n #sortedByLeadingNumberColumn(\n sort: Ordering,\n rows: readonly Row[],\n ): Row[] | undefined {\n const pk = this.#primaryIndexSort;\n // One leading column, then exactly the primary key ascending.\n if (sort.length !== pk.length + 1) {\n return undefined;\n }\n for (let i = 0; i < pk.length; i++) {\n if (sort[i + 1][0] !== pk[i][0] || sort[i + 1][1] !== pk[i][1]) {\n return undefined;\n }\n }\n const [column, direction] = sort[0];\n // Numbers only: this orders by subtraction, which strings and booleans do\n // not. Widening to strings would mean `compareUTF8` per comparison, a\n // smaller win worth measuring separately.\n if (this.#columns[column]?.type !== 'number') {\n return undefined;\n }\n\n const n = rows.length;\n // Pre-sized deliberately: these are filled by index immediately below, and\n // `Array.from({length: n})` would allocate and then fill them twice.\n // oxlint-disable-next-line unicorn/no-new-array\n const keys = new Array<number>(n);\n // oxlint-disable-next-line unicorn/no-new-array\n const order = new Array<number>(n);\n for (let i = 0; i < n; i++) {\n const v = rows[i][column];\n // A finite number, and nothing else. An optional column may hold null,\n // and a Postgres `double precision` may hold NaN or Infinity, for which\n // subtraction does not order (NaN - NaN is NaN, and so is\n // Infinity - Infinity). The general comparator orders those no better,\n // but it must stay the single definition of what that order is.\n //\n // `v - v === 0` is the finite test without a call: it is 0 for every\n // finite number and NaN for NaN and both infinities. `Number.isFinite`\n // says the same thing at the cost of a global lookup and a call per row;\n // the two were within run-to-run noise of each other here, so this is the\n // cheaper of two equals rather than a measured win.\n if (typeof v !== 'number' || v - v !== 0) {\n // Bailing part way through wastes the scan so far, and then the general\n // sort redoes it. That is the right trade: one null in the column makes\n // this path inapplicable, not slow.\n return undefined;\n }\n keys[i] = v;\n order[i] = i;\n }\n\n order.sort(\n direction === 'asc'\n ? (a, b) => keys[a] - keys[b]\n : (a, b) => keys[b] - keys[a],\n );\n\n // oxlint-disable-next-line unicorn/no-new-array\n const out = new Array<Row>(n);\n for (let i = 0; i < n; i++) {\n out[i] = rows[order[i]];\n }\n return out;\n }\n\n // For unit testing that we correctly clean up indexes.\n getIndexKeys(): string[] {\n return [...this.#indexes.keys()];\n }\n\n *#fetch(req: FetchRequest, conn: Connection): Stream<Node | 'yield'> {\n // multiConstraints is handled by driving sub-fetches off the first\n // entry's values and post-filtering matches against any remaining\n // entries. TableSource implements multi-IN natively via SQL `AND` of\n // `IN` clauses; the in-memory path is correct but not specially\n // optimized — it pays the index-seek cost per primary value, then\n // walks each result against the rest.\n if (\n req.multiConstraints &&\n req.multiConstraints.some(mc => mc.length > 0)\n ) {\n yield* this.#fetchMulti(req, conn);\n return;\n }\n const requestedSort = must(conn.sort);\n const {compareRows} = conn;\n // Avoid allocating a new closure when not reversing (the common case).\n const connectionComparator: Comparator = req.reverse\n ? (r1, r2) => compareRows(r2, r1)\n : compareRows;\n\n const reqFilter = req.filter;\n const connFilterCondition = conn.filters?.condition;\n const mergedFilterCondition: NoSubqueryCondition | undefined =\n connFilterCondition && reqFilter\n ? {type: 'and', conditions: [connFilterCondition, reqFilter]}\n : (connFilterCondition ?? reqFilter);\n const mergedFilterPredicate = mergePredicates(\n conn.filters?.predicate,\n reqFilter,\n );\n\n const pkConstraint = primaryKeyConstraintFromFilters(\n mergedFilterCondition,\n this.#primaryKey,\n );\n // The primary key constraint will be more limiting than the constraint\n // so swap out to that if it exists.\n const fetchOrPkConstraint = pkConstraint ?? req.constraint;\n\n // If there is a constraint, we need an index sorted by it first.\n const indexSort: OrderPart[] = [];\n if (fetchOrPkConstraint) {\n for (const key of Object.keys(fetchOrPkConstraint)) {\n indexSort.push([key, 'asc']);\n }\n }\n\n // For the special case of constraining by PK, we don't need to worry about\n // any requested sort since there can only be one result. Otherwise we also\n // need the index sorted by the requested sort.\n if (\n this.#primaryKey.length > 1 ||\n !fetchOrPkConstraint ||\n !constraintMatchesPrimaryKey(fetchOrPkConstraint, this.#primaryKey)\n ) {\n indexSort.push(...requestedSort);\n }\n\n const index = this.#getOrCreateIndex(indexSort);\n const {data, comparator: compare} = index;\n // Avoid allocating a new closure when not reversing (the common case).\n const indexComparator: Comparator = req.reverse\n ? (r1, r2) => compare(r2, r1)\n : compare;\n\n const startAt = req.start?.row;\n\n // If there is a constraint, we want to start our scan at the first row that\n // matches the constraint. But because the next OrderPart can be `desc`,\n // it's not true that {[constraintKey]: constraintValue} is the first\n // matching row. Because in that case, the other fields will all be\n // `undefined`, and in Zero `undefined` is always less than any other value.\n // So if the second OrderPart is descending then `undefined` values will\n // actually be the *last* row. We need a way to stay \"start at the first row\n // with this constraint value\". RowBound with the corresponding compareBound\n // comparator accomplishes this. The right thing is probably to teach the\n // btree library to support this concept.\n let scanStart: RowBound | undefined;\n\n if (fetchOrPkConstraint) {\n scanStart = {};\n for (const [key, dir] of indexSort) {\n if (hasOwn(fetchOrPkConstraint, key)) {\n assignProperty(scanStart, key, fetchOrPkConstraint[key]);\n } else {\n if (req.reverse) {\n assignProperty(scanStart, key, dir === 'asc' ? maxValue : minValue);\n } else {\n assignProperty(scanStart, key, dir === 'asc' ? minValue : maxValue);\n }\n }\n }\n } else {\n scanStart = startAt;\n }\n\n const rowsIterable = generateRows(data, scanStart, req.reverse);\n\n // Fast path: no overlay to apply, no `start`, and no primary-key constraint\n // hidden in the filters. This is the common shape for join child-lookups,\n // plain scans, filtered scans, and source fetches that sit beneath a\n // downstream `Filter` operator. In that case the whole generator stack\n // (generateWithOverlay → generateWithStart → skipYields →\n // generateWithConstraint → generateWithFilter) reduces to: walk rows from\n // `scanStart`, drop the ones the filter rejects, wrap the rest as Nodes, and\n // stop once the constraint no longer matches (rows are sorted by the\n // constraint key first, so matches are contiguous). Collapsing the five\n // chained generators into one loop removes a large amount of per-row\n // generator-resume overhead on the hottest path.\n //\n // The filter belongs on this path rather than in a fifth generator: on\n // Hermes, adding a connection filter to a 20,000-row ordered scan cost\n // 0.56us per row, while the predicate itself measures 0.03us. The other 95%\n // was the generator stack this path exists to avoid, and the loop applies\n // the predicate in the same place `generateWithFilter` did -- after the\n // constraint break, so a non-matching constraint still ends the scan rather\n // than filtering to the end of the index.\n //\n // A primary-key constraint derived from the filters is excluded because it\n // does not reach `req.constraint`: it is used to position `scanStart`\n // instead, and this loop would then walk from that row to the end of the\n // index, filtering all the way, rather than stopping. Correct, but O(N) for\n // what should be a point lookup.\n const overlayActive =\n this.#overlay && conn.lastPushedEpoch >= this.#overlay.epoch;\n if (!overlayActive && !req.start && !pkConstraint) {\n const {constraint} = req;\n for (const row of rowsIterable) {\n if (constraint && !constraintMatchesRow(constraint, row)) {\n break;\n }\n if (mergedFilterPredicate && !mergedFilterPredicate(row)) {\n continue;\n }\n yield {row, relationships: {}};\n }\n return;\n }\n\n const withOverlay = generateWithOverlay(\n startAt,\n pkConstraint ? once(rowsIterable) : rowsIterable,\n // use `req.constraint` here and not `fetchOrPkConstraint` since `fetchOrPkConstraint` could be the\n // primary key constraint. The primary key constraint comes from filters and is acting as a filter\n // rather than as the fetch constraint.\n req.constraint,\n this.#overlay,\n conn.lastPushedEpoch,\n // Use indexComparator, generateWithOverlayInner has a subtle dependency\n // on this. Since generateWithConstraint is done after\n // generateWithOverlay, the generator consumed by generateWithOverlayInner\n // does not end when the constraint stops matching and so the final\n // check to yield an add overlay if not yet yielded is not reached.\n // However, using the indexComparator the add overlay will be less than\n // the first row that does not match the constraint, and so any\n // not yet yielded add overlay will be yielded when the first row\n // not matching the constraint is reached.\n indexComparator,\n // `startAt` is `req.start.row`, a bound in the connection's sort order,\n // so it must be compared in that order -- not `indexComparator`, which\n // with a constraint leads with the constraint keys. The two agree only\n // when the overlay row and `startAt` share those key values; they do not\n // for `#fetchMulti`'s per-value sub-fetches, which pin one primary key\n // while still carrying the caller's connection-sort `start`. Comparing\n // there by the constraint key dropped the in-flight overlay and served\n // pre-push data. Same distinction #4926 drew for `generateWithStart`.\n connectionComparator,\n mergedFilterPredicate,\n );\n\n const withConstraint = generateWithConstraint(\n skipYields(\n generateWithStart(withOverlay, req.start, connectionComparator),\n ),\n // we use `req.constraint` and not `fetchOrPkConstraint` here because we need to\n // AND the constraint with what could have been the primary key constraint\n req.constraint,\n );\n\n yield* mergedFilterPredicate\n ? generateWithFilter(withConstraint, mergedFilterPredicate)\n : withConstraint;\n }\n\n *#fetchMulti(req: FetchRequest, conn: Connection): Stream<Node | 'yield'> {\n // Caller (`#fetch`) guards entry on `req.multiConstraints.some(mc =>\n // mc.length > 0)`, so `multis` is guaranteed non-empty after the\n // empty-entry filter. Per the MultiConstraint contract (operator.ts),\n // entries are non-empty, share key shape, are unique, and are\n // key-compatible with `req.constraint`.\n const multis = must(req.multiConstraints).filter(mc => mc.length > 0);\n const primary = multis[0];\n const rest = multis.slice(1);\n const baseConstraint = req.constraint;\n\n // Drive sub-fetches off `primary`. Within each sub-fetch the source\n // can use its index for `primary`; we then post-filter rows by\n // checking they also match every entry in `rest`. Per the\n // MultiConstraint contract (see operator.ts), entries are unique and\n // key-compatible with `baseConstraint`, so we don't dedupe or check\n // compatibility here.\n const subStreams: Stream<Node | 'yield'>[] = primary.map(c => {\n const merged: Constraint = baseConstraint ? {...baseConstraint, ...c} : c;\n return this.#fetch(\n {...req, constraint: merged, multiConstraints: undefined},\n conn,\n );\n });\n const merged = mergeSortedStreams(\n subStreams,\n req.reverse\n ? (a, b) => conn.compareRows(b.row, a.row)\n : (a, b) => conn.compareRows(a.row, b.row),\n );\n\n if (rest.length === 0) {\n yield* merged;\n return;\n }\n\n for (const node of merged) {\n if (node === 'yield') {\n yield 'yield';\n continue;\n }\n let matchesAll = true;\n for (const mc of rest) {\n let any = false;\n for (const c of mc) {\n if (constraintMatchesRow(c, node.row)) {\n any = true;\n break;\n }\n }\n if (!any) {\n matchesAll = false;\n break;\n }\n }\n if (matchesAll) yield node;\n }\n }\n\n /**\n * Pushes an add for each of `rows`.\n *\n * When the source holds no rows and nothing is connected to it (loading the\n * replica at startup) there is no output to notify and no secondary index to\n * keep in step, so the primary index is built bottom-up in O(N) (plus a sort\n * when `rows` are not already in primary key order) rather than doing one\n * tree insert, and one trip through the push machinery, per row.\n *\n * `rows` may be sorted in place. Rows must have distinct primary keys.\n */\n pushAdds(rows: Row[]): void {\n const index = this.#getPrimaryIndex();\n const canBulkLoad =\n this.#connections.length === 0 &&\n this.#indexes.size === 1 &&\n index.data.size === 0;\n if (!canBulkLoad) {\n for (const row of rows) {\n consume(this.push(makeSourceChangeAdd(row)));\n }\n return;\n }\n const {comparator} = index;\n // The check is not redundant with the sort. V8's TimSort is O(N) on sorted\n // input but Hermes' sort is not adaptive: always sorting doubled the load\n // time of an already ordered 180k row replica on Android (343ms -> 672ms).\n const sorted = isAscending(rows, comparator)\n ? rows\n : (sortedByStringKey(rows, this.#primaryKey) ?? rows.sort(comparator));\n index.data = BTreeSet.fromSorted(comparator, sorted);\n }\n\n *push(change: SourceChange): Stream<'yield'> {\n for (const result of this.genPush(change)) {\n if (result === 'yield') {\n yield result;\n }\n }\n }\n\n genPush(change: SourceChange) {\n const primaryIndex = this.#getPrimaryIndex();\n const {data} = primaryIndex;\n const exists = (row: Row) => data.has(row);\n const setOverlay = (o: Overlay | undefined) => (this.#overlay = o);\n const writeChange = (c: SourceChange) => this.#writeChange(c);\n return genPushAndWriteWithSplitEdit(\n this.#connections,\n change,\n exists,\n setOverlay,\n writeChange,\n () => ++this.#pushEpoch,\n );\n }\n\n #writeChange(change: SourceChange) {\n for (const {data} of this.#indexes.values()) {\n switch (change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD: {\n const added = data.add(change[SourceChangeIndex.ROW]);\n // must succeed since we checked has() above.\n assert(\n added,\n 'MemorySource: add must succeed since row existence was already checked',\n );\n break;\n }\n case ChangeType.REMOVE: {\n const removed = data.delete(change[SourceChangeIndex.ROW]);\n // must succeed since we checked has() above.\n assert(\n removed,\n 'MemorySource: remove must succeed since row existence was already checked',\n );\n break;\n }\n case ChangeType.EDIT: {\n // TODO: We could see if the PK (form the index tree's perspective)\n // changed and if not we could use set.\n // We cannot just do `set` with the new value since the `oldRow` might\n // not map to the same entry as the new `row` in the index btree.\n const removed = data.delete(change[SourceChangeIndex.OLD_ROW]);\n // must succeed since we checked has() above.\n assert(\n removed,\n 'MemorySource: edit remove must succeed since row existence was already checked',\n );\n data.add(change[SourceChangeIndex.ROW]);\n break;\n }\n default:\n unreachable(change);\n }\n }\n }\n}\n\nfunction mergePredicates(\n connPredicate: ((row: Row) => boolean) | undefined,\n reqFilter: NoSubqueryCondition | undefined,\n): ((row: Row) => boolean) | undefined {\n if (!reqFilter) {\n return connPredicate;\n }\n const reqPredicate = createPredicate(reqFilter);\n if (!connPredicate) {\n return reqPredicate;\n }\n return row => connPredicate(row) && reqPredicate(row);\n}\n\nfunction* generateWithConstraint(\n it: Stream<Node>,\n constraint: Constraint | undefined,\n) {\n for (const node of it) {\n if (constraint && !constraintMatchesRow(constraint, node.row)) {\n break;\n }\n yield node;\n }\n}\n\nfunction* generateWithFilter(it: Stream<Node>, filter: (row: Row) => boolean) {\n for (const node of it) {\n if (filter(node.row)) {\n yield node;\n }\n }\n}\n\nexport function* genPushAndWriteWithSplitEdit(\n connections: readonly Connection[],\n change: SourceChange,\n exists: ((row: Row) => boolean) | undefined,\n setOverlay: (o: Overlay | undefined) => Overlay | undefined,\n writeChange: (c: SourceChange) => void,\n getNextEpoch: () => number,\n) {\n let shouldSplitEdit = false;\n if (change[SourceChangeIndex.TYPE] === ChangeType.EDIT) {\n for (const {splitEditKeys} of connections) {\n if (splitEditKeys) {\n for (const key of splitEditKeys) {\n if (\n !valuesEqual(\n change[SourceChangeIndex.ROW][key],\n change[SourceChangeIndex.OLD_ROW][key],\n )\n ) {\n shouldSplitEdit = true;\n break;\n }\n }\n }\n }\n }\n\n if (change[SourceChangeIndex.TYPE] === ChangeType.EDIT && shouldSplitEdit) {\n yield* genPushAndWrite(\n connections,\n makeSourceChangeRemove(change[SourceChangeIndex.OLD_ROW]),\n exists,\n setOverlay,\n writeChange,\n getNextEpoch(),\n );\n yield* genPushAndWrite(\n connections,\n makeSourceChangeAdd(change[SourceChangeIndex.ROW]),\n exists,\n setOverlay,\n writeChange,\n getNextEpoch(),\n );\n } else {\n yield* genPushAndWrite(\n connections,\n change,\n exists,\n setOverlay,\n writeChange,\n getNextEpoch(),\n );\n }\n}\n\nfunction* genPushAndWrite(\n connections: readonly Connection[],\n change: SourceChangeAdd | SourceChangeRemove | SourceChangeEdit,\n exists: ((row: Row) => boolean) | undefined,\n setOverlay: (o: Overlay | undefined) => Overlay | undefined,\n writeChange: (c: SourceChange) => void,\n pushEpoch: number,\n) {\n for (const x of genPush(connections, change, exists, setOverlay, pushEpoch)) {\n yield x;\n }\n writeChange(change);\n}\n\nfunction* genPush(\n connections: readonly Connection[],\n change: SourceChange,\n exists: ((row: Row) => boolean) | undefined,\n setOverlay: (o: Overlay | undefined) => void,\n pushEpoch: number,\n) {\n if (exists) {\n switch (change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n assert(\n !exists(change[SourceChangeIndex.ROW]),\n () => `Row already exists ${stringify(change)}`,\n );\n break;\n case ChangeType.REMOVE:\n assert(\n exists(change[SourceChangeIndex.ROW]),\n () => `Row not found ${stringify(change)}`,\n );\n break;\n case ChangeType.EDIT:\n assert(\n exists(change[SourceChangeIndex.OLD_ROW]),\n () => `Row not found ${stringify(change)}`,\n );\n break;\n default:\n unreachable(change);\n }\n }\n\n setOverlay({epoch: pushEpoch, change});\n try {\n for (const conn of connections) {\n const {output, filters, input} = conn;\n if (output) {\n conn.lastPushedEpoch = pushEpoch;\n const outputChange: Change =\n change[SourceChangeIndex.TYPE] === ChangeType.EDIT\n ? makeEditChange(\n {row: change[SourceChangeIndex.ROW], relationships: {}},\n {row: change[SourceChangeIndex.OLD_ROW], relationships: {}},\n )\n : change[SourceChangeIndex.TYPE] === ChangeType.ADD\n ? makeAddChange({\n row: change[SourceChangeIndex.ROW],\n relationships: {},\n })\n : makeRemoveChange({\n row: change[SourceChangeIndex.ROW],\n relationships: {},\n });\n yield* filterPush(outputChange, output, input, filters?.predicate);\n yield undefined;\n }\n }\n\n for (const conn of connections) {\n const {output, input} = conn;\n if (output?.reconcile) {\n yield* output.reconcile(input);\n yield undefined;\n }\n }\n } finally {\n setOverlay(undefined);\n }\n}\n\nexport function* generateWithStart(\n nodes: Iterable<Node | 'yield'>,\n start: Start | undefined,\n compare: (r1: Row, r2: Row) => number,\n): Stream<Node | 'yield'> {\n if (!start) {\n yield* nodes;\n return;\n }\n let started = false;\n for (const node of nodes) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n if (!started) {\n if (start.basis === 'at') {\n if (compare(node.row, start.row) >= 0) {\n started = true;\n }\n } else if (start.basis === 'after') {\n if (compare(node.row, start.row) > 0) {\n started = true;\n }\n }\n }\n if (started) {\n yield node;\n }\n }\n}\n\n/**\n * Takes an iterator and overlay.\n * Splices the overlay into the iterator at the correct position.\n *\n * @param startAt - if there is a lower bound to the stream. If the lower bound of the stream\n * is above the overlay, the overlay will be skipped.\n * @param rows - the stream into which the overlay should be spliced\n * @param constraint - constraint that was applied to the rowIterator and should\n * also be applied to the overlay.\n * @param overlay - the overlay values to splice in\n * @param compare - the comparator to use to find the position for the overlay.\n * Must order rows the same way `rows` is ordered. For `MemorySource` that is\n * *index* order, which leads with the constraint keys.\n * @param startAtCompare - the comparator for `startAt`, which is a bound in the\n * *connection's* sort order. Only the same as `compare` when the stream's order\n * happens to be the connection's -- true for `TableSource` (SQL does the\n * ordering) but not for a constrained `MemorySource` fetch. Conflating the two\n * is what #4926 fixed for `generateWithStart`; this parameter is the same\n * distinction for the overlay's own `startAt` pruning.\n */\nexport function generateWithOverlay(\n startAt: Row | undefined,\n rows: Iterable<Row>,\n constraint: Constraint | undefined,\n overlay: Overlay | undefined,\n lastPushedEpoch: number,\n compare: Comparator,\n startAtCompare: Comparator,\n filterPredicate?: (row: Row) => boolean | undefined,\n multiConstraints?: readonly MultiConstraint[],\n) {\n let overlayToApply: Overlay | undefined = undefined;\n if (overlay && lastPushedEpoch >= overlay.epoch) {\n overlayToApply = overlay;\n }\n const overlays = computeOverlays(\n startAt,\n constraint,\n overlayToApply,\n startAtCompare,\n filterPredicate,\n multiConstraints,\n );\n return generateWithOverlayInner(rows, overlays, compare);\n}\n\nfunction computeOverlays(\n startAt: Row | undefined,\n constraint: Constraint | undefined,\n overlay: Overlay | undefined,\n // Only ever used for `overlaysForStartAt`, so this is the *connection*-order\n // comparator, not the one used to splice the overlay into the row stream.\n startAtCompare: Comparator,\n filterPredicate?: (row: Row) => boolean | undefined,\n multiConstraints?: readonly MultiConstraint[],\n): Overlays {\n let overlays: Overlays = {\n add: undefined,\n remove: undefined,\n };\n switch (overlay?.change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n overlays = {\n add: overlay.change[SourceChangeIndex.ROW],\n remove: undefined,\n };\n break;\n case ChangeType.REMOVE:\n overlays = {\n add: undefined,\n remove: overlay.change[SourceChangeIndex.ROW],\n };\n break;\n case ChangeType.EDIT:\n overlays = {\n add: overlay.change[SourceChangeIndex.ROW],\n remove: overlay.change[SourceChangeIndex.OLD_ROW],\n };\n break;\n }\n\n if (startAt) {\n overlays = overlaysForStartAt(overlays, startAt, startAtCompare);\n }\n\n if (constraint) {\n overlays = overlaysForConstraint(overlays, constraint);\n }\n\n overlays = applyMultiConstraintsToOverlays(overlays, multiConstraints);\n\n if (filterPredicate) {\n overlays = overlaysForFilterPredicate(overlays, filterPredicate);\n }\n\n return overlays;\n}\n\nfunction applyMultiConstraintsToOverlays(\n overlays: Overlays,\n multiConstraints: readonly MultiConstraint[] | undefined,\n): Overlays {\n if (!multiConstraints) return overlays;\n for (const mc of multiConstraints) {\n if (mc.length > 0) {\n overlays = overlaysForMultiConstraint(overlays, mc);\n }\n }\n return overlays;\n}\n\nexport {overlaysForMultiConstraint as overlaysForMultiConstraintForTest};\n\nfunction overlaysForMultiConstraint(\n {add, remove}: Overlays,\n multiConstraint: MultiConstraint,\n): Overlays {\n const matchesAny = (row: Row | undefined) => {\n if (row === undefined) return false;\n for (const c of multiConstraint) {\n if (constraintMatchesRow(c, row)) return true;\n }\n return false;\n };\n return {\n add: matchesAny(add) ? add : undefined,\n remove: matchesAny(remove) ? remove : undefined,\n };\n}\n\nexport {overlaysForStartAt as overlaysForStartAtForTest};\n\nfunction overlaysForStartAt(\n {add, remove}: Overlays,\n startAt: Row,\n compare: Comparator,\n): Overlays {\n const undefinedIfBeforeStartAt = (row: Row | undefined) =>\n row === undefined || compare(row, startAt) < 0 ? undefined : row;\n return {\n add: undefinedIfBeforeStartAt(add),\n remove: undefinedIfBeforeStartAt(remove),\n };\n}\n\nexport {overlaysForConstraint as overlaysForConstraintForTest};\n\nfunction overlaysForConstraint(\n {add, remove}: Overlays,\n constraint: Constraint,\n): Overlays {\n const undefinedIfDoesntMatchConstraint = (row: Row | undefined) =>\n row === undefined || !constraintMatchesRow(constraint, row)\n ? undefined\n : row;\n\n return {\n add: undefinedIfDoesntMatchConstraint(add),\n remove: undefinedIfDoesntMatchConstraint(remove),\n };\n}\n\nfunction overlaysForFilterPredicate(\n {add, remove}: Overlays,\n filterPredicate: (row: Row) => boolean | undefined,\n): Overlays {\n const undefinedIfDoesntMatchFilter = (row: Row | undefined) =>\n row === undefined || !filterPredicate(row) ? undefined : row;\n\n return {\n add: undefinedIfDoesntMatchFilter(add),\n remove: undefinedIfDoesntMatchFilter(remove),\n };\n}\n\nexport function* generateWithOverlayInner(\n rowIterator: Iterable<Row>,\n overlays: Overlays,\n compare: (r1: Row, r2: Row) => number,\n) {\n let addOverlayYielded = false;\n let removeOverlaySkipped = false;\n for (const row of rowIterator) {\n if (!addOverlayYielded && overlays.add) {\n const cmp = compare(overlays.add, row);\n if (cmp < 0) {\n addOverlayYielded = true;\n yield {row: overlays.add, relationships: {}};\n }\n }\n\n if (!removeOverlaySkipped && overlays.remove) {\n const cmp = compare(overlays.remove, row);\n if (cmp === 0) {\n removeOverlaySkipped = true;\n continue;\n }\n }\n yield {row, relationships: {}};\n }\n\n if (!addOverlayYielded && overlays.add) {\n yield {row: overlays.add, relationships: {}};\n }\n}\n\n/**\n * Like {@link generateWithOverlay} but for unordered streams.\n * No `startAt` or comparator needed. Injects remove/old-edit rows eagerly\n * at the start, and suppresses add/new-edit rows inline by PK match.\n */\nexport function generateWithOverlayUnordered(\n rows: Iterable<Row>,\n constraint: Constraint | undefined,\n overlay: Overlay | undefined,\n lastPushedEpoch: number,\n primaryKey: PrimaryKey,\n filterPredicate?: (row: Row) => boolean,\n multiConstraints?: readonly MultiConstraint[],\n) {\n let overlayToApply: Overlay | undefined = undefined;\n if (overlay && lastPushedEpoch >= overlay.epoch) {\n overlayToApply = overlay;\n }\n let overlays: Overlays = {add: undefined, remove: undefined};\n switch (overlayToApply?.change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n overlays = {\n add: overlayToApply.change[SourceChangeIndex.ROW],\n remove: undefined,\n };\n break;\n case ChangeType.REMOVE:\n overlays = {\n add: undefined,\n remove: overlayToApply.change[SourceChangeIndex.ROW],\n };\n break;\n case ChangeType.EDIT:\n overlays = {\n add: overlayToApply.change[SourceChangeIndex.ROW],\n remove: overlayToApply.change[SourceChangeIndex.OLD_ROW],\n };\n break;\n }\n if (constraint) {\n overlays = overlaysForConstraint(overlays, constraint);\n }\n overlays = applyMultiConstraintsToOverlays(overlays, multiConstraints);\n if (filterPredicate) {\n overlays = overlaysForFilterPredicate(overlays, filterPredicate);\n }\n return generateWithOverlayInnerUnordered(rows, overlays, primaryKey);\n}\n\nexport function* generateWithOverlayInnerUnordered(\n rowIterator: Iterable<Row>,\n overlays: Overlays,\n primaryKey: PrimaryKey,\n) {\n // Eager inject: yield the add overlay at the start (row not yet in storage)\n if (overlays.add) {\n yield {row: overlays.add, relationships: {}};\n }\n // Stream with inline suppress: skip the remove overlay (row still in storage)\n let removeSkipped = false;\n for (const row of rowIterator) {\n if (\n !removeSkipped &&\n overlays.remove &&\n rowMatchesPK(overlays.remove, row, primaryKey)\n ) {\n removeSkipped = true;\n continue;\n }\n yield {row, relationships: {}};\n }\n}\n\nfunction rowMatchesPK(a: Row, b: Row, primaryKey: PrimaryKey): boolean {\n for (const key of primaryKey) {\n if (!valuesEqual(a[key], b[key])) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * A location to begin scanning an index from. Can either be a specific value\n * or the min or max possible value for the type. This is used to start a scan\n * at the beginning of the rows matching a constraint.\n */\ntype Bound = Value | MinValue | MaxValue;\nexport type RowBound = Record<string, Bound>;\nexport const minValue = Symbol('min-value');\ntype MinValue = typeof minValue;\nexport const maxValue = Symbol('max-value');\ntype MaxValue = typeof maxValue;\n\nfunction isAscending(rows: Row[], comparator: Comparator): boolean {\n for (let i = 1; i < rows.length; i++) {\n if (comparator(rows[i - 1], rows[i]) > 0) {\n return false;\n }\n }\n return true;\n}\n\n// A string that sorts the same by UTF-16 code unit as it does by UTF-8 byte,\n// and that can be joined with U+0000, holds neither a surrogate nor U+0000.\nconst notJoinableRe = /[\\0\\ud800-\\udfff]/;\n\n/**\n * `rows` in primary key order without calling a comparator, for a key whose\n * columns all hold strings. Returns `undefined`, leaving `rows` untouched, when\n * a key value is not a string or cannot be ordered this way.\n *\n * Rows whose key is not their order in the replica (a compound key is stored\n * under a hash) reach `pushAdds` shuffled, so they get a full sort, and a\n * comparator sort calls back into JS for each of its N log N comparisons. On\n * Hermes that was 204ms for 60,000 rows with a two-column key. Sorting one\n * joined string per row with the engine's own string comparison takes 64ms\n * there, and the same as the comparator sort on V8 (33ms).\n *\n * The row's position rides at the end of its string. It never decides the\n * order, because primary keys are distinct.\n */\nfunction sortedByStringKey(\n rows: readonly Row[],\n key: PrimaryKey,\n): Row[] | undefined {\n const joined: string[] = [];\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n let s = '';\n for (let c = 0; c < key.length; c++) {\n const v = row[key[c]];\n if (typeof v !== 'string' || notJoinableRe.test(v)) {\n return undefined;\n }\n s += v + '\\0';\n }\n joined.push(s + i);\n }\n joined.sort();\n const sorted: Row[] = [];\n for (let i = 0; i < joined.length; i++) {\n const s = joined[i];\n sorted.push(rows[Number(s.slice(s.lastIndexOf('\\0') + 1))]);\n }\n return sorted;\n}\n\nexport function makeBoundComparator(sort: Ordering): Comparator {\n // Pre-extract the first two keys/directions to avoid per-call array access.\n // All paths share one function literal (single SFI) so the BTree comparator call site\n // stays monomorphic across indexes with different sort orderings, preventing V8 IC deopt.\n // Even a 2-SFI split (e.g. separate len=1 path) creates a polymorphic IC that\n // measurably regresses performance, so we keep a single return body.\n const len = sort.length;\n const k0 = sort[0][0];\n const a0 = sort[0][1] === 'asc';\n const k1 = len > 1 ? sort[1][0] : '';\n const a1 = len > 1 ? sort[1][1] === 'asc' : true;\n\n return (a: RowBound, b: RowBound) => {\n const c0 = a0 ? compareBounds(a[k0], b[k0]) : compareBounds(b[k0], a[k0]);\n if (len === 1 || c0 !== 0) return c0;\n const c1 = a1 ? compareBounds(a[k1], b[k1]) : compareBounds(b[k1], a[k1]);\n if (len === 2 || c1 !== 0) return c1;\n // Hot! Do not use destructuring\n for (let i = 2; i < len; i++) {\n const cmp = compareBounds(a[sort[i][0]], b[sort[i][0]]);\n if (cmp !== 0) return sort[i][1] === 'asc' ? cmp : -cmp;\n }\n return 0;\n };\n}\n\nfunction compareBounds(a: Bound, b: Bound): number {\n if (a === b) {\n return 0;\n }\n // Use typeof to guard the Symbol sentinel checks first. This gives V8 a\n // clear type discriminant so the common non-symbol path compiles as a\n // specialised numeric/string fast-path without a Smi deopt when the\n // minValue/maxValue sentinel symbols appear.\n if (typeof a === 'symbol') {\n return a === minValue ? -1 : 1;\n }\n if (typeof b === 'symbol') {\n return b === minValue ? 1 : -1;\n }\n return compareValues(a, b);\n}\n\nexport function generateRows(\n data: BTreeSet<Row>,\n scanStart: RowBound | undefined,\n reverse: boolean | undefined,\n) {\n return reverse\n ? data.valuesFromReversed(scanStart as Row | undefined)\n : data.valuesFrom(scanStart as Row | undefined);\n}\n\nfunction stringify(change: SourceChange) {\n return JSON.stringify(change, (_, v) =>\n typeof v === 'bigint' ? v.toString() : v,\n );\n}\n\n/**\n * N-way merge of pre-sorted Node streams. Each input stream must yield\n * Nodes in `compare` order (and may interleave 'yield' values, which are\n * forwarded as-is). The merged stream yields Nodes in `compare` order.\n *\n * Implemented as a binary min-heap keyed by `compare(entry.row, ...)`, so\n * each emit costs O(log K) (K = number of streams) rather than the O(K)\n * a linear-scan-of-heads merge would. Matters when FlippedJoin chunks a\n * large `multiConstraints` IN-list into hundreds of sub-fetches.\n *\n * If the merged stream is closed early (e.g. downstream `Take` `break`s\n * after hitting its limit, prompting JS to call `.return()` on this\n * generator), the `finally` block propagates `.return()` to each\n * non-exhausted sub-iterator so the underlying sources (SQLite cursors,\n * etc.) can run their cleanup. Without this, mid-merge early-termination\n * leaves cursors open, causing later writes on the same connection to\n * fail with \"database connection is busy executing a query\".\n */\nexport function* mergeSortedStreams(\n streams: readonly Stream<Node | 'yield'>[],\n compare: (a: Node, b: Node) => number,\n): Stream<Node | 'yield'> {\n const iterators: Iterator<Node | 'yield'>[] = streams.map(s =>\n s[Symbol.iterator](),\n );\n // True while iterators[i] hasn't yet returned `done`. The finally\n // block uses this to skip already-exhausted streams when propagating\n // `.return()`.\n const active = Array.from({length: iterators.length}).fill(true) as boolean[];\n\n // Min-heap of entries; `idx` tells us which stream to refill from\n // after the entry's row is emitted.\n type Entry = {row: Node; idx: number};\n const heap: Entry[] = [];\n\n const siftUp = (start: number) => {\n let i = start;\n while (i > 0) {\n const p = (i - 1) >> 1;\n if (compare(heap[i].row, heap[p].row) >= 0) return;\n const t = heap[i];\n heap[i] = heap[p];\n heap[p] = t;\n i = p;\n }\n };\n\n const siftDown = (start: number) => {\n let i = start;\n const n = heap.length;\n while (true) {\n const l = (i << 1) + 1;\n const r = l + 1;\n let smallest = i;\n if (l < n && compare(heap[l].row, heap[smallest].row) < 0) smallest = l;\n if (r < n && compare(heap[r].row, heap[smallest].row) < 0) smallest = r;\n if (smallest === i) return;\n const t = heap[i];\n heap[i] = heap[smallest];\n heap[smallest] = t;\n i = smallest;\n }\n };\n\n // Pull the next Node from iterator `idx`, forwarding any 'yield's.\n // Returns the Node, or `undefined` once the stream is exhausted.\n const pullNext = function* (\n idx: number,\n ): IterableIterator<'yield', Node | undefined, undefined> {\n while (true) {\n const r = iterators[idx].next();\n if (r.done) {\n active[idx] = false;\n return undefined;\n }\n if (r.value === 'yield') {\n yield 'yield';\n continue;\n }\n return r.value;\n }\n };\n\n try {\n // Prime: push the first row of each non-empty stream onto the heap.\n for (let i = 0; i < iterators.length; i++) {\n const row = yield* pullNext(i);\n if (row !== undefined) {\n heap.push({row, idx: i});\n siftUp(heap.length - 1);\n }\n }\n\n while (heap.length > 0) {\n // Root is the global min across all active streams.\n const top = heap[0];\n yield top.row;\n const next = yield* pullNext(top.idx);\n if (next !== undefined) {\n // Refill root in place (top === heap[0]) and sift down. The\n // already-yielded `top.row` value is captured by the yield, so\n // mutating it here doesn't affect what was emitted.\n top.row = next;\n siftDown(0);\n } else {\n // Stream exhausted. Move tail to root and shrink. Pop returns\n // the last entry; if the heap had only one entry it was the\n // root we just yielded, so we just leave the heap empty.\n const last = must(heap.pop());\n if (heap.length > 0) {\n heap[0] = last;\n siftDown(0);\n }\n }\n }\n } finally {\n // Close any iterators that aren't already exhausted so their\n // `finally` blocks (which release cursors / cached statements) run.\n for (let i = 0; i < iterators.length; i++) {\n if (active[i]) {\n iterators[i].return?.();\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqGA,IAAa,eAAb,MAAa,aAA+B;CAC1C;CACA;CACA;CACA;CACA,2BAAwC,IAAI,IAAI;CAChD,eAAsC,CAAC;CAEvC;CACA,aAAa;CAEb,YACE,WACA,SACA,YACA,kBACA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IAAI,GAAG,WAAW;GACtE,IAAI,IAAI,KAAK,QAAQ,KAAK,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,GAAG,IAAI,GAAG,WAAW;GACtE,IAAI,aAAa,GAAG;GACpB,MAAM,IAAI,KAAK;GACf,KAAK,KAAK,KAAK;GACf,KAAK,YAAY;GACjB,IAAI;EACN;CACF;CAIA,MAAM,WAAW,WACf,KACwD;EACxD,OAAO,MAAM;GACX,MAAM,IAAI,UAAU,IAAI,CAAC,KAAK;GAC9B,IAAI,EAAE,MAAM;IACV,OAAO,OAAO;IACd;GACF;GACA,IAAI,EAAE,UAAU,SAAS;IACvB,MAAM;IACN;GACF;GACA,OAAO,EAAE;EACX;CACF;CAEA,IAAI;EAEF,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;GACzC,MAAM,MAAM,OAAO,SAAS,CAAC;GAC7B,IAAI,QAAQ,KAAA,GAAW;IACrB,KAAK,KAAK;KAAC;KAAK,KAAK;IAAC,CAAC;IACvB,OAAO,KAAK,SAAS,CAAC;GACxB;EACF;EAEA,OAAO,KAAK,SAAS,GAAG;GAEtB,MAAM,MAAM,KAAK;GACjB,MAAM,IAAI;GACV,MAAM,OAAO,OAAO,SAAS,IAAI,GAAG;GACpC,IAAI,SAAS,KAAA,GAAW;IAItB,IAAI,MAAM;IACV,SAAS,CAAC;GACZ,OAAO;IAIL,MAAM,OAAO,KAAK,KAAK,IAAI,CAAC;IAC5B,IAAI,KAAK,SAAS,GAAG;KACnB,KAAK,KAAK;KACV,SAAS,CAAC;IACZ;GACF;EACF;CACF,UAAU;EAGR,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KACpC,IAAI,OAAO,IACT,UAAU,EAAE,CAAC,SAAS;CAG5B;AACF"}
1
+ {"version":3,"file":"memory-source.js","names":[],"sources":["../../../../../zql/src/ivm/memory-source.ts"],"sourcesContent":["import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {BTreeSet} from '../../../shared/src/btree-set.ts';\nimport {hasOwn} from '../../../shared/src/has-own.ts';\nimport {once} from '../../../shared/src/iterables.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {\n nativeSortIsAdaptive,\n sortByNaturalRuns,\n} from '../../../shared/src/natural-runs.ts';\nimport {assignProperty} from '../../../shared/src/objects.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {\n Condition,\n Ordering,\n OrderPart,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport type {SchemaValue} from '../../../zero-types/src/schema-value.ts';\nimport type {DebugDelegate} from '../builder/debug-delegate.ts';\nimport {\n createPredicate,\n transformFilters,\n type NoSubqueryCondition,\n} from '../builder/filter.ts';\nimport {assertOrderingIncludesPK} from '../query/complete-ordering.ts';\nimport {ChangeType} from './change-type.ts';\nimport type {Change} from './change.ts';\nimport {makeAddChange, makeEditChange, makeRemoveChange} from './change.ts';\nimport {\n constraintMatchesPrimaryKey,\n constraintMatchesRow,\n primaryKeyConstraintFromFilters,\n type Constraint,\n} from './constraint.ts';\nimport {\n compareValues,\n makeComparator,\n valuesEqual,\n type Comparator,\n type Node,\n} from './data.ts';\nimport {filterPush} from './filter-push.ts';\nimport {\n skipYields,\n type FetchRequest,\n type Input,\n type MultiConstraint,\n type Output,\n type Start,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {SourceChangeIndex} from './source-change-index.ts';\nimport type {\n Source,\n SourceChange,\n SourceChangeAdd,\n SourceChangeEdit,\n SourceChangeRemove,\n SourceInput,\n} from './source.ts';\nimport {makeSourceChangeAdd, makeSourceChangeRemove} from './source.ts';\nimport {\n andFinally,\n andThen,\n consume,\n doneResult,\n eachStream,\n type Stream,\n} from './stream.ts';\n\nexport type Overlay = {\n epoch: number;\n change: SourceChange;\n};\n\nexport type Overlays = {\n add: Row | undefined;\n remove: Row | undefined;\n};\n\ntype Index = {\n comparator: Comparator;\n data: BTreeSet<Row>;\n};\n\nexport type Connection = {\n input: Input;\n output: Output | undefined;\n sort?: Ordering | undefined;\n splitEditKeys: Set<string> | undefined;\n compareRows: Comparator;\n filters:\n | {\n condition: NoSubqueryCondition;\n predicate: (row: Row) => boolean;\n }\n | undefined;\n readonly debug?: DebugDelegate | undefined;\n lastPushedEpoch: number;\n};\n\n/**\n * A `MemorySource` is a source that provides data to the pipeline from an\n * in-memory data source.\n *\n * This data is kept in sorted order as downstream pipelines will always expect\n * the data they receive from `pull` to be in sorted order.\n */\nexport class MemorySource implements Source {\n readonly #tableName: string;\n readonly #columns: Record<string, SchemaValue>;\n readonly #primaryKey: PrimaryKey;\n readonly #primaryIndexSort: Ordering;\n readonly #indexes: Map<string, Index> = new Map();\n readonly #connections: Connection[] = [];\n\n #overlay: Overlay | undefined;\n #pushEpoch = 0;\n\n constructor(\n tableName: string,\n columns: Record<string, SchemaValue>,\n primaryKey: PrimaryKey,\n primaryIndexData?: BTreeSet<Row>,\n ) {\n this.#tableName = tableName;\n this.#columns = columns;\n this.#primaryKey = primaryKey;\n this.#primaryIndexSort = primaryKey.map(k => [k, 'asc']);\n const comparator = makeBoundComparator(this.#primaryIndexSort);\n this.#indexes.set(JSON.stringify(this.#primaryIndexSort), {\n comparator,\n data: primaryIndexData ?? new BTreeSet<Row>(comparator),\n });\n }\n\n get tableSchema() {\n return {\n name: this.#tableName,\n columns: this.#columns,\n primaryKey: this.#primaryKey,\n };\n }\n\n fork() {\n const primaryIndex = this.#getPrimaryIndex();\n return new MemorySource(\n this.#tableName,\n this.#columns,\n this.#primaryKey,\n primaryIndex.data.clone(),\n );\n }\n\n get data(): BTreeSet<Row> {\n return this.#getPrimaryIndex().data;\n }\n\n /** Whether any input is connected to this source. */\n get connected(): boolean {\n return this.#connections.length > 0;\n }\n\n #getSchema(connection: Connection, unordered: boolean): SourceSchema {\n return {\n tableName: this.#tableName,\n columns: this.#columns,\n primaryKey: this.#primaryKey,\n sort: unordered ? undefined : connection.sort,\n system: 'client',\n relationships: {},\n isHidden: false,\n compareRows: connection.compareRows,\n };\n }\n\n connect(\n sort: Ordering | undefined,\n filters?: Condition,\n splitEditKeys?: Set<string>,\n ): SourceInput {\n const transformedFilters = transformFilters(filters);\n const unordered = sort === undefined;\n const internalSort = sort ?? this.#primaryIndexSort;\n\n const input: SourceInput = {\n getSchema: () => schema,\n fetch: req => this.#fetch(req, connection),\n setOutput: output => {\n connection.output = output;\n },\n destroy: () => {\n this.#disconnect(input);\n },\n fullyAppliedFilters: !transformedFilters.conditionsRemoved,\n };\n\n const connection: Connection = {\n input,\n output: undefined,\n sort: internalSort,\n splitEditKeys,\n compareRows: makeComparator(internalSort),\n filters: transformedFilters.filters\n ? {\n condition: transformedFilters.filters,\n predicate: createPredicate(transformedFilters.filters),\n }\n : undefined,\n lastPushedEpoch: 0,\n };\n const schema = this.#getSchema(connection, unordered);\n if (!unordered) {\n assertOrderingIncludesPK(internalSort, this.#primaryKey);\n }\n this.#connections.push(connection);\n return input;\n }\n\n #disconnect(input: Input): void {\n const idx = this.#connections.findIndex(c => c.input === input);\n assert(idx !== -1, 'Connection not found');\n this.#connections.splice(idx, 1);\n\n // Indexes deliberately hold no reference back to the connections that use\n // them. They used to, to support deleting an index once its last user went\n // away. That deletion is gone (see below) but the `usedBy` set outlived it,\n // so an index kept every `Connection` — and through its `input` and\n // `output`, the whole torn-down pipeline — reachable for as long as the\n // source lived.\n //\n // TODO: We used to delete unused indexes here. But in common cases like\n // navigating into issue detail pages it caused a ton of constantly\n // building and destroying indexes.\n //\n // Perhaps some intelligent LRU or something is needed here but for now,\n // the opposite extreme of keeping all indexes for the lifetime of the\n // page seems better.\n }\n\n #getPrimaryIndex(): Index {\n const index = this.#indexes.get(JSON.stringify(this.#primaryIndexSort));\n assert(index, 'Primary index not found');\n return index;\n }\n\n #getOrCreateIndex(sort: Ordering): Index {\n const key = JSON.stringify(sort);\n const index = this.#indexes.get(key);\n // Future optimization could use existing index if it's the same just sorted\n // in reverse of needed.\n if (index) {\n return index;\n }\n\n const comparator = makeBoundComparator(sort);\n\n // When creating these synchronously becomes a problem, a few options:\n // 1. Allow users to specify needed indexes up front\n // 2. Create indexes in a different thread asynchronously (this would require\n // modifying the BTree to be able to be passed over structured-clone, or using\n // a different library.)\n // 3. We could even theoretically do (2) on multiple threads and then merge the\n // results!\n // `toArray` rather than spreading the tree: the iterator costs about\n // 0.5us/row on Hermes, and this materialization is what is left in this\n // function now that the sort is often skipped outright. The array is ours,\n // so the paths below may reorder it in place.\n const rows = this.#getPrimaryIndex().data.toArray();\n\n // Three ways to get the rows into the new index's order, cheapest first.\n //\n // Natural-run merging leads where it can win at all -- which is only where\n // the engine's own sort is not adaptive, since on V8 it already walks\n // ordered input in one pass and a JS pass over the same rows is strictly\n // worse. It is the only one of the three that can be O(N),\n // and because it hits more often than it looks: rows arrive here in\n // primary-key order, and a secondary sort key is usually a timestamp or\n // sequence number that moves with insertion order, so the input is often\n // already sorted, exactly reversed, or a few ordered batches. It declines\n // cheaply -- bounded by `maxRuns` comparisons -- and leaves `rows`\n // untouched when it does.\n //\n // The numeric path is next: it cannot reach O(N), but it beats a general\n // comparator sort on the shape it covers. The plain sort is the floor.\n const sorted =\n (nativeSortIsAdaptive()\n ? undefined\n : sortByNaturalRuns(rows, comparator)) ??\n this.#sortedByLeadingNumberColumn(sort, rows) ??\n rows.sort(comparator);\n const data = BTreeSet.fromSorted(comparator, sorted);\n\n const newIndex = {comparator, data};\n this.#indexes.set(key, newIndex);\n return newIndex;\n }\n\n /**\n * The rows for a new index, sorted without calling a row comparator once, for\n * the shape that dominates: one numeric column followed by the primary key.\n *\n * `#getOrCreateIndex` otherwise sorts every row through\n * `makeBoundComparator`, which reads its columns through variable keys and\n * compares two of them. On Hermes that one sort was 38ms of a 91ms cold-start\n * hydration -- 77% of the index build -- because an interpreter pays for the\n * dynamic property reads and the closure indirection that V8's JIT removes.\n *\n * Two observations collapse it. First, the trailing primary key never needs to\n * be compared: the input is the primary index, so it already arrives in\n * primary-key order, and `Array.prototype.sort` has been stable since ES2019,\n * so ties keep that order -- which is exactly what comparing the ascending\n * primary key would produce. Second, with only one key left, the sort can\n * decorate: extract the column once per row and sort an index array on\n * primitive subtraction, trading N*logN property reads for N.\n *\n * Measured over a 20,000-row cold start: the sort goes from 38.2ms to 17.0ms\n * on Hermes (2.25x) and 1.14x on V8, taking the whole hydration of one\n * `where` + `orderBy` query from 91ms to 70ms on Hermes. Returns `undefined`\n * when the shape does not apply, and the caller falls back to the general\n * sort.\n */\n #sortedByLeadingNumberColumn(\n sort: Ordering,\n rows: readonly Row[],\n ): Row[] | undefined {\n const pk = this.#primaryIndexSort;\n // One leading column, then exactly the primary key ascending.\n if (sort.length !== pk.length + 1) {\n return undefined;\n }\n for (let i = 0; i < pk.length; i++) {\n if (sort[i + 1][0] !== pk[i][0] || sort[i + 1][1] !== pk[i][1]) {\n return undefined;\n }\n }\n const [column, direction] = sort[0];\n // Numbers only: this orders by subtraction, which strings and booleans do\n // not. Widening to strings would mean `compareUTF8` per comparison, a\n // smaller win worth measuring separately.\n if (this.#columns[column]?.type !== 'number') {\n return undefined;\n }\n\n const n = rows.length;\n // Pre-sized deliberately: these are filled by index immediately below, and\n // `Array.from({length: n})` would allocate and then fill them twice.\n // oxlint-disable-next-line unicorn/no-new-array\n const keys = new Array<number>(n);\n // oxlint-disable-next-line unicorn/no-new-array\n const order = new Array<number>(n);\n for (let i = 0; i < n; i++) {\n const v = rows[i][column];\n // A finite number, and nothing else. An optional column may hold null,\n // and a Postgres `double precision` may hold NaN or Infinity, for which\n // subtraction does not order (NaN - NaN is NaN, and so is\n // Infinity - Infinity). The general comparator orders those no better,\n // but it must stay the single definition of what that order is.\n //\n // `v - v === 0` is the finite test without a call: it is 0 for every\n // finite number and NaN for NaN and both infinities. `Number.isFinite`\n // says the same thing at the cost of a global lookup and a call per row;\n // the two were within run-to-run noise of each other here, so this is the\n // cheaper of two equals rather than a measured win.\n if (typeof v !== 'number' || v - v !== 0) {\n // Bailing part way through wastes the scan so far, and then the general\n // sort redoes it. That is the right trade: one null in the column makes\n // this path inapplicable, not slow.\n return undefined;\n }\n keys[i] = v;\n order[i] = i;\n }\n\n order.sort(\n direction === 'asc'\n ? (a, b) => keys[a] - keys[b]\n : (a, b) => keys[b] - keys[a],\n );\n\n // oxlint-disable-next-line unicorn/no-new-array\n const out = new Array<Row>(n);\n for (let i = 0; i < n; i++) {\n out[i] = rows[order[i]];\n }\n return out;\n }\n\n // For unit testing that we correctly clean up indexes.\n getIndexKeys(): string[] {\n return [...this.#indexes.keys()];\n }\n\n #fetch(req: FetchRequest, conn: Connection): Stream<Node | 'yield'> {\n // multiConstraints is handled by driving sub-fetches off the first\n // entry's values and post-filtering matches against any remaining\n // entries. TableSource implements multi-IN natively via SQL `AND` of\n // `IN` clauses; the in-memory path is correct but not specially\n // optimized — it pays the index-seek cost per primary value, then\n // walks each result against the rest.\n if (\n req.multiConstraints &&\n req.multiConstraints.some(mc => mc.length > 0)\n ) {\n return this.#fetchMulti(req, conn);\n }\n const requestedSort = must(conn.sort);\n const {compareRows} = conn;\n // Avoid allocating a new closure when not reversing (the common case).\n const connectionComparator: Comparator = req.reverse\n ? (r1, r2) => compareRows(r2, r1)\n : compareRows;\n\n const reqFilter = req.filter;\n const connFilterCondition = conn.filters?.condition;\n const mergedFilterCondition: NoSubqueryCondition | undefined =\n connFilterCondition && reqFilter\n ? {type: 'and', conditions: [connFilterCondition, reqFilter]}\n : (connFilterCondition ?? reqFilter);\n const mergedFilterPredicate = mergePredicates(\n conn.filters?.predicate,\n reqFilter,\n );\n\n const pkConstraint = primaryKeyConstraintFromFilters(\n mergedFilterCondition,\n this.#primaryKey,\n );\n // The primary key constraint will be more limiting than the constraint\n // so swap out to that if it exists.\n const fetchOrPkConstraint = pkConstraint ?? req.constraint;\n\n // If there is a constraint, we need an index sorted by it first.\n const indexSort: OrderPart[] = [];\n if (fetchOrPkConstraint) {\n for (const key of Object.keys(fetchOrPkConstraint)) {\n indexSort.push([key, 'asc']);\n }\n }\n\n // For the special case of constraining by PK, we don't need to worry about\n // any requested sort since there can only be one result. Otherwise we also\n // need the index sorted by the requested sort.\n if (\n this.#primaryKey.length > 1 ||\n !fetchOrPkConstraint ||\n !constraintMatchesPrimaryKey(fetchOrPkConstraint, this.#primaryKey)\n ) {\n indexSort.push(...requestedSort);\n }\n\n const index = this.#getOrCreateIndex(indexSort);\n const {data, comparator: compare} = index;\n // Avoid allocating a new closure when not reversing (the common case).\n const indexComparator: Comparator = req.reverse\n ? (r1, r2) => compare(r2, r1)\n : compare;\n\n const startAt = req.start?.row;\n\n // If there is a constraint, we want to start our scan at the first row that\n // matches the constraint. But because the next OrderPart can be `desc`,\n // it's not true that {[constraintKey]: constraintValue} is the first\n // matching row. Because in that case, the other fields will all be\n // `undefined`, and in Zero `undefined` is always less than any other value.\n // So if the second OrderPart is descending then `undefined` values will\n // actually be the *last* row. We need a way to stay \"start at the first row\n // with this constraint value\". RowBound with the corresponding compareBound\n // comparator accomplishes this. The right thing is probably to teach the\n // btree library to support this concept.\n let scanStart: RowBound | undefined;\n\n if (fetchOrPkConstraint) {\n scanStart = {};\n for (const [key, dir] of indexSort) {\n if (hasOwn(fetchOrPkConstraint, key)) {\n assignProperty(scanStart, key, fetchOrPkConstraint[key]);\n } else {\n if (req.reverse) {\n assignProperty(scanStart, key, dir === 'asc' ? maxValue : minValue);\n } else {\n assignProperty(scanStart, key, dir === 'asc' ? minValue : maxValue);\n }\n }\n }\n } else {\n scanStart = startAt;\n }\n\n const rowsIterable = generateRows(data, scanStart, req.reverse);\n\n // Fast path: no overlay to apply, no `start`, and no primary-key constraint\n // hidden in the filters. This is the common shape for join child-lookups,\n // plain scans, filtered scans, and source fetches that sit beneath a\n // downstream `Filter` operator. In that case the whole generator stack\n // (generateWithOverlay → generateWithStart → skipYields →\n // generateWithConstraint → generateWithFilter) reduces to: walk rows from\n // `scanStart`, drop the ones the filter rejects, wrap the rest as Nodes, and\n // stop once the constraint no longer matches (rows are sorted by the\n // constraint key first, so matches are contiguous). Collapsing the five\n // chained generators into one loop removes a large amount of per-row\n // generator-resume overhead on the hottest path.\n //\n // The filter belongs on this path rather than in a fifth generator: on\n // Hermes, adding a connection filter to a 20,000-row ordered scan cost\n // 0.56us per row, while the predicate itself measures 0.03us. The other 95%\n // was the generator stack this path exists to avoid, and the loop applies\n // the predicate in the same place `generateWithFilter` did -- after the\n // constraint break, so a non-matching constraint still ends the scan rather\n // than filtering to the end of the index.\n //\n // A primary-key constraint derived from the filters is excluded because it\n // does not reach `req.constraint`: it is used to position `scanStart`\n // instead, and this loop would then walk from that row to the end of the\n // index, filtering all the way, rather than stopping. Correct, but O(N) for\n // what should be a point lookup.\n const overlayActive =\n this.#overlay && conn.lastPushedEpoch >= this.#overlay.epoch;\n if (!overlayActive && !req.start && !pkConstraint) {\n return new SourceNodes(\n rowsIterable,\n req.constraint,\n mergedFilterPredicate,\n );\n }\n\n const withOverlay = generateWithOverlay(\n startAt,\n pkConstraint ? once(rowsIterable) : rowsIterable,\n // use `req.constraint` here and not `fetchOrPkConstraint` since `fetchOrPkConstraint` could be the\n // primary key constraint. The primary key constraint comes from filters and is acting as a filter\n // rather than as the fetch constraint.\n req.constraint,\n this.#overlay,\n conn.lastPushedEpoch,\n // Use indexComparator, generateWithOverlayInner has a subtle dependency\n // on this. Since generateWithConstraint is done after\n // generateWithOverlay, the generator consumed by generateWithOverlayInner\n // does not end when the constraint stops matching and so the final\n // check to yield an add overlay if not yet yielded is not reached.\n // However, using the indexComparator the add overlay will be less than\n // the first row that does not match the constraint, and so any\n // not yet yielded add overlay will be yielded when the first row\n // not matching the constraint is reached.\n indexComparator,\n // `startAt` is `req.start.row`, a bound in the connection's sort order,\n // so it must be compared in that order -- not `indexComparator`, which\n // with a constraint leads with the constraint keys. The two agree only\n // when the overlay row and `startAt` share those key values; they do not\n // for `#fetchMulti`'s per-value sub-fetches, which pin one primary key\n // while still carrying the caller's connection-sort `start`. Comparing\n // there by the constraint key dropped the in-flight overlay and served\n // pre-push data. Same distinction #4926 drew for `generateWithStart`.\n connectionComparator,\n mergedFilterPredicate,\n );\n\n const withConstraint = generateWithConstraint(\n skipYields(\n generateWithStart(withOverlay, req.start, connectionComparator),\n ),\n // we use `req.constraint` and not `fetchOrPkConstraint` here because we need to\n // AND the constraint with what could have been the primary key constraint\n req.constraint,\n );\n\n return mergedFilterPredicate\n ? generateWithFilter(withConstraint, mergedFilterPredicate)\n : withConstraint;\n }\n\n *#fetchMulti(req: FetchRequest, conn: Connection): Stream<Node | 'yield'> {\n // Caller (`#fetch`) guards entry on `req.multiConstraints.some(mc =>\n // mc.length > 0)`, so `multis` is guaranteed non-empty after the\n // empty-entry filter. Per the MultiConstraint contract (operator.ts),\n // entries are non-empty, share key shape, are unique, and are\n // key-compatible with `req.constraint`.\n const multis = must(req.multiConstraints).filter(mc => mc.length > 0);\n const primary = multis[0];\n const rest = multis.slice(1);\n const baseConstraint = req.constraint;\n\n // Drive sub-fetches off `primary`. Within each sub-fetch the source\n // can use its index for `primary`; we then post-filter rows by\n // checking they also match every entry in `rest`. Per the\n // MultiConstraint contract (see operator.ts), entries are unique and\n // key-compatible with `baseConstraint`, so we don't dedupe or check\n // compatibility here.\n const subStreams: Stream<Node | 'yield'>[] = primary.map(c => {\n const merged: Constraint = baseConstraint ? {...baseConstraint, ...c} : c;\n return this.#fetch(\n {...req, constraint: merged, multiConstraints: undefined},\n conn,\n );\n });\n const merged = mergeSortedStreams(\n subStreams,\n req.reverse\n ? (a, b) => conn.compareRows(b.row, a.row)\n : (a, b) => conn.compareRows(a.row, b.row),\n );\n\n if (rest.length === 0) {\n yield* merged;\n return;\n }\n\n for (const node of merged) {\n if (node === 'yield') {\n yield 'yield';\n continue;\n }\n let matchesAll = true;\n for (const mc of rest) {\n let any = false;\n for (const c of mc) {\n if (constraintMatchesRow(c, node.row)) {\n any = true;\n break;\n }\n }\n if (!any) {\n matchesAll = false;\n break;\n }\n }\n if (matchesAll) yield node;\n }\n }\n\n /**\n * Pushes an add for each of `rows`.\n *\n * When the source holds no rows and nothing is connected to it (loading the\n * replica at startup) there is no output to notify and no secondary index to\n * keep in step, so the primary index is built bottom-up in O(N) (plus a sort\n * when `rows` are not already in primary key order) rather than doing one\n * tree insert, and one trip through the push machinery, per row.\n *\n * `rows` may be sorted in place. Rows must have distinct primary keys.\n */\n pushAdds(rows: Row[]): void {\n const index = this.#getPrimaryIndex();\n const canBulkLoad =\n this.#connections.length === 0 &&\n this.#indexes.size === 1 &&\n index.data.size === 0;\n if (!canBulkLoad) {\n for (const row of rows) {\n consume(this.push(makeSourceChangeAdd(row)));\n }\n return;\n }\n const {comparator} = index;\n // The check is not redundant with the sort. V8's TimSort is O(N) on sorted\n // input but Hermes' sort is not adaptive: always sorting doubled the load\n // time of an already ordered 180k row replica on Android (343ms -> 672ms).\n const sorted = isAscending(rows, comparator)\n ? rows\n : (sortedByStringKey(rows, this.#primaryKey) ?? rows.sort(comparator));\n index.data = BTreeSet.fromSorted(comparator, sorted);\n }\n\n push(change: SourceChange): Stream<'yield'> {\n const primaryIndex = this.#getPrimaryIndex();\n const {data} = primaryIndex;\n const exists = (row: Row) => data.has(row);\n const setOverlay = (o: Overlay | undefined) => (this.#overlay = o);\n const writeChange = (c: SourceChange) => this.#writeChange(c);\n return pushAndWriteWithSplitEdit(\n this.#connections,\n change,\n exists,\n setOverlay,\n writeChange,\n () => ++this.#pushEpoch,\n );\n }\n\n genPush(change: SourceChange) {\n const primaryIndex = this.#getPrimaryIndex();\n const {data} = primaryIndex;\n const exists = (row: Row) => data.has(row);\n const setOverlay = (o: Overlay | undefined) => (this.#overlay = o);\n const writeChange = (c: SourceChange) => this.#writeChange(c);\n return genPushAndWriteWithSplitEdit(\n this.#connections,\n change,\n exists,\n setOverlay,\n writeChange,\n () => ++this.#pushEpoch,\n );\n }\n\n #writeChange(change: SourceChange) {\n for (const {data} of this.#indexes.values()) {\n switch (change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD: {\n const added = data.add(change[SourceChangeIndex.ROW]);\n // must succeed since we checked has() above.\n assert(\n added,\n 'MemorySource: add must succeed since row existence was already checked',\n );\n break;\n }\n case ChangeType.REMOVE: {\n const removed = data.delete(change[SourceChangeIndex.ROW]);\n // must succeed since we checked has() above.\n assert(\n removed,\n 'MemorySource: remove must succeed since row existence was already checked',\n );\n break;\n }\n case ChangeType.EDIT: {\n // TODO: We could see if the PK (form the index tree's perspective)\n // changed and if not we could use set.\n // We cannot just do `set` with the new value since the `oldRow` might\n // not map to the same entry as the new `row` in the index btree.\n const removed = data.delete(change[SourceChangeIndex.OLD_ROW]);\n // must succeed since we checked has() above.\n assert(\n removed,\n 'MemorySource: edit remove must succeed since row existence was already checked',\n );\n data.add(change[SourceChangeIndex.ROW]);\n break;\n }\n default:\n unreachable(change);\n }\n }\n }\n}\n\nfunction mergePredicates(\n connPredicate: ((row: Row) => boolean) | undefined,\n reqFilter: NoSubqueryCondition | undefined,\n): ((row: Row) => boolean) | undefined {\n if (!reqFilter) {\n return connPredicate;\n }\n const reqPredicate = createPredicate(reqFilter);\n if (!connPredicate) {\n return reqPredicate;\n }\n return row => connPredicate(row) && reqPredicate(row);\n}\n\n/**\n * The fast path of `#fetch`: walks rows from the scan start, stops once the\n * constraint no longer matches, drops the rows the filter rejects and wraps\n * the rest as Nodes. An iterator rather than a generator, see `mapNodes` in\n * stream.ts.\n */\nclass SourceNodes implements IterableIterator<Node> {\n readonly #rows: Iterator<Row>;\n readonly #constraint: Constraint | undefined;\n readonly #predicate: ((row: Row) => boolean) | undefined;\n #done = false;\n\n constructor(\n rows: Iterator<Row>,\n constraint: Constraint | undefined,\n predicate: ((row: Row) => boolean) | undefined,\n ) {\n this.#rows = rows;\n this.#constraint = constraint;\n this.#predicate = predicate;\n }\n\n [Symbol.iterator](): this {\n return this;\n }\n\n next(): IteratorResult<Node> {\n if (this.#done) {\n return doneResult;\n }\n const constraint = this.#constraint;\n const predicate = this.#predicate;\n for (;;) {\n let row: Row;\n let matches: boolean;\n try {\n const r = this.#rows.next();\n if (r.done) {\n this.#done = true;\n return doneResult;\n }\n row = r.value;\n if (constraint && !constraintMatchesRow(constraint, row)) {\n this.#done = true;\n return doneResult;\n }\n matches = !predicate || predicate(row);\n } catch (e) {\n // A fetch that threw is over, as a generator's is.\n this.#done = true;\n throw e;\n }\n if (matches) {\n return {value: {row, relationships: {}}, done: false};\n }\n }\n }\n\n return(): IteratorResult<Node> {\n this.#done = true;\n return doneResult;\n }\n}\n\nfunction* generateWithConstraint(\n it: Stream<Node>,\n constraint: Constraint | undefined,\n) {\n for (const node of it) {\n if (constraint && !constraintMatchesRow(constraint, node.row)) {\n break;\n }\n yield node;\n }\n}\n\nfunction* generateWithFilter(it: Stream<Node>, filter: (row: Row) => boolean) {\n for (const node of it) {\n if (filter(node.row)) {\n yield node;\n }\n }\n}\n\nexport function* genPushAndWriteWithSplitEdit(\n connections: readonly Connection[],\n change: SourceChange,\n exists: ((row: Row) => boolean) | undefined,\n setOverlay: (o: Overlay | undefined) => Overlay | undefined,\n writeChange: (c: SourceChange) => void,\n getNextEpoch: () => number,\n) {\n if (mustSplitEdit(connections, change)) {\n yield* genPushAndWrite(\n connections,\n makeSourceChangeRemove(change[SourceChangeIndex.OLD_ROW]),\n exists,\n setOverlay,\n writeChange,\n getNextEpoch(),\n );\n yield* genPushAndWrite(\n connections,\n makeSourceChangeAdd(change[SourceChangeIndex.ROW]),\n exists,\n setOverlay,\n writeChange,\n getNextEpoch(),\n );\n } else {\n yield* genPushAndWrite(\n connections,\n change,\n exists,\n setOverlay,\n writeChange,\n getNextEpoch(),\n );\n }\n}\n\nfunction* genPushAndWrite(\n connections: readonly Connection[],\n change: SourceChangeAdd | SourceChangeRemove | SourceChangeEdit,\n exists: ((row: Row) => boolean) | undefined,\n setOverlay: (o: Overlay | undefined) => Overlay | undefined,\n writeChange: (c: SourceChange) => void,\n pushEpoch: number,\n) {\n for (const x of genPush(connections, change, exists, setOverlay, pushEpoch)) {\n yield x;\n }\n writeChange(change);\n}\n\nfunction* genPush(\n connections: readonly Connection[],\n change: SourceChange,\n exists: ((row: Row) => boolean) | undefined,\n setOverlay: (o: Overlay | undefined) => void,\n pushEpoch: number,\n) {\n assertCanPush(change, exists);\n setOverlay({epoch: pushEpoch, change});\n try {\n for (const conn of connections) {\n const {output, filters, input} = conn;\n if (output) {\n conn.lastPushedEpoch = pushEpoch;\n yield* filterPush(\n toOutputChange(change),\n output,\n input,\n filters?.predicate,\n );\n yield undefined;\n }\n }\n\n for (const conn of connections) {\n const {output, input} = conn;\n if (output?.reconcile) {\n yield* output.reconcile(input);\n yield undefined;\n }\n }\n } finally {\n setOverlay(undefined);\n }\n}\n\n/**\n * Whether `change` is an edit of a column that one of the connections splits\n * edits on, and so is pushed as a remove and an add.\n */\nfunction mustSplitEdit(\n connections: readonly Connection[],\n change: SourceChange,\n): change is SourceChangeEdit {\n if (change[SourceChangeIndex.TYPE] !== ChangeType.EDIT) {\n return false;\n }\n for (const {splitEditKeys} of connections) {\n if (splitEditKeys) {\n for (const key of splitEditKeys) {\n if (\n !valuesEqual(\n change[SourceChangeIndex.ROW][key],\n change[SourceChangeIndex.OLD_ROW][key],\n )\n ) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\nfunction assertCanPush(\n change: SourceChange,\n exists: ((row: Row) => boolean) | undefined,\n): void {\n if (!exists) {\n return;\n }\n switch (change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n assert(\n !exists(change[SourceChangeIndex.ROW]),\n () => `Row already exists ${stringify(change)}`,\n );\n break;\n case ChangeType.REMOVE:\n assert(\n exists(change[SourceChangeIndex.ROW]),\n () => `Row not found ${stringify(change)}`,\n );\n break;\n case ChangeType.EDIT:\n assert(\n exists(change[SourceChangeIndex.OLD_ROW]),\n () => `Row not found ${stringify(change)}`,\n );\n break;\n default:\n unreachable(change);\n }\n}\n\n/** The change a connection's output gets for a change to the source. */\nfunction toOutputChange(change: SourceChange): Change {\n return change[SourceChangeIndex.TYPE] === ChangeType.EDIT\n ? makeEditChange(\n {row: change[SourceChangeIndex.ROW], relationships: {}},\n {row: change[SourceChangeIndex.OLD_ROW], relationships: {}},\n )\n : change[SourceChangeIndex.TYPE] === ChangeType.ADD\n ? makeAddChange({\n row: change[SourceChangeIndex.ROW],\n relationships: {},\n })\n : makeRemoveChange({\n row: change[SourceChangeIndex.ROW],\n relationships: {},\n });\n}\n\n// `genPushAndWriteWithSplitEdit` and the two generators it uses, for\n// `MemorySource.push`: run without a generator for as long as nothing yields\n// (see `andThen` in stream.ts), and without the `undefined` the generators\n// yield after each connection, which `push` drops. `genPush` keeps the\n// generators for callers that step through a push connection by connection.\nfunction pushAndWriteWithSplitEdit(\n connections: readonly Connection[],\n change: SourceChange,\n exists: ((row: Row) => boolean) | undefined,\n setOverlay: (o: Overlay | undefined) => Overlay | undefined,\n writeChange: (c: SourceChange) => void,\n getNextEpoch: () => number,\n): Stream<'yield'> {\n if (mustSplitEdit(connections, change)) {\n return andThen(\n pushAndWrite(\n connections,\n makeSourceChangeRemove(change[SourceChangeIndex.OLD_ROW]),\n exists,\n setOverlay,\n writeChange,\n getNextEpoch(),\n ),\n () =>\n pushAndWrite(\n connections,\n makeSourceChangeAdd(change[SourceChangeIndex.ROW]),\n exists,\n setOverlay,\n writeChange,\n getNextEpoch(),\n ),\n );\n }\n return pushAndWrite(\n connections,\n change,\n exists,\n setOverlay,\n writeChange,\n getNextEpoch(),\n );\n}\n\nfunction pushAndWrite(\n connections: readonly Connection[],\n change: SourceChangeAdd | SourceChangeRemove | SourceChangeEdit,\n exists: ((row: Row) => boolean) | undefined,\n setOverlay: (o: Overlay | undefined) => Overlay | undefined,\n writeChange: (c: SourceChange) => void,\n pushEpoch: number,\n): Stream<'yield'> {\n assertCanPush(change, exists);\n setOverlay({epoch: pushEpoch, change});\n let s: Stream<'yield'>;\n try {\n s = pushToConnections(connections, change, pushEpoch);\n } catch (e) {\n setOverlay(undefined);\n throw e;\n }\n if (s === emptyArray) {\n setOverlay(undefined);\n writeChange(change);\n return emptyArray;\n }\n return andThen(\n andFinally(s, () => setOverlay(undefined)),\n () => {\n writeChange(change);\n return emptyArray;\n },\n );\n}\n\n/** Pushes `change` to each connection, then reconciles each. */\nfunction pushToConnections(\n connections: readonly Connection[],\n change: SourceChange,\n pushEpoch: number,\n): Stream<'yield'> {\n let i = 0;\n let reconciling = false;\n return eachStream(() => {\n if (!reconciling) {\n while (i < connections.length) {\n const conn = connections[i++];\n const {output, filters, input} = conn;\n if (output) {\n conn.lastPushedEpoch = pushEpoch;\n return filterPush(\n toOutputChange(change),\n output,\n input,\n filters?.predicate,\n );\n }\n }\n reconciling = true;\n i = 0;\n }\n while (i < connections.length) {\n const {output, input} = connections[i++];\n if (output?.reconcile) {\n return output.reconcile(input);\n }\n }\n return undefined;\n });\n}\n\nexport function* generateWithStart(\n nodes: Iterable<Node | 'yield'>,\n start: Start | undefined,\n compare: (r1: Row, r2: Row) => number,\n): Stream<Node | 'yield'> {\n if (!start) {\n yield* nodes;\n return;\n }\n let started = false;\n for (const node of nodes) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n if (!started) {\n if (start.basis === 'at') {\n if (compare(node.row, start.row) >= 0) {\n started = true;\n }\n } else if (start.basis === 'after') {\n if (compare(node.row, start.row) > 0) {\n started = true;\n }\n }\n }\n if (started) {\n yield node;\n }\n }\n}\n\n/**\n * Takes an iterator and overlay.\n * Splices the overlay into the iterator at the correct position.\n *\n * @param startAt - if there is a lower bound to the stream. If the lower bound of the stream\n * is above the overlay, the overlay will be skipped.\n * @param rows - the stream into which the overlay should be spliced\n * @param constraint - constraint that was applied to the rowIterator and should\n * also be applied to the overlay.\n * @param overlay - the overlay values to splice in\n * @param compare - the comparator to use to find the position for the overlay.\n * Must order rows the same way `rows` is ordered. For `MemorySource` that is\n * *index* order, which leads with the constraint keys.\n * @param startAtCompare - the comparator for `startAt`, which is a bound in the\n * *connection's* sort order. Only the same as `compare` when the stream's order\n * happens to be the connection's -- true for `TableSource` (SQL does the\n * ordering) but not for a constrained `MemorySource` fetch. Conflating the two\n * is what #4926 fixed for `generateWithStart`; this parameter is the same\n * distinction for the overlay's own `startAt` pruning.\n */\nexport function generateWithOverlay(\n startAt: Row | undefined,\n rows: Iterable<Row>,\n constraint: Constraint | undefined,\n overlay: Overlay | undefined,\n lastPushedEpoch: number,\n compare: Comparator,\n startAtCompare: Comparator,\n filterPredicate?: (row: Row) => boolean | undefined,\n multiConstraints?: readonly MultiConstraint[],\n) {\n let overlayToApply: Overlay | undefined = undefined;\n if (overlay && lastPushedEpoch >= overlay.epoch) {\n overlayToApply = overlay;\n }\n const overlays = computeOverlays(\n startAt,\n constraint,\n overlayToApply,\n startAtCompare,\n filterPredicate,\n multiConstraints,\n );\n return generateWithOverlayInner(rows, overlays, compare);\n}\n\nfunction computeOverlays(\n startAt: Row | undefined,\n constraint: Constraint | undefined,\n overlay: Overlay | undefined,\n // Only ever used for `overlaysForStartAt`, so this is the *connection*-order\n // comparator, not the one used to splice the overlay into the row stream.\n startAtCompare: Comparator,\n filterPredicate?: (row: Row) => boolean | undefined,\n multiConstraints?: readonly MultiConstraint[],\n): Overlays {\n let overlays: Overlays = {\n add: undefined,\n remove: undefined,\n };\n switch (overlay?.change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n overlays = {\n add: overlay.change[SourceChangeIndex.ROW],\n remove: undefined,\n };\n break;\n case ChangeType.REMOVE:\n overlays = {\n add: undefined,\n remove: overlay.change[SourceChangeIndex.ROW],\n };\n break;\n case ChangeType.EDIT:\n overlays = {\n add: overlay.change[SourceChangeIndex.ROW],\n remove: overlay.change[SourceChangeIndex.OLD_ROW],\n };\n break;\n }\n\n if (startAt) {\n overlays = overlaysForStartAt(overlays, startAt, startAtCompare);\n }\n\n if (constraint) {\n overlays = overlaysForConstraint(overlays, constraint);\n }\n\n overlays = applyMultiConstraintsToOverlays(overlays, multiConstraints);\n\n if (filterPredicate) {\n overlays = overlaysForFilterPredicate(overlays, filterPredicate);\n }\n\n return overlays;\n}\n\nfunction applyMultiConstraintsToOverlays(\n overlays: Overlays,\n multiConstraints: readonly MultiConstraint[] | undefined,\n): Overlays {\n if (!multiConstraints) return overlays;\n for (const mc of multiConstraints) {\n if (mc.length > 0) {\n overlays = overlaysForMultiConstraint(overlays, mc);\n }\n }\n return overlays;\n}\n\nexport {overlaysForMultiConstraint as overlaysForMultiConstraintForTest};\n\nfunction overlaysForMultiConstraint(\n {add, remove}: Overlays,\n multiConstraint: MultiConstraint,\n): Overlays {\n const matchesAny = (row: Row | undefined) => {\n if (row === undefined) return false;\n for (const c of multiConstraint) {\n if (constraintMatchesRow(c, row)) return true;\n }\n return false;\n };\n return {\n add: matchesAny(add) ? add : undefined,\n remove: matchesAny(remove) ? remove : undefined,\n };\n}\n\nexport {overlaysForStartAt as overlaysForStartAtForTest};\n\nfunction overlaysForStartAt(\n {add, remove}: Overlays,\n startAt: Row,\n compare: Comparator,\n): Overlays {\n const undefinedIfBeforeStartAt = (row: Row | undefined) =>\n row === undefined || compare(row, startAt) < 0 ? undefined : row;\n return {\n add: undefinedIfBeforeStartAt(add),\n remove: undefinedIfBeforeStartAt(remove),\n };\n}\n\nexport {overlaysForConstraint as overlaysForConstraintForTest};\n\nfunction overlaysForConstraint(\n {add, remove}: Overlays,\n constraint: Constraint,\n): Overlays {\n const undefinedIfDoesntMatchConstraint = (row: Row | undefined) =>\n row === undefined || !constraintMatchesRow(constraint, row)\n ? undefined\n : row;\n\n return {\n add: undefinedIfDoesntMatchConstraint(add),\n remove: undefinedIfDoesntMatchConstraint(remove),\n };\n}\n\nfunction overlaysForFilterPredicate(\n {add, remove}: Overlays,\n filterPredicate: (row: Row) => boolean | undefined,\n): Overlays {\n const undefinedIfDoesntMatchFilter = (row: Row | undefined) =>\n row === undefined || !filterPredicate(row) ? undefined : row;\n\n return {\n add: undefinedIfDoesntMatchFilter(add),\n remove: undefinedIfDoesntMatchFilter(remove),\n };\n}\n\nexport function* generateWithOverlayInner(\n rowIterator: Iterable<Row>,\n overlays: Overlays,\n compare: (r1: Row, r2: Row) => number,\n) {\n let addOverlayYielded = false;\n let removeOverlaySkipped = false;\n for (const row of rowIterator) {\n if (!addOverlayYielded && overlays.add) {\n const cmp = compare(overlays.add, row);\n if (cmp < 0) {\n addOverlayYielded = true;\n yield {row: overlays.add, relationships: {}};\n }\n }\n\n if (!removeOverlaySkipped && overlays.remove) {\n const cmp = compare(overlays.remove, row);\n if (cmp === 0) {\n removeOverlaySkipped = true;\n continue;\n }\n }\n yield {row, relationships: {}};\n }\n\n if (!addOverlayYielded && overlays.add) {\n yield {row: overlays.add, relationships: {}};\n }\n}\n\n/**\n * Like {@link generateWithOverlay} but for unordered streams.\n * No `startAt` or comparator needed. Injects remove/old-edit rows eagerly\n * at the start, and suppresses add/new-edit rows inline by PK match.\n */\nexport function generateWithOverlayUnordered(\n rows: Iterable<Row>,\n constraint: Constraint | undefined,\n overlay: Overlay | undefined,\n lastPushedEpoch: number,\n primaryKey: PrimaryKey,\n filterPredicate?: (row: Row) => boolean,\n multiConstraints?: readonly MultiConstraint[],\n) {\n let overlayToApply: Overlay | undefined = undefined;\n if (overlay && lastPushedEpoch >= overlay.epoch) {\n overlayToApply = overlay;\n }\n let overlays: Overlays = {add: undefined, remove: undefined};\n switch (overlayToApply?.change[SourceChangeIndex.TYPE]) {\n case ChangeType.ADD:\n overlays = {\n add: overlayToApply.change[SourceChangeIndex.ROW],\n remove: undefined,\n };\n break;\n case ChangeType.REMOVE:\n overlays = {\n add: undefined,\n remove: overlayToApply.change[SourceChangeIndex.ROW],\n };\n break;\n case ChangeType.EDIT:\n overlays = {\n add: overlayToApply.change[SourceChangeIndex.ROW],\n remove: overlayToApply.change[SourceChangeIndex.OLD_ROW],\n };\n break;\n }\n if (constraint) {\n overlays = overlaysForConstraint(overlays, constraint);\n }\n overlays = applyMultiConstraintsToOverlays(overlays, multiConstraints);\n if (filterPredicate) {\n overlays = overlaysForFilterPredicate(overlays, filterPredicate);\n }\n return generateWithOverlayInnerUnordered(rows, overlays, primaryKey);\n}\n\nexport function* generateWithOverlayInnerUnordered(\n rowIterator: Iterable<Row>,\n overlays: Overlays,\n primaryKey: PrimaryKey,\n) {\n // Eager inject: yield the add overlay at the start (row not yet in storage)\n if (overlays.add) {\n yield {row: overlays.add, relationships: {}};\n }\n // Stream with inline suppress: skip the remove overlay (row still in storage)\n let removeSkipped = false;\n for (const row of rowIterator) {\n if (\n !removeSkipped &&\n overlays.remove &&\n rowMatchesPK(overlays.remove, row, primaryKey)\n ) {\n removeSkipped = true;\n continue;\n }\n yield {row, relationships: {}};\n }\n}\n\nfunction rowMatchesPK(a: Row, b: Row, primaryKey: PrimaryKey): boolean {\n for (const key of primaryKey) {\n if (!valuesEqual(a[key], b[key])) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * A location to begin scanning an index from. Can either be a specific value\n * or the min or max possible value for the type. This is used to start a scan\n * at the beginning of the rows matching a constraint.\n */\ntype Bound = Value | MinValue | MaxValue;\nexport type RowBound = Record<string, Bound>;\nexport const minValue = Symbol('min-value');\ntype MinValue = typeof minValue;\nexport const maxValue = Symbol('max-value');\ntype MaxValue = typeof maxValue;\n\nfunction isAscending(rows: Row[], comparator: Comparator): boolean {\n for (let i = 1; i < rows.length; i++) {\n if (comparator(rows[i - 1], rows[i]) > 0) {\n return false;\n }\n }\n return true;\n}\n\n// A string that sorts the same by UTF-16 code unit as it does by UTF-8 byte,\n// and that can be joined with U+0000, holds neither a surrogate nor U+0000.\nconst notJoinableRe = /[\\0\\ud800-\\udfff]/;\n\n/**\n * `rows` in primary key order without calling a comparator, for a key whose\n * columns all hold strings. Returns `undefined`, leaving `rows` untouched, when\n * a key value is not a string or cannot be ordered this way.\n *\n * Rows whose key is not their order in the replica (a compound key is stored\n * under a hash) reach `pushAdds` shuffled, so they get a full sort, and a\n * comparator sort calls back into JS for each of its N log N comparisons. On\n * Hermes that was 204ms for 60,000 rows with a two-column key. Sorting one\n * joined string per row with the engine's own string comparison takes 64ms\n * there, and the same as the comparator sort on V8 (33ms).\n *\n * The row's position rides at the end of its string. It never decides the\n * order, because primary keys are distinct.\n */\nfunction sortedByStringKey(\n rows: readonly Row[],\n key: PrimaryKey,\n): Row[] | undefined {\n const joined: string[] = [];\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n let s = '';\n for (let c = 0; c < key.length; c++) {\n const v = row[key[c]];\n if (typeof v !== 'string' || notJoinableRe.test(v)) {\n return undefined;\n }\n s += v + '\\0';\n }\n joined.push(s + i);\n }\n joined.sort();\n const sorted: Row[] = [];\n for (let i = 0; i < joined.length; i++) {\n const s = joined[i];\n sorted.push(rows[Number(s.slice(s.lastIndexOf('\\0') + 1))]);\n }\n return sorted;\n}\n\nexport function makeBoundComparator(sort: Ordering): Comparator {\n // Pre-extract the first two keys/directions to avoid per-call array access.\n // All paths share one function literal (single SFI) so the BTree comparator call site\n // stays monomorphic across indexes with different sort orderings, preventing V8 IC deopt.\n // Even a 2-SFI split (e.g. separate len=1 path) creates a polymorphic IC that\n // measurably regresses performance, so we keep a single return body.\n const len = sort.length;\n const k0 = sort[0][0];\n const a0 = sort[0][1] === 'asc';\n const k1 = len > 1 ? sort[1][0] : '';\n const a1 = len > 1 ? sort[1][1] === 'asc' : true;\n\n return (a: RowBound, b: RowBound) => {\n const c0 = a0 ? compareBounds(a[k0], b[k0]) : compareBounds(b[k0], a[k0]);\n if (len === 1 || c0 !== 0) return c0;\n const c1 = a1 ? compareBounds(a[k1], b[k1]) : compareBounds(b[k1], a[k1]);\n if (len === 2 || c1 !== 0) return c1;\n // Hot! Do not use destructuring\n for (let i = 2; i < len; i++) {\n const cmp = compareBounds(a[sort[i][0]], b[sort[i][0]]);\n if (cmp !== 0) return sort[i][1] === 'asc' ? cmp : -cmp;\n }\n return 0;\n };\n}\n\nfunction compareBounds(a: Bound, b: Bound): number {\n if (a === b) {\n return 0;\n }\n // Use typeof to guard the Symbol sentinel checks first. This gives V8 a\n // clear type discriminant so the common non-symbol path compiles as a\n // specialised numeric/string fast-path without a Smi deopt when the\n // minValue/maxValue sentinel symbols appear.\n if (typeof a === 'symbol') {\n return a === minValue ? -1 : 1;\n }\n if (typeof b === 'symbol') {\n return b === minValue ? 1 : -1;\n }\n return compareValues(a, b);\n}\n\nexport function generateRows(\n data: BTreeSet<Row>,\n scanStart: RowBound | undefined,\n reverse: boolean | undefined,\n) {\n return reverse\n ? data.valuesFromReversed(scanStart as Row | undefined)\n : data.valuesFrom(scanStart as Row | undefined);\n}\n\nfunction stringify(change: SourceChange) {\n return JSON.stringify(change, (_, v) =>\n typeof v === 'bigint' ? v.toString() : v,\n );\n}\n\n/**\n * N-way merge of pre-sorted Node streams. Each input stream must yield\n * Nodes in `compare` order (and may interleave 'yield' values, which are\n * forwarded as-is). The merged stream yields Nodes in `compare` order.\n *\n * Implemented as a binary min-heap keyed by `compare(entry.row, ...)`, so\n * each emit costs O(log K) (K = number of streams) rather than the O(K)\n * a linear-scan-of-heads merge would. Matters when FlippedJoin chunks a\n * large `multiConstraints` IN-list into hundreds of sub-fetches.\n *\n * If the merged stream is closed early (e.g. downstream `Take` `break`s\n * after hitting its limit, prompting JS to call `.return()` on this\n * generator), the `finally` block propagates `.return()` to each\n * non-exhausted sub-iterator so the underlying sources (SQLite cursors,\n * etc.) can run their cleanup. Without this, mid-merge early-termination\n * leaves cursors open, causing later writes on the same connection to\n * fail with \"database connection is busy executing a query\".\n */\nexport function* mergeSortedStreams(\n streams: readonly Stream<Node | 'yield'>[],\n compare: (a: Node, b: Node) => number,\n): Stream<Node | 'yield'> {\n const iterators: Iterator<Node | 'yield'>[] = streams.map(s =>\n s[Symbol.iterator](),\n );\n // True while iterators[i] hasn't yet returned `done`. The finally\n // block uses this to skip already-exhausted streams when propagating\n // `.return()`.\n const active = Array.from({length: iterators.length}).fill(true) as boolean[];\n\n // Min-heap of entries; `idx` tells us which stream to refill from\n // after the entry's row is emitted.\n type Entry = {row: Node; idx: number};\n const heap: Entry[] = [];\n\n const siftUp = (start: number) => {\n let i = start;\n while (i > 0) {\n const p = (i - 1) >> 1;\n if (compare(heap[i].row, heap[p].row) >= 0) return;\n const t = heap[i];\n heap[i] = heap[p];\n heap[p] = t;\n i = p;\n }\n };\n\n const siftDown = (start: number) => {\n let i = start;\n const n = heap.length;\n while (true) {\n const l = (i << 1) + 1;\n const r = l + 1;\n let smallest = i;\n if (l < n && compare(heap[l].row, heap[smallest].row) < 0) smallest = l;\n if (r < n && compare(heap[r].row, heap[smallest].row) < 0) smallest = r;\n if (smallest === i) return;\n const t = heap[i];\n heap[i] = heap[smallest];\n heap[smallest] = t;\n i = smallest;\n }\n };\n\n // Pull the next Node from iterator `idx`, forwarding any 'yield's.\n // Returns the Node, or `undefined` once the stream is exhausted.\n const pullNext = function* (\n idx: number,\n ): IterableIterator<'yield', Node | undefined, undefined> {\n while (true) {\n const r = iterators[idx].next();\n if (r.done) {\n active[idx] = false;\n return undefined;\n }\n if (r.value === 'yield') {\n yield 'yield';\n continue;\n }\n return r.value;\n }\n };\n\n try {\n // Prime: push the first row of each non-empty stream onto the heap.\n for (let i = 0; i < iterators.length; i++) {\n const row = yield* pullNext(i);\n if (row !== undefined) {\n heap.push({row, idx: i});\n siftUp(heap.length - 1);\n }\n }\n\n while (heap.length > 0) {\n // Root is the global min across all active streams.\n const top = heap[0];\n yield top.row;\n const next = yield* pullNext(top.idx);\n if (next !== undefined) {\n // Refill root in place (top === heap[0]) and sift down. The\n // already-yielded `top.row` value is captured by the yield, so\n // mutating it here doesn't affect what was emitted.\n top.row = next;\n siftDown(0);\n } else {\n // Stream exhausted. Move tail to root and shrink. Pop returns\n // the last entry; if the heap had only one entry it was the\n // root we just yielded, so we just leave the heap empty.\n const last = must(heap.pop());\n if (heap.length > 0) {\n heap[0] = last;\n siftDown(0);\n }\n }\n }\n } finally {\n // Close any iterators that aren't already exhausted so their\n // `finally` blocks (which release cursors / cached statements) run.\n for (let i = 0; i < iterators.length; i++) {\n if (active[i]) {\n iterators[i].return?.();\n }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ACxD,OAAO,MAAM;GACX,MAAM,IAAI,UAAU,IAAI,CAAC,KAAK;GAC9B,IAAI,EAAE,MAAM;IACV,OAAO,OAAO;IACd;GACF;GACA,IAAI,EAAE,UAAU,SAAS;IACvB,MAAM;IACN;GACF;GACA,OAAO,EAAE;EACX;CACF;CAEA,IAAI;EAEF,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;GACzC,MAAM,MAAM,OAAO,SAAS,CAAC;GAC7B,IAAI,QAAQ,KAAA,GAAW;IACrB,KAAK,KAAK;KAAC;KAAK,KAAK;IAAC,CAAC;IACvB,OAAO,KAAK,SAAS,CAAC;GACxB;EACF;EAEA,OAAO,KAAK,SAAS,GAAG;GAEtB,MAAM,MAAM,KAAK;GACjB,MAAM,IAAI;GACV,MAAM,OAAO,OAAO,SAAS,IAAI,GAAG;GACpC,IAAI,SAAS,KAAA,GAAW;IAItB,IAAI,MAAM;IACV,SAAS,CAAC;GACZ,OAAO;IAIL,MAAM,OAAO,KAAK,KAAK,IAAI,CAAC;IAC5B,IAAI,KAAK,SAAS,GAAG;KACnB,KAAK,KAAK;KACV,SAAS,CAAC;IACZ;GACF;EACF;CACF,UAAU;EAGR,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KACpC,IAAI,OAAO,IACT,UAAU,EAAE,CAAC,SAAS;CAG5B;AACF"}
@@ -3,7 +3,7 @@ import { type Change } from './change.ts';
3
3
  import type { Node } from './data.ts';
4
4
  import type { InputBase, Output } from './operator.ts';
5
5
  import type { SourceSchema } from './schema.ts';
6
- import type { Stream } from './stream.ts';
6
+ import { type Stream } from './stream.ts';
7
7
  /**
8
8
  * # pushAccumulatedChanges
9
9
  *