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..d001a59 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 @@ -759,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/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..5c9cfe7 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 { 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'; @@ -35,7 +35,9 @@ import { WALHeaderSize, WALMagicBE, WALMagicLE, + PartialWAL, WALReader, + type WALBytes, WALEOFError, WALVersion, walChecksum, @@ -43,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 @@ -283,6 +285,26 @@ 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 }; + /** 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; + } +} + +const noop = (): void => {}; + export class LocalDatabase { readonly path: string; readonly metaPath: string; @@ -290,6 +312,54 @@ export class LocalDatabase { private conn: ReaderConnection | null = null; private openReader: OpenReader; private pageLoader: PageLoader | null = null; + /** + * 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 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 last: SyncState | null = null; + + /** The last sync or snapshot of this instance which runs or waits, see {@link exclusive}. */ + private queue: Promise = Promise.resolve(); + + /** + * 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 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 instance 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) { this.path = path; @@ -388,6 +458,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 +560,50 @@ export class LocalDatabase { * restore if it is higher (0 if none). */ async pos(): Promise { + 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; } - /** 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 (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 }; } } return best; @@ -546,10 +650,40 @@ export class LocalDatabase { return r.page_count; } - /** Sync builds a level-0 LTX file and writes it to the local cache. */ - async sync(): Promise { + /** + * 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. + * + * 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 this.exclusive(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. */ + private async syncOnce(): 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 }; + } = (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; this.beginRead(); @@ -562,12 +696,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, 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: WALBytes = + 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 +725,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 @@ -632,7 +783,13 @@ 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). + const headerWalSize = snapshotting ? (maxOffset > 0 ? maxOffset - WALHeaderSize : 0) : walSize; const fh = await open(tmp, 'w'); const sink = new FileSink(fh); @@ -648,9 +805,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, @@ -665,7 +820,20 @@ 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 = { + 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; return { level: 0, minTXID: txID, maxTXID: txID, size, createdAt: Date.now() }; @@ -674,6 +842,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(); @@ -687,7 +859,7 @@ export class LocalDatabase { commit: number, lockPg: number, pageMap: Map, - walBuf: Uint8Array, + walBuf: WALBytes, dbHandle: FileHandle, ): Promise { for (let pgno = 1; pgno <= commit; pgno++) { @@ -704,7 +876,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. @@ -741,7 +913,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); @@ -771,9 +943,15 @@ 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 this.exclusive(() => 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. + this.invalidate(); const maxTXID = pos === 0n ? 1n : pos; this.beginRead(); @@ -860,7 +1038,7 @@ export class LocalDatabase { pgno: number, pageSize: number, pageMap: Map, - walBuf: Uint8Array, + walBuf: WALBytes, dbHandle: FileHandle, ): Promise { const off = pageMap.get(pgno); @@ -874,24 +1052,70 @@ 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: 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 { + if (start <= WALHeaderSize) return this.readWalOrEmpty(); + let fh: FileHandle; + try { + fh = await open(this.walPath(), 'r'); + } 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; + 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; + } + // 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)); + } finally { + await fh.close(); + } + } + 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; } } /** 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, + ): 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 +1151,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; @@ -934,8 +1159,34 @@ 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. + * + * 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 { + 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 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; +} + /** 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. @@ -962,7 +1213,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/replica.ts b/packages/sqlite-js-stream/src/replica.ts index 9e825de..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). */ @@ -516,7 +525,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 +1380,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 +1625,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/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 new file mode 100644 index 0000000..59557d4 --- /dev/null +++ b/packages/sqlite-js-stream/test/db/db-sync-state.test.ts @@ -0,0 +1,387 @@ +import { test } from 'node:test'; +import { DatabaseSync } from 'node:sqlite'; +import assert from 'node:assert/strict'; +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'; +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. */ +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); +}); + +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); + 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); +}); + +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('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('the syncs and the snapshots of an instance run one at a time', async (t) => { + const tdb = createWALDB(['a']); + // 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) => { + 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 db = await LocalDatabase.open(tdb.path, openReader); + t.after(() => db.close()); + t.after(() => tdb.close()); + + await db.sync(); + + for (let round = 0; round < 10; round++) { + tdb.db.exec(`INSERT INTO t (name) VALUES ('round ${round}')`); + 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 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) => { + 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); + 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))); +}); +