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