@ocap/indexdb-sqlite 1.31.6 → 1.31.8

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/lib/index.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_kysely = require('./kysely.cjs');
3
+ const require_tx_ref_tx_type = require('./tx-ref-tx-type.cjs');
3
4
  const require_db_base = require('./db/base.cjs');
4
5
  const require_db_index = require('./db/index.cjs');
5
6
 
@@ -9,5 +10,15 @@ var src_default = require_db_index.default;
9
10
  //#endregion
10
11
  exports.DurableObjectSqliteDialect = require_kysely.DurableObjectSqliteDialect;
11
12
  exports.SqliteBaseIndexDB = require_db_base.default;
13
+ exports.TX_REF_TX_TYPE_INDEX = require_tx_ref_tx_type.TX_REF_TX_TYPE_INDEX;
14
+ exports.TX_REF_TX_TYPE_PROGRESS_TABLE = require_tx_ref_tx_type.TX_REF_TX_TYPE_PROGRESS_TABLE;
15
+ exports.TX_REF_TX_TYPE_SWEEP_BATCH_SIZE = require_tx_ref_tx_type.TX_REF_TX_TYPE_SWEEP_BATCH_SIZE;
16
+ exports.addTxRefTxTypeColumn = require_tx_ref_tx_type.addTxRefTxTypeColumn;
17
+ exports.backfillTxRefTxType = require_tx_ref_tx_type.backfillTxRefTxType;
12
18
  exports.default = src_default;
13
- exports.getRawDatabase = require_kysely.getRawDatabase;
19
+ exports.dropTxRefTxType = require_tx_ref_tx_type.dropTxRefTxType;
20
+ exports.getRawDatabase = require_kysely.getRawDatabase;
21
+ exports.hasTxRefTxTypeColumn = require_tx_ref_tx_type.hasTxRefTxTypeColumn;
22
+ exports.isTxRefTxTypeReady = require_tx_ref_tx_type.isTxRefTxTypeReady;
23
+ exports.migrateTxRefTxType = require_tx_ref_tx_type.migrateTxRefTxType;
24
+ exports.sweepTxRefTxTypeNulls = require_tx_ref_tx_type.sweepTxRefTxTypeNulls;
package/lib/index.d.cts CHANGED
@@ -1,4 +1,5 @@
1
1
  import SqliteBaseIndexDB from "./db/base.cjs";
2
2
  import { DurableObjectSqliteDialect, DurableObjectSqliteDialectConfig, IDurableObjectSqlStorage, IDurableObjectSqlStorageCursor, SqliteConfig, getRawDatabase } from "./kysely.cjs";
3
+ import { TX_REF_TX_TYPE_INDEX, TX_REF_TX_TYPE_PROGRESS_TABLE, TX_REF_TX_TYPE_SWEEP_BATCH_SIZE, TxRefTxTypeBackfillOptions, TxRefTxTypeBackfillStats, TxRefTxTypeBatch, TxRefTxTypeMigrationResult, TxRefTxTypeSweepStats, addTxRefTxTypeColumn, backfillTxRefTxType, dropTxRefTxType, hasTxRefTxTypeColumn, isTxRefTxTypeReady, migrateTxRefTxType, sweepTxRefTxTypeNulls } from "./tx-ref-tx-type.cjs";
3
4
  import SqliteIndexDB from "./db/index.cjs";
4
- export { DurableObjectSqliteDialect, type DurableObjectSqliteDialectConfig, type IDurableObjectSqlStorage, type IDurableObjectSqlStorageCursor, SqliteBaseIndexDB, type SqliteConfig, SqliteIndexDB as default, getRawDatabase };
5
+ export { DurableObjectSqliteDialect, type DurableObjectSqliteDialectConfig, type IDurableObjectSqlStorage, type IDurableObjectSqlStorageCursor, SqliteBaseIndexDB, type SqliteConfig, TX_REF_TX_TYPE_INDEX, TX_REF_TX_TYPE_PROGRESS_TABLE, TX_REF_TX_TYPE_SWEEP_BATCH_SIZE, type TxRefTxTypeBackfillOptions, type TxRefTxTypeBackfillStats, type TxRefTxTypeBatch, type TxRefTxTypeMigrationResult, type TxRefTxTypeSweepStats, addTxRefTxTypeColumn, backfillTxRefTxType, SqliteIndexDB as default, dropTxRefTxType, getRawDatabase, hasTxRefTxTypeColumn, isTxRefTxTypeReady, migrateTxRefTxType, sweepTxRefTxTypeNulls };
@@ -333,6 +333,8 @@ interface TxRefTable {
333
333
  type: string;
334
334
  value: string;
335
335
  time: string | null;
336
+ /** copy of tx.type (#1870); NULL only for rows not yet back-filled, orphans, or a NULL tx.type */
337
+ tx_type: string | null;
336
338
  }
