From 2084d747271961a9ad3d13a752257a025c29453d Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:03:45 +0100 Subject: [PATCH 1/6] perf: keep the cost of a sync flat as the local files and the WAL grow --- package.json | 1 + packages/sqlite-js-stream/README.md | 12 ++ .../bench/bench-sync-small-writes.ts | 96 ++++++++++ packages/sqlite-js-stream/package.json | 3 +- packages/sqlite-js-stream/src/db.ts | 158 ++++++++++++++-- packages/sqlite-js-stream/src/replica.ts | 8 +- .../test/db/db-sync-state.test.ts | 171 ++++++++++++++++++ 7 files changed, 433 insertions(+), 16 deletions(-) create mode 100644 packages/sqlite-js-stream/bench/bench-sync-small-writes.ts create mode 100644 packages/sqlite-js-stream/test/db/db-sync-state.test.ts diff --git a/package.json b/package.json index 4ae575c..2c02db3 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "test:paged-vfs": "pnpm --filter @platformatic/sqlite-js-stream-paged-vfs build:native && pnpm --filter @platformatic/sqlite-js-stream-paged-vfs build && pnpm --filter @platformatic/sqlite-js-stream-paged-vfs test && node --test packages/sqlite-js-stream/test/integration/paged-restore.test.ts", "bench": "pnpm --filter @platformatic/sqlite-js-stream bench", "bench:encode": "pnpm --filter @platformatic/sqlite-js-stream bench:encode", + "bench:small-writes": "pnpm --filter @platformatic/sqlite-js-stream bench:small-writes", "golden:go": "cd packages/sqlite-js-stream/tools/golden && go run ." }, "devDependencies": { diff --git a/packages/sqlite-js-stream/README.md b/packages/sqlite-js-stream/README.md index 529e4db..846014f 100644 --- a/packages/sqlite-js-stream/README.md +++ b/packages/sqlite-js-stream/README.md @@ -657,6 +657,18 @@ BASELINE=1 pnpm bench:encode PAGE_SIZE=65536 PAGES=256 pnpm bench:encode ``` +[`bench/bench-sync-small-writes.ts`](bench/bench-sync-small-writes.ts) measures what one write pays when +every write is followed by a sync: the time of the local step of a sync, block after block, as the local +LTX files and the WAL grow. It should stay flat: + +```bash +pnpm bench:small-writes +# more writes: +SYNCS=5000 BLOCK=500 pnpm bench:small-writes +# with the WAL checkpointed as an application which bounds it does: +CHECKPOINT=250 pnpm bench:small-writes +``` + ### Compaction & retention Over time `sync()` writes one level-0 LTX file per transaction. To keep the replica bounded and diff --git a/packages/sqlite-js-stream/bench/bench-sync-small-writes.ts b/packages/sqlite-js-stream/bench/bench-sync-small-writes.ts new file mode 100644 index 0000000..f02ccca --- /dev/null +++ b/packages/sqlite-js-stream/bench/bench-sync-small-writes.ts @@ -0,0 +1,96 @@ +/** + * Small writes benchmark. + * + * An application which replicates every write syncs after each of them: a sync + * then holds one small transaction, and its cost is what one write pays. This + * measures that cost as the writes add up, i.e. as the local LTX files and the + * WAL grow: it should stay flat. A cost which grows with the number of local + * files or with the size of the WAL shows as a time which rises block after + * block. + * + * Only the local step of a sync is measured, `LocalDatabase.sync()`: reading + * the WAL and writing the LTX file. Nothing is uploaded. + * + * Tunables (env): + * SYNCS syncs, one after each write (default 1000) + * BLOCK syncs in each reported block (default 100) + * CHECKPOINT checkpoint the WAL every this many syncs, as an + * application which bounds its WAL does; 0 never (default 0) + * + * Run: + * pnpm bench:small-writes + * SYNCS=5000 BLOCK=500 pnpm bench:small-writes + * CHECKPOINT=250 pnpm bench:small-writes + */ + +import { readdir, rm, stat } from 'node:fs/promises'; +import { dirname } from 'node:path'; + +import { LocalDatabase } from '../src/db.ts'; +import { runCheckpoint } from '../src/index.ts'; +import { createWALDB } from '../test/helpers/make-db.ts'; + +const SYNCS = Number(process.env.SYNCS ?? 1000); +const BLOCK = Number(process.env.BLOCK ?? 100); +const CHECKPOINT = Number(process.env.CHECKPOINT ?? 0); + +async function sizeOf(path: string): Promise { + try { + return (await stat(path)).size; + } catch { + return 0; + } +} + +async function main(): Promise { + const tdb = createWALDB(['value']); + const db = await LocalDatabase.open(tdb.path); + const update = tdb.db.prepare('UPDATE t SET name = ? WHERE id = 1'); + + try { + await db.sync(); + + console.log('small writes: one sync after each write of one row'); + console.log(`syncs=${SYNCS} block=${BLOCK} checkpoint=${CHECKPOINT === 0 ? 'never' : `every ${CHECKPOINT} syncs`}`); + console.log(''); + console.log('syncs ms/sync local files WAL bytes'); + + let first = 0; + let last = 0; + + for (let done = 0; done < SYNCS; ) { + const count = Math.min(BLOCK, SYNCS - done); + const start = performance.now(); + + for (let i = 0; i < count; i++) { + done++; + update.run(`value ${done}`); + await db.sync(); + + if (CHECKPOINT > 0 && done % CHECKPOINT === 0) { + // As an application does between its transactions: the next sync resumes in the WAL which follows. + runCheckpoint(tdb.db, await db.checkpointToken()); + } + } + + const each = (performance.now() - start) / count; + const files = (await readdir(db.ltxLevelDir(0))).length; + const wal = await sizeOf(tdb.walPath); + console.log( + `${String(done - count + 1).padStart(6)}-${String(done).padEnd(8)} ${each.toFixed(2).padStart(8)} ${String(files).padStart(13)} ${String(wal).padStart(11)}`, + ); + + if (first === 0) first = each; + last = each; + } + + console.log(''); + console.log(`last block against the first: ${(last / first).toFixed(2)}x`); + } finally { + db.close(); + tdb.close(); + await rm(dirname(tdb.path), { recursive: true, force: true }); + } +} + +await main(); diff --git a/packages/sqlite-js-stream/package.json b/packages/sqlite-js-stream/package.json index 7795d94..7b8c3ce 100644 --- a/packages/sqlite-js-stream/package.json +++ b/packages/sqlite-js-stream/package.json @@ -45,7 +45,8 @@ "build": "tsc -p tsconfig.build.json", "prepack": "pnpm build", "bench": "node bench/bench-sync-restore.ts", - "bench:encode": "node bench/bench-ltx-encode.ts" + "bench:encode": "node bench/bench-ltx-encode.ts", + "bench:small-writes": "node bench/bench-sync-small-writes.ts" }, "dependencies": { "lz4js": "^0.2.0" diff --git a/packages/sqlite-js-stream/src/db.ts b/packages/sqlite-js-stream/src/db.ts index cc80433..48113a8 100644 --- a/packages/sqlite-js-stream/src/db.ts +++ b/packages/sqlite-js-stream/src/db.ts @@ -290,6 +290,20 @@ export class LocalDatabase { private conn: ReaderConnection | null = null; private openReader: OpenReader; private pageLoader: PageLoader | null = null; + /** + * What the last sync of this instance published: the newest local file, the + * TXID of the last restore, and where that sync ended in the WAL, as its + * header says. The next sync starts from it without reading it back from + * the disk. It is the local position only: what the replica has is another + * matter, and a file whose upload failed is still there to upload. Null + * until a sync publishes a file, and after anything else changed the local + * files, see {@link invalidate}. + */ + private last: { + max: { level: number; minTXID: bigint; maxTXID: bigint }; + base: bigint; + prev: { walOffset: number; walSize: number; salt1: number; salt2: number; commit: number }; + } | null = null; private constructor(path: string, metaPath: string, pageSize: number, openReader: OpenReader) { this.path = path; @@ -388,6 +402,7 @@ export class LocalDatabase { * local LTX files first. */ async recordRestore(txid: bigint, wal: RestoredWAL | null): Promise { + this.invalidate(); await rm(this.restorePath(), { force: true }); await rm(this.checkpointPath(), { force: true }); await writeFile(this.baseTXIDPath(), `${txid}\n`); @@ -489,17 +504,47 @@ export class LocalDatabase { * restore if it is higher (0 if none). */ async pos(): Promise { + if (this.last !== null) return this.last.max.maxTXID; const m = await this.maxFile(); const base = await this.baseTXID(); return m === null || m.maxTXID < base ? base : m.maxTXID; } - /** Returns the local LTX file with the highest maxTXID across all levels. */ - private async maxFile(): Promise { - let best: FileInfo | null = null; + /** + * Forgets what the last sync published, so that the next sync reads the + * local files again. To call after the local LTX files were changed by + * anything but {@link sync}: a compaction, the retention, a restore. + */ + invalidate(): void { + this.last = null; + } + + /** + * Returns the TXID range of the local LTX file with the highest maxTXID + * across all levels. Every sync asks for it, so it reads the names of the + * files only: unlike {@link filesForLevel}, it does not stat each of them, + * which would make a sync cost grow with the number of local files. + */ + private async maxFile(): Promise<{ level: number; minTXID: bigint; maxTXID: bigint } | null> { + let best: { level: number; minTXID: bigint; maxTXID: bigint } | null = null; for (let level = 0; level <= SnapshotLevel; level++) { - for (const f of await this.filesForLevel(level)) { - if (best === null || f.maxTXID > best.maxTXID) best = f; + let entries; + try { + entries = await readdir(this.ltxLevelDir(level), { withFileTypes: true }); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue; + throw err; + } + for (const entry of entries) { + // As filesForLevel(): a directory or a link named as an LTX file is not one. + if (!entry.isFile()) continue; + let range: { minTXID: bigint; maxTXID: bigint }; + try { + range = parseFilename(entry.name); + } catch { + continue; + } + if (best === null || range.maxTXID > best.maxTXID) best = { level, ...range }; } } return best; @@ -549,7 +594,15 @@ export class LocalDatabase { /** Sync builds a level-0 LTX file and writes it to the local cache. */ async sync(): Promise { await this.assertComplete(); - const pos = await this.pos(); + // The newest local file and the TXID of the last restore give the position + // of the sync and where it resumes from: they are what the last sync of + // this instance left, or are read from the disk, once for the whole sync. + const known: { + max: { level: number; minTXID: bigint; maxTXID: bigint } | null; + base: bigint; + prev?: { walOffset: number; walSize: number; salt1: number; salt2: number; commit: number }; + } = this.last ?? { max: await this.maxFile(), base: await this.baseTXID() }; + const pos = known.max === null || known.max.maxTXID < known.base ? known.base : known.max.maxTXID; const txID = pos + 1n; this.beginRead(); @@ -562,12 +615,24 @@ export class LocalDatabase { const lockPg = lockPgno(pageSize); dbHandle = await open(this.path, 'r'); - const walBuf = await this.readWalOrEmpty(); // Determine the previous sync state to resume incremental reading. - let prev = await this.prevSyncInfo(); + let prev = await this.prevSyncInfo(known); let snapshotting = prev === null; + // A sync which resumes needs the header of the WAL, the frame before the + // point it resumes from, to check that the WAL is still the same one, and + // the frames after it: only those are read, at their place in a buffer of + // the size of the WAL. Reading it whole would cost more with every write + // until the WAL is checkpointed. Whenever the sync cannot resume, the WAL + // is read whole, as before. + const resumeFrom = prev === null ? 0 : prev.walOffset + prev.walSize; + let walBuf = + resumeFrom > WALHeaderSize + ? await this.readWalFrom(resumeFrom - (WALFrameHeaderSize + pageSize)) + : await this.readWalOrEmpty(); + let walPartial = resumeFrom > WALHeaderSize; + let reader: WALReader | null = null; let offset = WALHeaderSize; let salt1 = 0; @@ -579,6 +644,11 @@ export class LocalDatabase { if (!snapshotting && prev !== null) { reader = makeResumeReader(walBuf, prev.walOffset + prev.walSize, prev.salt1, prev.salt2); + if (reader === null && walPartial) { + // The WAL is not the one the last sync read: everything in it counts. + walBuf = await this.readWalOrEmpty(); + walPartial = false; + } if (reader === null && (await this.checkpointed(pos, prev))) { // The WAL was reset by runCheckpoint() right after the previous sync: // the database file holds the state at `pos`, and every frame of the @@ -634,6 +704,10 @@ export class LocalDatabase { const filename = this.ltxPath(0, txID, txID); const tmp = `${filename}.tmp`; + // A snapshot covers the WAL up to its last commit frame, so the next + // sync resumes right after it (not after uncommitted frames). + const headerWalSize = snapshotting ? (maxOffset > 0 ? maxOffset - WALHeaderSize : 0) : walSize; + const fh = await open(tmp, 'w'); const sink = new FileSink(fh); const enc = new Encoder(sink); @@ -648,9 +722,7 @@ export class LocalDatabase { timestamp: BigInt(Date.now()), preApplyChecksum: 0n, walOffset: BigInt(offset), - // A snapshot covers the WAL up to its last commit frame, so the next - // sync resumes right after it (not after uncommitted frames). - walSize: BigInt(snapshotting ? (maxOffset > 0 ? maxOffset - WALHeaderSize : 0) : walSize), + walSize: BigInt(headerWalSize), walSalt1: salt1, walSalt2: salt2, nodeID: 0n, @@ -667,6 +739,13 @@ export class LocalDatabase { await rename(tmp, filename); + // The file is published: it is the newest one, and its header is where the next sync resumes. + this.last = { + max: { level: 0, minTXID: txID, maxTXID: txID }, + base: known.base, + prev: { walOffset: offset, walSize: headerWalSize, salt1, salt2, commit: finalCommit }, + }; + const size = (await stat(filename)).size; return { level: 0, minTXID: txID, maxTXID: txID, size, createdAt: Date.now() }; } catch (err) { @@ -674,6 +753,10 @@ export class LocalDatabase { await rm(tmp, { force: true }).catch(() => {}); throw err; } + } catch (err) { + // A sync which failed may have left anything: the next one reads the local files again. + this.last = null; + throw err; } finally { if (dbHandle !== null) await dbHandle.close(); this.commitRead(); @@ -774,6 +857,8 @@ export class LocalDatabase { async snapshot(): Promise { await this.assertComplete(); const pos = await this.pos(); + // A snapshot adds a local file: the next sync reads the local files again. + this.invalidate(); const maxTXID = pos === 0n ? 1n : pos; this.beginRead(); @@ -874,6 +959,42 @@ export class LocalDatabase { } /** Reads the WAL file bytes, returning empty if it does not exist. */ + /** + * Reads the header of the WAL and its bytes from `start` on, into a buffer of + * the size of the WAL: the bytes in between are left as zeros, and must not + * be read. Returns the whole WAL when `start` is within its header, and an + * empty buffer when there is no WAL. + */ + private async readWalFrom(start: number): Promise { + if (start <= WALHeaderSize) return this.readWalOrEmpty(); + let fh: FileHandle; + try { + fh = await open(this.walPath(), 'r'); + } catch { + return new Uint8Array(0); + } + try { + const size = (await fh.stat()).size; + const buf = new Uint8Array(size); + if (size === 0) return buf; + await fh.read(buf, 0, Math.min(WALHeaderSize, size), 0); + // Shorter than the point to resume from: the WAL was reset, and the caller reads it whole. + if (start < size) { + let read = start; + while (read < size) { + const { bytesRead } = await fh.read(buf, read, size - read, read); + if (bytesRead === 0) break; + read += bytesRead; + } + } + return buf; + } catch { + return new Uint8Array(0); + } finally { + await fh.close(); + } + } + private async readWalOrEmpty(): Promise { try { return new Uint8Array(await readFile(this.walPath())); @@ -883,15 +1004,23 @@ export class LocalDatabase { } /** Decodes the header of the max-TXID local L0 file (or null if none). */ - private async prevSyncInfo(): Promise<{ + private async prevSyncInfo( + known: { + max: { level: number; minTXID: bigint; maxTXID: bigint } | null; + base: bigint; + prev?: { walOffset: number; walSize: number; salt1: number; salt2: number; commit: number }; + } | null = this.last, + ): Promise<{ walOffset: number; walSize: number; salt1: number; salt2: number; commit: number; } | null> { - const max = await this.maxFile(); - const base = await this.baseTXID(); + // The header of the file the last sync published, without reading it back. + if (known?.prev !== undefined) return known.prev; + const max = known !== null ? known.max : await this.maxFile(); + const base = known !== null ? known.base : await this.baseTXID(); // After a restore the WAL position of the local files, if any, does not // describe the restored database. The first frame of the WAL written by // the restore does: resuming after it, the next sync is incremental while @@ -927,6 +1056,7 @@ export class LocalDatabase { /** Close releases the internal read-only connection. */ close(): void { + this.invalidate(); if (this.conn !== null) { this.conn.close(); this.conn = null; diff --git a/packages/sqlite-js-stream/src/replica.ts b/packages/sqlite-js-stream/src/replica.ts index 9e825de..90614c6 100644 --- a/packages/sqlite-js-stream/src/replica.ts +++ b/packages/sqlite-js-stream/src/replica.ts @@ -516,7 +516,9 @@ export class Replica { await this.client.init(); const db = await this.localDb(); const info = await db.sync(); - const dbPos = await db.pos(); + // A file which was just written is the newest one: the local position is + // not read again from the local files. + const dbPos = info !== null ? info.maxTXID : await db.pos(); const remotePos = await this.pos(); // Local TXIDs the replica already has would never be uploaded. @@ -1369,6 +1371,8 @@ export class Replica { const cleanup: Array<{ destroy?: () => void }> = []; const readers: StreamLtxReader[] = []; const db = await this.localDb(); + // A compacted file joins the local ones: the next sync reads them again. + db.invalidate(); const outPath = db.ltxPath(dstLevel, minTXID, maxTXID); const tmpPath = `${outPath}.tmp`; await mkdir(nodePath.dirname(outPath), { recursive: true }); @@ -1612,6 +1616,8 @@ export class Replica { const p = db.ltxPath(f.level, f.minTXID, f.maxTXID); await rm(p, { force: true }).catch(() => {}); } + // Local files are gone: the next sync reads the ones which are left. + db.invalidate(); return files; } diff --git a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts new file mode 100644 index 0000000..d8aa171 --- /dev/null +++ b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts @@ -0,0 +1,171 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdir, readFile, symlink } from 'node:fs/promises'; +import { join } from 'node:path'; + +import { Decoder } from '../../src/index.ts'; +import { LocalDatabase } from '../../src/db.ts'; +import { createWALDB } from '../helpers/make-db.ts'; + +/** The header of a local level-0 file, and the number of its pages. */ +async function describe(db: LocalDatabase, txID: bigint) { + const dec = new Decoder(new Uint8Array(await readFile(db.ltxPath(0, txID, txID)))); + dec.decodeHeader(); + const header = dec.Header(); + const data = new Uint8Array(header.pageSize); + let pages = 0; + while (dec.decodePage(data) !== null) pages++; + dec.close(); + return { header, pages }; +} + +test('each sync resumes where the one before it ended, whether or not its state was kept', async (t) => { + const tdb = createWALDB(['a', 'b', 'c']); + const db = await LocalDatabase.open(tdb.path); + t.after(() => db.close()); + t.after(() => tdb.close()); + + await db.sync(); + for (let i = 2n; i <= 12n; i++) { + tdb.db.exec(`INSERT INTO t (name) VALUES ('row ${i}')`); + // Every third sync reads its state from the local files, as a new instance does + if (i % 3n === 0n) db.invalidate(); + const info = await db.sync(); + assert.equal(info?.minTXID, i); + assert.equal(await db.pos(), i); + } + + let end = 0n; + for (let i = 1n; i <= 12n; i++) { + const { header, pages } = await describe(db, i); + if (i > 1n) { + assert.equal(header.walOffset, end, `the file ${i} starts where the file ${i - 1n} ended in the WAL`); + assert.ok(pages <= 2, `the file ${i} holds the pages of one insert, not a snapshot (${pages})`); + } + end = header.walOffset + header.walSize; + } +}); + +test('an instance opened anew continues from the files of the one before it', async (t) => { + const tdb = createWALDB(['a', 'b', 'c']); + const first = await LocalDatabase.open(tdb.path); + t.after(() => tdb.close()); + + await first.sync(); + tdb.db.exec("INSERT INTO t (name) VALUES ('d')"); + await first.sync(); + const before = await describe(first, 2n); + first.close(); + + const second = await LocalDatabase.open(tdb.path); + t.after(() => second.close()); + assert.equal(await second.pos(), 2n); + + tdb.db.exec("INSERT INTO t (name) VALUES ('e')"); + assert.equal((await second.sync())?.minTXID, 3n); + const after = await describe(second, 3n); + assert.equal(after.header.walOffset, before.header.walOffset + before.header.walSize); + assert.ok(after.pages <= 2); +}); + +test('a directory or a link named as an LTX file is not the newest local file', async (t) => { + const tdb = createWALDB(['a']); + const db = await LocalDatabase.open(tdb.path); + t.after(() => db.close()); + t.after(() => tdb.close()); + + await db.sync(); + await mkdir(join(db.ltxLevelDir(0), '0000000000000063-0000000000000063.ltx')); + await symlink(db.ltxPath(0, 1n, 1n), join(db.ltxLevelDir(0), '0000000000000064-0000000000000064.ltx')); + db.invalidate(); + + assert.equal(await db.pos(), 1n); + tdb.db.exec("INSERT INTO t (name) VALUES ('b')"); + assert.equal((await db.sync())?.minTXID, 2n); +}); + +test('a snapshot between two syncs leaves the next one incremental', async (t) => { + const tdb = createWALDB(['a', 'b']); + const db = await LocalDatabase.open(tdb.path); + t.after(() => db.close()); + t.after(() => tdb.close()); + + await db.sync(); + tdb.db.exec("INSERT INTO t (name) VALUES ('c')"); + await db.sync(); + await db.snapshot(); + assert.equal(await db.pos(), 2n); + + tdb.db.exec("INSERT INTO t (name) VALUES ('d')"); + assert.equal((await db.sync())?.minTXID, 3n); + const { header, pages } = await describe(db, 3n); + const previous = await describe(db, 2n); + assert.equal(header.walOffset, previous.header.walOffset + previous.header.walSize); + assert.ok(pages <= 2); +}); + +test('a restore recorded on an instance replaces the position its syncs left', async (t) => { + const tdb = createWALDB(['a']); + const db = await LocalDatabase.open(tdb.path); + t.after(() => db.close()); + t.after(() => tdb.close()); + + await db.sync(); + tdb.db.exec("INSERT INTO t (name) VALUES ('b')"); + await db.sync(); + assert.equal(await db.pos(), 2n); + + await db.recordRestore(10n, null); + assert.equal(await db.pos(), 10n); + + // Nothing tells where the restored database stands in the WAL: the next file is a snapshot + tdb.db.exec("INSERT INTO t (name) VALUES ('c')"); + assert.equal((await db.sync())?.minTXID, 11n); + assert.equal((await describe(db, 11n)).pages, tdb.pageCount()); +}); + +test('when the WAL was reset behind its back, a sync reads it whole and writes a snapshot', async (t) => { + const tdb = createWALDB(['a', 'b', 'c']); + const db = await LocalDatabase.open(tdb.path); + t.after(() => db.close()); + t.after(() => tdb.close()); + + // Enough syncs for the next one to resume well inside the WAL + await db.sync(); + for (let i = 0; i < 20; i++) { + tdb.db.exec(`INSERT INTO t (name) VALUES ('row ${i}')`); + await db.sync(); + } + assert.equal(await db.pos(), 21n); + + // A checkpoint which is not the one of a sync: the WAL starts again, shorter than where the last sync ended + tdb.db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); + tdb.db.exec("INSERT INTO t (name) VALUES ('after the reset')"); + + assert.equal((await db.sync())?.minTXID, 22n); + assert.equal((await describe(db, 22n)).pages, tdb.pageCount()); + + // And the syncs after it are incremental again, in the new WAL + tdb.db.exec("INSERT INTO t (name) VALUES ('one more')"); + assert.equal((await db.sync())?.minTXID, 23n); + const last = await describe(db, 23n); + const snapshot = await describe(db, 22n); + assert.ok(last.pages <= 2); + assert.equal(last.header.walOffset, snapshot.header.walOffset + snapshot.header.walSize); +}); + +test('a sync with nothing to write keeps the position, and the next write follows it', async (t) => { + const tdb = createWALDB(['a']); + const db = await LocalDatabase.open(tdb.path); + t.after(() => db.close()); + t.after(() => tdb.close()); + + await db.sync(); + assert.equal(await db.sync(), null); + assert.equal(await db.sync(), null); + assert.equal(await db.pos(), 1n); + + tdb.db.exec("INSERT INTO t (name) VALUES ('b')"); + assert.equal((await db.sync())?.minTXID, 2n); + assert.ok((await describe(db, 2n)).pages <= 2); +}); From 789e973289ed1764700e7a0baa9059c67cf7be08 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:17:18 +0100 Subject: [PATCH 2/6] fix: never write a local LTX file over another one, and hold only the WAL frames a sync reads Two instances on the same database could write the same TXID: each keeps its position in memory, and a rename wrote over the file of the other. A file is now published with a hard link, which fails when the name is taken, and the sync reads the local files again. A sync which resumes allocated a buffer of the size of the WAL to read a few frames of it. It now holds its header and the frames it reads, which the reader takes by their offsets. --- packages/sqlite-js-stream/src/db.ts | 108 +++++++++++++----- packages/sqlite-js-stream/src/wal/reader.ts | 44 ++++++- .../test/db/db-sync-state.test.ts | 81 +++++++++++++ 3 files changed, 199 insertions(+), 34 deletions(-) diff --git a/packages/sqlite-js-stream/src/db.ts b/packages/sqlite-js-stream/src/db.ts index 48113a8..628ebc4 100644 --- a/packages/sqlite-js-stream/src/db.ts +++ b/packages/sqlite-js-stream/src/db.ts @@ -13,7 +13,7 @@ import { DatabaseSync } from 'node:sqlite'; import { randomBytes } from 'node:crypto'; import { rmSync, writeFileSync } from 'node:fs'; -import { open, readFile, readdir, rename, rm, stat, writeFile, type FileHandle } from 'node:fs/promises'; +import { access, link, open, readFile, readdir, rename, rm, stat, writeFile, type FileHandle } from 'node:fs/promises'; import { endianness } from 'node:os'; import nodePath from 'node:path'; @@ -35,7 +35,9 @@ import { WALHeaderSize, WALMagicBE, WALMagicLE, + PartialWAL, WALReader, + type WALBytes, WALEOFError, WALVersion, walChecksum, @@ -591,8 +593,25 @@ export class LocalDatabase { return r.page_count; } - /** Sync builds a level-0 LTX file and writes it to the local cache. */ + /** + * Sync builds a level-0 LTX file and writes it to the local cache. + * + * The file is never written over one which is there. Another instance on + * the same database, i.e. another `Replica` of the same path, may have + * published the next TXID since this one last read its position, which it + * keeps in memory: the sync then reads the local files again and writes the + * TXID which follows them. + */ async sync(): Promise { + const first = await this.syncOnce(); + if (first !== 'taken') return first; + const second = await this.syncOnce(); + if (second !== 'taken') return second; + throw new DatabaseError('sync: the local LTX files are written by another instance at the same time'); + } + + /** One attempt of a sync: `taken` when the TXID it was to write is there already. */ + private async syncOnce(): Promise { await this.assertComplete(); // The newest local file and the TXID of the last restore give the position // of the sync and where it resumes from: they are what the last sync of @@ -622,12 +641,12 @@ export class LocalDatabase { // A sync which resumes needs the header of the WAL, the frame before the // point it resumes from, to check that the WAL is still the same one, and - // the frames after it: only those are read, at their place in a buffer of - // the size of the WAL. Reading it whole would cost more with every write - // until the WAL is checkpointed. Whenever the sync cannot resume, the WAL - // is read whole, as before. + // the frames after it: only those are read, and only those are held in + // memory. Reading the WAL whole would cost more with every write until it + // is checkpointed. Whenever the sync cannot resume, the WAL is read + // whole, as before. const resumeFrom = prev === null ? 0 : prev.walOffset + prev.walSize; - let walBuf = + let walBuf: WALBytes = resumeFrom > WALHeaderSize ? await this.readWalFrom(resumeFrom - (WALFrameHeaderSize + pageSize)) : await this.readWalOrEmpty(); @@ -737,7 +756,12 @@ export class LocalDatabase { await sink.flush(); await fh.close(); - await rename(tmp, filename); + if (!(await publish(tmp, filename))) { + // The TXID is taken: what this instance knew of the local files is out of date. + await rm(tmp, { force: true }).catch(() => {}); + this.last = null; + return 'taken'; + } // The file is published: it is the newest one, and its header is where the next sync resumes. this.last = { @@ -770,7 +794,7 @@ export class LocalDatabase { commit: number, lockPg: number, pageMap: Map, - walBuf: Uint8Array, + walBuf: WALBytes, dbHandle: FileHandle, ): Promise { for (let pgno = 1; pgno <= commit; pgno++) { @@ -787,7 +811,7 @@ export class LocalDatabase { prevCommit: number, lockPg: number, pageMap: Map, - walBuf: Uint8Array, + walBuf: WALBytes, dbHandle: FileHandle, ): Promise { // Sorted page numbers present in the WAL change-set. @@ -945,7 +969,7 @@ export class LocalDatabase { pgno: number, pageSize: number, pageMap: Map, - walBuf: Uint8Array, + walBuf: WALBytes, dbHandle: FileHandle, ): Promise { const off = pageMap.get(pgno); @@ -960,12 +984,12 @@ export class LocalDatabase { /** Reads the WAL file bytes, returning empty if it does not exist. */ /** - * Reads the header of the WAL and its bytes from `start` on, into a buffer of - * the size of the WAL: the bytes in between are left as zeros, and must not - * be read. Returns the whole WAL when `start` is within its header, and an - * empty buffer when there is no WAL. + * Reads the header of the WAL and its bytes from `start` on: what a sync + * which resumes there needs, without the bytes in between, and without a + * buffer of the size of the WAL. Returns the whole WAL when `start` is + * within its header, and an empty one when there is no WAL. */ - private async readWalFrom(start: number): Promise { + private async readWalFrom(start: number): Promise { if (start <= WALHeaderSize) return this.readWalOrEmpty(); let fh: FileHandle; try { @@ -975,19 +999,18 @@ export class LocalDatabase { } try { const size = (await fh.stat()).size; - const buf = new Uint8Array(size); - if (size === 0) return buf; - await fh.read(buf, 0, Math.min(WALHeaderSize, size), 0); - // Shorter than the point to resume from: the WAL was reset, and the caller reads it whole. - if (start < size) { - let read = start; - while (read < size) { - const { bytesRead } = await fh.read(buf, read, size - read, read); - if (bytesRead === 0) break; - read += bytesRead; - } + const header = new Uint8Array(Math.min(WALHeaderSize, size)); + if (header.length > 0) await fh.read(header, 0, header.length, 0); + // A WAL shorter than the point to resume from was reset: its tail is empty, and the caller reads it whole. + const tail = new Uint8Array(Math.max(0, size - start)); + let read = 0; + while (read < tail.length) { + const { bytesRead } = await fh.read(tail, read, tail.length - read, start + read); + if (bytesRead === 0) break; + read += bytesRead; } - return buf; + // The WAL may have grown since its size was read, never shrunk without being reset: what was read is its length. + return new PartialWAL(start + read < size ? start + read : size, header, start, tail.subarray(0, read)); } catch { return new Uint8Array(0); } finally { @@ -1064,8 +1087,33 @@ export class LocalDatabase { } } +/** + * Moves a file which was just written to its name, unless a file is there + * already: returns whether it was moved. A hard link fails when the name is + * taken, where a rename would write over it; on a file system without hard + * links, the name is looked for first. + */ +async function publish(tmp: string, filename: string): Promise { + try { + await link(tmp, filename); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + if (code === 'EEXIST') return false; + if (code !== 'EPERM' && code !== 'ENOSYS' && code !== 'ENOTSUP' && code !== 'EOPNOTSUPP' && code !== 'EXDEV') throw err; + try { + await access(filename); + return false; + } catch { + await rename(tmp, filename); + return true; + } + } + await rm(tmp, { force: true }); + return true; +} + /** Creates a WALReader positioned at `offset`, or null if it cannot resume. */ -function makeResumeReader(walBuf: Uint8Array, offset: number, salt1: number, salt2: number): WALReader | null { +function makeResumeReader(walBuf: WALBytes, offset: number, salt1: number, salt2: number): WALReader | null { if (walBuf.length === 0) return null; if (offset <= WALHeaderSize) { // Starting fresh (or before any frames): read from the header. @@ -1092,7 +1140,7 @@ function makeResumeReader(walBuf: Uint8Array, offset: number, salt1: number, sal * null if the WAL is not the one that directly followed it (salt-1 is * incremented by one on every restart). */ -function makeNextReader(walBuf: Uint8Array, nextSalt1: number): WALReader | null { +function makeNextReader(walBuf: WALBytes, nextSalt1: number): WALReader | null { try { const r = new WALReader(walBuf); return r.salt1() === nextSalt1 ? r : null; diff --git a/packages/sqlite-js-stream/src/wal/reader.ts b/packages/sqlite-js-stream/src/wal/reader.ts index be26502..09f67f8 100644 --- a/packages/sqlite-js-stream/src/wal/reader.ts +++ b/packages/sqlite-js-stream/src/wal/reader.ts @@ -40,9 +40,45 @@ export interface WALPageMap { limited: boolean; } -/** WALReader reads and validates frames from an in-memory WAL byte buffer. */ +/** + * The bytes of a WAL, as a reader takes them: their number, and a range of + * them by its offsets in the WAL. A `Uint8Array` of the whole WAL is one. + */ +export interface WALBytes { + readonly length: number; + subarray(start: number, end: number): Uint8Array; +} + +/** + * A WAL of which only the header and the bytes from `tailStart` on are held: + * what a reader which resumes at an offset reads. Its length is the one of the + * WAL, and its bytes keep their offsets, so a reader is none the wiser; the + * bytes in between were not read, and asking for them throws. It holds the + * bytes it was given, not a buffer of the size of the WAL. + */ +export class PartialWAL implements WALBytes { + readonly length: number; + private readonly header: Uint8Array; + private readonly tailStart: number; + private readonly tail: Uint8Array; + + constructor(length: number, header: Uint8Array, tailStart: number, tail: Uint8Array) { + this.length = length; + this.header = header; + this.tailStart = tailStart; + this.tail = tail; + } + + subarray(start: number, end: number): Uint8Array { + if (end <= this.header.length) return this.header.subarray(start, end); + if (start >= this.tailStart) return this.tail.subarray(start - this.tailStart, end - this.tailStart); + throw new WALFormatError(`wal bytes ${start} to ${end} were not read: only its header and its bytes from ${this.tailStart}`); + } +} + +/** WALReader reads and validates frames from the bytes of a WAL held in memory. */ export class WALReader { - private data: Uint8Array; + private data: WALBytes; private bo!: ByteOrder; private pageSizeVal = 0; private seqVal = 0; @@ -52,13 +88,13 @@ export class WALReader { private chksum2 = 0; private frameN = 0; - constructor(data: Uint8Array) { + constructor(data: WALBytes) { this.data = data; this.readHeader(); } /** Creates a reader positioned at `offset`, loading salts from the caller. */ - static withOffset(data: Uint8Array, offset: number, salt1: number, salt2: number): WALReader { + static withOffset(data: WALBytes, offset: number, salt1: number, salt2: number): WALReader { if (offset <= WALHeaderSize) { throw new WALFormatError( `offset (${offset}) must be greater than the wal header size (${WALHeaderSize})`, diff --git a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts index d8aa171..f34b24e 100644 --- a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts +++ b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts @@ -5,6 +5,7 @@ import { join } from 'node:path'; import { Decoder } from '../../src/index.ts'; import { LocalDatabase } from '../../src/db.ts'; +import { PartialWAL, WALReader } from '../../src/wal/index.ts'; import { createWALDB } from '../helpers/make-db.ts'; /** The header of a local level-0 file, and the number of its pages. */ @@ -169,3 +170,83 @@ test('a sync with nothing to write keeps the position, and the next write follow assert.equal((await db.sync())?.minTXID, 2n); assert.ok((await describe(db, 2n)).pages <= 2); }); + +test('two instances on the same database never write the same TXID', async (t) => { + const tdb = createWALDB(['a']); + const a = await LocalDatabase.open(tdb.path); + const b = await LocalDatabase.open(tdb.path); + t.after(() => a.close()); + t.after(() => b.close()); + t.after(() => tdb.close()); + + assert.equal((await a.sync())?.minTXID, 1n); + tdb.db.exec("INSERT INTO t (name) VALUES ('b')"); + assert.equal((await b.sync())?.minTXID, 2n); + const second = await readFile(b.ltxPath(0, 2n, 2n)); + + // The first instance still has TXID 1 as the newest: it must not write over the file of the second + tdb.db.exec("INSERT INTO t (name) VALUES ('c')"); + assert.equal((await a.sync())?.minTXID, 3n); + assert.deepEqual(await readFile(a.ltxPath(0, 2n, 2n)), second); + assert.equal(await a.pos(), 3n); + + // And each file starts where the one before it ended in the WAL, whoever wrote it + const two = await describe(a, 2n); + const three = await describe(a, 3n); + assert.equal(three.header.walOffset, two.header.walOffset + two.header.walSize); + assert.ok(three.pages <= 2); + + tdb.db.exec("INSERT INTO t (name) VALUES ('d')"); + assert.equal((await b.sync())?.minTXID, 4n); +}); + +test('a sync which resumes holds the frames it reads, not a buffer of the size of the WAL', async (t) => { + const tdb = createWALDB(['a']); + const db = await LocalDatabase.open(tdb.path); + t.after(() => db.close()); + t.after(() => tdb.close()); + + // A WAL of some megabytes, which the first sync reads whole + const insert = tdb.db.prepare('INSERT INTO t (name) VALUES (?)'); + for (let i = 0; i < 400; i++) insert.run('x'.repeat(8000)); + await db.sync(); + + // Whatever array a resuming sync allocates stays far below the size of the WAL + const wal = (await readFile(tdb.walPath)).length; + assert.ok(wal > 3 * 1024 * 1024, `the WAL is ${wal} bytes`); + const allocated: number[] = []; + const Original = globalThis.Uint8Array; + // Counts the arrays made with a length: those are the buffers which are allocated + globalThis.Uint8Array = new Proxy(Original, { + construct(target, args, newTarget) { + if (typeof args[0] === 'number') allocated.push(args[0]); + return Reflect.construct(target, args, newTarget); + }, + }); + try { + tdb.db.exec("INSERT INTO t (name) VALUES ('one more')"); + assert.equal((await db.sync())?.minTXID, 2n); + } finally { + globalThis.Uint8Array = Original; + } + + const largest = Math.max(...allocated); + // Its other buffers, e.g. the one it writes the file through, are of a fixed size + assert.ok(largest < 1024 * 1024, `a resuming sync allocated ${largest} bytes at once, for a WAL of ${wal}`); + assert.ok((await describe(db, 2n)).pages <= 2); +}); + +test('a partial WAL gives its header and its tail by their offsets, and nothing in between', () => { + const header = Uint8Array.from({ length: 32 }, (_, i) => i); + const tail = Uint8Array.from({ length: 10 }, (_, i) => 100 + i); + const wal = new PartialWAL(1010, header, 1000, tail); + + assert.equal(wal.length, 1010); + assert.deepEqual([...wal.subarray(0, 4)], [0, 1, 2, 3]); + assert.deepEqual([...wal.subarray(1000, 1003)], [100, 101, 102]); + assert.deepEqual([...wal.subarray(1008, 1010)], [108, 109]); + assert.throws(() => wal.subarray(32, 64), /were not read/); + assert.throws(() => wal.subarray(990, 1004), /were not read/); + assert.throws(() => new WALReader(new PartialWAL(1010, new Uint8Array(32), 1000, tail))); +}); + From ee8a64ef1dbc59ec195b4ec68f35581e99602044 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:33:01 +0100 Subject: [PATCH 3/6] fix: share the position of the local files between instances, and write each sync to a file of its own Two instances on the same database each kept their position: once the retention removed a file, one of them could write its TXID again. The position is now the one of the local files, shared by the instances of a process. Two syncs which wrote the same TXID at once wrote the same temporary file, so the one published first could be changed by the other: each attempt has its own. Without hard links a file is renamed, as before: looking for the name first only looked safe. --- packages/sqlite-js-stream/src/db.ts | 71 ++++++++++++------- .../test/db/db-sync-state.test.ts | 55 +++++++++++++- 2 files changed, 101 insertions(+), 25 deletions(-) diff --git a/packages/sqlite-js-stream/src/db.ts b/packages/sqlite-js-stream/src/db.ts index 628ebc4..461df1b 100644 --- a/packages/sqlite-js-stream/src/db.ts +++ b/packages/sqlite-js-stream/src/db.ts @@ -11,9 +11,9 @@ */ import { DatabaseSync } from 'node:sqlite'; -import { randomBytes } from 'node:crypto'; +import { randomBytes, randomUUID } from 'node:crypto'; import { rmSync, writeFileSync } from 'node:fs'; -import { access, link, open, readFile, readdir, rename, rm, stat, writeFile, type FileHandle } from 'node:fs/promises'; +import { link, open, readFile, readdir, rename, rm, stat, writeFile, type FileHandle } from 'node:fs/promises'; import { endianness } from 'node:os'; import nodePath from 'node:path'; @@ -285,6 +285,16 @@ function headerPageSize(buf: Uint8Array): number { * LocalDatabase reads a database + WAL from disk, tracks the local replicated * position, and builds LTX files in the local cache. */ +/** What the last sync of a database published, see {@link LocalDatabase}. */ +interface SyncState { + max: { level: number; minTXID: bigint; maxTXID: bigint }; + base: bigint; + prev: { walOffset: number; walSize: number; salt1: number; salt2: number; commit: number }; +} + +/** The state of the local files of each database, by the path of its local cache. */ +const syncStates = new Map(); + export class LocalDatabase { readonly path: string; readonly metaPath: string; @@ -293,19 +303,30 @@ export class LocalDatabase { private openReader: OpenReader; private pageLoader: PageLoader | null = null; /** - * What the last sync of this instance published: the newest local file, the - * TXID of the last restore, and where that sync ended in the WAL, as its - * header says. The next sync starts from it without reading it back from - * the disk. It is the local position only: what the replica has is another - * matter, and a file whose upload failed is still there to upload. Null - * until a sync publishes a file, and after anything else changed the local - * files, see {@link invalidate}. + * What the last sync published: the newest local file, the TXID of the + * last restore, and where that sync ended in the WAL, as its header says. + * The next sync starts from it without reading it back from the disk. It is + * the local position only: what the replica has is another matter, and a + * file whose upload failed is still there to upload. Null until a sync + * publishes a file, and after anything else changed the local files, see + * {@link invalidate}. + * + * It is kept for the local files, not for this instance: the instances of a + * process on the same database share it, so that one which syncs after + * another starts from the file the other published, also once the retention + * removed the files in between. The local files of a database are written + * by one process: another process which wrote them is found out only when + * it left a file under the name this one is about to use, see + * {@link sync}. */ - private last: { - max: { level: number; minTXID: bigint; maxTXID: bigint }; - base: bigint; - prev: { walOffset: number; walSize: number; salt1: number; salt2: number; commit: number }; - } | null = null; + private get last(): SyncState | null { + return syncStates.get(this.metaPath) ?? null; + } + + private set last(state: SyncState | null) { + if (state === null) syncStates.delete(this.metaPath); + else syncStates.set(this.metaPath, state); + } private constructor(path: string, metaPath: string, pageSize: number, openReader: OpenReader) { this.path = path; @@ -721,7 +742,9 @@ export class LocalDatabase { const dir = this.ltxLevelDir(0); await mkdirAll(dir); const filename = this.ltxPath(0, txID, txID); - const tmp = `${filename}.tmp`; + // A name of its own: two syncs which write the same TXID at once must not write the same file, or the one + // which publishes first would see its bytes changed by the other. + const tmp = `${filename}.${randomUUID()}.tmp`; // A snapshot covers the WAL up to its last commit frame, so the next // sync resumes right after it (not after uncommitted frames). @@ -1090,8 +1113,13 @@ export class LocalDatabase { /** * Moves a file which was just written to its name, unless a file is there * already: returns whether it was moved. A hard link fails when the name is - * taken, where a rename would write over it; on a file system without hard - * links, the name is looked for first. + * taken, where a rename would write over it. + * + * On a file system without hard links the file is renamed, as it always was + * before the link: nothing there tells two writers of the same name apart at + * once, so the name is not looked for first, which would only look safe. The + * instances of a process do not meet there, since they share their position; + * two processes which write the local files of one database do. */ async function publish(tmp: string, filename: string): Promise { try { @@ -1100,13 +1128,8 @@ async function publish(tmp: string, filename: string): Promise { const code = (err as NodeJS.ErrnoException).code; if (code === 'EEXIST') return false; if (code !== 'EPERM' && code !== 'ENOSYS' && code !== 'ENOTSUP' && code !== 'EOPNOTSUPP' && code !== 'EXDEV') throw err; - try { - await access(filename); - return false; - } catch { - await rename(tmp, filename); - return true; - } + await rename(tmp, filename); + return true; } await rm(tmp, { force: true }); return true; diff --git a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts index f34b24e..0ef7629 100644 --- a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts +++ b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdir, readFile, symlink } from 'node:fs/promises'; +import { mkdir, readdir, readFile, rm, symlink } from 'node:fs/promises'; import { join } from 'node:path'; import { Decoder } from '../../src/index.ts'; @@ -200,6 +200,59 @@ test('two instances on the same database never write the same TXID', async (t) = assert.equal((await b.sync())?.minTXID, 4n); }); +test('two instances which sync at the same time write two files, each with its own bytes', async (t) => { + const tdb = createWALDB(['a']); + const a = await LocalDatabase.open(tdb.path); + const b = await LocalDatabase.open(tdb.path); + t.after(() => a.close()); + t.after(() => b.close()); + t.after(() => tdb.close()); + + await a.sync(); + + for (let round = 0; round < 10; round++) { + tdb.db.exec(`INSERT INTO t (name) VALUES ('round ${round}')`); + // Both see the same newest file, and the same write to sync + const results = await Promise.all([a.sync(), b.sync()]); + const written = results.filter((info) => info !== null); + assert.ok(written.length >= 1, 'the write was synced'); + assert.equal(new Set(written.map((info) => info!.minTXID)).size, written.length, 'no TXID was written twice'); + } + + // Every file is whole, follows the one before it in the WAL, and no temporary file is left + const names = await readdir(a.ltxLevelDir(0)); + assert.deepEqual(names.filter((name) => name.endsWith('.tmp')), []); + const pos = await a.pos(); + let end = 0n; + for (let i = 1n; i <= pos; i++) { + const { header } = await describe(a, i); + if (i > 1n) assert.equal(header.walOffset, end, `the file ${i} starts where the file ${i - 1n} ended`); + end = header.walOffset + header.walSize; + } +}); + +test('an instance does not write a TXID again once the retention removed its file', async (t) => { + const tdb = createWALDB(['a']); + const a = await LocalDatabase.open(tdb.path); + const b = await LocalDatabase.open(tdb.path); + t.after(() => a.close()); + t.after(() => b.close()); + t.after(() => tdb.close()); + + assert.equal((await a.sync())?.minTXID, 1n); + tdb.db.exec("INSERT INTO t (name) VALUES ('b')"); + assert.equal((await b.sync())?.minTXID, 2n); + tdb.db.exec("INSERT INTO t (name) VALUES ('c')"); + assert.equal((await b.sync())?.minTXID, 3n); + + // What the retention does to a local file of level 0 which was uploaded: its name is free again + await rm(b.ltxPath(0, 2n, 2n)); + + tdb.db.exec("INSERT INTO t (name) VALUES ('d')"); + assert.equal((await a.sync())?.minTXID, 4n); + assert.deepEqual((await a.l0Files()).map((file) => file.minTXID), [1n, 3n, 4n]); +}); + test('a sync which resumes holds the frames it reads, not a buffer of the size of the WAL', async (t) => { const tdb = createWALDB(['a']); const db = await LocalDatabase.open(tdb.path); From c4434721a1c47f70db3fab15ed34054ed214136d Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:47:15 +0100 Subject: [PATCH 4/6] fix: one position for a local cache whatever its path, checked against outside changes, and no rename over a file The position of the local files was shared by the path as it was given: two spellings of one path had two positions. It is kept by the canonical path of the local cache. A thread or a process which does not share it leaves a level-0 directory which changed: the local files are then read again. On a file system without hard links two syncs could both rename to the same TXID. A sync fails there, and says why: nothing else publishes a file without writing over another one. --- packages/sqlite-js-stream/src/db.ts | 72 ++++++++++++++----- .../test/db/db-sync-state.test.ts | 46 +++++++++++- 2 files changed, 98 insertions(+), 20 deletions(-) diff --git a/packages/sqlite-js-stream/src/db.ts b/packages/sqlite-js-stream/src/db.ts index 461df1b..b04d6df 100644 --- a/packages/sqlite-js-stream/src/db.ts +++ b/packages/sqlite-js-stream/src/db.ts @@ -13,7 +13,7 @@ import { DatabaseSync } from 'node:sqlite'; import { randomBytes, randomUUID } from 'node:crypto'; import { rmSync, writeFileSync } from 'node:fs'; -import { link, open, readFile, readdir, rename, rm, stat, writeFile, type FileHandle } from 'node:fs/promises'; +import { link, open, realpath, readFile, readdir, rename, rm, stat, writeFile, type FileHandle } from 'node:fs/promises'; import { endianness } from 'node:os'; import nodePath from 'node:path'; @@ -290,6 +290,17 @@ interface SyncState { max: { level: number; minTXID: bigint; maxTXID: bigint }; base: bigint; prev: { walOffset: number; walSize: number; salt1: number; salt2: number; commit: number }; + /** When the level-0 directory was last changed, as of the publication of `max`. */ + changed: bigint; +} + +/** When a directory was last changed, i.e. had an entry added or removed; 0 when it is not there. */ +async function levelZeroChange(dir: string): Promise { + try { + return (await stat(dir, { bigint: true })).mtimeNs; + } catch { + return 0n; + } } /** The state of the local files of each database, by the path of its local cache. */ @@ -320,17 +331,38 @@ export class LocalDatabase { * {@link sync}. */ private get last(): SyncState | null { - return syncStates.get(this.metaPath) ?? null; + return syncStates.get(this.stateKey) ?? null; } private set last(state: SyncState | null) { - if (state === null) syncStates.delete(this.metaPath); - else syncStates.set(this.metaPath, state); + if (state === null) syncStates.delete(this.stateKey); + else syncStates.set(this.stateKey, state); + } + + /** The canonical path of the local cache: what its state is kept under. */ + private readonly stateKey: string; + + /** + * The state the last sync left, if the level-0 directory was not changed + * since: a file published or removed there by anything which does not share + * this state, another thread or another process, changes its modification + * time, and the local files are then read again. This tells such a writer + * apart whenever the file system dates the two changes differently, which a + * coarse clock does not for two changes a moment apart: the local files of + * a database are for one thread of one process to write. + */ + private async currentState(): Promise { + const state = this.last; + if (state === null) return null; + if ((await levelZeroChange(this.ltxLevelDir(0))) === state.changed) return state; + this.last = null; + return null; } - private constructor(path: string, metaPath: string, pageSize: number, openReader: OpenReader) { + private constructor(path: string, metaPath: string, pageSize: number, openReader: OpenReader, stateKey: string) { this.path = path; this.metaPath = metaPath; + this.stateKey = stateKey; this.pageSize = pageSize; this.openReader = openReader; } @@ -356,7 +388,8 @@ export class LocalDatabase { /* database not present yet; use default page size */ } - return new LocalDatabase(path, metaPath, pageSize, openReader); + // Two paths to the same database, e.g. `data/app.db` and `./data/app.db`, are one local cache. + return new LocalDatabase(path, metaPath, pageSize, openReader, await realpath(metaPath)); } /** WalPath returns the path to the database's WAL file. */ @@ -527,7 +560,8 @@ export class LocalDatabase { * restore if it is higher (0 if none). */ async pos(): Promise { - if (this.last !== null) return this.last.max.maxTXID; + const state = await this.currentState(); + if (state !== null) return state.max.maxTXID; const m = await this.maxFile(); const base = await this.baseTXID(); return m === null || m.maxTXID < base ? base : m.maxTXID; @@ -641,7 +675,7 @@ export class LocalDatabase { max: { level: number; minTXID: bigint; maxTXID: bigint } | null; base: bigint; prev?: { walOffset: number; walSize: number; salt1: number; salt2: number; commit: number }; - } = this.last ?? { max: await this.maxFile(), base: await this.baseTXID() }; + } = (await this.currentState()) ?? { max: await this.maxFile(), base: await this.baseTXID() }; const pos = known.max === null || known.max.maxTXID < known.base ? known.base : known.max.maxTXID; const txID = pos + 1n; @@ -791,6 +825,7 @@ export class LocalDatabase { max: { level: 0, minTXID: txID, maxTXID: txID }, base: known.base, prev: { walOffset: offset, walSize: headerWalSize, salt1, salt2, commit: finalCommit }, + changed: await levelZeroChange(this.ltxLevelDir(0)), }; const size = (await stat(filename)).size; @@ -871,7 +906,7 @@ export class LocalDatabase { */ async checkpointToken(): Promise { const pos = await this.pos(); - const prev = await this.prevSyncInfo(); + const prev = await this.prevSyncInfo(await this.currentState()); // The frames the last sync covered, all in the WAL with prev's salts. const end = prev === null ? 0 : prev.walOffset + prev.walSize; const frames = (end - WALHeaderSize) / (this.pageSize + WALFrameHeaderSize); @@ -1055,7 +1090,7 @@ export class LocalDatabase { max: { level: number; minTXID: bigint; maxTXID: bigint } | null; base: bigint; prev?: { walOffset: number; walSize: number; salt1: number; salt2: number; commit: number }; - } | null = this.last, + } | null, ): Promise<{ walOffset: number; walSize: number; @@ -1115,11 +1150,9 @@ export class LocalDatabase { * already: returns whether it was moved. A hard link fails when the name is * taken, where a rename would write over it. * - * On a file system without hard links the file is renamed, as it always was - * before the link: nothing there tells two writers of the same name apart at - * once, so the name is not looked for first, which would only look safe. The - * instances of a process do not meet there, since they share their position; - * two processes which write the local files of one database do. + * A file system without hard links has no such operation: a rename there + * would let two syncs write the same TXID, each told that it did. The sync + * fails, and says why. */ async function publish(tmp: string, filename: string): Promise { try { @@ -1127,9 +1160,12 @@ async function publish(tmp: string, filename: string): Promise { } catch (err) { const code = (err as NodeJS.ErrnoException).code; if (code === 'EEXIST') return false; - if (code !== 'EPERM' && code !== 'ENOSYS' && code !== 'ENOTSUP' && code !== 'EOPNOTSUPP' && code !== 'EXDEV') throw err; - await rename(tmp, filename); - return true; + if (code === 'EPERM' || code === 'ENOSYS' || code === 'ENOTSUP' || code === 'EOPNOTSUPP' || code === 'EXDEV') { + throw new DatabaseError( + `sync: the file system of the local LTX files does not support hard links (${code}), which publish a file without writing over another one: ${nodePath.dirname(filename)}`, + ); + } + throw err; } await rm(tmp, { force: true }); return true; diff --git a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts index 0ef7629..28ccb07 100644 --- a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts +++ b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts @@ -1,7 +1,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdir, readdir, readFile, rm, symlink } from 'node:fs/promises'; -import { join } from 'node:path'; +import { copyFile, mkdir, readdir, readFile, rm, symlink } from 'node:fs/promises'; +import { basename, dirname, join } from 'node:path'; +import { setTimeout as sleep } from 'node:timers/promises'; import { Decoder } from '../../src/index.ts'; import { LocalDatabase } from '../../src/db.ts'; @@ -253,6 +254,47 @@ test('an instance does not write a TXID again once the retention removed its fil assert.deepEqual((await a.l0Files()).map((file) => file.minTXID), [1n, 3n, 4n]); }); +test('two paths to the same database are one local cache', async (t) => { + const tdb = createWALDB(['a']); + const a = await LocalDatabase.open(tdb.path); + // The same file, by another spelling of its path + const b = await LocalDatabase.open(join(dirname(tdb.path), '.', 'nowhere', '..', basename(tdb.path))); + t.after(() => a.close()); + t.after(() => b.close()); + t.after(() => tdb.close()); + + assert.equal((await a.sync())?.minTXID, 1n); + tdb.db.exec("INSERT INTO t (name) VALUES ('b')"); + assert.equal((await b.sync())?.minTXID, 2n); + tdb.db.exec("INSERT INTO t (name) VALUES ('c')"); + assert.equal((await b.sync())?.minTXID, 3n); + await rm(b.ltxPath(0, 2n, 2n)); + + tdb.db.exec("INSERT INTO t (name) VALUES ('d')"); + assert.equal((await a.sync())?.minTXID, 4n); +}); + +test('a file added to the local ones by something else is seen by the next sync', async (t) => { + const tdb = createWALDB(['a']); + const db = await LocalDatabase.open(tdb.path); + t.after(() => db.close()); + t.after(() => tdb.close()); + + await db.sync(); + tdb.db.exec("INSERT INTO t (name) VALUES ('b')"); + await db.sync(); + assert.equal(await db.pos(), 2n); + + // What another thread or process which syncs the same database leaves: a newer file, which this instance did not + // write and was not told of. A moment later, as a file system which dates its changes coarsely needs. + await sleep(50); + await copyFile(db.ltxPath(0, 2n, 2n), db.ltxPath(0, 7n, 7n)); + + assert.equal(await db.pos(), 7n); + tdb.db.exec("INSERT INTO t (name) VALUES ('c')"); + assert.equal((await db.sync())?.minTXID, 8n); +}); + test('a sync which resumes holds the frames it reads, not a buffer of the size of the WAL', async (t) => { const tdb = createWALDB(['a']); const db = await LocalDatabase.open(tdb.path); From d930a726c0baf8df780b17c49a26dbd42a937661 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:53:07 +0100 Subject: [PATCH 5/6] fix: run the syncs and the snapshots of a local cache one at a time A sync picks its TXID and publishes it some awaits later. Another instance could publish that TXID and the next one meanwhile, and the retention remove the first: the name was free again, and the sync published a second file under it, behind the newest one. The syncs and the snapshots of the instances of a process on the same database now wait for each other, from the choice of a TXID to its publication. --- packages/sqlite-js-stream/src/db.ts | 46 ++++++++++++++--- .../test/db/db-sync-state.test.ts | 51 +++++++++++++++++++ 2 files changed, 90 insertions(+), 7 deletions(-) diff --git a/packages/sqlite-js-stream/src/db.ts b/packages/sqlite-js-stream/src/db.ts index b04d6df..1802933 100644 --- a/packages/sqlite-js-stream/src/db.ts +++ b/packages/sqlite-js-stream/src/db.ts @@ -306,6 +306,29 @@ async function levelZeroChange(dir: string): Promise { /** The state of the local files of each database, by the path of its local cache. */ const syncStates = new Map(); +/** The last sync or snapshot of each local cache which runs or waits, see {@link exclusive}. */ +const syncQueues = new Map>(); + +/** + * Runs `fn` once the syncs and the snapshots of the same local cache which + * were asked for before it are done. A sync picks its TXID from the local + * files and publishes it some awaits later: another instance which synced in + * between, with the retention removing its file, would leave the name free + * for a TXID which is not the newest anymore. + */ +function exclusive(key: string, fn: () => Promise): Promise { + const run = (syncQueues.get(key) ?? Promise.resolve()).then(fn); + const done = run.then( + () => {}, + () => {}, + ); + syncQueues.set(key, done); + void done.then(() => { + if (syncQueues.get(key) === done) syncQueues.delete(key); + }); + return run; +} + export class LocalDatabase { readonly path: string; readonly metaPath: string; @@ -656,13 +679,18 @@ export class LocalDatabase { * published the next TXID since this one last read its position, which it * keeps in memory: the sync then reads the local files again and writes the * TXID which follows them. + * + * The syncs and the snapshots of the instances of a process on the same + * database run one at a time, from the choice of a TXID to its publication. */ - async sync(): Promise { - const first = await this.syncOnce(); - if (first !== 'taken') return first; - const second = await this.syncOnce(); - if (second !== 'taken') return second; - throw new DatabaseError('sync: the local LTX files are written by another instance at the same time'); + sync(): Promise { + return exclusive(this.stateKey, async () => { + const first = await this.syncOnce(); + if (first !== 'taken') return first; + const second = await this.syncOnce(); + if (second !== 'taken') return second; + throw new DatabaseError('sync: the local LTX files are written by another thread or process at the same time'); + }); } /** One attempt of a sync: `taken` when the TXID it was to write is there already. */ @@ -936,7 +964,11 @@ export class LocalDatabase { * MinTXID=1 and MaxTXID equal to the current local position. Returns null if * a snapshot would cover no data (empty database). */ - async snapshot(): Promise { + snapshot(): Promise { + return exclusive(this.stateKey, () => this.snapshotNow()); + } + + private async snapshotNow(): Promise { await this.assertComplete(); const pos = await this.pos(); // A snapshot adds a local file: the next sync reads the local files again. diff --git a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts index 28ccb07..0399e21 100644 --- a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts +++ b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts @@ -1,4 +1,5 @@ import { test } from 'node:test'; +import { DatabaseSync } from 'node:sqlite'; import assert from 'node:assert/strict'; import { copyFile, mkdir, readdir, readFile, rm, symlink } from 'node:fs/promises'; import { basename, dirname, join } from 'node:path'; @@ -254,6 +255,56 @@ test('an instance does not write a TXID again once the retention removed its fil assert.deepEqual((await a.l0Files()).map((file) => file.minTXID), [1n, 3n, 4n]); }); +test('the syncs of two instances on the same database run one at a time', async (t) => { + const tdb = createWALDB(['a']); + // Each sync holds a read transaction from after it picked its TXID to after it published it: none may overlap + let reading = 0; + let overlapped = false; + const openReader = (path: string) => { + const conn = new DatabaseSync(path, { readOnly: true }); + return { + exec(sql: string) { + if (sql === 'BEGIN') overlapped ||= ++reading > 1; + if (sql === 'COMMIT' || sql === 'ROLLBACK') reading--; + conn.exec(sql); + }, + prepare: (sql: string) => conn.prepare(sql), + close: () => conn.close(), + }; + }; + const a = await LocalDatabase.open(tdb.path, openReader); + const b = await LocalDatabase.open(tdb.path, openReader); + t.after(() => a.close()); + t.after(() => b.close()); + t.after(() => tdb.close()); + + await a.sync(); + + for (let round = 0; round < 10; round++) { + tdb.db.exec(`INSERT INTO t (name) VALUES ('round ${round}')`); + const first = a.sync(); + // While the first one is on its way: two syncs of the other instance, then what the retention does to a file + const others = (async () => { + const one = await b.sync(); + tdb.db.exec(`INSERT INTO t (name) VALUES ('more ${round}')`); + const two = await b.sync(); + if (one !== null) await rm(b.ltxPath(0, one.minTXID, one.maxTXID), { force: true }); + b.invalidate(); + return [one, two]; + })(); + + const written = [await first, ...(await others)].filter((info) => info !== null); + assert.equal(new Set(written.map((info) => info!.minTXID)).size, written.length, 'no TXID was written twice'); + + // The position is the newest file which is there, for both + const newest = (await a.l0Files()).at(-1)!.maxTXID; + assert.equal(await a.pos(), newest); + assert.equal(await b.pos(), newest); + } + + assert.equal(overlapped, false, 'two syncs ran at the same time'); +}); + test('two paths to the same database are one local cache', async (t) => { const tdb = createWALDB(['a']); const a = await LocalDatabase.open(tdb.path); From 646df0dd11c032dbfdbba6374e445a0fb98af788 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 22:54:12 +0100 Subject: [PATCH 6/6] fix: keep the sync state in the instance, one instance per replica, and fail on a WAL which cannot be read --- packages/sqlite-js-stream/README.md | 1 + packages/sqlite-js-stream/src/db.ts | 106 ++++++++---------- packages/sqlite-js-stream/src/replica.ts | 27 +++-- .../test/db/db-sync-state.test.ts | 85 ++++++-------- 4 files changed, 100 insertions(+), 119 deletions(-) diff --git a/packages/sqlite-js-stream/README.md b/packages/sqlite-js-stream/README.md index 846014f..d001a59 100644 --- a/packages/sqlite-js-stream/README.md +++ b/packages/sqlite-js-stream/README.md @@ -771,6 +771,7 @@ single-writer, single-file database. If host A has `row id=1 → "X"` and host B | Each host owns a **different** database | Give each its own prefix, e.g. `app/${tenantId}` — separate backup per DB, no conflict. | | Multiple app instances sharing one consistent dataset | Don't use SQLite + this replication. Use a client-server DB (Postgres/MySQL) or a real shared-file lock + single writer. | | Same data on every host (failover / DR) | Keep exactly one writer. On failover, **restore the standby from S3 first**, then let it take the lease — don't let a stale local file start writing. | +| Several `Replica` objects on the same database file | Don't. Create one `Replica` per database file, in one thread of one process: it owns the local files in `-litestream/` and keeps its position in them in memory. A second one writing there at the same time can write a transaction ID twice. | --- diff --git a/packages/sqlite-js-stream/src/db.ts b/packages/sqlite-js-stream/src/db.ts index 1802933..5c9cfe7 100644 --- a/packages/sqlite-js-stream/src/db.ts +++ b/packages/sqlite-js-stream/src/db.ts @@ -13,7 +13,7 @@ import { DatabaseSync } from 'node:sqlite'; import { randomBytes, randomUUID } from 'node:crypto'; import { rmSync, writeFileSync } from 'node:fs'; -import { link, open, realpath, readFile, readdir, rename, rm, stat, writeFile, type FileHandle } from 'node:fs/promises'; +import { link, open, readFile, readdir, rename, rm, stat, writeFile, type FileHandle } from 'node:fs/promises'; import { endianness } from 'node:os'; import nodePath from 'node:path'; @@ -45,7 +45,7 @@ import { } from './wal/index.ts'; import { SnapshotLevel } from './replica-client.ts'; import { mkdirAll } from './util/fs.ts'; -import { DatabaseError, ErrIncompleteDatabase } from './errors.ts'; +import { DatabaseError, ErrIncompleteDatabase, LTXFormatError } from './errors.ts'; /** * ReaderConnection is the minimal SQLite connection used to pin a WAL read @@ -303,31 +303,7 @@ async function levelZeroChange(dir: string): Promise { } } -/** The state of the local files of each database, by the path of its local cache. */ -const syncStates = new Map(); - -/** The last sync or snapshot of each local cache which runs or waits, see {@link exclusive}. */ -const syncQueues = new Map>(); - -/** - * Runs `fn` once the syncs and the snapshots of the same local cache which - * were asked for before it are done. A sync picks its TXID from the local - * files and publishes it some awaits later: another instance which synced in - * between, with the retention removing its file, would leave the name free - * for a TXID which is not the newest anymore. - */ -function exclusive(key: string, fn: () => Promise): Promise { - const run = (syncQueues.get(key) ?? Promise.resolve()).then(fn); - const done = run.then( - () => {}, - () => {}, - ); - syncQueues.set(key, done); - void done.then(() => { - if (syncQueues.get(key) === done) syncQueues.delete(key); - }); - return run; -} +const noop = (): void => {}; export class LocalDatabase { readonly path: string; @@ -345,34 +321,37 @@ export class LocalDatabase { * publishes a file, and after anything else changed the local files, see * {@link invalidate}. * - * It is kept for the local files, not for this instance: the instances of a - * process on the same database share it, so that one which syncs after - * another starts from the file the other published, also once the retention - * removed the files in between. The local files of a database are written - * by one process: another process which wrote them is found out only when - * it left a file under the name this one is about to use, see - * {@link sync}. + * It belongs to this instance: the local files of a database are for one + * instance to write. Another writer, be it a second instance, another + * thread or another process, is found out by the change it leaves on the + * level-0 directory, see {@link currentState}, or by the file it left under + * the name this one is about to use, see {@link sync}. */ - private get last(): SyncState | null { - return syncStates.get(this.stateKey) ?? null; - } + private last: SyncState | null = null; - private set last(state: SyncState | null) { - if (state === null) syncStates.delete(this.stateKey); - else syncStates.set(this.stateKey, state); - } + /** The last sync or snapshot of this instance which runs or waits, see {@link exclusive}. */ + private queue: Promise = Promise.resolve(); - /** The canonical path of the local cache: what its state is kept under. */ - private readonly stateKey: string; + /** + * Runs `fn` once the syncs and the snapshots asked to this instance before + * it are done: a sync picks its TXID from the local files and publishes it + * some awaits later, and a snapshot in between would read files which are + * about to change. + */ + private exclusive(fn: () => Promise): Promise { + const run = this.queue.then(fn); + this.queue = run.then(noop, noop); + return run; + } /** * The state the last sync left, if the level-0 directory was not changed - * since: a file published or removed there by anything which does not share - * this state, another thread or another process, changes its modification + * since: a file published or removed there by anything else, another + * instance, thread or process, changes its modification * time, and the local files are then read again. This tells such a writer * apart whenever the file system dates the two changes differently, which a * coarse clock does not for two changes a moment apart: the local files of - * a database are for one thread of one process to write. + * a database are for one instance to write. */ private async currentState(): Promise { const state = this.last; @@ -382,10 +361,9 @@ export class LocalDatabase { return null; } - private constructor(path: string, metaPath: string, pageSize: number, openReader: OpenReader, stateKey: string) { + private constructor(path: string, metaPath: string, pageSize: number, openReader: OpenReader) { this.path = path; this.metaPath = metaPath; - this.stateKey = stateKey; this.pageSize = pageSize; this.openReader = openReader; } @@ -411,8 +389,7 @@ export class LocalDatabase { /* database not present yet; use default page size */ } - // Two paths to the same database, e.g. `data/app.db` and `./data/app.db`, are one local cache. - return new LocalDatabase(path, metaPath, pageSize, openReader, await realpath(metaPath)); + return new LocalDatabase(path, metaPath, pageSize, openReader); } /** WalPath returns the path to the database's WAL file. */ @@ -621,8 +598,10 @@ export class LocalDatabase { let range: { minTXID: bigint; maxTXID: bigint }; try { range = parseFilename(entry.name); - } catch { - continue; + } catch (err) { + // Not the name of an LTX file, e.g. a temporary file of a sync: it is not a local file to count. + if (err instanceof LTXFormatError) continue; + throw err; } if (best === null || range.maxTXID > best.maxTXID) best = { level, ...range }; } @@ -680,11 +659,11 @@ export class LocalDatabase { * keeps in memory: the sync then reads the local files again and writes the * TXID which follows them. * - * The syncs and the snapshots of the instances of a process on the same - * database run one at a time, from the choice of a TXID to its publication. + * The syncs and the snapshots of an instance run one at a time, from the + * choice of a TXID to its publication. */ sync(): Promise { - return exclusive(this.stateKey, async () => { + return this.exclusive(async () => { const first = await this.syncOnce(); if (first !== 'taken') return first; const second = await this.syncOnce(); @@ -965,7 +944,7 @@ export class LocalDatabase { * a snapshot would cover no data (empty database). */ snapshot(): Promise { - return exclusive(this.stateKey, () => this.snapshotNow()); + return this.exclusive(() => this.snapshotNow()); } private async snapshotNow(): Promise { @@ -1084,8 +1063,10 @@ export class LocalDatabase { let fh: FileHandle; try { fh = await open(this.walPath(), 'r'); - } catch { - return new Uint8Array(0); + } catch (err) { + // No WAL: nothing was written since the last checkpoint, or the database is not in WAL mode yet. + if ((err as NodeJS.ErrnoException).code === 'ENOENT') return new Uint8Array(0); + throw err; } try { const size = (await fh.stat()).size; @@ -1101,8 +1082,6 @@ export class LocalDatabase { } // The WAL may have grown since its size was read, never shrunk without being reset: what was read is its length. return new PartialWAL(start + read < size ? start + read : size, header, start, tail.subarray(0, read)); - } catch { - return new Uint8Array(0); } finally { await fh.close(); } @@ -1111,8 +1090,11 @@ export class LocalDatabase { private async readWalOrEmpty(): Promise { try { return new Uint8Array(await readFile(this.walPath())); - } catch { - return new Uint8Array(0); + } catch (err) { + // No WAL: nothing was written since the last checkpoint, or the database is not in WAL mode yet. Any other + // failure must not look like one: the file would be built from the database without what is in the WAL. + if ((err as NodeJS.ErrnoException).code === 'ENOENT') return new Uint8Array(0); + throw err; } } diff --git a/packages/sqlite-js-stream/src/replica.ts b/packages/sqlite-js-stream/src/replica.ts index 90614c6..faee6e0 100644 --- a/packages/sqlite-js-stream/src/replica.ts +++ b/packages/sqlite-js-stream/src/replica.ts @@ -346,6 +346,7 @@ export class Replica { private logger: Logger; private posValue: bigint | null = null; private db: LocalDatabase | null = null; + private opening: Promise | null = null; private compactionLevelsValue: CompactionLevels = defaultCompactionLevels(); private leaserValue: Leaser | null = null; private leasePrimary = true; @@ -460,15 +461,23 @@ export class Replica { * missing page then fails, where it would return zeros otherwise. */ private async localDb(): Promise { - if (this.db === null) { - const vfs = this.paged !== null ? this.pagedVfs : null; - const openReader: OpenReader | undefined = - this.openReader ?? (vfs !== null ? (path) => new DatabaseSync(vfs.databaseUri(path), { readOnly: true }) : undefined); - this.db = await LocalDatabase.open(this.path, openReader); - const paged = this.paged; - if (paged !== null) this.db.setPageLoader((pgno) => paged.load(pgno)); - } - return this.db; + if (this.db !== null) return this.db; + // Calls which overlap while it opens get the same instance: the local files are for one instance to write. + this.opening ??= this.openLocal().finally(() => { + this.opening = null; + }); + return this.opening; + } + + private async openLocal(): Promise { + const vfs = this.paged !== null ? this.pagedVfs : null; + const openReader: OpenReader | undefined = + this.openReader ?? (vfs !== null ? (path) => new DatabaseSync(vfs.databaseUri(path), { readOnly: true }) : undefined); + const db = await LocalDatabase.open(this.path, openReader); + const paged = this.paged; + if (paged !== null) db.setPageLoader((pgno) => paged.load(pgno)); + this.db = db; + return db; } /** Pos returns the current replicated position (max level-0 maxTXID). */ diff --git a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts index 0399e21..59557d4 100644 --- a/packages/sqlite-js-stream/test/db/db-sync-state.test.ts +++ b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts @@ -1,8 +1,8 @@ import { test } from 'node:test'; import { DatabaseSync } from 'node:sqlite'; import assert from 'node:assert/strict'; -import { copyFile, mkdir, readdir, readFile, rm, symlink } from 'node:fs/promises'; -import { basename, dirname, join } from 'node:path'; +import { chmod, copyFile, mkdir, readdir, readFile, rm, symlink } from 'node:fs/promises'; +import { join } from 'node:path'; import { setTimeout as sleep } from 'node:timers/promises'; import { Decoder } from '../../src/index.ts'; @@ -157,6 +157,31 @@ test('when the WAL was reset behind its back, a sync reads it whole and writes a assert.equal(last.header.walOffset, snapshot.header.walOffset + snapshot.header.walSize); }); +const cannotDenyReads = process.platform === 'win32' || process.getuid?.() === 0; + +test('a WAL which cannot be read fails the sync and the snapshot, and no TXID is written', { skip: cannotDenyReads }, async (t) => { + const tdb = createWALDB(['a']); + const db = await LocalDatabase.open(tdb.path); + t.after(() => db.close()); + t.after(() => tdb.close()); + + // The reader of the instance has the WAL open already: only the reads of the instance itself fail + assert.equal((await db.sync())?.minTXID, 1n); + tdb.db.exec("INSERT INTO t (name) VALUES ('b')"); + + await chmod(db.walPath(), 0o000); + // A sync which resumes reads the end of the WAL, a snapshot reads it whole + await assert.rejects(db.sync(), { code: 'EACCES' }); + await assert.rejects(db.snapshot(), { code: 'EACCES' }); + assert.equal(await db.pos(), 1n); + assert.deepEqual(await readdir(db.ltxLevelDir(0)), ['0000000000000001-0000000000000001.ltx']); + await assert.rejects(readdir(db.ltxLevelDir(9)), { code: 'ENOENT' }); + + await chmod(db.walPath(), 0o644); + assert.equal((await db.sync())?.minTXID, 2n); + assert.ok((await describe(db, 2n)).pages <= 2); +}); + test('a sync with nothing to write keeps the position, and the next write follows it', async (t) => { const tdb = createWALDB(['a']); const db = await LocalDatabase.open(tdb.path); @@ -255,9 +280,9 @@ test('an instance does not write a TXID again once the retention removed its fil assert.deepEqual((await a.l0Files()).map((file) => file.minTXID), [1n, 3n, 4n]); }); -test('the syncs of two instances on the same database run one at a time', async (t) => { +test('the syncs and the snapshots of an instance run one at a time', async (t) => { const tdb = createWALDB(['a']); - // Each sync holds a read transaction from after it picked its TXID to after it published it: none may overlap + // Each of them holds a read transaction while it reads the database: none may overlap let reading = 0; let overlapped = false; const openReader = (path: string) => { @@ -272,57 +297,21 @@ test('the syncs of two instances on the same database run one at a time', async close: () => conn.close(), }; }; - const a = await LocalDatabase.open(tdb.path, openReader); - const b = await LocalDatabase.open(tdb.path, openReader); - t.after(() => a.close()); - t.after(() => b.close()); + const db = await LocalDatabase.open(tdb.path, openReader); + t.after(() => db.close()); t.after(() => tdb.close()); - await a.sync(); + await db.sync(); for (let round = 0; round < 10; round++) { tdb.db.exec(`INSERT INTO t (name) VALUES ('round ${round}')`); - const first = a.sync(); - // While the first one is on its way: two syncs of the other instance, then what the retention does to a file - const others = (async () => { - const one = await b.sync(); - tdb.db.exec(`INSERT INTO t (name) VALUES ('more ${round}')`); - const two = await b.sync(); - if (one !== null) await rm(b.ltxPath(0, one.minTXID, one.maxTXID), { force: true }); - b.invalidate(); - return [one, two]; - })(); - - const written = [await first, ...(await others)].filter((info) => info !== null); - assert.equal(new Set(written.map((info) => info!.minTXID)).size, written.length, 'no TXID was written twice'); - - // The position is the newest file which is there, for both - const newest = (await a.l0Files()).at(-1)!.maxTXID; - assert.equal(await a.pos(), newest); - assert.equal(await b.pos(), newest); + const results = await Promise.all([db.sync(), db.snapshot(), db.sync()]); + const written = [results[0], results[2]].filter((info) => info !== null); + assert.equal(written.length, 1, 'the write was synced once'); + assert.equal(written[0]!.minTXID, BigInt(round + 2)); } - assert.equal(overlapped, false, 'two syncs ran at the same time'); -}); - -test('two paths to the same database are one local cache', async (t) => { - const tdb = createWALDB(['a']); - const a = await LocalDatabase.open(tdb.path); - // The same file, by another spelling of its path - const b = await LocalDatabase.open(join(dirname(tdb.path), '.', 'nowhere', '..', basename(tdb.path))); - t.after(() => a.close()); - t.after(() => b.close()); - t.after(() => tdb.close()); - - assert.equal((await a.sync())?.minTXID, 1n); - tdb.db.exec("INSERT INTO t (name) VALUES ('b')"); - assert.equal((await b.sync())?.minTXID, 2n); - tdb.db.exec("INSERT INTO t (name) VALUES ('c')"); - assert.equal((await b.sync())?.minTXID, 3n); - await rm(b.ltxPath(0, 2n, 2n)); - - tdb.db.exec("INSERT INTO t (name) VALUES ('d')"); - assert.equal((await a.sync())?.minTXID, 4n); + assert.equal(overlapped, false, 'two of them ran at the same time'); }); test('a file added to the local ones by something else is seen by the next sync', async (t) => {