@syncular/server 0.38.0 → 0.39.1

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.
@@ -5,7 +5,7 @@ import { serveNotReadyError } from './readiness.js';
5
5
  import { bindAuthoritativePartition, postgresPlaceholders, prepareAuthoritativeQuery, } from './authoritative-query.js';
6
6
  import { syncError } from './errors.js';
7
7
  import { asBytes, asNumber, } from './pg-executor.js';
8
- import { assertPhysicalColumns, assertStoredLayouts, COMMIT_WINDOW_BATCH_SQL, LATEST_SCOPED_CHANGE_BATCH_SQL, deleteRowSql, dropTableDdl, indexRowPageStatement, layoutsOf, migratePayload, parseLayouts, quoteIdent, retiredTableNames, rewritePlan, rewriteRowSql, rewriteValues, SCHEMA_META_DDL_POSTGRES, SYNC_COLUMN_VERSIONS_COLUMN, SYNC_PARTITION_COLUMN, SYNC_PAYLOAD_COLUMN, SYNC_ROW_ID_COLUMN, SYNC_SCOPES_COLUMN, SYNC_VERSION_COLUMN, scanRowBatchSql, scanRowPageSql, indexSignature, schemaDdl, selectRowScopesSql, selectRowSql, prefetchRowsSql, selectRowsForRewriteSql, upsertSql, upsertValues, } from './relational-rows.js';
8
+ import { assertPhysicalColumns, assertStoredLayouts, COMMIT_WINDOW_BATCH_SQL, LATEST_SCOPED_CHANGE_BATCH_SQL, deleteRowSql, dropTableDdl, indexRowPageStatement, layoutsOf, migratePayload, parseLayouts, quoteIdent, tableColumnNames, retiredTableNames, rewritePlan, columnSqlType, rewriteValues, SCHEMA_META_DDL_POSTGRES, SYNC_COLUMN_VERSIONS_COLUMN, SYNC_PARTITION_COLUMN, SYNC_PAYLOAD_COLUMN, SYNC_ROW_ID_COLUMN, SYNC_SCOPES_COLUMN, SYNC_VERSION_COLUMN, scanRowBatchSql, scanRowPageSql, indexSignature, schemaDdl, selectRowScopesSql, selectRowSql, prefetchRowsSql, selectRowsForRewriteSql, upsertSql, upsertValues, } from './relational-rows.js';
9
9
  import { matchesEffective, sha256Hex } from './scopes.js';
10
10
  import { isPostgresConstraintError, StorageConstraintError, } from './storage-errors.js';
11
11
  import { assertScopeIndexedScan, resolveIndexRowScan } from './storage-query.js';
@@ -22,7 +22,7 @@ import { assertScopeIndexedScan, resolveIndexRowScan } from './storage-query.js'
22
22
  * their table.
23
23
  *
24
24
  * `sync_row_scopes_by_row (partition, tbl, row_id)` is the one secondary
25
- * scope index: `writeRowOn` and `deleteRow` replace a row's scope entries
25
+ * scope index: `writeRowsOn` and `deleteRow` replace a row's scope entries
26
26
  * with a `(partition, tbl, row_id)` predicate, and `row_id` is the LAST
27
27
  * column of the inverted PRIMARY KEY, so without this index that predicate
28
28
  * scans the table's whole scope range on every row written (a bulk import