337
339
  /**
338
340
  * IndexFailure table: durable log of failed indexdb writes from connectIndexDB() (see #67).
package/lib/kysely.cjs CHANGED
@@ -1515,6 +1515,25 @@ function resolveWalCheckpointIntervalMs(config) {
1515
1515
  const v = config.walCheckpointIntervalMs ?? fromEnv;
1516
1516
  return Number.isFinite(v) && v > 0 ? Math.floor(v) : void 0;
1517
1517
  }
1518
+ /** Default `PRAGMA mmap_size` (8 GiB). */
1519
+ const DEFAULT_MMAP_SIZE = 8 * 1024 * 1024 * 1024;
1520
+ /** Env var overriding the default `PRAGMA mmap_size` (bytes, `0` disables). */
1521
+ const MMAP_SIZE_ENV = "SQLITE_INDEXDB_MMAP_SIZE";
1522
+ function parseMmapSize(value, source) {
1523
+ if (value === void 0) return void 0;
1524
+ let n;
1525
+ if (typeof value === "number") n = value;
1526
+ else if (typeof value === "string" && /^\d+$/.test(value.trim())) n = Number(value.trim());
1527
+ if (n !== void 0 && Number.isSafeInteger(n) && n >= 0) return n;
1528
+ console.warn(`[sqlite] ignoring invalid mmap_size from ${source}: ${JSON.stringify(String(value))}`);
1529
+ }
1530
+ /**
1531
+ * Resolve `PRAGMA mmap_size`: valid `config.mmapSize` wins, then a valid `SQLITE_INDEXDB_MMAP_SIZE`, then
1532
+ * `DEFAULT_MMAP_SIZE`. Invalid input never becomes `0` (an empty env var is not "disable").
1533
+ */
1534
+ function resolveMmapSize(config, env = process.env) {
1535
+ return parseMmapSize(config.mmapSize, "config.mmapSize") ?? parseMmapSize(env[MMAP_SIZE_ENV], MMAP_SIZE_ENV) ?? DEFAULT_MMAP_SIZE;
1536
+ }
1518
1537
  /**
1519
1538
  * Create a Kysely instance with SQLite dialect
1520
1539
  * Automatically uses DurableObjectSqliteDialect when `config.doStorage` is provided,
@@ -1544,21 +1563,29 @@ function createKysely(config) {
1544
1563
  const bunReq = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : typeof require === "function" ? require : {}.require;
1545
1564
  const { BunSqliteDialect } = bunReq("kysely-bun-sqlite");
1546
1565
  const { Database: BunDatabase } = bunReq("bun:sqlite");
1547
- const sqlite$1 = new BunDatabase(filename, {
1566
+ const sqlite = new BunDatabase(filename, {
1548
1567
  create: config.create !== false,
1549
1568
  readonly: config.readonly === true
1550
1569
  });
1551
1570
  if (config.walMode !== false && !config.readonly && filename !== ":memory:") {
1552
- sqlite$1.exec("PRAGMA journal_mode = WAL");
1553
- sqlite$1.exec("PRAGMA synchronous = NORMAL");
1571
+ sqlite.exec("PRAGMA journal_mode = WAL");
1572
+ sqlite.exec("PRAGMA synchronous = NORMAL");
1554
1573
  const walCp = resolveWalAutoCheckpoint(config);
1555
- if (walCp !== void 0) sqlite$1.exec(`PRAGMA wal_autocheckpoint = ${walCp}`);
1574
+ if (walCp !== void 0) sqlite.exec(`PRAGMA wal_autocheckpoint = ${walCp}`);
1556
1575
  }
1557
- sqlite$1.exec("PRAGMA foreign_keys = ON");
1558
- sqlite$1.exec("PRAGMA busy_timeout = 5000");
1559
- return new kysely.Kysely({ dialect: new BunSqliteDialect({ database: sqlite$1 }) });
1576
+ sqlite.exec("PRAGMA foreign_keys = ON");
1577
+ sqlite.exec("PRAGMA busy_timeout = 5000");
1578
+ sqlite.exec(`PRAGMA mmap_size = ${resolveMmapSize(config)}`);
1579
+ return new kysely.Kysely({ dialect: new BunSqliteDialect({ database: sqlite }) });
1560
1580
  }
1561
- const sqlite = new (require("better-sqlite3"))(filename, {
1581
+ return new kysely.Kysely({ dialect: new kysely.SqliteDialect({ database: openBetterSqlite3(require("better-sqlite3"), filename, config) }) });
1582
+ }
1583
+ /**
1584
+ * Open a better-sqlite3 connection and apply connection pragmas (Node.js runtime path).
1585
+ * Exported so tests running under bun can exercise this path with a fake driver.
1586
+ */
1587
+ function openBetterSqlite3(BetterSqlite3, filename, config) {
1588
+ const sqlite = new BetterSqlite3(filename, {
1562
1589
  readonly: config.readonly === true,
1563
1590
  fileMustExist: config.create === false
1564
1591
  });
@@ -1570,7 +1597,8 @@ function createKysely(config) {
1570
1597
  }
1571
1598
  sqlite.pragma("foreign_keys = ON");
1572
1599
  sqlite.pragma("busy_timeout = 5000");
1573
- return new kysely.Kysely({ dialect: new kysely.SqliteDialect({ database: sqlite }) });
1600
+ sqlite.pragma(`mmap_size = ${resolveMmapSize(config)}`);
1601
+ return sqlite;
1574
1602
  }
1575
1603
  /**
1576
1604
  * Get the underlying SQLite database instance from Kysely
@@ -1583,8 +1611,12 @@ function getRawDatabase(db) {
1583
1611
  }
1584
1612
 
1585
1613
  //#endregion
1614
+ exports.DEFAULT_MMAP_SIZE = DEFAULT_MMAP_SIZE;
1586
1615
  exports.DurableObjectSqliteDialect = DurableObjectSqliteDialect;
1616
+ exports.MMAP_SIZE_ENV = MMAP_SIZE_ENV;
1587
1617
  exports.createKysely = createKysely;
1588
1618
  exports.getDoStorageWriteEpoch = getDoStorageWriteEpoch;
1589
1619
  exports.getRawDatabase = getRawDatabase;
1620
+ exports.openBetterSqlite3 = openBetterSqlite3;
1621
+ exports.resolveMmapSize = resolveMmapSize;
1590
1622
  exports.resolveWalCheckpointIntervalMs = resolveWalCheckpointIntervalMs;
package/lib/kysely.d.cts CHANGED
@@ -87,8 +87,25 @@ interface SqliteConfig {
87
87
  * Disabled by default (0 / undefined).
88
88
  */
