@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
@@ -3,6 +3,7 @@ import { makeAddChange } from "./change.js";
3
3
  import { valueToKey } from "./data.js";
4
4
  import { throwOutput } from "./operator.js";
5
5
  import { emptyArray } from "../../../shared/src/sentinels.js";
6
+ import { andThen, doneResult } from "./stream.js";
6
7
  import { constraintMatchesPartitionKey, makePartitionKeyComparator } from "./take.js";
7
8
  //#region ../zql/src/ivm/cap.ts
8
9
  /**
@@ -45,35 +46,16 @@ var Cap = class {
45
46
  getSchema() {
46
47
  return this.#input.getSchema();
47
48
  }
48
- *fetch(req) {
49
+ fetch(req) {
49
50
  assert(!req.start, "Cap does not support start");
50
51
  assert(!req.reverse, "Cap does not support reverse");
51
52
  assert(!this.#partitionKey || req.constraint !== void 0 && constraintMatchesPartitionKey(req.constraint, this.#partitionKey), "Cap fetch: constraint must match partition key when partitioned");
52
53
  const capStateKey = getCapStateKey(this.#partitionKey, req.constraint);
53
54
  const capState = this.#storage.get(capStateKey);
54
- if (!capState) {
55
- yield* this.#initialFetch(req, capStateKey);
56
- return;
57
- }
58
- if (capState.size === 0) return;
59
- if (req.countOnly) {
60
- for (let i = 0; i < capState.size; i++) yield placeholderNode;
61
- return;
62
- }
63
- for (const pk of capState.pks) {
64
- const pkConstraint = deserializePKToConstraint(pk, this.#primaryKey);
65
- const constraint = req.constraint ? {
66
- ...req.constraint,
67
- ...pkConstraint
68
- } : pkConstraint;
69
- for (const inputNode of this.#input.fetch({ constraint })) {
70
- if (inputNode === "yield") {
71
- yield inputNode;
72
- continue;
73
- }
74
- yield inputNode;
75
- }
76
- }
55
+ if (!capState) return this.#initialFetch(req, capStateKey);
56
+ if (capState.size === 0) return emptyArray;
57
+ if (req.countOnly) return placeholderNodes(capState.size);
58
+ return new CapNodes(this.#input, capState.pks, this.#primaryKey, req.constraint);
77
59
  }
78
60
  *#initialFetch(req, capStateKey) {
79
61
  if (this.#limit === 0) return;
@@ -107,14 +89,11 @@ var Cap = class {
107
89
  }
108
90
  }
109
91
  }
110
- *push(change) {
111
- if (change[0] === 2) {
112
- yield* this.#pushEditChange(change);
113
- return;
114
- }
92
+ push(change) {
93
+ if (change[0] === 2) return this.#pushEditChange(change);
115
94
  const capStateKey = getCapStateKey(this.#partitionKey, change[1].row);
116
95
  const capState = this.#storage.get(capStateKey);
117
- if (!capState) return;
96
+ if (!capState) return emptyArray;
118
97
  const pk = serializePK(change[1].row, this.#primaryKey);
119
98
  if (change[0] === 0) {
120
99
  if (capState.size < this.#limit) {
@@ -123,53 +102,73 @@ var Cap = class {
123
102
  size: capState.size + 1,
124
103
  pks
125
104
  });
126
- yield* this.#output.push(change, this);
127
- return;
105
+ return this.#output.push(change, this);
128
106
  }
129
- return;
107
+ return emptyArray;
130
108
  } else if (change[0] === 1) {
131
109
  const pkIndex = capState.pks.indexOf(pk);
132
- if (pkIndex === -1) return;
110
+ if (pkIndex === -1) return emptyArray;
133
111
  const pks = [...capState.pks];
134
112
  pks.splice(pkIndex, 1);
135
113
  const newSize = capState.size - 1;
136
114
  const pkSet = new Set(pks);
137
115
  const constraint = this.#partitionKey ? Object.fromEntries(this.#partitionKey.map((key) => [key, change[1].row[key]])) : void 0;
138
- let replacement;
139
- for (const node of this.#input.fetch({ constraint })) {
140
- if (node === "yield") {
141
- yield node;
142
- continue;
143
- }
144
- const nodePK = serializePK(node.row, this.#primaryKey);
145
- if (!pkSet.has(nodePK)) {
146
- replacement = node;
147
- break;
148
- }
116
+ const it = this.#input.fetch({ constraint })[Symbol.iterator]();
117
+ const replacement = this.#readReplacement(it, pkSet);
118
+ if (replacement === "yield") return this.#refillAfterYield(change, capStateKey, pks, newSize, pkSet, it);
119
+ if (replacement) it.return?.();
120
+ return this.#pushRemove(change, capStateKey, pks, newSize, replacement);
121
+ }
122
+ return new Set(capState.pks).has(pk) ? this.#output.push(change, this) : emptyArray;
123
+ }
124
+ /**
125
+ * Reads `it` up to the first row that is not tracked, which takes the place
126
+ * of a removed one. Returns 'yield' if the fetch yields before that, and
127
+ * `undefined` if the fetch ends.
128
+ */
129
+ #readReplacement(it, pkSet) {
130
+ for (;;) {
131
+ const r = it.next();
132
+ if (r.done) return;
133
+ const node = r.value;
134
+ if (node === "yield" || !pkSet.has(serializePK(node.row, this.#primaryKey))) return node;
135
+ }
136
+ }
137
+ /** The rest of a remove whose fetch for a replacement has yielded. */
138
+ *#refillAfterYield(change, capStateKey, pks, newSize, pkSet, it) {
139
+ let replacement = "yield";
140
+ try {
141
+ while (replacement === "yield") {
142
+ yield "yield";
143
+ replacement = this.#readReplacement(it, pkSet);
149
144
  }
150
- if (replacement) {
151
- this.#storage.set(capStateKey, {
152
- size: newSize,
153
- pks
154
- });
155
- yield* this.#output.push(change, this);
145
+ } finally {
146
+ if (replacement !== void 0) it.return?.();
147
+ }
148
+ yield* this.#pushRemove(change, capStateKey, pks, newSize, replacement);
149
+ }
150
+ /** Forwards a remove and, if there is one, the add of its replacement. */
151
+ #pushRemove(change, capStateKey, pks, newSize, replacement) {
152
+ if (replacement) {
153
+ this.#storage.set(capStateKey, {
154
+ size: newSize,
155
+ pks
156
+ });
157
+ return andThen(this.#output.push(change, this), () => {
156
158
  const replacementPK = serializePK(replacement.row, this.#primaryKey);
157
159
  pks.push(replacementPK);
158
160
  this.#storage.set(capStateKey, {
159
161
  size: newSize + 1,
160
162
  pks
161
163
  });