@@ -368,23 +368,52 @@ function toStoredChange(record) {
368
368
  */
369
369
  async function rewriteRowsOn(q, table, oldLayout) {
370
370
  const select = selectRowsForRewriteSql(table, 'postgres');
371
- const update = rewriteRowSql(table, 'postgres');
372
- const BATCH = 500;
371
+ // One UPDATE per page: behind a network hop (Hyperdrive, a managed
372
+ // database) every statement is a round trip, and the bump holds the
373
+ // migration lock for its whole duration. The page's rows bind as one
374
+ // VALUES list with typed placeholders (`rewriteValues` order: projection
375
+ // columns, payload, partition, row id).
376
+ const types = [
377
+ ...(table.materialize
378
+ ? table.columns.map((column) => columnSqlType(column, 'postgres'))
379
+ : []),
380
+ 'BYTEA',
381
+ 'TEXT',
382
+ 'TEXT',
383
+ ];
384
+ const projected = table.materialize ? table.columns : [];
385
+ const sets = [
386
+ ...projected.map((column, i) => `${quoteIdent(column.name)}=v.c${i}`),
387
+ `${quoteIdent(SYNC_PAYLOAD_COLUMN)}=v.c${projected.length}`,
388
+ ].join(', ');
389
+ const aliases = types.map((_, i) => `c${i}`).join(', ');
390
+ const partitionAlias = `c${projected.length + 1}`;
391
+ const rowIdAlias = `c${projected.length + 2}`;
392
+ // A page binds types.length parameters per row; PGlite corrupts its state
393
+ // above 32,767 bound parameters (see PG_CHANGES_PER_STATEMENT).
394
+ const batch = Math.max(1, Math.min(500, Math.floor(30_000 / types.length)));
373
395
  let afterPartition = '';
374
396
  let afterRowId = '';
375
397
  for (;;) {
376
- const { rows } = await q.query(select, [afterPartition, afterRowId, BATCH]);
398
+ const { rows } = await q.query(select, [afterPartition, afterRowId, batch]);
377
399
  if (rows.length === 0)
378
400
  break;
379
- for (const row of rows) {
401
+ const params = [];
402
+ const values = rows.map((row) => {
380
403
  const bytes = asBytes(row.payload);
381
404
  const payload = oldLayout !== undefined
382
405
  ? migratePayload(oldLayout, table, bytes)
383
406
  : bytes;
384
- await q.query(update, rewriteValues(table, row.partition, row.row_id, payload, 'postgres'));
385
- }
407
+ const base = params.length;
408
+ params.push(...rewriteValues(table, row.partition, row.row_id, payload, 'postgres'));
409
+ return `(${types.map((type, i) => `$${base + i + 1}::${type}`).join(',')})`;
410
+ });
411
+ await q.query(`UPDATE ${quoteIdent(table.name)} AS t SET ${sets}
412
+ FROM (VALUES ${values.join(',')}) AS v(${aliases})
413
+ WHERE t.${quoteIdent(SYNC_PARTITION_COLUMN)}=v.${partitionAlias}
414
+ AND t.${quoteIdent(SYNC_ROW_ID_COLUMN)}=v.${rowIdAlias}`, params);
386
415
  const last = rows[rows.length - 1];
387
- if (last === undefined || rows.length < BATCH)
416
+ if (last === undefined || rows.length < batch)
388
417
  break;
389
418
  afterPartition = last.partition;
390
419
  afterRowId = last.row_id;
@@ -402,29 +431,51 @@ async function scanRowsByIndexOn(q, compiled, partition, query) {
402
431
  const { rows } = await q.query(statement.sql, statement.params);
403
432
  return rows.map(toStoredRow);
404
433
  }
405
- async function writeRowOn(q, compiled, partition, row) {
406
- // One statement per row write: the upsert, and the scope index synced to
407
- // the row's scope map (entries outside it deleted, missing ones inserted).
408
- // No index entry is touched twice, so the writable CTEs cannot conflict.
409
- // The scopes bind as text before the JSONB cast (see `appendCommit`).
410
- const params = upsertValues(compiled, partition, row, 'postgres');
411
- const n = params.length;
412
- await q.query(`WITH upserted AS (${upsertSql(compiled, 'postgres')}),
413
- scope AS (SELECT key, value FROM jsonb_each_text($${n + 1}::text::jsonb)),
414
- removed AS (
415
- DELETE FROM sync_row_scopes
416
- WHERE partition=$${n + 2} AND tbl=$${n + 3} AND row_id=$${n + 4}
417
- AND (var, value) NOT IN (SELECT key, value FROM scope)
418
- )
419
- INSERT INTO sync_row_scopes(partition, tbl, var, value, row_id)
420
- SELECT $${n + 2}, $${n + 3}, key, value, $${n + 4} FROM scope
421
- ON CONFLICT DO NOTHING`, [
422
- ...params,
423
- JSON.stringify(row.scopes),
424
- partition,
425
- compiled.name,
426
- row.rowId,
427
- ]);
434
+ /**
435
+ * Write rows of one table in one statement per chunk: the upsert, and the
436
+ * scope index synced to each row's scope map (entries outside it deleted,
437
+ * missing ones inserted). Row ids are distinct, so no index entry is touched
438
+ * twice and the writable CTEs cannot conflict. The scopes bind as text
439
+ * before the JSONB cast (see `appendCommit`). Every chunk is handed to `q`
440
+ * before the first one settles, so a statement issued after this call
441
+ * queues behind all of them on the transaction FIFO.
442
+ */
443
+ function writeRowsOn(q, compiled, partition, rows) {
444
+ const width = tableColumnNames(compiled).length;
445
+ // PGlite corrupts its state above 32,767 bound parameters (see
446
+ // PG_CHANGES_PER_STATEMENT).
447
+ const chunk = Math.max(1, Math.floor(30_000 / width));
448
+ const writes = [];
449
+ for (let first = 0; first < rows.length; first += chunk) {
450
+ const slice = rows.slice(first, first + chunk);
451
+ const params = slice.flatMap((entry) => entry.values);
452
+ const n = params.length;
453
+ writes.push(q.query(`WITH upserted AS (${upsertSql(compiled, 'postgres', slice.length)}),
454
+ batch AS (
455
+ SELECT row_id, scopes
456
+ FROM jsonb_to_recordset($${n + 1}::text::jsonb) AS r(row_id text, scopes jsonb)
457
+ ),
458
+ scope AS (
459
+ SELECT batch.row_id, entry.key, entry.value
460
+ FROM batch CROSS JOIN LATERAL jsonb_each_text(batch.scopes) AS entry
461
+ ),
462
+ removed AS (
463
+ DELETE FROM sync_row_scopes existing
464
+ USING batch
465
+ WHERE existing.partition=$${n + 2} AND existing.tbl=$${n + 3}
466
+ AND existing.row_id=batch.row_id
467
+ AND batch.scopes->>existing.var IS DISTINCT FROM existing.value
468
+ )
469
+ INSERT INTO sync_row_scopes(partition, tbl, var, value, row_id)
470
+ SELECT $${n + 2}, $${n + 3}, key, value, row_id FROM scope
471
+ ON CONFLICT DO NOTHING`, [
472
+ ...params,
473
+ JSON.stringify(slice.map(({ row }) => ({ row_id: row.rowId, scopes: row.scopes }))),
474
+ partition,
475
+ compiled.name,
476
+ ]));
477
+ }
478
+ return Promise.all(writes);
428
479
  }
429
480
  async function getPushResultOn(q, partition, clientId, clientCommitId) {
430
481
  const { rows } = await q.query('SELECT result FROM sync_push_results WHERE partition=$1 AND client_id=$2 AND client_commit_id=$3', [partition, clientId, clientCommitId]);
@@ -450,6 +501,8 @@ async function queryAuthoritativeOn(client, partition, prepared) {
450
501
  }
451
502
  class PostgresTransaction {
452
503
  #client;
504
+ /** The FIFO without the staged-write prelude (see the constructor). */
505
+ #serial;
453
506
  #partition;
454
507
  /** Storage-owned relation rewrite, bound to this transaction's partition. */
455
508
  #prepareQuery;
@@ -465,6 +518,15 @@ class PostgresTransaction {
465
518
  */
466
519
  #prefetchedRows = new Map();
467
520
  #prefetchedTombstones = new Map();
521
+ /**
522
+ * Upserts staged per table (row id → row and its push operation index).
523
+ * Every statement of this transaction writes them first (see the
524
+ * constructor), so reads and later writes observe them; a commit's rows
525
+ * reach the database as one statement per table instead of one per row.
526
+ * Tables with a unique index write immediately: a violation must name its
527
+ * operation.
528
+ */
529
+ #staged = new Map();
468
530
  /** Resolves/rejects the `transaction(fn)` wrapper (see `begin`). */
469
531
  #resolve;
470
532
  #reject;
@@ -476,13 +538,31 @@ class PostgresTransaction {
476
538
  // issued through this transaction is chained on one FIFO — the same
477
539
  // shape as `SqliteServerStorage.queryAuthoritative`.
478
540
  let tail = Promise.resolve();
479
- this.#client = {
541
+ const serial = {
480
542
  query: (text, params) => {
481
543
  const run = tail.then(() => client.query(text, params));
482
544
  tail = run.then(() => undefined, () => undefined);
483
545
  return run;
484
546
  },
485
547
  };
548
+ this.#serial = serial;
549
+ this.#client = {
550
+ query: async (text, params) => {
551
+ // Queue the staged writes ahead of this statement synchronously, so
552
+ // a concurrently issued statement cannot overtake them.
553
+ const staged = this.#writeStaged();
554
+ const run = serial.query(text, params);
555
+ try {
556
+ await staged;
557
+ }
558
+ catch (error) {
559
+ // The aborted transaction fails the queued statement too.
560
+ run.catch(() => undefined);
561
+ throw error;
562
+ }
563
+ return run;
564
+ },
565
+ };
486
566
  this.#partition = partition;
487
567
  this.#writerVersion = writerVersion;
488
568
  this.#resolveTable = resolveTable;
@@ -494,6 +574,23 @@ class PostgresTransaction {
494
574
  if (!this.#open)
495
575
  throw new Error('transaction already finished');
496
576
  }
577
+ #writeStaged() {
578
+ if (this.#staged.size === 0)
579
+ return Promise.resolve();
580
+ const staged = [...this.#staged];
581
+ this.#staged.clear();
582
+ return Promise.all(staged.map(([table, rows]) => {
583
+ const entries = [...rows.values()];
584
+ return writeRowsOn(this.#serial, table, this.#partition, entries).catch((error) => {
585
+ // Staged tables have no unique index, so a violation is a column
586
+ // constraint; it names the first staged operation of the table.
587
+ if (isPostgresConstraintError(error)) {
588
+ throw new StorageConstraintError(error, entries[0]?.opIndex);
589
+ }
590
+ throw error;
591
+ });
592
+ }));
593
+ }
497
594
  getRow(table, rowId) {
498
595
  this.#assertOpen();
499
596
  const prefetched = this.#prefetchedRows.get(`${table}\u0000${rowId}`);
@@ -619,6 +716,7 @@ class PostgresTransaction {
619
716
  if (!this.#pushApplySavepoint) {
620
717
  throw new Error('push rejection requires its apply savepoint');
621
718
  }
719
+ this.#staged.clear();
622
720
  await this.#client.query('ROLLBACK TO SAVEPOINT syncular_push_candidate');
623
721
  await this.#client.query('RELEASE SAVEPOINT syncular_push_candidate');
624
722
  this.#pushApplySavepoint = false;
@@ -628,8 +726,28 @@ class PostgresTransaction {
628
726
  async upsertRow(table, row, context) {
629
727
  this.#assertOpen();
630
728
  this.#prefetchedRows.delete(`${table}\u0000${row.rowId}`);
729
+ const compiled = this.#resolveTable(table);
730
+ // Decodes the payload: an undecodable row fails here, at its operation.
731
+ const values = upsertValues(compiled, this.#partition, row, 'postgres');
732
+ if (!compiled.indexes.some((index) => index.unique === true)) {
733
+ let rows = this.#staged.get(compiled);
734
+ if (rows === undefined) {
735
+ rows = new Map();
736
+ this.#staged.set(compiled, rows);
737
+ }
738
+ // A later upsert of the same row in this transaction replaces it.
739
+ rows.delete(row.rowId);
740
+ rows.set(row.rowId, {
741
+ row,
742
+ values,
743
+ ...(context === undefined ? {} : { opIndex: context.opIndex }),
744
+ });
745
+ return;
746
+ }
631
747
  try {
632
- await writeRowOn(this.#client, this.#resolveTable(table), this.#partition, row);
748
+ await writeRowsOn(this.#client, compiled, this.#partition, [
749
+ { row, values },
750
+ ]);
633
751
  }
634
752
  catch (error) {
635
753
  if (isPostgresConstraintError(error)) {
@@ -757,6 +875,7 @@ class PostgresTransaction {
757
875
  }
758
876
  async commit() {
759
877
  this.#assertOpen();
878
+ await this.#writeStaged();
760
879
  this.#open = false;
761
880
  // Signal the transaction wrapper to COMMIT; wait for it to actually land.
762
881
  this.#resolve();
@@ -765,6 +884,7 @@ class PostgresTransaction {
765
884
  async rollback() {
766
885
  if (!this.#open)
767
886
  return;
887
+ this.#staged.clear();
768
888
  this.#open = false;
769
889
  this.#reject(new RollbackSignal());
770
890
  // Swallow — a rollback is a normal outcome, not an error to the caller.
@@ -794,33 +914,39 @@ export class PostgresServerStorage {
794
914
  #schemaVersion;
795
915
  /**
796
916
  * Page reads waiting for the end of the current microtask turn, keyed by
797
- * statement and partition. A pull starts the window read (or first
917
+ * batch stream and partition. A pull starts the window read (or first
798
918
  * snapshot page) of every subscription before awaiting any of them, so the
799
- * window reads of all tables leave as ONE set-based statement (snapshot
800
- * pages as one per table, whose SQL names the table) instead of one round
801
- * trip per subscription or table (SYNCULAR-PULL-ROUNDTRIPS-001).
919
+ * reads of all tables leave as ONE set-based statement per stream instead
920
+ * of one round trip per subscription or table
921
+ * (SYNCULAR-PULL-ROUNDTRIPS-001).
802
922
  */
803
923
  #pageBatches = new Map();
804
924
  constructor(exec) {
805
925
  this.#exec = exec;
806
926
  }
807
927
  /**
808
- * Queue one page read into the batch for (`sql`, `partition`). The batch
809
- * runs as a single statement with the queued specs bound as a JSON array
810
- * (`$2`); each spec gets its position as `i`, and the result rows are
811
- * split back by their `sub` column.
928
+ * Queue one page read into the batch for (`key`, `partition`). `sql` is the
929
+ * statement every batch of that stream shares, or a builder over the queued
930
+ * specs when the statement names what the batch contains (the snapshot scan
931
+ * joins one branch per table present). The batch runs as a single statement
932
+ * with the queued specs bound as a JSON array (`$2`); each spec gets its
933
+ * position as `i`, and the result rows are split back by their `sub`
934
+ * column.
812
935
  */
813
- #batchedPage(sql, partition, spec) {
814
- const key = `${sql}\u0000${partition}`;
815
- let batch = this.#pageBatches.get(key);
936
+ #batchedPage(key, sql, partition, spec) {
937
+ const batchKey = `${key}\u0000${partition}`;
938
+ let batch = this.#pageBatches.get(batchKey);
816
939
  if (batch === undefined) {
817
940
  const queued = [];
818
941
  batch = queued;
819
- this.#pageBatches.set(key, queued);
942
+ this.#pageBatches.set(batchKey, queued);
820
943
  queueMicrotask(() => {
821
- this.#pageBatches.delete(key);
822
- const specs = JSON.stringify(queued.map((entry, i) => ({ ...entry.spec, i })));
823
- this.#exec.query(sql, [partition, specs]).then(({ rows }) => {
944
+ this.#pageBatches.delete(batchKey);
945
+ const specs = queued.map((entry, i) => ({ ...entry.spec, i }));
946
+ const statement = typeof sql === 'string' ? sql : sql(specs);
947
+ this.#exec
948
+ .query(statement, [partition, JSON.stringify(specs)])
949
+ .then(({ rows }) => {
824
950
  const grouped = queued.map(() => []);
825
951
  for (const row of rows)
826
952
  grouped[asNumber(row.sub)]?.push(row);
@@ -987,8 +1113,6 @@ FOR EACH ROW EXECUTE FUNCTION syncular_writer_fence()`,
987
1113
  // backfill for flipped-on materialization) — all inside one
988
1114
  // transaction (Postgres DDL is transactional — a failed bump leaves
989
1115
  // no half-state).
990
- const layouts = parseLayouts(typeof marker.layouts === 'string' ? marker.layouts : undefined);
991
- const retiredTables = retiredTableNames(schema, layouts);
992
1116
  await this.#exec.transaction(async (client) => {
993
1117
  // RFC 0007 migration barrier: `LOCK TABLE ... EXCLUSIVE` is the FIRST
994
1118
  // statement, before any read, DDL, rewrite, marker or checkpoint
@@ -1001,6 +1125,24 @@ FOR EACH ROW EXECUTE FUNCTION syncular_writer_fence()`,
1001
1125
  // when it takes this lock, so a writer already inside completes while
1002
1126
  // the migration waits.
1003
1127
  await client.query('LOCK TABLE sync_partitions IN EXCLUSIVE MODE');
1128
+ // The probe ran before the lock. A concurrent `ensureSchema` (another
1129
+ // isolate, the Durable Object's first request) may have bumped while
1130
+ // this one waited; re-running the rewrite would decode its new-layout
1131
+ // payloads with the old layout. The locked marker decides.
1132
+ const { rows: lockedMarker } = await client.query('SELECT schema_version, layouts FROM sync_schema_meta WHERE id=1');
1133
+ const lockedVersion = lockedMarker[0]?.schema_version === null ||
1134
+ lockedMarker[0]?.schema_version === undefined
1135
+ ? undefined
1136
+ : asNumber(lockedMarker[0].schema_version);
1137
+ if (lockedVersion !== undefined && lockedVersion > schema.version) {
1138
+ throw new Error(`stored schema version ${lockedVersion} is newer than the configured schema (${schema.version}) — refusing to run an older server against a migrated database`);
1139
+ }
1140
+ if (lockedVersion === schema.version)
1141
+ return;
1142
+ const layouts = parseLayouts(typeof lockedMarker[0]?.layouts === 'string'
1143
+ ? lockedMarker[0].layouts
1144
+ : undefined);
1145
+ const retiredTables = retiredTableNames(schema, layouts);
1004
1146
  const existing = new Map();
1005
1147
  const existingIndexes = new Map();
1006
1148
  for (const table of schema.tables.values()) {
@@ -1047,13 +1189,15 @@ FOR EACH ROW EXECUTE FUNCTION syncular_writer_fence()`,
1047
1189
  ])));
1048
1190
  }
1049
1191
  }
1192
+ if (retiredTables.length > 0) {
1193
+ // Neither index leads with `tbl`: one scan per table, not one per
1194
+ // retired table.
1195
+ await client.query(`DELETE FROM sync_row_scopes
1196
+ WHERE tbl IN (SELECT jsonb_array_elements_text($1::text::jsonb))`, [JSON.stringify(retiredTables)]);
1197
+ await client.query(`DELETE FROM sync_blob_refs
1198
+ WHERE tbl IN (SELECT jsonb_array_elements_text($1::text::jsonb))`, [JSON.stringify(retiredTables)]);
1199
+ }
1050
1200
  for (const tableName of retiredTables) {
1051
- await client.query('DELETE FROM sync_row_scopes WHERE tbl=$1', [
1052
- tableName,
1053
- ]);
1054
- await client.query('DELETE FROM sync_blob_refs WHERE tbl=$1', [
1055
- tableName,
1056
- ]);
1057
1201
  await client.query(dropTableDdl(tableName));
1058
1202
  }
1059
1203
  for (const statement of schemaDdl(schema, existing, 'postgres', existingIndexes)) {
@@ -1496,7 +1640,7 @@ FOR EACH ROW EXECUTE FUNCTION syncular_writer_fence()`,
1496
1640
  if (firstVariable === undefined || values.length === 0)
1497
1641
  return 0;
1498
1642
  // Concurrent reads of a pull share one statement across tables.
1499
- const [row] = await this.#batchedPage(LATEST_SCOPED_CHANGE_BATCH_SQL, partition, { tbl: query.table, var: firstVariable, vals: values });
1643
+ const [row] = await this.#batchedPage('latestScopedChange', LATEST_SCOPED_CHANGE_BATCH_SQL, partition, { tbl: query.table, var: firstVariable, vals: values });
1500
1644
  return row === undefined ? 0 : asNumber(row.seq);
1501
1645
  }
1502
1646
  async readCommitWindow(partition, query) {
@@ -1519,7 +1663,7 @@ FOR EACH ROW EXECUTE FUNCTION syncular_writer_fence()`,
1519
1663
  let afterSeq = query.afterSeq;
1520
1664
  const batchSize = Math.max(64, query.limitChanges);
1521
1665
  while (deliveredChanges < query.limitChanges) {
1522
- const records = await this.#batchedPage(COMMIT_WINDOW_BATCH_SQL, partition, {
1666
+ const records = await this.#batchedPage('commitWindow', COMMIT_WINDOW_BATCH_SQL, partition, {
1523
1667
  tbl: query.table,
1524
1668
  var: firstVariable,
1525
1669
  vals: firstValues,
@@ -1592,15 +1736,14 @@ FOR EACH ROW EXECUTE FUNCTION syncular_writer_fence()`,
1592
1736
  return [];
1593
1737
  // Candidates via the inverted index (ordered + LIMITed at the covering
1594
1738
  // PK) LEFT JOINed to the row table — one round trip per page, never one
1595
- // per row, and pages of concurrent scans on the same table share one
1596
- // statement (see `scanRowBatchSql`). Exact multi-variable verification
1597
- // against the stored scope map happens below.
1598
- const sql = scanRowBatchSql(this.table(query.table));
1739
+ // per row, and concurrent scans across tables share one statement (see
1740
+ // `scanRowBatchSql`). Exact multi-variable verification against the
1741
+ // stored scope map happens below.
1599
1742
  const rows = [];
1600
1743
  let afterRowId = query.afterRowId ?? '';
1601
1744
  const batchSize = Math.max(64, query.limit);
1602
1745
  while (rows.length < query.limit) {
1603
- const records = await this.#batchedPage(sql, partition, {
1746
+ const records = await this.#batchedPage('scanRows', (specs) => scanRowBatchSql([...new Set(specs.map((spec) => String(spec.tbl)))].map((table) => this.table(table))), partition, {
1604
1747
  tbl: query.table,
1605
1748
  var: firstVariable,
1606
1749
  vals: firstValues,
package/dist/pull.d.ts CHANGED
@@ -42,8 +42,8 @@ export interface PullSectionTrace {
42
42
  /**
43
43
  * The storage reads a section needs before its first frame. A pull starts
44
44
  * them for every subscription before awaiting any, so a storage that batches
45
- * concurrent page reads (PostgreSQL, D1) answers all subscriptions of one
46
- * table with one statement, and the horizon re-check runs once per pull.
45
+ * concurrent page reads (PostgreSQL, D1) answers the first pages of every
46
+ * subscription in one statement, and the horizon re-check runs once per pull.
47
47
  */
48
48
  export interface PreparedSection {
49
49
  /** §4.5 window read for an incremental cursor; empty when none was read. */
@@ -57,7 +57,11 @@ export interface PreparedSection {
57
57
  readonly firstPage: StoredRow[] | undefined;
58
58
  /** §4.7 pin of a fresh bootstrap; absent ⇒ `maxCommitSeq`. */
59
59
  readonly pin: number | undefined;
60
- /** §5.3 stored image for a sqlite-lane bootstrap's reuse key, if any. */
60
+ /**
61
+ * §5.3 stored image for a sqlite-lane bootstrap's reuse key. Read only when
62
+ * the eligibility probe shows a snapshot larger than one rows page, since a
63
+ * smaller table can never match a stored image.
64
+ */
61
65
  readonly image: SegmentRecord | undefined;
62
66
  }
63
67
  /** Run the pre-frame storage reads of every subscription concurrently. */
package/dist/pull.js CHANGED
@@ -375,18 +375,27 @@ export async function prepareSections(ctx, schema, limits, plans, maxSeq, horizo
375
375
  const pin = Math.min(maxSeq, Math.max(latest, horizonSeq));
376
376
  return { asOf: pin, pin };
377
377
  });
378
- const lane = pinned.then(async ({ asOf, pin }) => ({
379
- pin,
380
- image: await ctx.segments.find({
381
- partition: ctx.partition,
382
- logEpoch,
383
- table: plan.table.name,
384
- schemaVersion: schema.version,
385
- mediaType: 'sqlite',
386
- scopeDigest: await scopeDigest(plan.effective),
387
- asOfCommitSeq: asOf,
388
- }, clockOf(ctx)()),
389
- }));
378
+ const lane = pinned.then(async ({ asOf, pin }) => {
379
+ // §5.3 eligibility: a stored image only matches a snapshot larger than
380
+ // one rows page, so the probe decides before the reuse lookup; a remote
381
+ // `find` on a small table would be a wasted round trip.
382
+ const probe = await firstPage;
383
+ if (probe.length <= limits.limitSnapshotRows) {
384
+ return { pin, image: undefined };
385
+ }
386
+ return {
387
+ pin,
388
+ image: await ctx.segments.find({
389
+ partition: ctx.partition,
390
+ logEpoch,
391
+ table: plan.table.name,
392
+ schemaVersion: schema.version,
393
+ mediaType: 'sqlite',
394
+ scopeDigest: await scopeDigest(plan.effective),
395
+ asOfCommitSeq: asOf,
396
+ }, clockOf(ctx)()),
397
+ };
398
+ });
390
399
  return { firstPage, lane };
391
400
  });
392
401
  const settled = await Promise.all(reads.map(async (read) => ({
@@ -176,8 +176,12 @@ export declare function toSqlValue(column: RowColumn, value: RowValue, dialect:
176
176
  * statement, so they cannot drift.
177
177
  */
178
178
  export declare function upsertValues(table: CompiledTable, partition: string, row: StoredRow, dialect: RelationalDialect): unknown[];
179
- /** Upsert statement text (bind with `upsertValues`). */
180
- export declare function upsertSql(table: CompiledTable, dialect: RelationalDialect): string;
179
+ /**
180
+ * Upsert statement text (bind with `upsertValues`). PostgreSQL takes `rows`
181
+ * rows in one statement, bound as consecutive `upsertValues` lists; their
182
+ * row ids must be distinct.
183
+ */
184
+ export declare function upsertSql(table: CompiledTable, dialect: RelationalDialect, rows?: number): string;
181
185
  /**
182
186
  * SELECT one stored row. Aliased to the legacy record shape
183
187
  * (`row_id`/`server_version`/`scopes`/`payload`) so the existing
@@ -246,17 +250,19 @@ export declare function scanRowPageSql(table: CompiledTable, valueCount: number,
246
250
  export declare function commitWindowPageSql(valueCount: number, dialect: RelationalDialect): string;
247
251
  /**
248
252
  * PostgreSQL set-based form of `scanRowPageSql`: one statement answers the
249
- * page of every subscription scanning `table` in a pull. `$2` is a JSON array
250
- * of `{i, tbl, var, vals, after, lim}` records; each record runs the same
251
- * index-first candidate subquery through a LATERAL join, so every
252
- * subscription keeps its own keyset cursor and LIMIT. Rows arrive ordered
253
- * by (i, row_id).
253
+ * page of every subscription scanning any table in a pull. `$2` is a JSON
254
+ * array of `{i, tbl, var, vals, after, lim}` records; each record runs the
255
+ * same index-first candidate subquery through a LATERAL join, so every
256
+ * subscription keeps its own keyset cursor and LIMIT. The candidate side is
257
+ * table-agnostic (a spec names its table), so the statement joins the row
258
+ * table once per table present in the batch through a UNION ALL branch that
259
+ * keeps only its own candidates. Rows arrive ordered by (i, row_id).
254
260
  *
255
261
  * Params: [partition, specs (JSON text)]. The specs bind as text before
256
262
  * the JSONB cast, so a driver that JSON-encodes a string bound to a `jsonb`
257
263
  * parameter (Bun.sql) cannot turn the array into a JSON string.
258
264
  */
259
- export declare function scanRowBatchSql(table: CompiledTable): string;
265
+ export declare function scanRowBatchSql(tables: readonly CompiledTable[]): string;
260
266
  /**
261
267
  * PostgreSQL set-based form of `commitWindowPageSql`: one statement answers
262
268
  * the window page of every subscription in a pull, across all tables. `$2`
@@ -363,10 +369,10 @@ export declare function migratePayload(oldLayout: readonly StoredColumnLayout[],
363
369
  */
364
370
  export declare function selectRowsForRewriteSql(table: CompiledTable, dialect: RelationalDialect): string;
365
371
  /**
366
- * Rewrite one row during a migration: refresh the projection columns (when
372
+ * SQLite/D1: rewrite one row during a migration: refresh the projection columns (when
367
373
  * materialized) and the payload. Bind with `rewriteValues`.
368
374
  */
369
- export declare function rewriteRowSql(table: CompiledTable, dialect: RelationalDialect): string;
375
+ export declare function rewriteRowSql(table: CompiledTable): string;
370
376
  /** Bind values for `rewriteRowSql` from the (already migrated) payload. */
371
377
  export declare function rewriteValues(table: CompiledTable, partition: string, rowId: string, payload: Uint8Array, dialect: RelationalDialect): unknown[];
372
378
  /**