@pretable/core 0.20.3 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -5264,6 +5264,7 @@ var CompiledQueryPlan = class CompiledQueryPlan {
5264
5264
  constructor(capturedColumns, capturedQuery, operation, filterAuthority, sortAuthority) {
5265
5265
  _classPrivateMethodInitSpec(this, _CompiledQueryPlan_brand);
5266
5266
  _defineProperty(this, "activeColumnIds", void 0);
5267
+ _defineProperty(this, "aggregateColumnIds", void 0);
5267
5268
  _classPrivateFieldInitSpec(this, _publicColumns, void 0);
5268
5269
  _classPrivateFieldInitSpec(this, _publicQuery, void 0);
5269
5270
  _classPrivateFieldInitSpec(this, _runtimeColumns, void 0);
@@ -5293,6 +5294,7 @@ var CompiledQueryPlan = class CompiledQueryPlan {
5293
5294
  _classPrivateFieldGet2(_runtimeQuery, this).rowGroups.forEach((entry) => activeIds.add(entry.columnId));
5294
5295
  _classPrivateFieldGet2(_runtimeQuery, this).sort.forEach((entry) => activeIds.add(entry.columnId));
5295
5296
  _classPrivateFieldSet2(_aggregateColumns, this, _classPrivateFieldGet2(_runtimeColumns, this).filter((column) => column.aggregate !== void 0));
5297
+ this.aggregateColumnIds = Object.freeze(_classPrivateFieldGet2(_aggregateColumns, this).map((column) => column.id));
5296
5298
  _classPrivateFieldGet2(_aggregateColumns, this).forEach((column) => activeIds.add(column.id));
5297
5299
  _classPrivateFieldSet2(_active, this, _classPrivateFieldGet2(_runtimeColumns, this).filter((column) => activeIds.has(column.id)));
5298
5300
  this.activeColumnIds = Object.freeze(_classPrivateFieldGet2(_active, this).map((column) => column.id));
@@ -5747,45 +5749,22 @@ function compileQuery(input) {
5747
5749
  return new CompiledQueryPlan(captured.columns, captured.query, (_input$operation = input.operation) !== null && _input$operation !== void 0 ? _input$operation : "set-query", captured.filterAuthority, captured.sortAuthority);
5748
5750
  }
5749
5751
 
5750
- // ../row-model/dist/membership-bitset.js
5752
+ // ../row-model/dist/ordered-row-entry.js
5751
5753
  /**
5752
- * Membership bitsets: one bit per SLOT (see `slot-allocator`). A committed
5753
- * root's verdict is its membership (the filter-membership invariant); the
5754
- * bitset is a faster INDEX of that same structural answer for flat roots,
5755
- * never a stored verdict. Grouped roots carry `EMPTY_MEMBERSHIP` and keep
5756
- * answering from the group index.
5757
- *
5758
- * Mutable while a producer is building the next revision's set; frozen by
5759
- * convention once a root captures it (no Object.freeze — typed arrays do not
5760
- * support it; discipline is "producers build fresh or clone, never write a
5761
- * captured root's bitset", the same convention every persistent structure
5762
- * here relies on).
5754
+ * Standalone module because both visible-index and group-index need it and
5755
+ * visible-index already imports group-index — either home would cycle.
5763
5756
  *
5764
- * Whole-copy on change is the point: 50k rows is 6.25KB, negligible per
5765
- * commit (M0 measured ~1µs), so no COW machinery exists at this layer.
5757
+ * Decorates a record for tree residence: ONE store get, at insert time. The
5758
+ * record must already be evaluated (or swap-filled) under `queryPlan` —
5759
+ * `sortKeysOf` throws otherwise, which is the fail-loud contract. Entry keys
5760
+ * stay valid for the tree's lifetime because a tree is bound to one plan
5761
+ * (the A2 rebuild-or-reseed invariant) and row updates replace the entry.
5766
5762
  */
5767
- /** Shared sentinel for roots whose membership lives elsewhere (grouped). */
5768
- const EMPTY_MEMBERSHIP = /* @__PURE__ */ new Uint32Array(0);
5769
- function createMembership(capacity) {
5770
- return new Uint32Array(capacity + 31 >>> 5);
5771
- }
5772
- /** Clone, growing to `capacity` when it exceeds the source's words. */
5773
- function cloneMembership(bits, capacity) {
5774
- const words = Math.max(bits.length, capacity + 31 >>> 5);
5775
- const next = new Uint32Array(words);
5776
- next.set(bits);
5777
- return next;
5778
- }
5779
- function setMembershipBit(bits, slot) {
5780
- bits[slot >>> 5] |= 1 << (slot & 31);
5781
- }
5782
- function clearMembershipBit(bits, slot) {
5783
- bits[slot >>> 5] &= ~(1 << (slot & 31));
5784
- }
5785
- /** Out-of-range slots read as false — the EMPTY sentinel relies on this. */
5786
- function testMembershipBit(bits, slot) {
5787
- const word = bits[slot >>> 5];
5788
- return word === void 0 ? false : (word >>> (slot & 31) & 1) === 1;
5763
+ function orderedRowEntry(queryPlan, record) {
5764
+ return Object.freeze({
5765
+ record,
5766
+ keys: sortKeysOf(queryPlan, record)
5767
+ });
5789
5768
  }
5790
5769
 
5791
5770
  // ../row-model/dist/persistent/transient.js
@@ -6865,98 +6844,6 @@ function instrumentMeasuredOrderStatisticTree(tree, instrumentation, beforeCombi
6865
6844
  return tree[attachInstrumentation$1](instrumentation, beforeCombine);
6866
6845
  }
6867
6846
 
6868
- // ../row-model/dist/slot-vector.js
6869
- /**
6870
- * Immutable chunked slot-indexed vector: a chunk table over
6871
- * `SLOT_VECTOR_CHUNK`-element chunks, copy-on-write per commit. A commit
6872
- * touching k slots copies the table plus each touched chunk once — this is
6873
- * what keeps old snapshots valid under slot reuse: every revision holds its
6874
- * own table, so revision N still binds slot s to whatever row owned s at
6875
- * revision N no matter what later commits do (M0 priced maintenance at
6876
- * ~33–98µs per 100-write commit).
6877
- *
6878
- * Holes (`undefined`) are free slots. Iteration hole-skips, which is why no
6879
- * separate "live" bitset exists (recorded plan deviation from the spec).
6880
- */
6881
- const SLOT_VECTOR_CHUNK = 1024;
6882
- const EMPTY = Object.freeze({ chunks: Object.freeze([]) });
6883
- function slotVectorFromEntries(entries, capacity) {
6884
- const tableSize = Math.ceil(capacity / SLOT_VECTOR_CHUNK);
6885
- const limit = tableSize * SLOT_VECTOR_CHUNK;
6886
- const chunks = new Array(tableSize);
6887
- for (const [slot, value] of entries) {
6888
- if (slot >= limit) throw new RangeError(`Slot ${slot} is beyond capacity ${capacity}.`);
6889
- const index = slot / SLOT_VECTOR_CHUNK | 0;
6890
- let chunk = chunks[index];
6891
- if (chunk === void 0) {
6892
- chunk = new Array(SLOT_VECTOR_CHUNK);
6893
- chunks[index] = chunk;
6894
- }
6895
- chunk[slot % SLOT_VECTOR_CHUNK] = value;
6896
- }
6897
- return { chunks };
6898
- }
6899
- /**
6900
- * One commit's writes (`undefined` value = clear the slot), COW: table copied
6901
- * once, each touched chunk copied once. `capacity` may exceed the old
6902
- * table's reach (allocator growth).
6903
- *
6904
- * `chunksTouched` counts every chunk this commit allocated or copied,
6905
- * including a brand-new chunk created for a hole beyond the old table — that
6906
- * counts as touched even though nothing was copied.
6907
- */
6908
- function slotVectorWithAll(vector, writes, capacity) {
6909
- const tableSize = Math.max(vector.chunks.length, Math.ceil(capacity / SLOT_VECTOR_CHUNK));
6910
- const limit = tableSize * SLOT_VECTOR_CHUNK;
6911
- const chunks = new Array(tableSize);
6912
- for (let i = 0; i < vector.chunks.length; i += 1) chunks[i] = vector.chunks[i];
6913
- let chunksTouched = 0;
6914
- for (const [slot, value] of writes) {
6915
- if (slot >= limit) throw new RangeError(`Slot ${slot} is beyond capacity ${capacity}.`);
6916
- const index = slot / SLOT_VECTOR_CHUNK | 0;
6917
- if (chunks[index] === void 0 || chunks[index] === vector.chunks[index]) {
6918
- const existing = chunks[index];
6919
- chunks[index] = existing === void 0 ? new Array(SLOT_VECTOR_CHUNK) : existing.slice();
6920
- chunksTouched += 1;
6921
- }
6922
- chunks[index][slot % SLOT_VECTOR_CHUNK] = value;
6923
- }
6924
- return {
6925
- next: { chunks },
6926
- chunksTouched
6927
- };
6928
- }
6929
- /** Hole-skipping walk in slot order. */
6930
- function forEachSlotEntry(vector, callback) {
6931
- for (let index = 0; index < vector.chunks.length; index += 1) {
6932
- const chunk = vector.chunks[index];
6933
- if (chunk === void 0) continue;
6934
- const base = index * SLOT_VECTOR_CHUNK;
6935
- for (let offset = 0; offset < chunk.length; offset += 1) {
6936
- const value = chunk[offset];
6937
- if (value !== void 0) callback(value, base + offset);
6938
- }
6939
- }
6940
- }
6941
-
6942
- // ../row-model/dist/ordered-row-entry.js
6943
- /**
6944
- * Standalone module because both visible-index and group-index need it and
6945
- * visible-index already imports group-index — either home would cycle.
6946
- *
6947
- * Decorates a record for tree residence: ONE store get, at insert time. The
6948
- * record must already be evaluated (or swap-filled) under `queryPlan` —
6949
- * `sortKeysOf` throws otherwise, which is the fail-loud contract. Entry keys
6950
- * stay valid for the tree's lifetime because a tree is bound to one plan
6951
- * (the A2 rebuild-or-reseed invariant) and row updates replace the entry.
6952
- */
6953
- function orderedRowEntry(queryPlan, record) {
6954
- return Object.freeze({
6955
- record,
6956
- keys: sortKeysOf(queryPlan, record)
6957
- });
6958
- }
6959
-
6960
6847
  // ../row-model/dist/persistent/aggregate-tree.js
6961
6848
  const attachInstrumentation = Symbol("attachAggregateInstrumentation");
6962
6849
  const createDeferredMeasureDraft = Symbol("createDeferredMeasureDraft");
@@ -8526,6 +8413,307 @@ function nearestVisible(root, ref, policy) {
8526
8413
  }
8527
8414
  }
8528
8415
 
8416
+ // ../row-model/dist/filter-membership.js
8417
+ /**
8418
+ * Filter verdicts are not stored. A committed root already carries the answer
8419
+ * structurally: a row passes this root's filters exactly when it is a MEMBER
8420
+ * of the root's visible structure. This module is the one place that knows
8421
+ * which structure answers for which root shape.
8422
+ *
8423
+ * - **Flat root** (`query.rowGroups.length === 0`): `root.visible.rows` holds
8424
+ * one entry per passing row and nothing else, so membership is a lookup.
8425
+ * This is the same predicate `nearestVisibleRef` has always used.
8426
+ * - **Grouped root**: `root.visible.rows` is deliberately EMPTY (a grouped
8427
+ * visible index attaches the group index to an empty flat tree), so the
8428
+ * answer lives in the group index: every inserted row — passing or not —
8429
+ * gets a `rowParents` entry, and only passing rows are inserted into their
8430
+ * leaf group's `leaves` tree. So `rowParents` locates the leaf group and
8431
+ * `leaves` holds the verdict.
8432
+ *
8433
+ * Absence is the answer, not a fault: a row this root never saw, or one its
8434
+ * filters reject, is simply not a member. Nothing here fails loud.
8435
+ *
8436
+ * These read a COMMITTED root, so they answer "did this row pass under the
8437
+ * plan that built this root" — the OLD verdict at every site that compares
8438
+ * against a new one. A NEW verdict is computed, never resolved: producers
8439
+ * call `filterVerdict(plan, record)` and use it locally to decide where the
8440
+ * row goes.
8441
+ */
8442
+ /** Did `rowId` pass the filters of the plan that built `root`? */
8443
+ function rowPassesFilter(root, rowId) {
8444
+ const grouped = getGroupIndex(root.visible);
8445
+ return grouped === void 0 ? root.visible.rows.get(rowId) !== void 0 : rowPassesFilterInGroupIndex(grouped, rowId);
8446
+ }
8447
+
8448
+ // ../row-model/dist/summary-index.js
8449
+ function emptyRoots(plan, instrumentation) {
8450
+ const roots = /* @__PURE__ */ new Map();
8451
+ for (const column of plan.derivations) {
8452
+ if (column.aggregate === void 0) continue;
8453
+ const aggregate = lowerCalendarDateAggregate(column.type, column.aggregate);
8454
+ const factory = createAggregateTree;
8455
+ const tree = isScalarBuiltinAggregator(aggregate) ? createScalarAggregateCell({
8456
+ columnId: column.id,
8457
+ aggregator: aggregate
8458
+ }) : factory({
8459
+ columnId: column.id,
8460
+ aggregator: aggregate,
8461
+ compare: (a, b) => compareWithSortKeys(plan, {
8462
+ rowId: a.id,
8463
+ row: a.row,
8464
+ sourceOrder: a.dependency.sourceOrder
8465
+ }, a.dependency.sortKeys, {
8466
+ rowId: b.id,
8467
+ row: b.row,
8468
+ sourceOrder: b.dependency.sourceOrder
8469
+ }, b.dependency.sortKeys)
8470
+ });
8471
+ roots.set(column.id, instrumentAggregateTree(tree, instrumentation));
8472
+ }
8473
+ return roots;
8474
+ }
8475
+ function finish(roots) {
8476
+ const results = {};
8477
+ for (const scope of ["all", "filtered"]) {
8478
+ const trees = roots[scope];
8479
+ if (trees === void 0) continue;
8480
+ const values = Object.create(null);
8481
+ for (const [id, tree] of trees) values[id] = tree.finalize();
8482
+ results[scope] = Object.freeze({
8483
+ scope,
8484
+ values: Object.freeze(values)
8485
+ });
8486
+ }
8487
+ return Object.freeze({
8488
+ roots: Object.freeze(roots),
8489
+ results: Object.freeze(results)
8490
+ });
8491
+ }
8492
+ function contribute(roots, record, plan, add, instrumentation) {
8493
+ if (instrumentation) instrumentation.work.summaryRowsVisited += 1;
8494
+ const next = new Map(roots);
8495
+ for (const entry of record.metadata.aggregateLeaves) {
8496
+ const tree = next.get(entry.columnId);
8497
+ if (tree === void 0) continue;
8498
+ if (instrumentation) instrumentation.work.summaryCellsUpdated += 1;
8499
+ const leaf = {
8500
+ ...entry.allLeaf,
8501
+ dependency: {
8502
+ sourceOrder: record.sourceOrder,
8503
+ sortKeys: sortKeysOf(plan, record)
8504
+ }
8505
+ };
8506
+ next.set(entry.columnId, add ? tree.insertOrReplace(leaf) : tree.remove(record.rowId, leaf));
8507
+ }
8508
+ return next;
8509
+ }
8510
+ /** Only affected records are visited, scalar cells apply exact inverse deltas. */
8511
+ function updateSummaryIndex(previous, next, ids, instrumentation) {
8512
+ if (previous.summaries === void 0) return void 0;
8513
+ const roots = { ...previous.summaries.roots };
8514
+ for (const scope of ["all", "filtered"]) {
8515
+ let trees = roots[scope];
8516
+ if (trees === void 0) continue;
8517
+ for (const id of ids) {
8518
+ const old = previous.rows.get(id);
8519
+ const current = next.rows.get(id);
8520
+ if (old && (scope === "all" || rowPassesFilter(previous, id))) trees = contribute(trees, old, previous.queryPlan, false, instrumentation);
8521
+ if (current && (scope === "all" || rowPassesFilter(next, id))) trees = contribute(trees, current, next.queryPlan, true, instrumentation);
8522
+ }
8523
+ roots[scope] = trees;
8524
+ }
8525
+ return finish(roots);
8526
+ }
8527
+ function retainSummaryScopes(index, scopes) {
8528
+ if (index === void 0 || scopes.length === 0) return void 0;
8529
+ const roots = {};
8530
+ const results = {};
8531
+ for (const scope of scopes) {
8532
+ roots[scope] = index.roots[scope];
8533
+ results[scope] = index.results[scope];
8534
+ }
8535
+ return Object.freeze({
8536
+ roots: Object.freeze(roots),
8537
+ results: Object.freeze(results)
8538
+ });
8539
+ }
8540
+ /** A private rebuild: one source record or replay record per cooperative step. */
8541
+ function createSummaryBuild(captured, plan, scopes, instrumentation) {
8542
+ let activeScopes = [...scopes];
8543
+ const roots = {};
8544
+ for (const scope of activeScopes) roots[scope] = emptyRoots(plan, instrumentation);
8545
+ const records = /* @__PURE__ */ new Map();
8546
+ let iterator = captured.rows.entries();
8547
+ const deltas = /* @__PURE__ */ new Map();
8548
+ function replace(id, original) {
8549
+ const old = records.get(id);
8550
+ if (old) {
8551
+ for (const scope of activeScopes) if (scope === "all" || old.matches) roots[scope] = contribute(roots[scope], old.record, plan, false, instrumentation);
8552
+ }
8553
+ records.delete(id);
8554
+ if (!original) return;
8555
+ const record = plan === captured.queryPlan ? original : {
8556
+ ...original,
8557
+ metadata: plan.evaluate({
8558
+ rowId: id,
8559
+ row: original.row,
8560
+ sourceOrder: original.sourceOrder,
8561
+ slot: original.slot
8562
+ })
8563
+ };
8564
+ const matches = filterVerdict(plan, record);
8565
+ records.set(id, {
8566
+ record,
8567
+ matches
8568
+ });
8569
+ for (const scope of activeScopes) if (scope === "all" || matches) roots[scope] = contribute(roots[scope], record, plan, true, instrumentation);
8570
+ }
8571
+ return {
8572
+ retainScopes(requested) {
8573
+ activeScopes = activeScopes.filter((scope) => requested.includes(scope));
8574
+ for (const scope of ["all", "filtered"]) if (!activeScopes.includes(scope)) delete roots[scope];
8575
+ },
8576
+ append(target, ids) {
8577
+ for (const id of ids) deltas.set(id, target.rows.get(id));
8578
+ },
8579
+ step() {
8580
+ if (iterator) {
8581
+ const item = iterator.next();
8582
+ if (!item.done) {
8583
+ replace(item.value[0], item.value[1]);
8584
+ return false;
8585
+ }
8586
+ iterator = void 0;
8587
+ }
8588
+ const delta = deltas.entries().next();
8589
+ if (!delta.done) {
8590
+ deltas.delete(delta.value[0]);
8591
+ replace(delta.value[0], delta.value[1]);
8592
+ return false;
8593
+ }
8594
+ return true;
8595
+ },
8596
+ finish() {
8597
+ return finish(roots);
8598
+ }
8599
+ };
8600
+ }
8601
+
8602
+ // ../row-model/dist/membership-bitset.js
8603
+ /**
8604
+ * Membership bitsets: one bit per SLOT (see `slot-allocator`). A committed
8605
+ * root's verdict is its membership (the filter-membership invariant); the
8606
+ * bitset is a faster INDEX of that same structural answer for flat roots,
8607
+ * never a stored verdict. Grouped roots carry `EMPTY_MEMBERSHIP` and keep
8608
+ * answering from the group index.
8609
+ *
8610
+ * Mutable while a producer is building the next revision's set; frozen by
8611
+ * convention once a root captures it (no Object.freeze — typed arrays do not
8612
+ * support it; discipline is "producers build fresh or clone, never write a
8613
+ * captured root's bitset", the same convention every persistent structure
8614
+ * here relies on).
8615
+ *
8616
+ * Whole-copy on change is the point: 50k rows is 6.25KB, negligible per
8617
+ * commit (M0 measured ~1µs), so no COW machinery exists at this layer.
8618
+ */
8619
+ /** Shared sentinel for roots whose membership lives elsewhere (grouped). */
8620
+ const EMPTY_MEMBERSHIP = /* @__PURE__ */ new Uint32Array(0);
8621
+ function createMembership(capacity) {
8622
+ return new Uint32Array(capacity + 31 >>> 5);
8623
+ }
8624
+ /** Clone, growing to `capacity` when it exceeds the source's words. */
8625
+ function cloneMembership(bits, capacity) {
8626
+ const words = Math.max(bits.length, capacity + 31 >>> 5);
8627
+ const next = new Uint32Array(words);
8628
+ next.set(bits);
8629
+ return next;
8630
+ }
8631
+ function setMembershipBit(bits, slot) {
8632
+ bits[slot >>> 5] |= 1 << (slot & 31);
8633
+ }
8634
+ function clearMembershipBit(bits, slot) {
8635
+ bits[slot >>> 5] &= ~(1 << (slot & 31));
8636
+ }
8637
+ /** Out-of-range slots read as false — the EMPTY sentinel relies on this. */
8638
+ function testMembershipBit(bits, slot) {
8639
+ const word = bits[slot >>> 5];
8640
+ return word === void 0 ? false : (word >>> (slot & 31) & 1) === 1;
8641
+ }
8642
+
8643
+ // ../row-model/dist/slot-vector.js
8644
+ /**
8645
+ * Immutable chunked slot-indexed vector: a chunk table over
8646
+ * `SLOT_VECTOR_CHUNK`-element chunks, copy-on-write per commit. A commit
8647
+ * touching k slots copies the table plus each touched chunk once — this is
8648
+ * what keeps old snapshots valid under slot reuse: every revision holds its
8649
+ * own table, so revision N still binds slot s to whatever row owned s at
8650
+ * revision N no matter what later commits do (M0 priced maintenance at
8651
+ * ~33–98µs per 100-write commit).
8652
+ *
8653
+ * Holes (`undefined`) are free slots. Iteration hole-skips, which is why no
8654
+ * separate "live" bitset exists (recorded plan deviation from the spec).
8655
+ */
8656
+ const SLOT_VECTOR_CHUNK = 1024;
8657
+ const EMPTY = Object.freeze({ chunks: Object.freeze([]) });
8658
+ function slotVectorFromEntries(entries, capacity) {
8659
+ const tableSize = Math.ceil(capacity / SLOT_VECTOR_CHUNK);
8660
+ const limit = tableSize * SLOT_VECTOR_CHUNK;
8661
+ const chunks = new Array(tableSize);
8662
+ for (const [slot, value] of entries) {
8663
+ if (slot >= limit) throw new RangeError(`Slot ${slot} is beyond capacity ${capacity}.`);
8664
+ const index = slot / SLOT_VECTOR_CHUNK | 0;
8665
+ let chunk = chunks[index];
8666
+ if (chunk === void 0) {
8667
+ chunk = new Array(SLOT_VECTOR_CHUNK);
8668
+ chunks[index] = chunk;
8669
+ }
8670
+ chunk[slot % SLOT_VECTOR_CHUNK] = value;
8671
+ }
8672
+ return { chunks };
8673
+ }
8674
+ /**
8675
+ * One commit's writes (`undefined` value = clear the slot), COW: table copied
8676
+ * once, each touched chunk copied once. `capacity` may exceed the old
8677
+ * table's reach (allocator growth).
8678
+ *
8679
+ * `chunksTouched` counts every chunk this commit allocated or copied,
8680
+ * including a brand-new chunk created for a hole beyond the old table — that
8681
+ * counts as touched even though nothing was copied.
8682
+ */
8683
+ function slotVectorWithAll(vector, writes, capacity) {
8684
+ const tableSize = Math.max(vector.chunks.length, Math.ceil(capacity / SLOT_VECTOR_CHUNK));
8685
+ const limit = tableSize * SLOT_VECTOR_CHUNK;
8686
+ const chunks = new Array(tableSize);
8687
+ for (let i = 0; i < vector.chunks.length; i += 1) chunks[i] = vector.chunks[i];
8688
+ let chunksTouched = 0;
8689
+ for (const [slot, value] of writes) {
8690
+ if (slot >= limit) throw new RangeError(`Slot ${slot} is beyond capacity ${capacity}.`);
8691
+ const index = slot / SLOT_VECTOR_CHUNK | 0;
8692
+ if (chunks[index] === void 0 || chunks[index] === vector.chunks[index]) {
8693
+ const existing = chunks[index];
8694
+ chunks[index] = existing === void 0 ? new Array(SLOT_VECTOR_CHUNK) : existing.slice();
8695
+ chunksTouched += 1;
8696
+ }
8697
+ chunks[index][slot % SLOT_VECTOR_CHUNK] = value;
8698
+ }
8699
+ return {
8700
+ next: { chunks },
8701
+ chunksTouched
8702
+ };
8703
+ }
8704
+ /** Hole-skipping walk in slot order. */
8705
+ function forEachSlotEntry(vector, callback) {
8706
+ for (let index = 0; index < vector.chunks.length; index += 1) {
8707
+ const chunk = vector.chunks[index];
8708
+ if (chunk === void 0) continue;
8709
+ const base = index * SLOT_VECTOR_CHUNK;
8710
+ for (let offset = 0; offset < chunk.length; offset += 1) {
8711
+ const value = chunk[offset];
8712
+ if (value !== void 0) callback(value, base + offset);
8713
+ }
8714
+ }
8715
+ }
8716
+
8529
8717
  // ../row-model/dist/visible-index.js
8530
8718
  function createFlatVisibleIndex(records, queryPlan) {
8531
8719
  const draft = createFlatVisibleTree(queryPlan).asTransient();
@@ -8582,6 +8770,11 @@ function createFlatSnapshot(root) {
8582
8770
  const count = visibleCount(grouped, policy);
8583
8771
  const dataCount = visibleDataCount(grouped, policy);
8584
8772
  return Object.freeze({
8773
+ getSummary: (scope) => {
8774
+ var _root$summaries;
8775
+ return (_root$summaries = root.summaries) === null || _root$summaries === void 0 ? void 0 : _root$summaries.results[scope];
8776
+ },
8777
+ aggregateColumnIds: root.queryPlan.aggregateColumnIds,
8585
8778
  revision: root.revision,
8586
8779
  sourceRowCount: root.rows.size,
8587
8780
  visibleRowCount: count,
@@ -8616,6 +8809,11 @@ function createFlatSnapshot(root) {
8616
8809
  };
8617
8810
  const lookupRank = (ref) => ref.kind === "data" ? visible.rankOf(ref.rowId) : void 0;
8618
8811
  return Object.freeze({
8812
+ getSummary: (scope) => {
8813
+ var _root$summaries2;
8814
+ return (_root$summaries2 = root.summaries) === null || _root$summaries2 === void 0 ? void 0 : _root$summaries2.results[scope];
8815
+ },
8816
+ aggregateColumnIds: root.queryPlan.aggregateColumnIds,
8619
8817
  revision: root.revision,
8620
8818
  sourceRowCount: root.rows.size,
8621
8819
  visibleRowCount: visible.size,
@@ -8748,38 +8946,6 @@ function rebuildRootForFilterOnlyChange(options) {
8748
8946
  return root;
8749
8947
  }
8750
8948
 
8751
- // ../row-model/dist/filter-membership.js
8752
- /**
8753
- * Filter verdicts are not stored. A committed root already carries the answer
8754
- * structurally: a row passes this root's filters exactly when it is a MEMBER
8755
- * of the root's visible structure. This module is the one place that knows
8756
- * which structure answers for which root shape.
8757
- *
8758
- * - **Flat root** (`query.rowGroups.length === 0`): `root.visible.rows` holds
8759
- * one entry per passing row and nothing else, so membership is a lookup.
8760
- * This is the same predicate `nearestVisibleRef` has always used.
8761
- * - **Grouped root**: `root.visible.rows` is deliberately EMPTY (a grouped
8762
- * visible index attaches the group index to an empty flat tree), so the
8763
- * answer lives in the group index: every inserted row — passing or not —
8764
- * gets a `rowParents` entry, and only passing rows are inserted into their
8765
- * leaf group's `leaves` tree. So `rowParents` locates the leaf group and
8766
- * `leaves` holds the verdict.
8767
- *
8768
- * Absence is the answer, not a fault: a row this root never saw, or one its
8769
- * filters reject, is simply not a member. Nothing here fails loud.
8770
- *
8771
- * These read a COMMITTED root, so they answer "did this row pass under the
8772
- * plan that built this root" — the OLD verdict at every site that compares
8773
- * against a new one. A NEW verdict is computed, never resolved: producers
8774
- * call `filterVerdict(plan, record)` and use it locally to decide where the
8775
- * row goes.
8776
- */
8777
- /** Did `rowId` pass the filters of the plan that built `root`? */
8778
- function rowPassesFilter(root, rowId) {
8779
- const grouped = getGroupIndex(root.visible);
8780
- return grouped === void 0 ? root.visible.rows.get(rowId) !== void 0 : rowPassesFilterInGroupIndex(grouped, rowId);
8781
- }
8782
-
8783
8949
  // ../row-model/dist/sort-rebuild.js
8784
8950
  /**
8785
8951
  * Synchronous whole-root rebuild for a sort-only plan change on an ungrouped
@@ -11394,10 +11560,21 @@ function applyFlatTransactionDraft(input) {
11394
11560
  const slotWrites = [...removedRecords.map((record) => [record.slot, void 0]), ...prepared.map((record) => [record.slot, record])];
11395
11561
  const { next: recordsBySlot, chunksTouched } = slotVectorWithAll(input.root.recordsBySlot, slotWrites, input.slots.capacity);
11396
11562
  if (input.instrumentation !== void 0) input.instrumentation.work.slotChunksTouched += chunksTouched;
11563
+ const frozenSource = sourceDraft.freeze();
11564
+ const summaries = input.root.summaries === void 0 ? void 0 : updateSummaryIndex(input.root, {
11565
+ ...input.root,
11566
+ rows: frozenRows,
11567
+ sourceOrder: frozenSource,
11568
+ visible,
11569
+ recordsBySlot,
11570
+ visibleSlots,
11571
+ queryPlan: input.queryPlan
11572
+ }, [...effectiveRemoves, ...prepared.map((record) => record.rowId)], input.instrumentation);
11397
11573
  for (const record of removedRecords) input.slots.release(record.slot);
11398
11574
  return {
11399
11575
  rows: frozenRows,
11400
- sourceOrder: sourceDraft.freeze(),
11576
+ sourceOrder: frozenSource,
11577
+ summaries,
11401
11578
  visible,
11402
11579
  recordsBySlot,
11403
11580
  visibleSlots,
@@ -11619,10 +11796,20 @@ function replaceFlatRowsDraft(input) {
11619
11796
  const slotWrites = [...removedRecords.map((record) => [record.slot, void 0]), ...changedRecords.map((record) => [record.slot, record])];
11620
11797
  const { next: recordsBySlot, chunksTouched } = slotVectorWithAll(input.root.recordsBySlot, slotWrites, input.slots.capacity);
11621
11798
  if (input.instrumentation !== void 0) input.instrumentation.work.slotChunksTouched += chunksTouched;
11799
+ const summaries = input.root.summaries === void 0 ? void 0 : updateSummaryIndex(input.root, {
11800
+ ...input.root,
11801
+ rows: frozenRows,
11802
+ sourceOrder: frozenSource,
11803
+ visible,
11804
+ recordsBySlot,
11805
+ visibleSlots,
11806
+ queryPlan: input.queryPlan
11807
+ }, [...removedRecords.map((record) => record.rowId), ...changedRecords.map((record) => record.rowId)], input.instrumentation);
11622
11808
  for (const slot of reusableRemovedSlots) input.slots.release(slot);
11623
11809
  return {
11624
11810
  rows: frozenRows,
11625
11811
  sourceOrder: frozenSource,
11812
+ summaries,
11626
11813
  visible,
11627
11814
  recordsBySlot,
11628
11815
  visibleSlots,
@@ -11928,6 +12115,25 @@ function createLocalRowModel$1(options) {
11928
12115
  let nextSourceOrder = initialStore.records.length;
11929
12116
  let nextTransitionId = 1;
11930
12117
  let activeTransition;
12118
+ const summaryLeases = /* @__PURE__ */ new Map();
12119
+ const requestedSummaryScopes = () => ["all", "filtered"].filter((scope) => {
12120
+ var _summaryLeases$get;
12121
+ return ((_summaryLeases$get = summaryLeases.get(scope)) !== null && _summaryLeases$get !== void 0 ? _summaryLeases$get : 0) > 0;
12122
+ });
12123
+ let summaryAcquisition;
12124
+ let cancelSummaryRetry;
12125
+ const cancelSummaryAcquisition = () => {
12126
+ try {
12127
+ cancelSummaryRetry === null || cancelSummaryRetry === void 0 || cancelSummaryRetry();
12128
+ } catch (_unused2) {}
12129
+ cancelSummaryRetry = void 0;
12130
+ const pending = summaryAcquisition;
12131
+ summaryAcquisition = void 0;
12132
+ try {
12133
+ var _pending$cancel;
12134
+ pending === null || pending === void 0 || (_pending$cancel = pending.cancel) === null || _pending$cancel === void 0 || _pending$cancel.call(pending);
12135
+ } catch (_unused3) {}
12136
+ };
11931
12137
  const listeners = /* @__PURE__ */ new Set();
11932
12138
  const changeJournal = createChangeJournal(options.changeJournalCapacity);
11933
12139
  const sortFastPathRowLimit = (_options$ɵsortFastPa = options.ɵsortFastPathRowLimit) !== null && _options$ɵsortFastPa !== void 0 ? _options$ɵsortFastPa : SORT_FAST_PATH_ROW_LIMIT_DEFAULT;
@@ -11979,9 +12185,10 @@ function createLocalRowModel$1(options) {
11979
12185
  const notify = () => {
11980
12186
  for (const listener of Array.from(listeners)) try {
11981
12187
  listener();
11982
- } catch (_unused2) {}
12188
+ } catch (_unused4) {}
11983
12189
  };
11984
12190
  const publishCommittedRoot = (committedRoot, previousRevision, revision, barrierReason = "bulk-replace") => {
12191
+ cancelSummaryAcquisition();
11985
12192
  queryPlan = committedRoot.queryPlan;
11986
12193
  query = committedRoot.queryPlan.query;
11987
12194
  derivations = committedRoot.queryPlan.derivations;
@@ -12004,7 +12211,8 @@ function createLocalRowModel$1(options) {
12004
12211
  transition.cancelScheduled = void 0;
12005
12212
  try {
12006
12213
  cancelScheduled === null || cancelScheduled === void 0 || cancelScheduled();
12007
- } catch (_unused3) {}
12214
+ } catch (_unused5) {}
12215
+ transition.summaryBuild = void 0;
12008
12216
  transition.candidate.release();
12009
12217
  transition.reject(new PretableTransitionCancelledError(transition.id, reason));
12010
12218
  return transition;
@@ -12017,7 +12225,8 @@ function createLocalRowModel$1(options) {
12017
12225
  transition.cancelScheduled = void 0;
12018
12226
  try {
12019
12227
  cancelScheduled === null || cancelScheduled === void 0 || cancelScheduled();
12020
- } catch (_unused4) {}
12228
+ } catch (_unused6) {}
12229
+ transition.summaryBuild = void 0;
12021
12230
  transition.candidate.release();
12022
12231
  const typed = (_findPretableReentran = findPretableReentrantMutationError(error)) !== null && _findPretableReentran !== void 0 ? _findPretableReentran : transitionError(error, transition.operation);
12023
12232
  state = Object.freeze({
@@ -12049,7 +12258,18 @@ function createLocalRowModel$1(options) {
12049
12258
  const runTransitionSlice = (transition) => {
12050
12259
  if (activeTransition !== transition || disposed) return false;
12051
12260
  try {
12052
- const complete = runCooperativeTransitionSlice(transitionRuntime, () => transition.candidate.step());
12261
+ var _transition$summaryBu3;
12262
+ const scopes = requestedSummaryScopes();
12263
+ const key = scopes.join(",");
12264
+ if (transition.summaryScopesKey !== key) {
12265
+ transition.summaryScopesKey = key;
12266
+ transition.summaryBuild = scopes.length ? createSummaryBuild(root, transition.summaryPlan, scopes, instrumentation) : void 0;
12267
+ }
12268
+ const complete = runCooperativeTransitionSlice(transitionRuntime, () => {
12269
+ var _transition$summaryBu, _transition$summaryBu2;
12270
+ if (!transition.candidate.step()) return false;
12271
+ return (_transition$summaryBu = (_transition$summaryBu2 = transition.summaryBuild) === null || _transition$summaryBu2 === void 0 ? void 0 : _transition$summaryBu2.step()) !== null && _transition$summaryBu !== void 0 ? _transition$summaryBu : true;
12272
+ });
12053
12273
  if (activeTransition !== transition || disposed) return false;
12054
12274
  if (!complete) {
12055
12275
  state = Object.freeze({
@@ -12061,14 +12281,18 @@ function createLocalRowModel$1(options) {
12061
12281
  }
12062
12282
  const previousRevision = root.revision;
12063
12283
  const revision = previousRevision + 1;
12064
- const committedRoot = transition.candidate.finish(revision);
12284
+ const committedRoot = Object.freeze({
12285
+ ...transition.candidate.finish(revision),
12286
+ summaries: (_transition$summaryBu3 = transition.summaryBuild) === null || _transition$summaryBu3 === void 0 ? void 0 : _transition$summaryBu3.finish()
12287
+ });
12065
12288
  activeTransition = void 0;
12066
12289
  const cancelScheduled = transition.cancelScheduled;
12067
12290
  transition.cancelScheduled = void 0;
12068
12291
  try {
12069
12292
  cancelScheduled === null || cancelScheduled === void 0 || cancelScheduled();
12070
- } catch (_unused5) {}
12293
+ } catch (_unused7) {}
12071
12294
  publishCommittedRoot(committedRoot, previousRevision, revision);
12295
+ transition.summaryBuild = void 0;
12072
12296
  transition.candidate.release();
12073
12297
  transition.resolve(revision);
12074
12298
  return true;
@@ -12096,6 +12320,9 @@ function createLocalRowModel$1(options) {
12096
12320
  operation,
12097
12321
  instrumentation
12098
12322
  }),
12323
+ summaryPlan: nextPlan,
12324
+ summaryScopesKey: "",
12325
+ summaryBuild: void 0,
12099
12326
  finished,
12100
12327
  resolve,
12101
12328
  reject,
@@ -12110,6 +12337,14 @@ function createLocalRowModel$1(options) {
12110
12337
  return transition;
12111
12338
  };
12112
12339
  const appendTransitionDelta = (target, affectedRowIds) => {
12340
+ var _activeTransition$sum;
12341
+ if (summaryAcquisition) {
12342
+ if (summaryAcquisition.rebase !== void 0 || summaryAcquisition.plan !== target.queryPlan) {
12343
+ summaryAcquisition.plan = target.queryPlan;
12344
+ summaryAcquisition.rebase = target;
12345
+ } else summaryAcquisition.build.append(target, affectedRowIds);
12346
+ }
12347
+ activeTransition === null || activeTransition === void 0 || (_activeTransition$sum = activeTransition.summaryBuild) === null || _activeTransition$sum === void 0 || _activeTransition$sum.append(target, affectedRowIds);
12113
12348
  activeTransition === null || activeTransition === void 0 || activeTransition.candidate.append(Object.freeze({
12114
12349
  target,
12115
12350
  affectedRowIds: Object.freeze([...affectedRowIds])
@@ -12169,9 +12404,139 @@ function createLocalRowModel$1(options) {
12169
12404
  throw remapOperationError(error, operation);
12170
12405
  }
12171
12406
  };
12407
+ const reportSummaryFailure = (error) => {
12408
+ if (activeTransition === void 0) state = Object.freeze({
12409
+ snapshot,
12410
+ status: Object.freeze({
12411
+ kind: "error",
12412
+ transitionId: nextTransitionId++,
12413
+ error: transitionError(error, "set-derivations")
12414
+ })
12415
+ });
12416
+ };
12417
+ const restartSummaryAcquisition = () => {
12418
+ const scopes = requestedSummaryScopes();
12419
+ const key = scopes.join(",");
12420
+ if ((summaryAcquisition === null || summaryAcquisition === void 0 ? void 0 : summaryAcquisition.key) === key && summaryAcquisition.plan === root.queryPlan) return;
12421
+ if (scopes.every((scope) => {
12422
+ var _root$summaries;
12423
+ return ((_root$summaries = root.summaries) === null || _root$summaries === void 0 ? void 0 : _root$summaries.results[scope]) !== void 0;
12424
+ })) {
12425
+ cancelSummaryAcquisition();
12426
+ return;
12427
+ }
12428
+ const previousAcquisition = summaryAcquisition;
12429
+ const pending = {
12430
+ plan: root.queryPlan,
12431
+ key,
12432
+ rebase: void 0,
12433
+ build: createSummaryBuild(root, root.queryPlan, scopes, instrumentation),
12434
+ cancel: void 0
12435
+ };
12436
+ summaryAcquisition = pending;
12437
+ const advance = () => {
12438
+ if (disposed || summaryAcquisition !== pending) return;
12439
+ if (pending.rebase !== void 0) {
12440
+ pending.build = createSummaryBuild(pending.rebase, pending.plan, requestedSummaryScopes(), instrumentation);
12441
+ pending.rebase = void 0;
12442
+ }
12443
+ if (runCooperativeTransitionSlice(transitionRuntime, () => pending.build.step())) {
12444
+ const previous = root;
12445
+ const next = Object.freeze({
12446
+ ...root,
12447
+ revision: root.revision + 1,
12448
+ parentRevision: root.revision,
12449
+ summaries: retainSummaryScopes(pending.build.finish(), requestedSummaryScopes())
12450
+ });
12451
+ summaryAcquisition = void 0;
12452
+ appendTransitionDelta(next, []);
12453
+ commit(next);
12454
+ changeJournal.appendChanges(previous.revision, next.revision, Object.freeze([]));
12455
+ } else pending.cancel = transitionRuntime.scheduler.schedule(() => {
12456
+ if (disposed || summaryAcquisition !== pending) return;
12457
+ try {
12458
+ guarded("set-derivations", advance);
12459
+ } catch (error) {
12460
+ cancelSummaryAcquisition();
12461
+ reportSummaryFailure(error);
12462
+ }
12463
+ notify();
12464
+ });
12465
+ };
12466
+ try {
12467
+ advance();
12468
+ } catch (error) {
12469
+ try {
12470
+ var _pending$cancel2;
12471
+ (_pending$cancel2 = pending.cancel) === null || _pending$cancel2 === void 0 || _pending$cancel2.call(pending);
12472
+ } catch (_unused8) {}
12473
+ summaryAcquisition = previousAcquisition;
12474
+ throw error;
12475
+ }
12476
+ try {
12477
+ var _previousAcquisition$;
12478
+ previousAcquisition === null || previousAcquisition === void 0 || (_previousAcquisition$ = previousAcquisition.cancel) === null || _previousAcquisition$ === void 0 || _previousAcquisition$.call(previousAcquisition);
12479
+ } catch (_unused9) {}
12480
+ };
12172
12481
  const model = {
12173
12482
  getState: () => state,
12174
12483
  getColumns: () => columns,
12484
+ acquireSummaryScopes(scopes) {
12485
+ assertCommandAllowed("set-derivations");
12486
+ const unique = [...new Set(scopes)];
12487
+ if (unique.some((scope) => scope !== "all" && scope !== "filtered")) throw new TypeError("Unknown summary scope.");
12488
+ guarded("set-derivations", () => {
12489
+ var _summaryLeases$get2;
12490
+ for (const scope of unique) summaryLeases.set(scope, ((_summaryLeases$get2 = summaryLeases.get(scope)) !== null && _summaryLeases$get2 !== void 0 ? _summaryLeases$get2 : 0) + 1);
12491
+ try {
12492
+ restartSummaryAcquisition();
12493
+ } catch (error) {
12494
+ for (const scope of unique) summaryLeases.set(scope, summaryLeases.get(scope) - 1);
12495
+ throw error;
12496
+ }
12497
+ });
12498
+ notify();
12499
+ let released = false;
12500
+ return () => {
12501
+ if (released || disposed) return;
12502
+ guarded("set-derivations", () => {
12503
+ released = true;
12504
+ for (const scope of unique) summaryLeases.set(scope, summaryLeases.get(scope) - 1);
12505
+ const retained = retainSummaryScopes(root.summaries, requestedSummaryScopes());
12506
+ commit(Object.freeze({
12507
+ ...root,
12508
+ summaries: retained
12509
+ }));
12510
+ const requested = requestedSummaryScopes();
12511
+ if (summaryAcquisition) {
12512
+ summaryAcquisition.build.retainScopes(requested);
12513
+ summaryAcquisition.key = requested.join(",");
12514
+ if (requested.every((scope) => {
12515
+ var _root$summaries2;
12516
+ return ((_root$summaries2 = root.summaries) === null || _root$summaries2 === void 0 ? void 0 : _root$summaries2.results[scope]) !== void 0;
12517
+ })) cancelSummaryAcquisition();
12518
+ } else if (requested.some((scope) => {
12519
+ var _root$summaries3;
12520
+ return ((_root$summaries3 = root.summaries) === null || _root$summaries3 === void 0 ? void 0 : _root$summaries3.results[scope]) === void 0;
12521
+ })) try {
12522
+ cancelSummaryRetry === null || cancelSummaryRetry === void 0 || cancelSummaryRetry();
12523
+ cancelSummaryRetry = transitionRuntime.scheduler.schedule(() => {
12524
+ cancelSummaryRetry = void 0;
12525
+ if (disposed) return;
12526
+ try {
12527
+ guarded("set-derivations", restartSummaryAcquisition);
12528
+ } catch (error) {
12529
+ reportSummaryFailure(error);
12530
+ }
12531
+ notify();
12532
+ });
12533
+ } catch (error) {
12534
+ reportSummaryFailure(error);
12535
+ }
12536
+ });
12537
+ notify();
12538
+ };
12539
+ },
12175
12540
  subscribe(listener) {
12176
12541
  if (disposed) return () => void 0;
12177
12542
  listeners.add(listener);
@@ -12239,6 +12604,7 @@ function createLocalRowModel$1(options) {
12239
12604
  revision: previousRevision + 1,
12240
12605
  parentRevision: previousRevision,
12241
12606
  rows: drafted.rows,
12607
+ summaries: drafted.summaries,
12242
12608
  sourceOrder: drafted.sourceOrder,
12243
12609
  recordsBySlot: drafted.recordsBySlot,
12244
12610
  slotCapacity: slots.capacity,
@@ -12291,6 +12657,7 @@ function createLocalRowModel$1(options) {
12291
12657
  revision: result.revision,
12292
12658
  parentRevision: previousRoot.revision,
12293
12659
  rows: drafted.rows,
12660
+ summaries: drafted.summaries,
12294
12661
  sourceOrder: drafted.sourceOrder,
12295
12662
  recordsBySlot: drafted.recordsBySlot,
12296
12663
  slotCapacity: slots.capacity,
@@ -12344,7 +12711,7 @@ function createLocalRowModel$1(options) {
12344
12711
  };
12345
12712
  }
12346
12713
  const residentRowCount = root.rows.size;
12347
- const fastPath = nextPlan.query.rowGroups.length > 0 ? void 0 : isSortOnlyChange(queryPlan, nextPlan) ? residentRowCount <= sortFastPathRowLimit ? Object.freeze({
12714
+ const fastPath = nextPlan.query.rowGroups.length > 0 || requestedSummaryScopes().length > 0 ? void 0 : isSortOnlyChange(queryPlan, nextPlan) ? residentRowCount <= sortFastPathRowLimit ? Object.freeze({
12348
12715
  rebuild: rebuildRootForSortOnlyChange,
12349
12716
  barrierReason: "reorder"
12350
12717
  }) : void 0 : isFilterOnlyChange(queryPlan, nextPlan) ? residentRowCount <= filterFastPathRowLimit ? Object.freeze({
@@ -12539,6 +12906,8 @@ function createLocalRowModel$1(options) {
12539
12906
  if (activeMutation !== void 0) throw new PretableReentrantMutationError("dispose", activeMutation);
12540
12907
  if (disposed) return;
12541
12908
  const current = guarded("dispose", () => {
12909
+ cancelSummaryAcquisition();
12910
+ summaryLeases.clear();
12542
12911
  cancelActiveTransition("disposed");
12543
12912
  distinctValues.dispose(new PretableDisposedModelError("distinct-values"));
12544
12913
  changeJournal.clear();
@@ -12554,7 +12923,7 @@ function createLocalRowModel$1(options) {
12554
12923
  });
12555
12924
  for (const listener of current) try {
12556
12925
  listener();
12557
- } catch (_unused6) {}
12926
+ } catch (_unused10) {}
12558
12927
  }
12559
12928
  };
12560
12929
  modelChangeJournals.set(model, changeJournal);