162
- yield* this.#output.push(makeAddChange(replacement), this);
163
- } else {
164
- this.#storage.set(capStateKey, {
165
- size: newSize,
166
- pks
167
- });
168
- yield* this.#output.push(change, this);
169
- }
170
- } else if (change[0] === 3) {
171
- if (new Set(capState.pks).has(pk)) yield* this.#output.push(change, this);
164
+ return this.#output.push(makeAddChange(replacement), this);
165
+ });
172
166
  }
167
+ this.#storage.set(capStateKey, {
168
+ size: newSize,
169
+ pks
170
+ });
171
+ return this.#output.push(change, this);
173
172
  }
174
173
  #pushEditChange(change) {
175
174
  assert(!this.#partitionKeyComparator || this.#partitionKeyComparator(change[2].row, change[1].row) === 0, "Unexpected change of partition key");
@@ -194,10 +193,64 @@ var Cap = class {
194
193
  this.#input.destroy();
195
194
  this.#storage.destroy();
196
195
  }
197
- *reconcile(_pusher) {
198
- if (this.#output.reconcile) yield* this.#output.reconcile(this);
196
+ reconcile(_pusher) {
197
+ return this.#output.reconcile ? this.#output.reconcile(this) : emptyArray;
198
+ }
199
+ };
200
+ /**
201
+ * The tracked rows of a Cap, each fetched by its primary key. An iterator
202
+ * rather than a generator, see `mapNodes` in stream.ts.
203
+ */
204
+ var CapNodes = class {
205
+ #input;
206
+ #pks;
207
+ #primaryKey;
208
+ #constraint;
209
+ #next = 0;
210
+ #it = void 0;
211
+ constructor(input, pks, primaryKey, constraint) {
212
+ this.#input = input;
213
+ this.#pks = pks;
214
+ this.#primaryKey = primaryKey;
215
+ this.#constraint = constraint;
216
+ }
217
+ [Symbol.iterator]() {
218
+ return this;
219
+ }
220
+ next() {
221
+ try {
222
+ for (;;) {
223
+ if (this.#it !== void 0) {
224
+ const r = this.#it.next();
225
+ if (!r.done) return r;
226
+ this.#it = void 0;
227
+ }
228
+ if (this.#next >= this.#pks.length) return doneResult;
229
+ const pkConstraint = deserializePKToConstraint(this.#pks[this.#next++], this.#primaryKey);
230
+ const constraint = this.#constraint ? {
231
+ ...this.#constraint,
232
+ ...pkConstraint
233
+ } : pkConstraint;
234
+ this.#it = this.#input.fetch({ constraint })[Symbol.iterator]();
235
+ }
236
+ } catch (e) {
237
+ this.#it = void 0;
238
+ this.#next = this.#pks.length;
239
+ throw e;
240
+ }
241
+ }
242
+ return() {
243
+ const it = this.#it;
244
+ this.#it = void 0;
245
+ this.#next = this.#pks.length;
246
+ it?.return?.();
247
+ return doneResult;
199
248
  }
200
249
  };
250
+ /** `size` placeholder nodes, for a countOnly fetch. */
251
+ function placeholderNodes(size) {
252
+ return Array.from({ length: size }).fill(placeholderNode);
253
+ }
201
254
  var placeholderNode = Object.freeze({
202
255
  row: Object.freeze({}),
203
256
  relationships: Object.freeze({})
@@ -1 +1 @@
1
- {"version":3,"file":"cap.js","names":[],"sources":["../../../../../zql/src/ivm/cap.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {makeAddChange, type Change, type EditChange} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {valueToKey, type Comparator, type Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type InputBase,\n type Operator,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\nimport {\n constraintMatchesPartitionKey,\n makePartitionKeyComparator,\n type PartitionKey,\n} from './take.ts';\n\ntype CapState = {\n size: number;\n pks: string[];\n};\n\ninterface CapStorage {\n get(key: string): CapState | undefined;\n set(key: string, value: CapState): void;\n del(key: string): void;\n destroy(): void;\n}\n\n/**\n * The Cap operator is a count-based limiter for EXISTS subqueries that\n * does not require ordering. Unlike Take, it tracks membership by primary\n * key set rather than by a sorted bound. This means:\n *\n * - No comparator needed (no ordering requirement)\n * - No `start` or `reverse` fetch support\n * - No `#rowHiddenFromFetch` complexity (we can defer when adding to the pk set)\n *\n * Cap is used in EXISTS child pipelines where only the count of matching\n * rows matters, not their order. This allows SQLite to skip ORDER BY\n * entirely, enabling much faster query plans.\n *\n * Cap can count rows globally or by unique value of some partition key\n * (same as Take).\n */\nexport class Cap implements Operator {\n readonly #input: Input;\n readonly #storage: CapStorage;\n readonly #limit: number;\n readonly #partitionKey: PartitionKey | undefined;\n readonly #partitionKeyComparator: Comparator | undefined;\n readonly #primaryKey: PrimaryKey;\n\n #output: Output = throwOutput;\n\n constructor(\n input: Input,\n storage: Storage,\n limit: number,\n partitionKey?: PartitionKey,\n ) {\n assert(limit >= 0, 'Limit must be non-negative');\n input.setOutput(this);\n this.#input = input;\n this.#storage = storage as CapStorage;\n this.#limit = limit;\n this.#partitionKey = partitionKey;\n this.#partitionKeyComparator =\n partitionKey && makePartitionKeyComparator(partitionKey);\n this.#primaryKey = input.getSchema().primaryKey;\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n assert(!req.start, 'Cap does not support start');\n assert(!req.reverse, 'Cap does not support reverse');\n\n // Cap is only built for non-flipped EXISTS subqueries, whose only\n // downstream consumer is a Join that always fetches with a constraint\n // built from the correlation's childField — which is Cap's partition\n // key. So either partitionKey is undefined, or constraint matches.\n assert(\n !this.#partitionKey ||\n (req.constraint !== undefined &&\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey)),\n 'Cap fetch: constraint must match partition key when partitioned',\n );\n\n const capStateKey = getCapStateKey(this.#partitionKey, req.constraint);\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n yield* this.#initialFetch(req, capStateKey);\n return;\n }\n if (capState.size === 0) {\n return;\n }\n if (req.countOnly) {\n for (let i = 0; i < capState.size; i++) {\n yield placeholderNode;\n }\n return;\n }\n // PK-based point lookups: fetch each tracked row by its PK directly,\n // rather than scanning the partition and filtering.\n for (const pk of capState.pks) {\n const pkConstraint = deserializePKToConstraint(pk, this.#primaryKey);\n // Preserve req.constraint (the partition key) so upstream partitioned\n // operators (e.g. Take) retain their partition scope and do not throw.\n const constraint = req.constraint\n ? {...req.constraint, ...pkConstraint}\n : pkConstraint;\n for (const inputNode of this.#input.fetch({constraint})) {\n if (inputNode === 'yield') {\n yield inputNode;\n continue;\n }\n yield inputNode;\n }\n }\n }\n\n *#initialFetch(\n req: FetchRequest,\n capStateKey: string,\n ): Stream<Node | 'yield'> {\n if (this.#limit === 0) {\n return;\n }\n\n assert(\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey),\n 'Constraint should match partition key',\n );\n\n // The caller (fetch) has already checked that there is no state for\n // capStateKey.\n\n let size = 0;\n const pks: string[] = [];\n let downstreamEarlyReturn = true;\n let exceptionThrown = false;\n try {\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield 'yield';\n continue;\n }\n yield inputNode;\n pks.push(serializePK(inputNode.row, this.#primaryKey));\n size++;\n if (size === this.#limit) {\n break;\n }\n }\n downstreamEarlyReturn = false;\n } catch (e) {\n exceptionThrown = true;\n throw e;\n } finally {\n if (!exceptionThrown) {\n this.#storage.set(capStateKey, {size, pks});\n // If it becomes necessary to support downstream early return, this\n // assert should be removed, and replaced with code that consumes\n // the input stream until limit is reached or the input stream is\n // exhausted so that capState is properly hydrated.\n assert(\n !downstreamEarlyReturn,\n 'Unexpected early return prevented full hydration',\n );\n }\n }\n }\n\n *push(change: Change): Stream<'yield'> {\n if (change[ChangeIndex.TYPE] === ChangeType.EDIT) {\n yield* this.#pushEditChange(change);\n return;\n }\n\n const capStateKey = getCapStateKey(\n this.#partitionKey,\n change[ChangeIndex.NODE].row,\n );\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n return;\n }\n\n const pk = serializePK(change[ChangeIndex.NODE].row, this.#primaryKey);\n\n if (change[ChangeIndex.TYPE] === ChangeType.ADD) {\n if (capState.size < this.#limit) {\n const pks = [...capState.pks, pk];\n this.#storage.set(capStateKey, {size: capState.size + 1, pks});\n yield* this.#output.push(change, this);\n return;\n }\n // Full — drop\n return;\n } else if (change[ChangeIndex.TYPE] === ChangeType.REMOVE) {\n const pkIndex = capState.pks.indexOf(pk);\n if (pkIndex === -1) {\n // Not in our set — drop\n return;\n }\n // Remove from set\n const pks = [...capState.pks];\n pks.splice(pkIndex, 1);\n const newSize = capState.size - 1;\n\n // Try to refill: fetch from input with partition constraint,\n // find first row NOT in PK set\n const pkSet = new Set(pks);\n const constraint = this.#partitionKey\n ? (Object.fromEntries(\n this.#partitionKey.map(\n key => [key, change[ChangeIndex.NODE].row[key]] as const,\n ),\n ) as Constraint)\n : undefined;\n\n let replacement: Node | undefined;\n for (const node of this.#input.fetch({constraint})) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n const nodePK = serializePK(node.row, this.#primaryKey);\n if (!pkSet.has(nodePK)) {\n replacement = node;\n break;\n }\n }\n\n if (replacement) {\n // Store state WITHOUT replacement during remove forward,\n // matching Take's pattern of hiding in-flight changes from re-fetches.\n this.#storage.set(capStateKey, {size: newSize, pks});\n yield* this.#output.push(change, this);\n // Now add replacement to set and forward the add.\n const replacementPK = serializePK(replacement.row, this.#primaryKey);\n pks.push(replacementPK);\n this.#storage.set(capStateKey, {size: newSize + 1, pks});\n yield* this.#output.push(makeAddChange(replacement), this);\n } else {\n this.#storage.set(capStateKey, {size: newSize, pks});\n yield* this.#output.push(change, this);\n }\n } else if (change[ChangeIndex.TYPE] === ChangeType.CHILD) {\n const pkSet = new Set(capState.pks);\n if (pkSet.has(pk)) {\n yield* this.#output.push(change, this);\n }\n }\n }\n\n #pushEditChange(change: EditChange): Stream<'yield'> {\n assert(\n !this.#partitionKeyComparator ||\n this.#partitionKeyComparator(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n ) === 0,\n 'Unexpected change of partition key',\n );\n const capStateKey = getCapStateKey(\n this.#partitionKey,\n change[ChangeIndex.OLD_NODE].row,\n );\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n return emptyArray;\n }\n\n const oldPK = serializePK(\n change[ChangeIndex.OLD_NODE].row,\n this.#primaryKey,\n );\n const pkSet = new Set(capState.pks);\n if (pkSet.has(oldPK)) {\n // Update the PK in our set if it changed\n const newPK = serializePK(change[ChangeIndex.NODE].row, this.#primaryKey);\n if (oldPK !== newPK) {\n const pks = capState.pks.map(p => (p === oldPK ? newPK : p));\n this.#storage.set(capStateKey, {size: capState.size, pks});\n }\n return this.#output.push(change, this);\n }\n // If not in our set, drop\n return emptyArray;\n }\n\n destroy(): void {\n this.#input.destroy();\n this.#storage.destroy();\n }\n\n *reconcile(_pusher: InputBase): Stream<'yield'> {\n if (this.#output.reconcile) {\n yield* this.#output.reconcile(this);\n }\n }\n}\n\n// Yielded for each tracked row of a countOnly fetch.\nconst placeholderNode: Node = Object.freeze({\n row: Object.freeze({}),\n relationships: Object.freeze({}),\n});\n\nfunction getCapStateKey(\n partitionKey: PartitionKey | undefined,\n rowOrConstraint: Row | Constraint | undefined,\n): string {\n if (partitionKey?.length === 1 && rowOrConstraint) {\n return 'cap:' + valueToKey(rowOrConstraint[partitionKey[0]]);\n }\n const partitionValues: Value[] = [];\n\n if (partitionKey && rowOrConstraint) {\n for (const key of partitionKey) {\n partitionValues.push(rowOrConstraint[key]);\n }\n }\n\n return JSON.stringify(['cap', ...partitionValues]);\n}\n\nfunction serializePK(row: Row, primaryKey: PrimaryKey): string {\n return JSON.stringify(primaryKey.map(k => row[k]));\n}\n\nfunction deserializePKToConstraint(\n pk: string,\n primaryKey: PrimaryKey,\n): Constraint {\n const values = JSON.parse(pk) as Value[];\n const constraint: Record<string, Value> = {};\n for (let i = 0; i < primaryKey.length; i++) {\n constraint[primaryKey[i]] = values[i];\n }\n return constraint;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,MAAb,MAAqC;CACnC;CACA;CACA;CACA;CACA;CACA;CAEA,UAAkB;CAElB,YACE,OACA,SACA,OACA,cACA;EACA,OAAO,SAAS,GAAG,4BAA4B;EAC/C,MAAM,UAAU,IAAI;EACpB,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,KAAK,SAAS;EACd,KAAK,gBAAgB;EACrB,KAAK,0BACH,gBAAgB,2BAA2B,YAAY;EACzD,KAAK,cAAc,MAAM,UAAU,CAAC,CAAC;CACvC;CAEA,UAAU,QAAsB;EAC9B,KAAK,UAAU;CACjB;CAEA,YAA0B;EACxB,OAAO,KAAK,OAAO,UAAU;CAC/B;CAEA,CAAC,MAAM,KAA2C;EAChD,OAAO,CAAC,IAAI,OAAO,4BAA4B;EAC/C,OAAO,CAAC,IAAI,SAAS,8BAA8B;EAMnD,OACE,CAAC,KAAK,iBACH,IAAI,eAAe,KAAA,KAClB,8BAA8B,IAAI,YAAY,KAAK,aAAa,GACpE,iEACF;EAEA,MAAM,cAAc,eAAe,KAAK,eAAe,IAAI,UAAU;EACrE,MAAM,WAAW,KAAK,SAAS,IAAI,WAAW;EAC9C,IAAI,CAAC,UAAU;GACb,OAAO,KAAK,cAAc,KAAK,WAAW;GAC1C;EACF;EACA,IAAI,SAAS,SAAS,GACpB;EAEF,IAAI,IAAI,WAAW;GACjB,KAAK,IAAI,IAAI,GAAG,IAAI,SAAS,MAAM,KACjC,MAAM;GAER;EACF;EAGA,KAAK,MAAM,MAAM,SAAS,KAAK;GAC7B,MAAM,eAAe,0BAA0B,IAAI,KAAK,WAAW;GAGnE,MAA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AK,MAAM,OAAO,cAChB,gBAAgB,KAAK,gBAAgB,IAAI;CAI7C,OAAO,KAAK,UAAU,CAAC,OAAO,GAAG,eAAe,CAAC;AACnD;AAEA,SAAS,YAAY,KAAU,YAAgC;CAC7D,OAAO,KAAK,UAAU,WAAW,KAAI,MAAK,IAAI,EAAE,CAAC;AACnD;AAEA,SAAS,0BACP,IACA,YACY;CACZ,MAAM,SAAS,KAAK,MAAM,EAAE;CAC5B,MAAM,aAAoC,CAAC;CAC3C,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,WAAW,WAAW,MAAM,OAAO;CAErC,OAAO;AACT"}
1
+ {"version":3,"file":"cap.js","names":[],"sources":["../../../../../zql/src/ivm/cap.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {makeAddChange, type Change, type EditChange} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {valueToKey, type Comparator, type Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type InputBase,\n type Operator,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {andThen, doneResult, type Stream} from './stream.ts';\nimport {\n constraintMatchesPartitionKey,\n makePartitionKeyComparator,\n type PartitionKey,\n} from './take.ts';\n\ntype CapState = {\n size: number;\n pks: string[];\n};\n\ninterface CapStorage {\n get(key: string): CapState | undefined;\n set(key: string, value: CapState): void;\n del(key: string): void;\n destroy(): void;\n}\n\n/**\n * The Cap operator is a count-based limiter for EXISTS subqueries that\n * does not require ordering. Unlike Take, it tracks membership by primary\n * key set rather than by a sorted bound. This means:\n *\n * - No comparator needed (no ordering requirement)\n * - No `start` or `reverse` fetch support\n * - No `#rowHiddenFromFetch` complexity (we can defer when adding to the pk set)\n *\n * Cap is used in EXISTS child pipelines where only the count of matching\n * rows matters, not their order. This allows SQLite to skip ORDER BY\n * entirely, enabling much faster query plans.\n *\n * Cap can count rows globally or by unique value of some partition key\n * (same as Take).\n */\nexport class Cap implements Operator {\n readonly #input: Input;\n readonly #storage: CapStorage;\n readonly #limit: number;\n readonly #partitionKey: PartitionKey | undefined;\n readonly #partitionKeyComparator: Comparator | undefined;\n readonly #primaryKey: PrimaryKey;\n\n #output: Output = throwOutput;\n\n constructor(\n input: Input,\n storage: Storage,\n limit: number,\n partitionKey?: PartitionKey,\n ) {\n assert(limit >= 0, 'Limit must be non-negative');\n input.setOutput(this);\n this.#input = input;\n this.#storage = storage as CapStorage;\n this.#limit = limit;\n this.#partitionKey = partitionKey;\n this.#partitionKeyComparator =\n partitionKey && makePartitionKeyComparator(partitionKey);\n this.#primaryKey = input.getSchema().primaryKey;\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n fetch(req: FetchRequest): Stream<Node | 'yield'> {\n assert(!req.start, 'Cap does not support start');\n assert(!req.reverse, 'Cap does not support reverse');\n\n // Cap is only built for non-flipped EXISTS subqueries, whose only\n // downstream consumer is a Join that always fetches with a constraint\n // built from the correlation's childField — which is Cap's partition\n // key. So either partitionKey is undefined, or constraint matches.\n assert(\n !this.#partitionKey ||\n (req.constraint !== undefined &&\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey)),\n 'Cap fetch: constraint must match partition key when partitioned',\n );\n\n const capStateKey = getCapStateKey(this.#partitionKey, req.constraint);\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n return this.#initialFetch(req, capStateKey);\n }\n if (capState.size === 0) {\n return emptyArray;\n }\n if (req.countOnly) {\n return placeholderNodes(capState.size);\n }\n // PK-based point lookups: fetch each tracked row by its PK directly,\n // rather than scanning the partition and filtering.\n return new CapNodes(\n this.#input,\n capState.pks,\n this.#primaryKey,\n req.constraint,\n );\n }\n\n *#initialFetch(\n req: FetchRequest,\n capStateKey: string,\n ): Stream<Node | 'yield'> {\n if (this.#limit === 0) {\n return;\n }\n\n assert(\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey),\n 'Constraint should match partition key',\n );\n\n // The caller (fetch) has already checked that there is no state for\n // capStateKey.\n\n let size = 0;\n const pks: string[] = [];\n let downstreamEarlyReturn = true;\n let exceptionThrown = false;\n try {\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield 'yield';\n continue;\n }\n yield inputNode;\n pks.push(serializePK(inputNode.row, this.#primaryKey));\n size++;\n if (size === this.#limit) {\n break;\n }\n }\n downstreamEarlyReturn = false;\n } catch (e) {\n exceptionThrown = true;\n throw e;\n } finally {\n if (!exceptionThrown) {\n this.#storage.set(capStateKey, {size, pks});\n // If it becomes necessary to support downstream early return, this\n // assert should be removed, and replaced with code that consumes\n // the input stream until limit is reached or the input stream is\n // exhausted so that capState is properly hydrated.\n assert(\n !downstreamEarlyReturn,\n 'Unexpected early return prevented full hydration',\n );\n }\n }\n }\n\n push(change: Change): Stream<'yield'> {\n if (change[ChangeIndex.TYPE] === ChangeType.EDIT) {\n return this.#pushEditChange(change);\n }\n\n const capStateKey = getCapStateKey(\n this.#partitionKey,\n change[ChangeIndex.NODE].row,\n );\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n return emptyArray;\n }\n\n const pk = serializePK(change[ChangeIndex.NODE].row, this.#primaryKey);\n\n if (change[ChangeIndex.TYPE] === ChangeType.ADD) {\n if (capState.size < this.#limit) {\n const pks = [...capState.pks, pk];\n this.#storage.set(capStateKey, {size: capState.size + 1, pks});\n return this.#output.push(change, this);\n }\n // Full — drop\n return emptyArray;\n } else if (change[ChangeIndex.TYPE] === ChangeType.REMOVE) {\n const pkIndex = capState.pks.indexOf(pk);\n if (pkIndex === -1) {\n // Not in our set — drop\n return emptyArray;\n }\n // Remove from set\n const pks = [...capState.pks];\n pks.splice(pkIndex, 1);\n const newSize = capState.size - 1;\n\n // Try to refill: fetch from input with partition constraint,\n // find first row NOT in PK set\n const pkSet = new Set(pks);\n const constraint = this.#partitionKey\n ? (Object.fromEntries(\n this.#partitionKey.map(\n key => [key, change[ChangeIndex.NODE].row[key]] as const,\n ),\n ) as Constraint)\n : undefined;\n\n const it = this.#input.fetch({constraint})[Symbol.iterator]();\n const replacement = this.#readReplacement(it, pkSet);\n if (replacement === 'yield') {\n return this.#refillAfterYield(\n change,\n capStateKey,\n pks,\n newSize,\n pkSet,\n it,\n );\n }\n if (replacement) {\n it.return?.();\n }\n return this.#pushRemove(change, capStateKey, pks, newSize, replacement);\n }\n const pkSet = new Set(capState.pks);\n return pkSet.has(pk) ? this.#output.push(change, this) : emptyArray;\n }\n\n /**\n * Reads `it` up to the first row that is not tracked, which takes the place\n * of a removed one. Returns 'yield' if the fetch yields before that, and\n * `undefined` if the fetch ends.\n */\n #readReplacement(\n it: Iterator<Node | 'yield'>,\n pkSet: Set<string>,\n ): Node | 'yield' | undefined {\n for (;;) {\n const r = it.next();\n if (r.done) {\n return undefined;\n }\n const node = r.value;\n if (\n node === 'yield' ||\n !pkSet.has(serializePK(node.row, this.#primaryKey))\n ) {\n return node;\n }\n }\n }\n\n /** The rest of a remove whose fetch for a replacement has yielded. */\n *#refillAfterYield(\n change: Change,\n capStateKey: string,\n pks: string[],\n newSize: number,\n pkSet: Set<string>,\n it: Iterator<Node | 'yield'>,\n ): Stream<'yield'> {\n let replacement: Node | 'yield' | undefined = 'yield';\n try {\n while (replacement === 'yield') {\n yield 'yield';\n replacement = this.#readReplacement(it, pkSet);\n }\n } finally {\n // Not at its end: a replacement was found, or the consumer stopped\n // reading at a 'yield'.\n if (replacement !== undefined) {\n it.return?.();\n }\n }\n yield* this.#pushRemove(change, capStateKey, pks, newSize, replacement);\n }\n\n /** Forwards a remove and, if there is one, the add of its replacement. */\n #pushRemove(\n change: Change,\n capStateKey: string,\n pks: string[],\n newSize: number,\n replacement: Node | undefined,\n ): Stream<'yield'> {\n if (replacement) {\n // Store state WITHOUT replacement during remove forward,\n // matching Take's pattern of hiding in-flight changes from re-fetches.\n this.#storage.set(capStateKey, {size: newSize, pks});\n return andThen(this.#output.push(change, this), () => {\n // Now add replacement to set and forward the add.\n const replacementPK = serializePK(replacement.row, this.#primaryKey);\n pks.push(replacementPK);\n this.#storage.set(capStateKey, {size: newSize + 1, pks});\n return this.#output.push(makeAddChange(replacement), this);\n });\n }\n this.#storage.set(capStateKey, {size: newSize, pks});\n return this.#output.push(change, this);\n }\n\n #pushEditChange(change: EditChange): Stream<'yield'> {\n assert(\n !this.#partitionKeyComparator ||\n this.#partitionKeyComparator(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n ) === 0,\n 'Unexpected change of partition key',\n );\n const capStateKey = getCapStateKey(\n this.#partitionKey,\n change[ChangeIndex.OLD_NODE].row,\n );\n const capState = this.#storage.get(capStateKey);\n if (!capState) {\n return emptyArray;\n }\n\n const oldPK = serializePK(\n change[ChangeIndex.OLD_NODE].row,\n this.#primaryKey,\n );\n const pkSet = new Set(capState.pks);\n if (pkSet.has(oldPK)) {\n // Update the PK in our set if it changed\n const newPK = serializePK(change[ChangeIndex.NODE].row, this.#primaryKey);\n if (oldPK !== newPK) {\n const pks = capState.pks.map(p => (p === oldPK ? newPK : p));\n this.#storage.set(capStateKey, {size: capState.size, pks});\n }\n return this.#output.push(change, this);\n }\n // If not in our set, drop\n return emptyArray;\n }\n\n destroy(): void {\n this.#input.destroy();\n this.#storage.destroy();\n }\n\n reconcile(_pusher: InputBase): Stream<'yield'> {\n return this.#output.reconcile ? this.#output.reconcile(this) : emptyArray;\n }\n}\n\n/**\n * The tracked rows of a Cap, each fetched by its primary key. An iterator\n * rather than a generator, see `mapNodes` in stream.ts.\n */\nclass CapNodes implements IterableIterator<Node | 'yield'> {\n readonly #input: Input;\n readonly #pks: readonly string[];\n readonly #primaryKey: PrimaryKey;\n readonly #constraint: Constraint | undefined;\n #next = 0;\n #it: Iterator<Node | 'yield'> | undefined = undefined;\n\n constructor(\n input: Input,\n pks: readonly string[],\n primaryKey: PrimaryKey,\n constraint: Constraint | undefined,\n ) {\n this.#input = input;\n this.#pks = pks;\n this.#primaryKey = primaryKey;\n this.#constraint = constraint;\n }\n\n [Symbol.iterator](): this {\n return this;\n }\n\n next(): IteratorResult<Node | 'yield'> {\n try {\n for (;;) {\n if (this.#it !== undefined) {\n const r = this.#it.next();\n if (!r.done) {\n return r;\n }\n this.#it = undefined;\n }\n if (this.#next >= this.#pks.length) {\n return doneResult;\n }\n const pkConstraint = deserializePKToConstraint(\n this.#pks[this.#next++],\n this.#primaryKey,\n );\n // Preserve req.constraint (the partition key) so upstream partitioned\n // operators (e.g. Take) retain their partition scope and do not throw.\n const constraint = this.#constraint\n ? {...this.#constraint, ...pkConstraint}\n : pkConstraint;\n this.#it = this.#input.fetch({constraint})[Symbol.iterator]();\n }\n } catch (e) {\n // A fetch that threw is over, as a generator's is: it does not go on\n // to the next row.\n this.#it = undefined;\n this.#next = this.#pks.length;\n throw e;\n }\n }\n\n return(): IteratorResult<Node | 'yield'> {\n const it = this.#it;\n this.#it = undefined;\n this.#next = this.#pks.length;\n it?.return?.();\n return doneResult;\n }\n}\n\n/** `size` placeholder nodes, for a countOnly fetch. */\nfunction placeholderNodes(size: number): Node[] {\n return Array.from<Node>({length: size}).fill(placeholderNode);\n}\n\n// Yielded for each tracked row of a countOnly fetch.\nconst placeholderNode: Node = Object.freeze({\n row: Object.freeze({}),\n relationships: Object.freeze({}),\n});\n\nfunction getCapStateKey(\n partitionKey: PartitionKey | undefined,\n rowOrConstraint: Row | Constraint | undefined,\n): string {\n if (partitionKey?.length === 1 && rowOrConstraint) {\n return 'cap:' + valueToKey(rowOrConstraint[partitionKey[0]]);\n }\n const partitionValues: Value[] = [];\n\n if (partitionKey && rowOrConstraint) {\n for (const key of partitionKey) {\n partitionValues.push(rowOrConstraint[key]);\n }\n }\n\n return JSON.stringify(['cap', ...partitionValues]);\n}\n\nfunction serializePK(row: Row, primaryKey: PrimaryKey): string {\n return JSON.stringify(primaryKey.map(k => row[k]));\n}\n\nfunction deserializePKToConstraint(\n pk: string,\n primaryKey: PrimaryKey,\n): Constraint {\n const values = JSON.parse(pk) as Value[];\n const constraint: Record<string, Value> = {};\n for (let i = 0; i < primaryKey.length; i++) {\n constraint[primaryKey[i]] = values[i];\n }\n return constraint;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,MAAb,MAAqC;CACnC;CACA;CACA;CACA;CACA;CACA;CAEA,UAAkB;CAElB,YACE,OACA,SACA,OACA,cACA;EACA,OAAO,SAAS,GAAG,4BAA4B;EAC/C,MAAM,UAAU,IAAI;EACpB,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,KAAK,SAAS;EACd,KAAK,gBAAgB;EACrB,KAAK,0BACH,gBAAgB,2BAA2B,YAAY;EACzD,KAAK,cAAc,MAAM,UAAU,CAAC,CAAC;CACvC;CAEA,UAAU,QAAsB;EAC9B,KAAK,UAAU;CACjB;CAEA,YAA0B;EACxB,OAAO,KAAK,OAAO,UAAU;CAC/B;CAEA,MAAM,KAA2C;EAC/C,OAAO,CAAC,IAAI,OAAO,4BAA4B;EAC/C,OAAO,CAAC,IAAI,SAAS,8BAA8B;EAMnD,OACE,CAAC,KAAK,iBACH,IAAI,eAAe,KAAA,KAClB,8BAA8B,IAAI,YAAY,KAAK,aAAa,GACpE,iEACF;EAEA,MAAM,cAAc,eAAe,KAAK,eAAe,IAAI,UAAU;EACrE,MAAM,WAAW,KAAK,SAAS,IAAI,WAAW;EAC9C,IAAI,CAAC,UACH,OAAO,KAAK,cAAc,KAAK,WAAW;EAE5C,IAAI,SAAS,SAAS,GACpB,OAAO;EAET,IAAI,IAAI,WACN,OAAO,iBAAiB,SAAS,IAAI;EAIvC,OAAO,IAAI,SACT,KAAK,QACL,SAAS,KACT,KAAK,aACL,IAAI,UACN;CACF;CAEA,CAAC,cAC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,cAAc,WAAW,KAAK,iBAChC,OAAO,SAAS,WAAW,gBAAgB,aAAa,GAAG;CAE7D,MAAM,kBAA2B,CAAC;CAElC,IAAI,gBAAgB,iBAClB,KAAK,MAAM,OAAO,cAChB,gBAAgB,KAAK,gBAAgB,IAAI;CAI7C,OAAO,KAAK,UAAU,CAAC,OAAO,GAAG,eAAe,CAAC;AACnD;AAEA,SAAS,YAAY,KAAU,YAAgC;CAC7D,OAAO,KAAK,UAAU,WAAW,KAAI,MAAK,IAAI,EAAE,CAAC;AACnD;AAEA,SAAS,0BACP,IACA,YACY;CACZ,MAAM,SAAS,KAAK,MAAM,EAAE;CAC5B,MAAM,aAAoC,CAAC;CAC3C,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,WAAW,WAAW,MAAM,OAAO;CAErC,OAAO;AACT"}
@@ -1,7 +1,7 @@
1
1
  import { assert } from "../../../shared/src/asserts.js";
2
2
  import { makeAddChange } from "./change.js";
3
- import { consume } from "./stream.js";
4
3
  import { emptyArray } from "../../../shared/src/sentinels.js";
4
+ import { consume } from "./stream.js";
5
5
  //#region ../zql/src/ivm/deferred-input.ts
6
6
  /**
7
7
  * A placeholder `Input` for a view whose pipeline has not been built yet.
@@ -1 +1 @@
1
- {"version":3,"file":"exists.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/exists.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,mCAAmC,CAAC;AAGnE,OAAO,EAAkC,KAAK,MAAM,EAAC,MAAM,aAAa,CAAC;AACzE,OAAO,EAGL,KAAK,IAAI,EAEV,MAAM,WAAW,CAAC;AACnB,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,YAAY,EAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,eAAe,CAAC;AAC7C,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,aAAa,CAAC;AAC9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;;IAoB3C,YACE,KAAK,EAAE,WAAW,EAClB,gBAAgB,EAAE,MAAM,EACxB,aAAa,EAAE,WAAW,EAC1B,IAAI,EAAE,QAAQ,GAAG,YAAY,EAC7B,wBAAwB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,EAoB/C;IAED,eAAe,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,CAE1C;IAED,WAAW,SAEV;IAED,SAAS,SAGR;IAED,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CA8BrD;IAeD,OAAO,IAAI,IAAI,CAEd;IAED,SAAS,IAAI,YAAY,CAExB;IAED,SAAS,CAAC,OAAO,EAAE,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAE7C;IAED,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAWpC;CA6NF"}
@@ -1,7 +1,10 @@
1
1
  import { assert, unreachable } from "../../../shared/src/asserts.js";
2
+ import { makeEmptyIteratorWithReturn } from "../../../shared/src/iterables.js";
2
3
  import { areEqual } from "../../../shared/src/arrays.js";
3
4
  import { makeAddChange, makeRemoveChange } from "./change.js";
4
5
  import { normalizeUndefined, valueToKey } from "./data.js";
6
+ import { emptyArray } from "../../../shared/src/sentinels.js";
7
+ import { andFinally } from "./stream.js";
5
8
  import { throwFilterOutput } from "./filter-operators.js";
6
9
  //#region ../zql/src/ivm/exists.ts
7
10
  /**
@@ -47,17 +50,30 @@ var Exists = class {
47
50
  this.#cache = /* @__PURE__ */ new Map();
48
51
  this.#output.endFilter();
49
52
  }
50
- *filter(node) {
53
+ filter(node) {
51
54
  let exists;
52
55
  if (!this.#noSizeReuse && !this.#inPush) {
53
56
  const key = this.#getCacheKey(node, this.#parentJoinKey);
54
57
  exists = this.#cache.get(key);
55
58
  if (exists === void 0) {
56
- exists = yield* this.#fetchExists(node);
59
+ const size = this.#fetchSizeNow(node);
60
+ if (typeof size !== "number") return this.#filterRest(node, key, size);
61
+ exists = size > 0;
57
62
  this.#cache.set(key, exists);
58
63
  } else if (this.#cacheHitCountsForTesting) this.#cacheHitCountsForTesting.set(key, (this.#cacheHitCountsForTesting.get(key) ?? 0) + 1);
59
64
  }
60
- return (yield* this.#filter(node, exists)) && (yield* this.#output.filter(node));
65
+ if (exists === void 0) {
66
+ const size = this.#fetchSizeNow(node);
67
+ if (typeof size !== "number") return this.#filterRest(node, void 0, size);
68
+ exists = size > 0;
69
+ }
70
+ return (this.#not ? !exists : exists) ? this.#output.filter(node) : emptyIteratorReturnFalse;
71
+ }
72
+ /** filter() from the point where reading the node's relationship yielded. */
73
+ *#filterRest(node, cacheKey, read) {
74
+ const exists = (yield* this.#fetchSizeRest(node, read)) > 0;
75
+ if (cacheKey !== void 0) this.#cache.set(cacheKey, exists);
76
+ return (this.#not ? !exists : exists) && (yield* this.#output.filter(node));
61
77
  }
62
78
  destroy() {
63
79
  this.#input.destroy();
@@ -65,73 +81,62 @@ var Exists = class {
65
81
  getSchema() {
66
82
  return this.#input.getSchema();
67
83
  }
68
- *reconcile(_pusher) {
69
- if (this.#output.reconcile) yield* this.#output.reconcile(this);
84
+ reconcile(_pusher) {
85
+ return this.#output.reconcile ? this.#output.reconcile(this) : emptyArray;
70
86
  }
71
- *push(change) {
87
+ push(change) {
72
88
  assert(!this.#inPush, "Unexpected re-entrancy");
73
89
  this.#inPush = true;
90
+ let s;
74
91
  try {
75
- switch (change[0]) {
76
- case 0:
77
- case 2:
78
- case 1:
79
- yield* this.#pushWithFilter(change);
80
- return;
81
- case 3:
82
- if (change[2].relationshipName !== this.#relationshipName || change[2].change[0] === 2 || change[2].change[0] === 3) {
83
- yield* this.#pushWithFilter(change);
84
- return;
85
- }
86
- switch (change[2].change[0]) {
87
- case 0: {
88
- const size = yield* this.#fetchSize(change[1]);
89
- if (size === 1) {
90
- if (this.#not) yield* this.#output.push(makeRemoveChange({
91
- row: change[1].row,
92
- relationships: {
93
- ...change[1].relationships,
94
- [this.#relationshipName]: () => []
95
- }
96
- }), this);
97
- else yield* this.#output.push(makeAddChange(change[1]), this);
98
- } else yield* this.#pushWithFilter(change, size > 0);
99
- return;
100
- }
101
- case 1: {
102
- const size = yield* this.#fetchSize(change[1]);
103
- if (size === 0) {
104
- if (this.#not) yield* this.#output.push(makeAddChange(change[1]), this);
105
- else yield* this.#output.push(makeRemoveChange({
106
- row: change[1].row,
107
- relationships: {
108
- ...change[1].relationships,
109
- [this.#relationshipName]: () => [change[2].change[1]]
110
- }
111
- }), this);
112
- } else yield* this.#pushWithFilter(change, size > 0);
113
- return;
114
- }
115
- }
116
- return;
117
- default: unreachable(change);
118
- }
119
- } finally {
92
+ s = this.#pushInPush(change);
93
+ } catch (e) {
120
94
  this.#inPush = false;
95
+ throw e;
121
96
  }
97
+ return andFinally(s, this.#endPush);
122
98
  }
123
- /**
124
- * Returns whether or not the node's this.#relationshipName
125
- * relationship passes the exist/not exists filter condition.
126
- * If the optional `size` is passed it is used.
127
- * Otherwise, if there is a stored size for the row it is used.
128
- * Otherwise the size is computed by streaming the node's
129
- * relationship with this.#relationshipName (this computed size is also
130
- * stored).
131
- */
132
- *#filter(node, exists) {
133
- exists = exists ?? (yield* this.#fetchExists(node));
134
- return this.#not ? !exists : exists;
99
+ #endPush = () => {
100
+ this.#inPush = false;
101
+ };
102
+ #pushInPush(change) {
103
+ switch (change[0]) {
104
+ case 0:
105
+ case 2:
106
+ case 1: return this.#pushWithFilter(change);
107
+ case 3:
108
+ if (change[2].relationshipName !== this.#relationshipName || change[2].change[0] === 2 || change[2].change[0] === 3) return this.#pushWithFilter(change);
109
+ switch (change[2].change[0]) {
110
+ case 0: return this.#withSize(change[1], (size) => {
111
+ if (size === 1) {
112
+ if (this.#not) return this.#output.push(makeRemoveChange({
113
+ row: change[1].row,
114
+ relationships: {
115
+ ...change[1].relationships,
116
+ [this.#relationshipName]: () => []
117
+ }
118
+ }), this);
119
+ return this.#output.push(makeAddChange(change[1]), this);
120
+ }
121
+ return this.#pushWithFilter(change, size > 0);
122
+ });
123
+ case 1: return this.#withSize(change[1], (size) => {
124
+ if (size === 0) {
125
+ if (this.#not) return this.#output.push(makeAddChange(change[1]), this);
126
+ return this.#output.push(makeRemoveChange({
127
+ row: change[1].row,
128
+ relationships: {
129
+ ...change[1].relationships,
130
+ [this.#relationshipName]: () => [change[2].change[1]]
131
+ }
132
+ }), this);
133
+ }
134
+ return this.#pushWithFilter(change, size > 0);
135
+ });
136
+ }
137
+ return emptyArray;
138
+ default: unreachable(change);
139
+ }
135
140
  }
136
141
  #getCacheKey(node, def) {
137
142
  if (def.length === 1) return valueToKey(node.row[def[0]]);
@@ -142,28 +147,86 @@ var Exists = class {
142
147
  /**
143
148
  * Pushes a change if this.#filter is true for its row.
144
149
  */
145
- *#pushWithFilter(change, exists) {
146
- if (yield* this.#filter(change[1], exists)) yield* this.#output.push(change, this);
150
+ #pushWithFilter(change, exists) {
151
+ if (exists === void 0) return this.#withSize(change[1], (size) => this.#pushIfPasses(change, size > 0));
152
+ return this.#pushIfPasses(change, exists);
147
153
  }
148
- *#fetchExists(node) {
149
- return (yield* this.#fetchSize(node)) > 0;
154
+ #pushIfPasses(change, exists) {
155
+ return (this.#not ? !exists : exists) ? this.#output.push(change, this) : emptyArray;
150
156
  }
151
- *#fetchSize(node) {
157
+ /**
158
+ * Calls `rest` with the size of the node's relationship: right away, or
159
+ * once the stream returned has been read if reading the relationship yields.
160
+ */
161
+ #withSize(node, rest) {
162
+ const size = this.#fetchSizeNow(node);
163
+ return typeof size === "number" ? rest(size) : this.#withSizeRest(node, size, rest);
164
+ }
165
+ *#withSizeRest(node, read, rest) {
166
+ yield* rest(yield* this.#fetchSizeRest(node, read));
167
+ }
168
+ /**
169
+ * The size of the node's this.#relationshipName relationship, or, if
170
+ * reading it yields, what was read up to there, for #fetchSizeRest.
171
+ */
172
+ #fetchSizeNow(node) {
152
173
  const relationship = node.relationships[this.#relationshipName];
153
174
  assert(relationship, () => `Exists: relationship "${this.#relationshipName}" not found on node`);
154
175
  if (this.#inPush) {
155
176
  let size = 0;
156
- for (const n of relationship(true)) if (n === "yield") yield "yield";
157
- else size++;
158
- return size;
177
+ const it = relationship(true)[Symbol.iterator]();
178
+ for (;;) {
179
+ const r = it.next();
180
+ if (r.done) return size;
181
+ if (r.value === "yield") return {
182
+ it,
183
+ size,
184
+ children: void 0
185
+ };
186
+ size++;
187
+ }
159
188
  }
160
189
  const children = [];
161
- for (const n of relationship()) if (n === "yield") yield "yield";
162
- else children.push(n);
190
+ const it = relationship()[Symbol.iterator]();
191
+ for (;;) {
192
+ const r = it.next();
193
+ if (r.done) break;
194
+ if (r.value === "yield") return {
195
+ it,
196
+ size: 0,
197
+ children
198
+ };
199
+ children.push(r.value);
200
+ }
163
201
  node.relationships[this.#relationshipName] = () => children;
164
202
  return children.length;
165
203
  }
204
+ /** #fetchSizeNow from the 'yield' it stopped at. */
205
+ *#fetchSizeRest(node, { it, size, children }) {
206
+ let ended = false;
207
+ try {
208
+ yield "yield";
209
+ for (;;) {
210
+ const r = it.next();
211
+ if (r.done) {
212
+ ended = true;
213
+ break;
214
+ }
215
+ if (r.value === "yield") yield "yield";
216
+ else if (children) children.push(r.value);
217
+ else size++;
218
+ }
219
+ } finally {
220
+ if (!ended) it.return?.();
221
+ }
222
+ if (children) {
223
+ node.relationships[this.#relationshipName] = () => children;
224
+ return children.length;
225
+ }
226
+ return size;
227
+ }
166
228
  };
229
+ var emptyIteratorReturnFalse = makeEmptyIteratorWithReturn(false);
167
230
  //#endregion
168
231
  export { Exists };
169
232