89
89
  walCheckpointIntervalMs?: number;
90
+ /**
91
+ * `PRAGMA mmap_size` in bytes, applied to every better-sqlite3 / bun:sqlite connection (readonly included).
92
+ * Memory-mapped reads skip the pread syscall + copy into the small page cache on large databases.
93
+ * SQLite clamps the value to its compile-time `SQLITE_MAX_MMAP_SIZE` (better-sqlite3 11.x: 2147418112).
94
+ * `0` disables. Falls back to the `SQLITE_INDEXDB_MMAP_SIZE` env var, then 8 GiB.
95
+ * Invalid values (negative, fractional, non-numeric) are ignored with a warning.
96
+ */
97
+ mmapSize?: number;
90
98
  }
91
99
  declare function resolveWalCheckpointIntervalMs(config: SqliteConfig): number | undefined;
100
+ /** Default `PRAGMA mmap_size` (8 GiB). */
101
+ declare const DEFAULT_MMAP_SIZE: number;
102
+ /** Env var overriding the default `PRAGMA mmap_size` (bytes, `0` disables). */
103
+ declare const MMAP_SIZE_ENV = "SQLITE_INDEXDB_MMAP_SIZE";
104
+ /**
105
+ * Resolve `PRAGMA mmap_size`: valid `config.mmapSize` wins, then a valid `SQLITE_INDEXDB_MMAP_SIZE`, then
106
+ * `DEFAULT_MMAP_SIZE`. Invalid input never becomes `0` (an empty env var is not "disable").
107
+ */
108
+ declare function resolveMmapSize(config: SqliteConfig, env?: Record<string, string | undefined>): number;
92
109
  /**
93
110
  * Create a Kysely instance with SQLite dialect
94
111
  * Automatically uses DurableObjectSqliteDialect when `config.doStorage` is provided,
@@ -107,6 +124,11 @@ declare function resolveWalCheckpointIntervalMs(config: SqliteConfig): number |
107
124
  * ```
108
125
  */
109
126
  declare function createKysely(config: SqliteConfig): Kysely<Database>;
127
+ /**
128
+ * Open a better-sqlite3 connection and apply connection pragmas (Node.js runtime path).
129
+ * Exported so tests running under bun can exercise this path with a fake driver.
130
+ */
131
+ declare function openBetterSqlite3(BetterSqlite3: new (filename: string, options: Record<string, unknown>) => any, filename: string, config: SqliteConfig): any;
110
132
  /**
111
133
  * Get the underlying SQLite database instance from Kysely
112
134
  * Useful for executing raw SQL or pragmas
@@ -114,4 +136,4 @@ declare function createKysely(config: SqliteConfig): Kysely<Database>;
114
136
  */
115
137
  declare function getRawDatabase(db: Kysely<Database>): any;
116
138
  //#endregion
117
- export { DurableObjectSqliteDialect, DurableObjectSqliteDialectConfig, IDurableObjectSqlStorage, IDurableObjectSqlStorageCursor, SqliteConfig, createKysely, getDoStorageWriteEpoch, getRawDatabase, resolveWalCheckpointIntervalMs };
139
+ export { DEFAULT_MMAP_SIZE, DurableObjectSqliteDialect, DurableObjectSqliteDialectConfig, IDurableObjectSqlStorage, IDurableObjectSqlStorageCursor, MMAP_SIZE_ENV, SqliteConfig, createKysely, getDoStorageWriteEpoch, getRawDatabase, openBetterSqlite3, resolveMmapSize, resolveWalCheckpointIntervalMs };
@@ -0,0 +1,28 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+
3
+ //#region src/migrations/011-tx-ref-tx-type.ts
4
+ var _011_tx_ref_tx_type_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
5
+ down: () => down,
6
+ up: () => up
7
+ });
8
+ /**
9
+ * Migration 011 - intentionally a no-op (#1885).
10
+ *
11
+ * #1884 shipped 011 as the tx_ref.tx_type back-fill + index, run at startup. That work now runs only offline
12
+ * (`scripts/ops/indexdb-migrate.mjs` -> `migrateTxRefTxType` in ../tx-ref-tx-type), never while a node starts.
13
+ * The entry stays in the chain because databases created from master after #1884 have `011-tx-ref-tx-type`
14
+ * recorded in kysely_migration, and Kysely refuses to run when a recorded migration is missing from the provider.
15
+ * Keeping the name also keeps 012+ ordered after it.
16
+ */
17
+ async function up(_db) {}
18
+ async function down(_db) {}
19
+
20
+ //#endregion
21
+ Object.defineProperty(exports, '_011_tx_ref_tx_type_exports', {
22
+ enumerable: true,
23
+ get: function () {
24
+ return _011_tx_ref_tx_type_exports;
25
+ }
26
+ });
27
+ exports.down = down;
28
+ exports.up = up;
@@ -0,0 +1,17 @@
1
+ import { Kysely } from "kysely";
2
+
3
+ //#region src/migrations/011-tx-ref-tx-type.d.ts
4
+
5
+ /**
6
+ * Migration 011 - intentionally a no-op (#1885).
7
+ *
8
+ * #1884 shipped 011 as the tx_ref.tx_type back-fill + index, run at startup. That work now runs only offline
9
+ * (`scripts/ops/indexdb-migrate.mjs` -> `migrateTxRefTxType` in ../tx-ref-tx-type), never while a node starts.
10
+ * The entry stays in the chain because databases created from master after #1884 have `011-tx-ref-tx-type`
11
+ * recorded in kysely_migration, and Kysely refuses to run when a recorded migration is missing from the provider.
12
+ * Keeping the name also keeps 012+ ordered after it.
13
+ */
14
+ declare function up(_db: Kysely<unknown>): Promise<void>;
15
+ declare function down(_db: Kysely<unknown>): Promise<void>;
16
+ //#endregion
17
+ export { down, up };
@@ -9,6 +9,7 @@ const require_migrations_007_token_factory_feerate_integer = require('./007-toke
9
9
  const require_migrations_008_index_failure = require('./008-index-failure.cjs');
10
10
  const require_migrations_009_tx_gas_payer = require('./009-tx-gas-payer.cjs');
11
11
  const require_migrations_010_tx_evidences = require('./010-tx-evidences.cjs');
12
+ const require_migrations_011_tx_ref_tx_type = require('./011-tx-ref-tx-type.cjs');
12
13
  let kysely = require("kysely");
13
14
 
14
15
  //#region src/migrations/index.ts
@@ -28,7 +29,8 @@ var InMemoryMigrationProvider = class {
28
29
  "007-token-factory-feerate-integer": require_migrations_007_token_factory_feerate_integer._007_token_factory_feerate_integer_exports,
29
30
  "008-index-failure": require_migrations_008_index_failure._008_index_failure_exports,
30
31
  "009-tx-gas-payer": require_migrations_009_tx_gas_payer._009_tx_gas_payer_exports,
31
- "010-tx-evidences": require_migrations_010_tx_evidences._010_tx_evidences_exports
32
+ "010-tx-evidences": require_migrations_010_tx_evidences._010_tx_evidences_exports,
33
+ "011-tx-ref-tx-type": require_migrations_011_tx_ref_tx_type._011_tx_ref_tx_type_exports
32
34
  };
33
35
  }
34
36
  };
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
3
  const require_table_base = require('./base.cjs');
4
+ const require_tx_ref_tx_type = require('../tx-ref-tx-type.cjs');
4
5
  let kysely = require("kysely");
5
6
  let _ocap_indexdb = require("@ocap/indexdb");
6
7
 
@@ -22,6 +23,13 @@ const TX_REF_TYPES = [
22
23
  * and maintain the tx_ref junction table for fast JSON array lookups
23
24
  */
24
25
  var TransactionTable = class extends require_table_base.default {
26
+ setTxRefTxTypeColumn(present) {
27
+ this.txRefHasTxType = present;
28
+ }
29
+ async writesTxRefTxType(executor) {
30
+ if (this.txRefHasTxType === void 0) this.txRefHasTxType = await require_tx_ref_tx_type.hasTxRefTxTypeColumn(executor);
31
+ return this.txRefHasTxType;
32
+ }
25
33
  /**
26
34
  * Override _insert to format transaction before inserting
27
35
  * This populates assets, tokens, factories, etc. from itxJson,
@@ -61,6 +69,8 @@ var TransactionTable = class extends require_table_base.default {
61
69
  const executor = this.getExecutor(context);
62
70
  if (replaceExisting) await kysely.sql`DELETE FROM tx_ref WHERE hash = ${hash}`.execute(executor);
63
71
  const time = data.time || null;
72
+ const withTxType = await this.writesTxRefTxType(executor);
73
+ const txType = typeof data.type === "string" ? data.type : null;
64
74
  for (const [type, field] of TX_REF_TYPES) {
65
75
  let values = data[field];
66
76
  if (typeof values === "string") try {
@@ -69,7 +79,8 @@ var TransactionTable = class extends require_table_base.default {
69
79
  continue;
70
80
  }
71
81
  if (!Array.isArray(values) || values.length === 0) continue;
72
- for (const v of values) if (typeof v === "string" && v) await kysely.sql`INSERT OR IGNORE INTO tx_ref (hash, type, value, time) VALUES (${hash}, ${type}, ${v}, ${time})`.execute(executor);
82
+ for (const v of values) if (typeof v === "string" && v) if (withTxType) await kysely.sql`INSERT OR IGNORE INTO tx_ref (hash, type, value, time, tx_type) VALUES (${hash}, ${type}, ${v}, ${time}, ${txType})`.execute(executor);
83
+ else await kysely.sql`INSERT OR IGNORE INTO tx_ref (hash, type, value, time) VALUES (${hash}, ${type}, ${v}, ${time})`.execute(executor);
73
84
  }
74
85
  }
75
86
  /**
@@ -10,6 +10,13 @@ import { TIndexedTransaction } from "@ocap/types";
10
10
  * and maintain the tx_ref junction table for fast JSON array lookups
11
11
  */
12
12
  declare class TransactionTable extends SqliteTable<TIndexedTransaction> {
13
+ /**
14
+ * Whether tx_ref has the tx_type column. Set by SqliteIndexDB.initialize() (and after migrateTxRefTxType);
15
+ * detected lazily on the first write otherwise. The schema only changes offline, so it is never re-read.
16
+ */
17
+ private txRefHasTxType;
18
+ setTxRefTxTypeColumn(present: boolean | undefined): void;
19
+ private writesTxRefTxType;
13
20
  /**
14
21
  * Override _insert to format transaction before inserting
15
22
  * This populates assets, tokens, factories, etc. from itxJson,
@@ -0,0 +1,222 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let kysely = require("kysely");
3
+
4
+ //#region src/tx-ref-tx-type.ts
5
+ /**
6
+ * tx_ref.tx_type + idx_tx_ref_type_value_txtype_time (#1870, step 2 of #1861) - OFFLINE ONLY (#1885)
7
+ *
8
+ * `tx_ref.tx_type` is a denormalized copy of `tx.type`, so a type-filtered count of an account's history
9
+ * (`tx_ref type/value + tx.type in (...)`, the wallet's `page { total }`) is answered from one covering index
10
+ * on tx_ref instead of probing every `tx` row of the account.
11
+ *
12
+ * Not part of the startup migration chain (migration 011 is a recorded no-op): a chain node never adds the
13
+ * column, back-fills or builds the index while starting. The only entry point is `migrateTxRefTxType`, run by
14
+ * `scripts/ops/indexdb-migrate.mjs` with the chain stopped. SqliteIndexDB.initialize() only detects the state:
15
+ * - no column (1.31.7 schema): writes and queries use exactly the 1.31.7 SQL
16
+ * - column but no index (offline run interrupted): writes fill tx_type, queries stay on the 1.31.7 SQL
17
+ * - column + index: writes fill tx_type, listTransactions uses the tx_type path
18
+ *
19
+ * `migrateTxRefTxType` steps (each idempotent, so an interrupted run is simply re-run):
20
+ * 1. `ALTER TABLE tx_ref ADD COLUMN tx_type` (instant, metadata only).
21
+ * 2. Back-fill driven by `tx` rowid batches: `UPDATE tx_ref ... FROM (SELECT hash, type FROM tx WHERE rowid
22
+ * in batch)`, one transaction per batch that also stores the next rowid in `tx_ref_tx_type_backfill`, so a
23
+ * resumed run continues where the killed one stopped. Yields to the event loop between batches.
24
+ * Driving from `tx` reads every tx row once, in order. Driving from tx_ref would read a tx row once per
25
+ * tx_ref row (2.4M vs 0.7M on main), and reading `tx.type` walks the overflow pages of the big `tx`
26
+ * JSON column that precedes it, so that is several passes over a table larger than main's RAM.
27
+ * Only `tx_type IS NULL` rows are written. Rows written meanwhile by TransactionTable (same process, or a
28
+ * node started on a half-migrated file) already carry tx_type.
29
+ * 3. `CREATE INDEX` - only after the back-fill finished. Query-side readiness is "this index exists"
30
+ * (see isTxRefTxTypeReady), so a partially filled column is never queried. Then the progress table is
31
+ * dropped.
32
+ *
33
+ * Rows left NULL after the back-fill have no `tx` row (orphans) or a NULL `tx.type`; neither can match a
34
+ * `type in (...)` filter on either path, so results stay identical.
35
+ */
36
+ const TX_REF_TX_TYPE_INDEX = "idx_tx_ref_type_value_txtype_time";
37
+ /** Progress of an unfinished back-fill: one row, the next tx rowid to process. Dropped once the index exists. */
38
+ const TX_REF_TX_TYPE_PROGRESS_TABLE = "tx_ref_tx_type_backfill";
39
+ /** tx rows per back-fill batch (~3.4 tx_ref rows each on main); keeps each write-lock hold short. */
40
+ const TX_REF_TX_TYPE_BATCH_SIZE = 5e3;
41
+ const now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
42
+ const yieldToEventLoop = () => new Promise((resolve) => {
43
+ if (typeof setImmediate === "function") setImmediate(resolve);
44
+ else setTimeout(resolve, 0);
45
+ });
46
+ /** Whether tx_ref has the tx_type column (added only by migrateTxRefTxType). */
47
+ async function hasTxRefTxTypeColumn(db) {
48
+ return ((await kysely.sql`PRAGMA table_info('tx_ref')`.execute(db)).rows || []).some((r) => r.name === "tx_type");
49
+ }
50
+ /**
51
+ * Whether listTransactions may use tx_ref.tx_type: the column exists and the index (created only after a
52
+ * complete back-fill) exists.
53
+ */
54
+ async function isTxRefTxTypeReady(db) {
55
+ if (!await hasTxRefTxTypeColumn(db)) return false;
56
+ return (await kysely.sql`
57
+ SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'tx_ref' AND name = ${TX_REF_TX_TYPE_INDEX}
58
+ `.execute(db)).rows.length > 0;
59
+ }
60
+ /**
61
+ * Fill tx_ref.tx_type from tx.type for rows where it is NULL, in committed tx-rowid batches, resuming from the
62
+ * stored progress. Requires the column.
63
+ */
64
+ async function backfillTxRefTxType(db, { batchSize = TX_REF_TX_TYPE_BATCH_SIZE, onBatch } = {}) {
65
+ const started = now();
66
+ const stats = {
67
+ batches: 0,
68
+ updated: 0,
69
+ maxBatchMs: 0,
70
+ sweepUpdated: 0,
71
+ sweepMs: 0,
72
+ totalMs: 0
73
+ };
74
+ await kysely.sql`
75
+ CREATE TABLE IF NOT EXISTS tx_ref_tx_type_backfill (id INTEGER PRIMARY KEY CHECK (id = 1), next_rowid INTEGER NOT NULL)
76
+ `.execute(db);
77
+ const progress = await kysely.sql`SELECT next_rowid AS next FROM tx_ref_tx_type_backfill WHERE id = 1`.execute(db);
78
+ const bounds = await kysely.sql`
79
+ SELECT min(rowid) AS lo, max(rowid) AS hi FROM tx
80
+ `.execute(db);
81
+ const readMaxRowid = async () => {
82
+ const r = await kysely.sql`SELECT max(rowid) AS id FROM tx`.execute(db);
83
+ return Number(r.rows[0]?.id ?? 0);
84
+ };
85
+ let from = progress.rows.length ? Number(progress.rows[0].next) : Number(bounds.rows[0]?.lo ?? 1);
86
+ let max = Number(bounds.rows[0]?.hi ?? 0);
87
+ while (from <= max) {
88
+ const to = from + batchSize;
89
+ const t0 = now();
90
+ const updated = await db.transaction().execute(async (trx) => {
91
+ const res = await kysely.sql`
92
+ UPDATE tx_ref SET tx_type = t.type
93
+ FROM (SELECT hash, type FROM tx WHERE rowid >= ${from} AND rowid < ${to}) AS t
94
+ WHERE tx_ref.hash = t.hash AND tx_ref.tx_type IS NULL
95
+ `.execute(trx);
96
+ await kysely.sql`
97
+ INSERT INTO tx_ref_tx_type_backfill (id, next_rowid) VALUES (1, ${to})
98
+ ON CONFLICT (id) DO UPDATE SET next_rowid = excluded.next_rowid
99
+ `.execute(trx);
100
+ return Number(res.numAffectedRows ?? 0);
101
+ });
102
+ const ms = now() - t0;
103
+ stats.batches++;
104
+ stats.updated += updated;
105
+ stats.maxBatchMs = Math.max(stats.maxBatchMs, ms);
106
+ await onBatch?.({
107
+ from,
108
+ to,
109
+ updated,
110
+ ms,
111
+ maxRowid: max
112
+ });
113
+ await yieldToEventLoop();
114
+ from = to;
115
+ if (from > max) max = await readMaxRowid();
116
+ }
117
+ const sweep = await sweepTxRefTxTypeNulls(db);
118
+ stats.sweepUpdated = sweep.updated;
119
+ stats.updated += stats.sweepUpdated;
120
+ stats.sweepMs = sweep.ms;
121
+ stats.totalMs = now() - started;
122
+ return stats;
123
+ }
124
+ /** tx_ref rows per sweep batch (rowid range; only the `tx_type IS NULL` rows in it are looked up in tx). */
125
+ const TX_REF_TX_TYPE_SWEEP_BATCH_SIZE = 5e4;
126
+ /**
127
+ * Fill tx_ref.tx_type for rows still NULL whose tx has a type, in committed tx_ref-rowid batches (one short write
128
+ * transaction each, not one statement over the whole table). Catches what the back-fill missed (stale progress)
129
+ * and rows written without tx_type after the migration, e.g. by a release that predates the column (downgrade,
130
+ * then upgrade again). Orphans and NULL tx.type stay NULL.
131
+ */
132
+ async function sweepTxRefTxTypeNulls(db, { batchSize = TX_REF_TX_TYPE_SWEEP_BATCH_SIZE } = {}) {
133
+ const t0 = now();
134
+ const stats = {
135
+ updated: 0,
136
+ batches: 0,
137
+ ms: 0
138
+ };
139
+ const bounds = await kysely.sql`
140
+ SELECT min(rowid) AS lo, max(rowid) AS hi FROM tx_ref
141
+ `.execute(db);
142
+ const lo = bounds.rows[0]?.lo;
143
+ const hi = bounds.rows[0]?.hi;
144
+ if (lo !== null && lo !== void 0 && hi !== null && hi !== void 0) for (let from = Number(lo); from <= Number(hi); from += batchSize) {
145
+ const to = from + batchSize;
146
+ const res = await kysely.sql`
147
+ UPDATE tx_ref SET tx_type = (SELECT tx.type FROM tx WHERE tx.hash = tx_ref.hash)
148
+ WHERE rowid >= ${from} AND rowid < ${to} AND tx_type IS NULL
149
+ AND (SELECT tx.type FROM tx WHERE tx.hash = tx_ref.hash) IS NOT NULL
150
+ `.execute(db);
151
+ stats.updated += Number(res.numAffectedRows ?? 0);
152
+ stats.batches++;
153
+ await yieldToEventLoop();
154
+ }
155
+ stats.ms = now() - t0;
156
+ return stats;
157
+ }
158
+ /** Step 1 of migrateTxRefTxType: add the column if missing (metadata only). Returns whether it was added. */
159
+ async function addTxRefTxTypeColumn(db) {
160
+ if (await hasTxRefTxTypeColumn(db)) return false;
161
+ await kysely.sql`ALTER TABLE tx_ref ADD COLUMN tx_type TEXT`.execute(db);
162
+ return true;
163
+ }
164
+ /**
165
+ * The offline tx_ref.tx_type migration (#1870, #1885): add the column if missing, resumable batched back-fill,
166
+ * final sweep, then the index. On an already migrated database it only sweeps rows still NULL (written by a
167
+ * release without tx_type between two runs). Idempotent and resumable after an interruption. Never called at
168
+ * startup; a node detects the result at its next start.
169
+ *
170
+ * No other SqliteIndexDB instance or process may have the file open while this runs: their cached "tx_ref has
171
+ * tx_type" flag (TransactionTable#txRefHasTxType) is not refreshed, so their later writes would leave tx_type NULL.
172
+ * In production call it only through scripts/ops/indexdb-migrate.mjs, which refuses to run while the file is in use.
173
+ */
174
+ async function migrateTxRefTxType(db, options = {}) {
175
+ const started = now();
176
+ const columnAdded = await addTxRefTxTypeColumn(db);
177
+ if (await isTxRefTxTypeReady(db)) {
178
+ await kysely.sql`DROP TABLE IF EXISTS tx_ref_tx_type_backfill`.execute(db);
179
+ return {
180
+ columnAdded,
181
+ alreadyMigrated: true,
182
+ backfill: null,
183
+ sweep: await sweepTxRefTxTypeNulls(db),
184
+ indexMs: 0,
185
+ totalMs: now() - started
186
+ };
187
+ }
188
+ const backfill = await backfillTxRefTxType(db, options);
189
+ const t0 = now();
190
+ await kysely.sql`CREATE INDEX IF NOT EXISTS idx_tx_ref_type_value_txtype_time ON tx_ref(type, value, tx_type, time)`.execute(db);
191
+ await kysely.sql`DROP TABLE IF EXISTS tx_ref_tx_type_backfill`.execute(db);
192
+ return {
193
+ columnAdded,
194
+ alreadyMigrated: false,
195
+ backfill,
196
+ sweep: null,
197
+ indexMs: now() - t0,
198
+ totalMs: now() - started
199
+ };
200
+ }
201
+ /**
202
+ * Undo migrateTxRefTxType (index, progress table, column): back to the 1.31.7 schema, e.g. before running a
203
+ * release that does not write tx_type on this file. Offline only, like the migration.
204
+ */
205
+ async function dropTxRefTxType(db) {
206
+ await kysely.sql`DROP INDEX IF EXISTS idx_tx_ref_type_value_txtype_time`.execute(db);
207
+ await kysely.sql`DROP TABLE IF EXISTS tx_ref_tx_type_backfill`.execute(db);
208
+ if (await hasTxRefTxTypeColumn(db)) await kysely.sql`ALTER TABLE tx_ref DROP COLUMN tx_type`.execute(db);
209
+ }
210
+
211
+ //#endregion
212
+ exports.TX_REF_TX_TYPE_BATCH_SIZE = TX_REF_TX_TYPE_BATCH_SIZE;
213
+ exports.TX_REF_TX_TYPE_INDEX = TX_REF_TX_TYPE_INDEX;
214
+ exports.TX_REF_TX_TYPE_PROGRESS_TABLE = TX_REF_TX_TYPE_PROGRESS_TABLE;
215
+ exports.TX_REF_TX_TYPE_SWEEP_BATCH_SIZE = TX_REF_TX_TYPE_SWEEP_BATCH_SIZE;
216
+ exports.addTxRefTxTypeColumn = addTxRefTxTypeColumn;
217
+ exports.backfillTxRefTxType = backfillTxRefTxType;
218
+ exports.dropTxRefTxType = dropTxRefTxType;
219
+ exports.hasTxRefTxTypeColumn = hasTxRefTxTypeColumn;
220
+ exports.isTxRefTxTypeReady = isTxRefTxTypeReady;
221
+ exports.migrateTxRefTxType = migrateTxRefTxType;
222
+ exports.sweepTxRefTxTypeNulls = sweepTxRefTxTypeNulls;
@@ -0,0 +1,131 @@
1
+ import { Kysely } from "kysely";
2
+
3
+ //#region src/tx-ref-tx-type.d.ts
4
+
5
+ /**
6
+ * tx_ref.tx_type + idx_tx_ref_type_value_txtype_time (#1870, step 2 of #1861) - OFFLINE ONLY (#1885)
7
+ *
8
+ * `tx_ref.tx_type` is a denormalized copy of `tx.type`, so a type-filtered count of an account's history
9
+ * (`tx_ref type/value + tx.type in (...)`, the wallet's `page { total }`) is answered from one covering index
10
+ * on tx_ref instead of probing every `tx` row of the account.
11
+ *
12
+ * Not part of the startup migration chain (migration 011 is a recorded no-op): a chain node never adds the
13
+ * column, back-fills or builds the index while starting. The only entry point is `migrateTxRefTxType`, run by
14
+ * `scripts/ops/indexdb-migrate.mjs` with the chain stopped. SqliteIndexDB.initialize() only detects the state:
15
+ * - no column (1.31.7 schema): writes and queries use exactly the 1.31.7 SQL
16
+ * - column but no index (offline run interrupted): writes fill tx_type, queries stay on the 1.31.7 SQL
17
+ * - column + index: writes fill tx_type, listTransactions uses the tx_type path
18
+ *
19
+ * `migrateTxRefTxType` steps (each idempotent, so an interrupted run is simply re-run):
20
+ * 1. `ALTER TABLE tx_ref ADD COLUMN tx_type` (instant, metadata only).
21
+ * 2. Back-fill driven by `tx` rowid batches: `UPDATE tx_ref ... FROM (SELECT hash, type FROM tx WHERE rowid
22
+ * in batch)`, one transaction per batch that also stores the next rowid in `tx_ref_tx_type_backfill`, so a
23
+ * resumed run continues where the killed one stopped. Yields to the event loop between batches.
24
+ * Driving from `tx` reads every tx row once, in order. Driving from tx_ref would read a tx row once per
25
+ * tx_ref row (2.4M vs 0.7M on main), and reading `tx.type` walks the overflow pages of the big `tx`
26
+ * JSON column that precedes it, so that is several passes over a table larger than main's RAM.
27
+ * Only `tx_type IS NULL` rows are written. Rows written meanwhile by TransactionTable (same process, or a
28
+ * node started on a half-migrated file) already carry tx_type.
29
+ * 3. `CREATE INDEX` - only after the back-fill finished. Query-side readiness is "this index exists"
30
+ * (see isTxRefTxTypeReady), so a partially filled column is never queried. Then the progress table is
31
+ * dropped.
32
+ *
33
+ * Rows left NULL after the back-fill have no `tx` row (orphans) or a NULL `tx.type`; neither can match a
34
+ * `type in (...)` filter on either path, so results stay identical.
35
+ */
36
+ declare const TX_REF_TX_TYPE_INDEX = "idx_tx_ref_type_value_txtype_time";
37
+ /** Progress of an unfinished back-fill: one row, the next tx rowid to process. Dropped once the index exists. */
38
+ declare const TX_REF_TX_TYPE_PROGRESS_TABLE = "tx_ref_tx_type_backfill";
39
+ /** tx rows per back-fill batch (~3.4 tx_ref rows each on main); keeps each write-lock hold short. */
40
+ declare const TX_REF_TX_TYPE_BATCH_SIZE = 5000;
41
+ interface TxRefTxTypeBatch {
42
+ /** inclusive tx rowid lower bound */
43
+ from: number;
44
+ /** exclusive tx rowid upper bound */
45
+ to: number;
46
+ /** tx_ref rows updated */
47
+ updated: number;
48
+ ms: number;
49
+ /** current max(rowid) of tx, for progress reporting */
50
+ maxRowid: number;
51
+ }
52
+ interface TxRefTxTypeBackfillOptions {
53
+ batchSize?: number;
54
+ /** called after each committed batch (progress logging; tests use it to interrupt or write concurrently) */
55
+ onBatch?: (batch: TxRefTxTypeBatch) => void | Promise<void>;
56
+ }
57
+ interface TxRefTxTypeBackfillStats {
58
+ batches: number;
59
+ updated: number;
60
+ maxBatchMs: number;
61
+ /** rows fixed by the final sweep (0 unless the progress was stale, e.g. VACUUM renumbered tx rowids) */
62
+ sweepUpdated: number;
63
+ sweepMs: number;
64
+ totalMs: number;
65
+ }
66
+ /** Whether tx_ref has the tx_type column (added only by migrateTxRefTxType). */
67
+ declare function hasTxRefTxTypeColumn(db: Kysely<unknown>): Promise<boolean>;
68
+ /**
69
+ * Whether listTransactions may use tx_ref.tx_type: the column exists and the index (created only after a
70
+ * complete back-fill) exists.
71
+ */
72
+ declare function isTxRefTxTypeReady(db: Kysely<unknown>): Promise<boolean>;
73
+ /**
74
+ * Fill tx_ref.tx_type from tx.type for rows where it is NULL, in committed tx-rowid batches, resuming from the
75
+ * stored progress. Requires the column.
76
+ */
77
+ declare function backfillTxRefTxType(db: Kysely<unknown>, {
78
+ batchSize,
79
+ onBatch
80
+ }?: TxRefTxTypeBackfillOptions): Promise<TxRefTxTypeBackfillStats>;
81
+ /** tx_ref rows per sweep batch (rowid range; only the `tx_type IS NULL` rows in it are looked up in tx). */
82
+ declare const TX_REF_TX_TYPE_SWEEP_BATCH_SIZE = 50000;
83
+ interface TxRefTxTypeSweepStats {
84
+ updated: number;
85
+ batches: number;
86
+ ms: number;
87
+ }
88
+ /**
89
+ * Fill tx_ref.tx_type for rows still NULL whose tx has a type, in committed tx_ref-rowid batches (one short write
90
+ * transaction each, not one statement over the whole table). Catches what the back-fill missed (stale progress)
91
+ * and rows written without tx_type after the migration, e.g. by a release that predates the column (downgrade,
92
+ * then upgrade again). Orphans and NULL tx.type stay NULL.
93
+ */
94
+ declare function sweepTxRefTxTypeNulls(db: Kysely<unknown>, {
95
+ batchSize
96
+ }?: {
97
+ batchSize?: number;
98
+ }): Promise<TxRefTxTypeSweepStats>;
99
+ /** Step 1 of migrateTxRefTxType: add the column if missing (metadata only). Returns whether it was added. */
100
+ declare function addTxRefTxTypeColumn(db: Kysely<unknown>): Promise<boolean>;
101
+ interface TxRefTxTypeMigrationResult {
102
+ /** the column was missing and this run added it */
103
+ columnAdded: boolean;
104
+ /** the index already existed: no back-fill, only the NULL sweep (`sweep`) */
105
+ alreadyMigrated: boolean;
106
+ /** null when alreadyMigrated */
107
+ backfill: TxRefTxTypeBackfillStats | null;
108
+ /** NULL sweep of an already migrated database (rows written without tx_type, e.g. during a downgrade); null otherwise */
109
+ sweep: TxRefTxTypeSweepStats | null;
110
+ /** time spent building the index (0 when alreadyMigrated) */
111
+ indexMs: number;
112
+ totalMs: number;
113
+ }
114
+ /**
115
+ * The offline tx_ref.tx_type migration (#1870, #1885): add the column if missing, resumable batched back-fill,
116
+ * final sweep, then the index. On an already migrated database it only sweeps rows still NULL (written by a
117
+ * release without tx_type between two runs). Idempotent and resumable after an interruption. Never called at
118
+ * startup; a node detects the result at its next start.
119
+ *
120
+ * No other SqliteIndexDB instance or process may have the file open while this runs: their cached "tx_ref has
121
+ * tx_type" flag (TransactionTable#txRefHasTxType) is not refreshed, so their later writes would leave tx_type NULL.
122
+ * In production call it only through scripts/ops/indexdb-migrate.mjs, which refuses to run while the file is in use.
123
+ */
124
+ declare function migrateTxRefTxType(db: Kysely<unknown>, options?: TxRefTxTypeBackfillOptions): Promise<TxRefTxTypeMigrationResult>;
125
+ /**
126
+ * Undo migrateTxRefTxType (index, progress table, column): back to the 1.31.7 schema, e.g. before running a
127
+ * release that does not write tx_type on this file. Offline only, like the migration.
128
+ */
129
+ declare function dropTxRefTxType(db: Kysely<unknown>): Promise<void>;
130
+ //#endregion
131
+ export { TX_REF_TX_TYPE_BATCH_SIZE, TX_REF_TX_TYPE_INDEX, TX_REF_TX_TYPE_PROGRESS_TABLE, TX_REF_TX_TYPE_SWEEP_BATCH_SIZE, TxRefTxTypeBackfillOptions, TxRefTxTypeBackfillStats, TxRefTxTypeBatch, TxRefTxTypeMigrationResult, TxRefTxTypeSweepStats, addTxRefTxTypeColumn, backfillTxRefTxType, dropTxRefTxType, hasTxRefTxTypeColumn, isTxRefTxTypeReady, migrateTxRefTxType, sweepTxRefTxTypeNulls };