From 499b239158c10d996d1df44c2e53773dfc287e53 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:04:42 +0100 Subject: [PATCH 1/6] feat(pg): write several LTX files in one transaction --- packages/backend-pg/src/index.ts | 3 + packages/backend-pg/src/replica-client.ts | 205 +++++++++ .../backend-pg/test/write-ltx-files.test.ts | 392 ++++++++++++++++++ 3 files changed, 600 insertions(+) create mode 100644 packages/backend-pg/test/write-ltx-files.test.ts diff --git a/packages/backend-pg/src/index.ts b/packages/backend-pg/src/index.ts index c32028a..25ebeae 100644 --- a/packages/backend-pg/src/index.ts +++ b/packages/backend-pg/src/index.ts @@ -10,10 +10,13 @@ export { DefaultChunkSize, PgReplicaClient, + PgWriteLtxFilesError, newReplicaClientFromURL, ReplicaClientType, type PgDeletePrefixOptions, type PgReplicaClientOptions, + type PgWriteLtxFile, + type PgWriteLtxFileResult, } from './replica-client.ts'; export { PgLeaser, type PgLeaserOptions } from './leaser.ts'; diff --git a/packages/backend-pg/src/replica-client.ts b/packages/backend-pg/src/replica-client.ts index 8d3cd16..4afcc21 100644 --- a/packages/backend-pg/src/replica-client.ts +++ b/packages/backend-pg/src/replica-client.ts @@ -71,6 +71,57 @@ export interface PgReplicaClientOptions { max?: number; } +/** A file of {@link PgReplicaClient.writeLtxFiles}: where it goes, and its bytes. */ +export interface PgWriteLtxFile { + /** The client of the replica the file belongs to: its prefix and its generation are used. */ + client: PgReplicaClient; + level: number; + minTXID: bigint; + maxTXID: bigint; + /** The whole file. */ + body: Uint8Array; +} + +/** The outcome of one file of {@link PgReplicaClient.writeLtxFiles}. */ +export type PgWriteLtxFileResult = { info: FileInfo; error?: undefined } | { info?: undefined; error: Error }; + +/** + * Thrown by {@link PgReplicaClient.writeLtxFiles} when the whole call fails. + * `outcome` tells what is known of the transaction: `rolled-back` when none of + * the files was written, and `unknown` when that could not be told, i.e. the + * connection was lost while the transaction committed and could not be used + * to look. With `unknown`, the files may all be stored: check before writing + * them again. + */ +export class PgWriteLtxFilesError extends Error { + readonly outcome: 'rolled-back' | 'unknown'; + + constructor(outcome: 'rolled-back' | 'unknown', cause: unknown) { + const reason = cause instanceof Error ? cause.message : String(cause); + super( + outcome === 'rolled-back' + ? `write ltx files: none of the files was written: ${reason}` + : `write ltx files: whether the files were written is not known: ${reason}`, + { cause }, + ); + this.name = 'PgWriteLtxFilesError'; + this.outcome = outcome; + } +} + +/** A row of the files table which {@link PgReplicaClient.writeLtxFiles} writes. */ +interface BatchFileRow { + prefix: string; + level: number; + min_txid: string; + max_txid: string; + size: number; + created_at: Date; +} + +/** Rows of one `INSERT` of {@link PgReplicaClient.writeLtxFiles}: well below the parameters a statement can take. */ +const BatchInsertRows = 1000; + /** Configuration for {@link PgReplicaClient.deletePrefix}. */ export interface PgDeletePrefixOptions { /** @@ -519,6 +570,160 @@ export class PgReplicaClient implements ReplicaClient { } } + /** + * Writes several LTX files, of one replica or of several, in one + * transaction: one commit for all of them, where {@link writeLtxFile} pays + * one for each. It is meant for many small files which are ready at the same + * time, e.g. those of many databases replicated to the same tables. + * + * The clients of the files must share their connection, schema, table prefix + * and chunk size. The files of a replica are written in the order they are + * given. + * + * Fencing is checked for each replica, as {@link writeLtxFile} does: the + * generation rows of the replicas are locked (`FOR SHARE`) first, and the + * files of a replica whose registered generation is above the one of its + * client are left out, with {@link ErrGenerationSuperseded} as their result. + * A file too short to hold a header is left out too, **and so is every later + * file of its replica**: a replica never gets a file whose predecessor in + * the call was not written, which would leave a hole in its history. The + * files of the other replicas are written all the same. + * + * Returns one result for each file, in order: its `info`, or the `error` + * which left it out. + * + * Any other failure rejects the whole call with {@link PgWriteLtxFilesError}. + * When the transaction failed, e.g. for a file which exists already, its + * `outcome` is `rolled-back`: nothing was written, write the files one by + * one. A failure can also come after the commit, when the connection is lost + * before its answer: the call then looks for the files. If they are all + * stored, with their sizes and timestamps, it returns as if it had + * succeeded; if it cannot look, the `outcome` is `unknown`. + */ + static async writeLtxFiles(files: readonly PgWriteLtxFile[]): Promise { + if (files.length === 0) return []; + + const first = files[0].client; + for (const { client } of files) { + if ( + client.sql !== first.sql || + client.schema !== first.schema || + client.tablePrefix !== first.tablePrefix || + client.chunkSize !== first.chunkSize + ) { + throw new InvalidArgumentError( + 'pg replica client: the files of a batch must use the same connection, schema, table prefix and chunk size', + ); + } + } + await first.init(); + + const results: (PgWriteLtxFileResult | null)[] = files.map(() => null); + const timestamps: number[] = []; + // The replicas which had a file left out: their later files are left out too. + const broken = new Set(); + for (let i = 0; i < files.length; i++) { + const { client, body } = files[i]; + if (broken.has(client.prefix)) { + results[i] = { error: new InvalidArgumentError('write ltx file: an earlier file of the replica was not written') }; + timestamps.push(0); + } else if (body.length < HeaderSize) { + results[i] = { error: new InvalidArgumentError('write ltx file: input too short to contain a header') }; + broken.add(client.prefix); + timestamps.push(0); + } else { + timestamps.push(Number(unmarshalHeader(body.subarray(0, HeaderSize)).timestamp)); + } + } + + const sql = first.sql; + const chunkSize = first.chunkSize; + // What the transaction stored, once its statements are done: a failure after that is one of the commit. + let written: BatchFileRow[] | null = null; + + try { + await sql.begin(async (tx) => { + // The fenced replicas: their generation rows stay locked until the commit. + const fenced = [...new Set(files.filter((f) => f.client.generation !== null).map((f) => f.client.prefix))]; + const stored = new Map(); + if (fenced.length > 0) { + const rows = await tx` + SELECT prefix, generation FROM ${sql(first.generationsTable())} + WHERE prefix IN ${sql(fenced)} ORDER BY prefix FOR SHARE + `; + for (const row of rows) stored.set(row.prefix, BigInt(row.generation)); + } + + const chunks: { prefix: string; level: number; min_txid: string; max_txid: string; seq: number; data: Uint8Array }[] = []; + const metadata: BatchFileRow[] = []; + + for (let i = 0; i < files.length; i++) { + if (results[i] !== null) continue; + const { client, level, minTXID, maxTXID, body } = files[i]; + const registered = stored.get(client.prefix); + if (client.generation !== null && registered !== undefined && registered > client.generation) { + results[i] = { error: new ErrGenerationSuperseded(registered) }; + continue; + } + + const key = { prefix: client.prefix, level, min_txid: txid(minTXID), max_txid: txid(maxTXID) }; + for (let offset = 0, seq = 0; offset < body.length; offset += chunkSize, seq++) { + chunks.push({ ...key, seq, data: body.subarray(offset, Math.min(offset + chunkSize, body.length)) }); + } + metadata.push({ ...key, size: body.length, created_at: new Date(timestamps[i]) }); + results[i] = { info: { level, minTXID, maxTXID, size: body.length, createdAt: timestamps[i] } }; + } + + for (let i = 0; i < chunks.length; i += BatchInsertRows) { + await tx` + INSERT INTO ${sql(first.chunksTable())} + ${sql(chunks.slice(i, i + BatchInsertRows), 'prefix', 'level', 'min_txid', 'max_txid', 'seq', 'data')} + `; + } + for (let i = 0; i < metadata.length; i += BatchInsertRows) { + await tx` + INSERT INTO ${sql(first.filesTable())} + ${sql(metadata.slice(i, i + BatchInsertRows), 'prefix', 'level', 'min_txid', 'max_txid', 'size', 'created_at')} + `; + } + written = metadata; + }); + } catch (err) { + // A statement failed: the transaction was rolled back, and nothing is stored. + if (written === null) { + throw new PgWriteLtxFilesError('rolled-back', err); + } + + // The commit failed, or its answer was lost: whether the files are stored is read back. + let stored: number; + try { + stored = await first.countStored(written); + } catch { + throw new PgWriteLtxFilesError('unknown', err); + } + if (stored !== (written as BatchFileRow[]).length) { + throw new PgWriteLtxFilesError('rolled-back', err); + } + } + + return results as PgWriteLtxFileResult[]; + } + + /** How many of these files are stored, with the same size and timestamp. */ + private async countStored(files: readonly BatchFileRow[]): Promise { + let stored = 0; + for (const file of files) { + const rows = await this.sql` + SELECT 1 FROM ${this.sql(this.filesTable())} + WHERE prefix = ${file.prefix} AND level = ${file.level} + AND min_txid = ${file.min_txid} AND max_txid = ${file.max_txid} + AND size = ${file.size} AND created_at = ${file.created_at} + `; + stored += rows.length; + } + return stored; + } + /** * Deletes LTX files in one transaction. With a generation set, the * transaction first locks the generation row (`FOR SHARE`) and fails with diff --git a/packages/backend-pg/test/write-ltx-files.test.ts b/packages/backend-pg/test/write-ltx-files.test.ts new file mode 100644 index 0000000..a6d1c61 --- /dev/null +++ b/packages/backend-pg/test/write-ltx-files.test.ts @@ -0,0 +1,392 @@ +import { test, type TestContext } from "node:test"; +import assert from "node:assert/strict"; + +import { + ErrGenerationSuperseded, + marshalHeader, + type Header, +} from "@platformatic/sqlite-js-stream"; + +import type { Sql } from "postgres"; + +import { PgReplicaClient, PgWriteLtxFilesError } from "../src/index.ts"; +import { connectForTest } from "./helpers/db.ts"; + +const skip = process.env.PG_URL ? false : "PG_URL is not set"; +// Own tables, so this file never creates the tables of the other test files concurrently. +const tablePrefix = "batch_ltx"; + +let seq = 0; +function makePrefix(): string { + return `batch/${Date.now().toString(36)}/${seq++}`; +} + +function makeBody( + txID: bigint, + size: number, + timestamp = 1700000000000, +): Uint8Array { + const hdr: Header = { + version: 3, + flags: 0, + pageSize: 4096, + commit: 1, + minTXID: txID, + maxTXID: txID, + timestamp: BigInt(timestamp), + preApplyChecksum: 0n, + walOffset: 0n, + walSize: 0n, + walSalt1: 0, + walSalt2: 0, + nodeID: 0n, + }; + const header = marshalHeader(hdr); + const body = new Uint8Array(header.length + size); + body.set(header, 0); + for (let i = 0; i < size; i++) + {body[header.length + i] = (i + Number(txID)) % 251;} + return body; +} + +function setup(t: TestContext, opts: { chunkSize?: number } = {}) { + const sql = connectForTest(t); + const client = (prefix: string, generation: bigint | null = null) => + new PgReplicaClient({ sql, prefix, generation, tablePrefix, ...opts }); + return { sql, client }; +} + +async function read( + client: PgReplicaClient, + txID: bigint, +): Promise { + const chunks: Uint8Array[] = []; + for await (const chunk of await client.openLtxFile({ + level: 0, + minTXID: txID, + maxTXID: txID, + offset: 0, + size: 0, + })) { + chunks.push(chunk as Uint8Array); + } + return Buffer.concat(chunks); +} + +async function txIDs(client: PgReplicaClient): Promise { + const ids: bigint[] = []; + for await (const info of client.ltxFiles({ + level: 0, + seek: 0n, + useMetadata: false, + })) + {ids.push(info.maxTXID);} + return ids; +} + +test( + "writeLtxFiles writes the files of several replicas in one call", + { skip }, + async (t) => { + const { client } = setup(t, { chunkSize: 64 }); + const a = client(makePrefix()); + const b = client(makePrefix()); + const files = [ + { + client: a, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10, 1700000000001), + }, + { + client: b, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 300), + }, + // Two files of the same replica, in order + { + client: a, + level: 0, + minTXID: 2n, + maxTXID: 2n, + body: makeBody(2n, 200), + }, + ]; + + const results = await PgReplicaClient.writeLtxFiles(files); + + assert.deepEqual( + results.map((result) => result.info), + [ + { + level: 0, + minTXID: 1n, + maxTXID: 1n, + size: files[0].body.length, + createdAt: 1700000000001, + }, + { + level: 0, + minTXID: 1n, + maxTXID: 1n, + size: files[1].body.length, + createdAt: 1700000000000, + }, + { + level: 0, + minTXID: 2n, + maxTXID: 2n, + size: files[2].body.length, + createdAt: 1700000000000, + }, + ], + ); + assert.deepEqual(await txIDs(a), [1n, 2n]); + assert.deepEqual(await txIDs(b), [1n]); + + // The bodies, larger than a chunk, read back whole + assert.deepEqual(new Uint8Array(await read(a, 1n)), files[0].body); + assert.deepEqual(new Uint8Array(await read(b, 1n)), files[1].body); + assert.deepEqual(new Uint8Array(await read(a, 2n)), files[2].body); + }, +); + +test( + "writeLtxFiles leaves out the files of a superseded replica, and writes the others", + { skip }, + async (t) => { + const { client } = setup(t); + const prefix = makePrefix(); + const stale = client(prefix, 1n); + await stale.registerGeneration(1n); + await client(prefix, 2n).registerGeneration(2n); + const current = client(makePrefix(), 5n); + await current.registerGeneration(5n); + const unfenced = client(makePrefix()); + + const results = await PgReplicaClient.writeLtxFiles([ + { + client: stale, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + { + client: current, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + { + client: unfenced, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + ]); + + assert.ok(results[0].error instanceof ErrGenerationSuperseded); + assert.equal(results[1].error, undefined); + assert.equal(results[2].error, undefined); + assert.deepEqual(await txIDs(stale), []); + assert.deepEqual(await txIDs(current), [1n]); + assert.deepEqual(await txIDs(unfenced), [1n]); + }, +); + +test( + "writeLtxFiles leaves out a file too short for a header, and the later files of its replica", + { skip }, + async (t) => { + const { client } = setup(t); + const a = client(makePrefix()); + const b = client(makePrefix()); + + const results = await PgReplicaClient.writeLtxFiles([ + { + client: a, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: new Uint8Array(3), + }, + { client: b, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, + // Written, it would leave the replica with 2 and without 1: a sync would then start at 3 + { client: a, level: 0, minTXID: 2n, maxTXID: 2n, body: makeBody(2n, 10) }, + ]); + + assert.match(String(results[0].error), /too short/); + assert.equal(results[1].error, undefined); + assert.match(String(results[2].error), /earlier file/); + assert.deepEqual(await txIDs(a), []); + assert.deepEqual(await txIDs(b), [1n]); + }, +); + +test( + "writeLtxFiles writes nothing when a file exists already", + { skip }, + async (t) => { + const { client } = setup(t); + const a = client(makePrefix()); + const b = client(makePrefix()); + await PgReplicaClient.writeLtxFiles([ + { client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, + ]); + + await assert.rejects( + PgReplicaClient.writeLtxFiles([ + { + client: b, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + { + client: a, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + ]), + (err: unknown) => + err instanceof PgWriteLtxFilesError && err.outcome === "rolled-back", + ); + assert.deepEqual(await txIDs(b), []); + }, +); + +// A connection whose transactions commit, and whose answer to the commit is then lost. With `dead`, nothing can be +// asked on it afterwards either. +function losingTheCommit(sql: Sql, { dead = false } = {}): Sql { + let lost = false; + return new Proxy(sql, { + get(target, property, receiver) { + if (property === "begin") { + return async (...args: unknown[]) => { + await (target.begin as (...a: unknown[]) => Promise)( + ...args, + ); + lost = true; + throw new Error("the connection was lost"); + }; + } + return Reflect.get(target, property, receiver); + }, + apply(target, thisArg, args) { + if (dead && lost) throw new Error("the connection is closed"); + return Reflect.apply( + target as unknown as (...a: unknown[]) => unknown, + thisArg, + args, + ); + }, + }) as Sql; +} + +test( + "writeLtxFiles succeeds when the answer to its commit is lost and the files are stored", + { skip }, + async (t) => { + const { sql, client } = setup(t); + await client(makePrefix()).init(); + const lossy = losingTheCommit(sql); + const a = new PgReplicaClient({ + sql: lossy, + prefix: makePrefix(), + tablePrefix, + createTables: false, + }); + const b = new PgReplicaClient({ + sql: lossy, + prefix: makePrefix(), + tablePrefix, + createTables: false, + }); + + const results = await PgReplicaClient.writeLtxFiles([ + { client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, + { client: b, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 20) }, + ]); + + assert.deepEqual( + results.map((result) => result.info?.size), + [makeBody(1n, 10).length, makeBody(1n, 20).length], + ); + assert.deepEqual(await txIDs(client(a.prefix)), [1n]); + assert.deepEqual(await txIDs(client(b.prefix)), [1n]); + }, +); + +test( + "writeLtxFiles tells when it cannot know whether the files were written", + { skip }, + async (t) => { + const { sql, client } = setup(t); + await client(makePrefix()).init(); + const a = new PgReplicaClient({ + sql: losingTheCommit(sql, { dead: true }), + prefix: makePrefix(), + tablePrefix, + createTables: false, + }); + + await assert.rejects( + PgReplicaClient.writeLtxFiles([ + { + client: a, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + { + client: a, + level: 0, + minTXID: 2n, + maxTXID: 2n, + body: makeBody(2n, 10), + }, + ]), + (err: unknown) => + err instanceof PgWriteLtxFilesError && err.outcome === "unknown", + ); + // They were written: a caller which looks before it writes again finds them + assert.deepEqual(await txIDs(client(a.prefix)), [1n, 2n]); + }, +); + +test( + "writeLtxFiles needs clients of the same tables, and takes no files", + { skip }, + async (t) => { + const { sql, client } = setup(t); + const a = client(makePrefix()); + const other = new PgReplicaClient({ + sql, + prefix: makePrefix(), + tablePrefix: "batch_other_ltx", + }); + const file = (c: PgReplicaClient) => ({ + client: c, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }); + + await assert.rejects( + PgReplicaClient.writeLtxFiles([file(a), file(other)]), + /same connection/, + ); + assert.deepEqual(await PgReplicaClient.writeLtxFiles([]), []); + }, +); From 8af7418ff34cd58ffd90938a55a8cdaa79c329fc Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:11:52 +0100 Subject: [PATCH 2/6] test(pg): reflow the tests of writeLtxFiles --- .../backend-pg/test/write-ltx-files.test.ts | 470 ++++++++---------- 1 file changed, 212 insertions(+), 258 deletions(-) diff --git a/packages/backend-pg/test/write-ltx-files.test.ts b/packages/backend-pg/test/write-ltx-files.test.ts index a6d1c61..14f707a 100644 --- a/packages/backend-pg/test/write-ltx-files.test.ts +++ b/packages/backend-pg/test/write-ltx-files.test.ts @@ -1,31 +1,23 @@ -import { test, type TestContext } from "node:test"; -import assert from "node:assert/strict"; +import { test, type TestContext } from 'node:test'; +import assert from 'node:assert/strict'; -import { - ErrGenerationSuperseded, - marshalHeader, - type Header, -} from "@platformatic/sqlite-js-stream"; +import { ErrGenerationSuperseded, marshalHeader, type Header } from '@platformatic/sqlite-js-stream'; -import type { Sql } from "postgres"; +import type { Sql } from 'postgres'; -import { PgReplicaClient, PgWriteLtxFilesError } from "../src/index.ts"; -import { connectForTest } from "./helpers/db.ts"; +import { PgReplicaClient, PgWriteLtxFilesError } from '../src/index.ts'; +import { connectForTest } from './helpers/db.ts'; -const skip = process.env.PG_URL ? false : "PG_URL is not set"; +const skip = process.env.PG_URL ? false : 'PG_URL is not set'; // Own tables, so this file never creates the tables of the other test files concurrently. -const tablePrefix = "batch_ltx"; +const tablePrefix = 'batch_ltx'; let seq = 0; function makePrefix(): string { return `batch/${Date.now().toString(36)}/${seq++}`; } -function makeBody( - txID: bigint, - size: number, - timestamp = 1700000000000, -): Uint8Array { +function makeBody(txID: bigint, size: number, timestamp = 1700000000000): Uint8Array { const hdr: Header = { version: 3, flags: 0, @@ -44,8 +36,9 @@ function makeBody( const header = marshalHeader(hdr); const body = new Uint8Array(header.length + size); body.set(header, 0); - for (let i = 0; i < size; i++) - {body[header.length + i] = (i + Number(txID)) % 251;} + for (let i = 0; i < size; i++) { + body[header.length + i] = (i + Number(txID)) % 251; + } return body; } @@ -56,10 +49,7 @@ function setup(t: TestContext, opts: { chunkSize?: number } = {}) { return { sql, client }; } -async function read( - client: PgReplicaClient, - txID: bigint, -): Promise { +async function read(client: PgReplicaClient, txID: bigint): Promise { const chunks: Uint8Array[] = []; for await (const chunk of await client.openLtxFile({ level: 0, @@ -79,129 +69,122 @@ async function txIDs(client: PgReplicaClient): Promise { level: 0, seek: 0n, useMetadata: false, - })) - {ids.push(info.maxTXID);} + })) { + ids.push(info.maxTXID); + } return ids; } -test( - "writeLtxFiles writes the files of several replicas in one call", - { skip }, - async (t) => { - const { client } = setup(t, { chunkSize: 64 }); - const a = client(makePrefix()); - const b = client(makePrefix()); - const files = [ +test('writeLtxFiles writes the files of several replicas in one call', { skip }, async (t) => { + const { client } = setup(t, { chunkSize: 64 }); + const a = client(makePrefix()); + const b = client(makePrefix()); + const files = [ + { + client: a, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10, 1700000000001), + }, + { + client: b, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 300), + }, + // Two files of the same replica, in order + { + client: a, + level: 0, + minTXID: 2n, + maxTXID: 2n, + body: makeBody(2n, 200), + }, + ]; + + const results = await PgReplicaClient.writeLtxFiles(files); + + assert.deepEqual( + results.map((result) => result.info), + [ { - client: a, level: 0, minTXID: 1n, maxTXID: 1n, - body: makeBody(1n, 10, 1700000000001), + size: files[0].body.length, + createdAt: 1700000000001, }, { - client: b, level: 0, minTXID: 1n, maxTXID: 1n, - body: makeBody(1n, 300), + size: files[1].body.length, + createdAt: 1700000000000, }, - // Two files of the same replica, in order { - client: a, level: 0, minTXID: 2n, maxTXID: 2n, - body: makeBody(2n, 200), + size: files[2].body.length, + createdAt: 1700000000000, }, - ]; - - const results = await PgReplicaClient.writeLtxFiles(files); - - assert.deepEqual( - results.map((result) => result.info), - [ - { - level: 0, - minTXID: 1n, - maxTXID: 1n, - size: files[0].body.length, - createdAt: 1700000000001, - }, - { - level: 0, - minTXID: 1n, - maxTXID: 1n, - size: files[1].body.length, - createdAt: 1700000000000, - }, - { - level: 0, - minTXID: 2n, - maxTXID: 2n, - size: files[2].body.length, - createdAt: 1700000000000, - }, - ], - ); - assert.deepEqual(await txIDs(a), [1n, 2n]); - assert.deepEqual(await txIDs(b), [1n]); + ], + ); + assert.deepEqual(await txIDs(a), [1n, 2n]); + assert.deepEqual(await txIDs(b), [1n]); - // The bodies, larger than a chunk, read back whole - assert.deepEqual(new Uint8Array(await read(a, 1n)), files[0].body); - assert.deepEqual(new Uint8Array(await read(b, 1n)), files[1].body); - assert.deepEqual(new Uint8Array(await read(a, 2n)), files[2].body); - }, -); + // The bodies, larger than a chunk, read back whole + assert.deepEqual(new Uint8Array(await read(a, 1n)), files[0].body); + assert.deepEqual(new Uint8Array(await read(b, 1n)), files[1].body); + assert.deepEqual(new Uint8Array(await read(a, 2n)), files[2].body); +}); -test( - "writeLtxFiles leaves out the files of a superseded replica, and writes the others", - { skip }, - async (t) => { - const { client } = setup(t); - const prefix = makePrefix(); - const stale = client(prefix, 1n); - await stale.registerGeneration(1n); - await client(prefix, 2n).registerGeneration(2n); - const current = client(makePrefix(), 5n); - await current.registerGeneration(5n); - const unfenced = client(makePrefix()); +test('writeLtxFiles leaves out the files of a superseded replica, and writes the others', { skip }, async (t) => { + const { client } = setup(t); + const prefix = makePrefix(); + const stale = client(prefix, 1n); + await stale.registerGeneration(1n); + await client(prefix, 2n).registerGeneration(2n); + const current = client(makePrefix(), 5n); + await current.registerGeneration(5n); + const unfenced = client(makePrefix()); - const results = await PgReplicaClient.writeLtxFiles([ - { - client: stale, - level: 0, - minTXID: 1n, - maxTXID: 1n, - body: makeBody(1n, 10), - }, - { - client: current, - level: 0, - minTXID: 1n, - maxTXID: 1n, - body: makeBody(1n, 10), - }, - { - client: unfenced, - level: 0, - minTXID: 1n, - maxTXID: 1n, - body: makeBody(1n, 10), - }, - ]); + const results = await PgReplicaClient.writeLtxFiles([ + { + client: stale, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + { + client: current, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + { + client: unfenced, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + ]); - assert.ok(results[0].error instanceof ErrGenerationSuperseded); - assert.equal(results[1].error, undefined); - assert.equal(results[2].error, undefined); - assert.deepEqual(await txIDs(stale), []); - assert.deepEqual(await txIDs(current), [1n]); - assert.deepEqual(await txIDs(unfenced), [1n]); - }, -); + assert.ok(results[0].error instanceof ErrGenerationSuperseded); + assert.equal(results[1].error, undefined); + assert.equal(results[2].error, undefined); + assert.deepEqual(await txIDs(stale), []); + assert.deepEqual(await txIDs(current), [1n]); + assert.deepEqual(await txIDs(unfenced), [1n]); +}); test( - "writeLtxFiles leaves out a file too short for a header, and the later files of its replica", + 'writeLtxFiles leaves out a file too short for a header, and the later files of its replica', { skip }, async (t) => { const { client } = setup(t); @@ -229,40 +212,33 @@ test( }, ); -test( - "writeLtxFiles writes nothing when a file exists already", - { skip }, - async (t) => { - const { client } = setup(t); - const a = client(makePrefix()); - const b = client(makePrefix()); - await PgReplicaClient.writeLtxFiles([ - { client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, - ]); +test('writeLtxFiles writes nothing when a file exists already', { skip }, async (t) => { + const { client } = setup(t); + const a = client(makePrefix()); + const b = client(makePrefix()); + await PgReplicaClient.writeLtxFiles([{ client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }]); - await assert.rejects( - PgReplicaClient.writeLtxFiles([ - { - client: b, - level: 0, - minTXID: 1n, - maxTXID: 1n, - body: makeBody(1n, 10), - }, - { - client: a, - level: 0, - minTXID: 1n, - maxTXID: 1n, - body: makeBody(1n, 10), - }, - ]), - (err: unknown) => - err instanceof PgWriteLtxFilesError && err.outcome === "rolled-back", - ); - assert.deepEqual(await txIDs(b), []); - }, -); + await assert.rejects( + PgReplicaClient.writeLtxFiles([ + { + client: b, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + { + client: a, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + ]), + (err: unknown) => err instanceof PgWriteLtxFilesError && err.outcome === 'rolled-back', + ); + assert.deepEqual(await txIDs(b), []); +}); // A connection whose transactions commit, and whose answer to the commit is then lost. With `dead`, nothing can be // asked on it afterwards either. @@ -270,123 +246,101 @@ function losingTheCommit(sql: Sql, { dead = false } = {}): Sql { let lost = false; return new Proxy(sql, { get(target, property, receiver) { - if (property === "begin") { + if (property === 'begin') { return async (...args: unknown[]) => { - await (target.begin as (...a: unknown[]) => Promise)( - ...args, - ); + await (target.begin as (...a: unknown[]) => Promise)(...args); lost = true; - throw new Error("the connection was lost"); + throw new Error('the connection was lost'); }; } return Reflect.get(target, property, receiver); }, apply(target, thisArg, args) { - if (dead && lost) throw new Error("the connection is closed"); - return Reflect.apply( - target as unknown as (...a: unknown[]) => unknown, - thisArg, - args, - ); + if (dead && lost) throw new Error('the connection is closed'); + return Reflect.apply(target as unknown as (...a: unknown[]) => unknown, thisArg, args); }, }) as Sql; } -test( - "writeLtxFiles succeeds when the answer to its commit is lost and the files are stored", - { skip }, - async (t) => { - const { sql, client } = setup(t); - await client(makePrefix()).init(); - const lossy = losingTheCommit(sql); - const a = new PgReplicaClient({ - sql: lossy, - prefix: makePrefix(), - tablePrefix, - createTables: false, - }); - const b = new PgReplicaClient({ - sql: lossy, - prefix: makePrefix(), - tablePrefix, - createTables: false, - }); +test('writeLtxFiles succeeds when the answer to its commit is lost and the files are stored', { skip }, async (t) => { + const { sql, client } = setup(t); + await client(makePrefix()).init(); + const lossy = losingTheCommit(sql); + const a = new PgReplicaClient({ + sql: lossy, + prefix: makePrefix(), + tablePrefix, + createTables: false, + }); + const b = new PgReplicaClient({ + sql: lossy, + prefix: makePrefix(), + tablePrefix, + createTables: false, + }); - const results = await PgReplicaClient.writeLtxFiles([ - { client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, - { client: b, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 20) }, - ]); + const results = await PgReplicaClient.writeLtxFiles([ + { client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, + { client: b, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 20) }, + ]); - assert.deepEqual( - results.map((result) => result.info?.size), - [makeBody(1n, 10).length, makeBody(1n, 20).length], - ); - assert.deepEqual(await txIDs(client(a.prefix)), [1n]); - assert.deepEqual(await txIDs(client(b.prefix)), [1n]); - }, -); + assert.deepEqual( + results.map((result) => result.info?.size), + [makeBody(1n, 10).length, makeBody(1n, 20).length], + ); + assert.deepEqual(await txIDs(client(a.prefix)), [1n]); + assert.deepEqual(await txIDs(client(b.prefix)), [1n]); +}); -test( - "writeLtxFiles tells when it cannot know whether the files were written", - { skip }, - async (t) => { - const { sql, client } = setup(t); - await client(makePrefix()).init(); - const a = new PgReplicaClient({ - sql: losingTheCommit(sql, { dead: true }), - prefix: makePrefix(), - tablePrefix, - createTables: false, - }); +test('writeLtxFiles tells when it cannot know whether the files were written', { skip }, async (t) => { + const { sql, client } = setup(t); + await client(makePrefix()).init(); + const a = new PgReplicaClient({ + sql: losingTheCommit(sql, { dead: true }), + prefix: makePrefix(), + tablePrefix, + createTables: false, + }); - await assert.rejects( - PgReplicaClient.writeLtxFiles([ - { - client: a, - level: 0, - minTXID: 1n, - maxTXID: 1n, - body: makeBody(1n, 10), - }, - { - client: a, - level: 0, - minTXID: 2n, - maxTXID: 2n, - body: makeBody(2n, 10), - }, - ]), - (err: unknown) => - err instanceof PgWriteLtxFilesError && err.outcome === "unknown", - ); - // They were written: a caller which looks before it writes again finds them - assert.deepEqual(await txIDs(client(a.prefix)), [1n, 2n]); - }, -); + await assert.rejects( + PgReplicaClient.writeLtxFiles([ + { + client: a, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }, + { + client: a, + level: 0, + minTXID: 2n, + maxTXID: 2n, + body: makeBody(2n, 10), + }, + ]), + (err: unknown) => err instanceof PgWriteLtxFilesError && err.outcome === 'unknown', + ); + // They were written: a caller which looks before it writes again finds them + assert.deepEqual(await txIDs(client(a.prefix)), [1n, 2n]); +}); -test( - "writeLtxFiles needs clients of the same tables, and takes no files", - { skip }, - async (t) => { - const { sql, client } = setup(t); - const a = client(makePrefix()); - const other = new PgReplicaClient({ - sql, - prefix: makePrefix(), - tablePrefix: "batch_other_ltx", - }); - const file = (c: PgReplicaClient) => ({ - client: c, - level: 0, - minTXID: 1n, - maxTXID: 1n, - body: makeBody(1n, 10), - }); +test('writeLtxFiles needs clients of the same tables, and takes no files', { skip }, async (t) => { + const { sql, client } = setup(t); + const a = client(makePrefix()); + const other = new PgReplicaClient({ + sql, + prefix: makePrefix(), + tablePrefix: 'batch_other_ltx', + }); + const file = (c: PgReplicaClient) => ({ + client: c, + level: 0, + minTXID: 1n, + maxTXID: 1n, + body: makeBody(1n, 10), + }); - await assert.rejects( - PgReplicaClient.writeLtxFiles([file(a), file(other)]), - /same connection/, - ); - assert.deepEqual(await PgReplicaClient.writeLtxFiles([]), []); - }, -); + await assert.rejects(PgReplicaClient.writeLtxFiles([file(a), file(other)]), /same connection/); + assert.deepEqual(await PgReplicaClient.writeLtxFiles([]), []); +}); From c102e3668bfad46e3255e78e284572f70d7bcd08 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:17:21 +0100 Subject: [PATCH 3/6] fix(pg): an ambiguous commit is unknown, and a fenced-out file takes the later files of its replica A commit whose answer is lost can still become visible after a look for its files, and a file of the same size does not prove it is the one which was written: the outcome is unknown whenever the failure comes with the commit, and the files are not looked for. A file of a superseded client left the later files of the same replica in the batch, from a current client, to be written after it: they are left out too. --- packages/backend-pg/src/replica-client.ts | 75 +++++------- .../backend-pg/test/write-ltx-files.test.ts | 112 +++++++----------- 2 files changed, 73 insertions(+), 114 deletions(-) diff --git a/packages/backend-pg/src/replica-client.ts b/packages/backend-pg/src/replica-client.ts index 4afcc21..9924ce4 100644 --- a/packages/backend-pg/src/replica-client.ts +++ b/packages/backend-pg/src/replica-client.ts @@ -87,11 +87,12 @@ export type PgWriteLtxFileResult = { info: FileInfo; error?: undefined } | { inf /** * Thrown by {@link PgReplicaClient.writeLtxFiles} when the whole call fails. - * `outcome` tells what is known of the transaction: `rolled-back` when none of - * the files was written, and `unknown` when that could not be told, i.e. the - * connection was lost while the transaction committed and could not be used - * to look. With `unknown`, the files may all be stored: check before writing - * them again. + * `outcome` tells what is known of the transaction: `rolled-back` when a + * statement failed, so none of the files was written, and `unknown` when the + * failure came with the commit, e.g. the connection was lost before its + * answer. With `unknown`, the files may all be stored, or be stored a moment + * later: a caller which writes them again must take a file which is there + * already as written. */ export class PgWriteLtxFilesError extends Error { readonly outcome: 'rolled-back' | 'unknown'; @@ -584,21 +585,22 @@ export class PgReplicaClient implements ReplicaClient { * generation rows of the replicas are locked (`FOR SHARE`) first, and the * files of a replica whose registered generation is above the one of its * client are left out, with {@link ErrGenerationSuperseded} as their result. - * A file too short to hold a header is left out too, **and so is every later - * file of its replica**: a replica never gets a file whose predecessor in - * the call was not written, which would leave a hole in its history. The - * files of the other replicas are written all the same. + * A file too short to hold a header is left out too. **A file which is left + * out takes every later file of its replica with it**, whichever client + * they come from: a replica never gets a file whose predecessor in the call + * was not written, which would leave a hole in its history. The files of + * the other replicas are written all the same. * * Returns one result for each file, in order: its `info`, or the `error` * which left it out. * * Any other failure rejects the whole call with {@link PgWriteLtxFilesError}. - * When the transaction failed, e.g. for a file which exists already, its + * When a statement failed, e.g. for a file which exists already, its * `outcome` is `rolled-back`: nothing was written, write the files one by - * one. A failure can also come after the commit, when the connection is lost - * before its answer: the call then looks for the files. If they are all - * stored, with their sizes and timestamps, it returns as if it had - * succeeded; if it cannot look, the `outcome` is `unknown`. + * one. When the failure came with the commit, the `outcome` is `unknown`: + * the call does not look for the files, since a commit whose answer was lost + * can still become visible after such a look, and a file found with the + * same size would not prove that it is this one. */ static async writeLtxFiles(files: readonly PgWriteLtxFile[]): Promise { if (files.length === 0) return []; @@ -638,8 +640,8 @@ export class PgReplicaClient implements ReplicaClient { const sql = first.sql; const chunkSize = first.chunkSize; - // What the transaction stored, once its statements are done: a failure after that is one of the commit. - let written: BatchFileRow[] | null = null; + // Whether every statement of the transaction was done: a failure after that is one of the commit. + let statementsDone = false; try { await sql.begin(async (tx) => { @@ -660,9 +662,15 @@ export class PgReplicaClient implements ReplicaClient { for (let i = 0; i < files.length; i++) { if (results[i] !== null) continue; const { client, level, minTXID, maxTXID, body } = files[i]; + // An earlier file of the replica was left out, by this loop: this one would leave a hole after it. + if (broken.has(client.prefix)) { + results[i] = { error: new InvalidArgumentError('write ltx file: an earlier file of the replica was not written') }; + continue; + } const registered = stored.get(client.prefix); if (client.generation !== null && registered !== undefined && registered > client.generation) { results[i] = { error: new ErrGenerationSuperseded(registered) }; + broken.add(client.prefix); continue; } @@ -686,44 +694,17 @@ export class PgReplicaClient implements ReplicaClient { ${sql(metadata.slice(i, i + BatchInsertRows), 'prefix', 'level', 'min_txid', 'max_txid', 'size', 'created_at')} `; } - written = metadata; + statementsDone = true; }); } catch (err) { - // A statement failed: the transaction was rolled back, and nothing is stored. - if (written === null) { - throw new PgWriteLtxFilesError('rolled-back', err); - } - - // The commit failed, or its answer was lost: whether the files are stored is read back. - let stored: number; - try { - stored = await first.countStored(written); - } catch { - throw new PgWriteLtxFilesError('unknown', err); - } - if (stored !== (written as BatchFileRow[]).length) { - throw new PgWriteLtxFilesError('rolled-back', err); - } + // A statement failed: the transaction was rolled back, and nothing is stored. Otherwise the statements were + // all done and the commit failed, or its answer was lost: whether the files are stored cannot be told from here. + throw new PgWriteLtxFilesError(statementsDone ? 'unknown' : 'rolled-back', err); } return results as PgWriteLtxFileResult[]; } - /** How many of these files are stored, with the same size and timestamp. */ - private async countStored(files: readonly BatchFileRow[]): Promise { - let stored = 0; - for (const file of files) { - const rows = await this.sql` - SELECT 1 FROM ${this.sql(this.filesTable())} - WHERE prefix = ${file.prefix} AND level = ${file.level} - AND min_txid = ${file.min_txid} AND max_txid = ${file.max_txid} - AND size = ${file.size} AND created_at = ${file.created_at} - `; - stored += rows.length; - } - return stored; - } - /** * Deletes LTX files in one transaction. With a generation set, the * transaction first locks the generation row (`FOR SHARE`) and fails with diff --git a/packages/backend-pg/test/write-ltx-files.test.ts b/packages/backend-pg/test/write-ltx-files.test.ts index 14f707a..f1b099a 100644 --- a/packages/backend-pg/test/write-ltx-files.test.ts +++ b/packages/backend-pg/test/write-ltx-files.test.ts @@ -240,90 +240,68 @@ test('writeLtxFiles writes nothing when a file exists already', { skip }, async assert.deepEqual(await txIDs(b), []); }); -// A connection whose transactions commit, and whose answer to the commit is then lost. With `dead`, nothing can be -// asked on it afterwards either. -function losingTheCommit(sql: Sql, { dead = false } = {}): Sql { - let lost = false; +// A connection whose transactions commit, and whose answer to the commit is then lost +function losingTheCommit(sql: Sql): Sql { return new Proxy(sql, { get(target, property, receiver) { if (property === 'begin') { return async (...args: unknown[]) => { await (target.begin as (...a: unknown[]) => Promise)(...args); - lost = true; throw new Error('the connection was lost'); }; } return Reflect.get(target, property, receiver); }, - apply(target, thisArg, args) { - if (dead && lost) throw new Error('the connection is closed'); - return Reflect.apply(target as unknown as (...a: unknown[]) => unknown, thisArg, args); - }, }) as Sql; } -test('writeLtxFiles succeeds when the answer to its commit is lost and the files are stored', { skip }, async (t) => { - const { sql, client } = setup(t); - await client(makePrefix()).init(); - const lossy = losingTheCommit(sql); - const a = new PgReplicaClient({ - sql: lossy, - prefix: makePrefix(), - tablePrefix, - createTables: false, - }); - const b = new PgReplicaClient({ - sql: lossy, - prefix: makePrefix(), - tablePrefix, - createTables: false, - }); +test( + 'writeLtxFiles tells that it cannot know whether the files were written when its commit fails', + { skip }, + async (t) => { + const { sql, client } = setup(t); + await client(makePrefix()).init(); + const a = new PgReplicaClient({ + sql: losingTheCommit(sql), + prefix: makePrefix(), + tablePrefix, + createTables: false, + }); - const results = await PgReplicaClient.writeLtxFiles([ - { client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, - { client: b, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 20) }, - ]); + await assert.rejects( + PgReplicaClient.writeLtxFiles([ + { client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, + { client: a, level: 0, minTXID: 2n, maxTXID: 2n, body: makeBody(2n, 10) }, + ]), + (err: unknown) => err instanceof PgWriteLtxFilesError && err.outcome === 'unknown', + ); + // Here they were written: a caller which writes them again finds them there + assert.deepEqual(await txIDs(client(a.prefix)), [1n, 2n]); + }, +); - assert.deepEqual( - results.map((result) => result.info?.size), - [makeBody(1n, 10).length, makeBody(1n, 20).length], - ); - assert.deepEqual(await txIDs(client(a.prefix)), [1n]); - assert.deepEqual(await txIDs(client(b.prefix)), [1n]); -}); +test( + 'writeLtxFiles leaves out the files of a replica which come after one of a superseded client', + { skip }, + async (t) => { + const { client } = setup(t); + const prefix = makePrefix(); + const stale = client(prefix, 1n); + await stale.registerGeneration(1n); + const current = client(prefix, 2n); + await current.registerGeneration(2n); -test('writeLtxFiles tells when it cannot know whether the files were written', { skip }, async (t) => { - const { sql, client } = setup(t); - await client(makePrefix()).init(); - const a = new PgReplicaClient({ - sql: losingTheCommit(sql, { dead: true }), - prefix: makePrefix(), - tablePrefix, - createTables: false, - }); + // Written, the second would leave the replica with 2 and without 1 + const results = await PgReplicaClient.writeLtxFiles([ + { client: stale, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, + { client: current, level: 0, minTXID: 2n, maxTXID: 2n, body: makeBody(2n, 10) }, + ]); - await assert.rejects( - PgReplicaClient.writeLtxFiles([ - { - client: a, - level: 0, - minTXID: 1n, - maxTXID: 1n, - body: makeBody(1n, 10), - }, - { - client: a, - level: 0, - minTXID: 2n, - maxTXID: 2n, - body: makeBody(2n, 10), - }, - ]), - (err: unknown) => err instanceof PgWriteLtxFilesError && err.outcome === 'unknown', - ); - // They were written: a caller which looks before it writes again finds them - assert.deepEqual(await txIDs(client(a.prefix)), [1n, 2n]); -}); + assert.ok(results[0].error instanceof ErrGenerationSuperseded); + assert.match(String(results[1].error), /earlier file/); + assert.deepEqual(await txIDs(current), []); + }, +); test('writeLtxFiles needs clients of the same tables, and takes no files', { skip }, async (t) => { const { sql, client } = setup(t); From 5ef1e44c857d19c923de5ad8c36096847ec08b38 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:32:59 +0100 Subject: [PATCH 4/6] fix(pg): write the files of a replica which come before one which is left out A file too short to be one marked its replica before the transaction, and the files before it were then left out with it. Only the files after it are; the files left out for their generation are tracked apart. --- packages/backend-pg/src/replica-client.ts | 11 +++++++---- packages/backend-pg/test/write-ltx-files.test.ts | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/packages/backend-pg/src/replica-client.ts b/packages/backend-pg/src/replica-client.ts index 9924ce4..740edfd 100644 --- a/packages/backend-pg/src/replica-client.ts +++ b/packages/backend-pg/src/replica-client.ts @@ -622,7 +622,7 @@ export class PgReplicaClient implements ReplicaClient { const results: (PgWriteLtxFileResult | null)[] = files.map(() => null); const timestamps: number[] = []; - // The replicas which had a file left out: their later files are left out too. + // The replicas which had a file too short to be one: their later files are left out too, and only those. const broken = new Set(); for (let i = 0; i < files.length; i++) { const { client, body } = files[i]; @@ -656,21 +656,24 @@ export class PgReplicaClient implements ReplicaClient { for (const row of rows) stored.set(row.prefix, BigInt(row.generation)); } + // The replicas which had a file left out for its generation: their later files are left out too. + const fencedOut = new Set(); const chunks: { prefix: string; level: number; min_txid: string; max_txid: string; seq: number; data: Uint8Array }[] = []; const metadata: BatchFileRow[] = []; for (let i = 0; i < files.length; i++) { if (results[i] !== null) continue; const { client, level, minTXID, maxTXID, body } = files[i]; - // An earlier file of the replica was left out, by this loop: this one would leave a hole after it. - if (broken.has(client.prefix)) { + // An earlier file of the replica was left out for its generation: this one would leave a hole after it. + // The files which come before one which is too short are not concerned: they are written. + if (fencedOut.has(client.prefix)) { results[i] = { error: new InvalidArgumentError('write ltx file: an earlier file of the replica was not written') }; continue; } const registered = stored.get(client.prefix); if (client.generation !== null && registered !== undefined && registered > client.generation) { results[i] = { error: new ErrGenerationSuperseded(registered) }; - broken.add(client.prefix); + fencedOut.add(client.prefix); continue; } diff --git a/packages/backend-pg/test/write-ltx-files.test.ts b/packages/backend-pg/test/write-ltx-files.test.ts index f1b099a..3d3ae8d 100644 --- a/packages/backend-pg/test/write-ltx-files.test.ts +++ b/packages/backend-pg/test/write-ltx-files.test.ts @@ -212,6 +212,22 @@ test( }, ); +test('writeLtxFiles writes the files of a replica which come before one which is left out', { skip }, async (t) => { + const { client } = setup(t); + const a = client(makePrefix()); + + const results = await PgReplicaClient.writeLtxFiles([ + { client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, + { client: a, level: 0, minTXID: 2n, maxTXID: 2n, body: new Uint8Array(3) }, + { client: a, level: 0, minTXID: 3n, maxTXID: 3n, body: makeBody(3n, 10) }, + ]); + + assert.equal(results[0].error, undefined); + assert.match(String(results[1].error), /too short/); + assert.match(String(results[2].error), /earlier file/); + assert.deepEqual(await txIDs(a), [1n]); +}); + test('writeLtxFiles writes nothing when a file exists already', { skip }, async (t) => { const { client } = setup(t); const a = client(makePrefix()); From 6121b29d45cfa0d22bc156663045e29c3d41eb96 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Tue, 1 Dec 2026 17:47:12 +0100 Subject: [PATCH 5/6] fix(pg): every failure of writeLtxFiles before its transaction tells that nothing was written The tables which cannot be created rejected the call with a raw error, and so did a header which is not one. The first is rolled-back, as nothing was written; the second leaves its file out, as a file too short to hold a header does. --- packages/backend-pg/src/replica-client.ts | 28 +++++++++++---- .../backend-pg/test/write-ltx-files.test.ts | 34 +++++++++++++++++++ 2 files changed, 55 insertions(+), 7 deletions(-) diff --git a/packages/backend-pg/src/replica-client.ts b/packages/backend-pg/src/replica-client.ts index 740edfd..f22ae16 100644 --- a/packages/backend-pg/src/replica-client.ts +++ b/packages/backend-pg/src/replica-client.ts @@ -585,7 +585,8 @@ export class PgReplicaClient implements ReplicaClient { * generation rows of the replicas are locked (`FOR SHARE`) first, and the * files of a replica whose registered generation is above the one of its * client are left out, with {@link ErrGenerationSuperseded} as their result. - * A file too short to hold a header is left out too. **A file which is left + * A file too short to hold a header, or whose header is not one, is left + * out too. **A file which is left * out takes every later file of its replica with it**, whichever client * they come from: a replica never gets a file whose predecessor in the call * was not written, which would leave a hole in its history. The files of @@ -594,10 +595,11 @@ export class PgReplicaClient implements ReplicaClient { * Returns one result for each file, in order: its `info`, or the `error` * which left it out. * - * Any other failure rejects the whole call with {@link PgWriteLtxFilesError}. - * When a statement failed, e.g. for a file which exists already, its - * `outcome` is `rolled-back`: nothing was written, write the files one by - * one. When the failure came with the commit, the `outcome` is `unknown`: + * Any other failure rejects the whole call with {@link PgWriteLtxFilesError}, + * and with nothing else, but for clients which do not share their tables, + * which is a mistake of the caller. When the tables could not be created or + * a statement failed, e.g. for a file which exists already, its `outcome` is + * `rolled-back`: nothing was written, write the files one by one. When the failure came with the commit, the `outcome` is `unknown`: * the call does not look for the files, since a commit whose answer was lost * can still become visible after such a look, and a file found with the * same size would not prove that it is this one. @@ -618,7 +620,12 @@ export class PgReplicaClient implements ReplicaClient { ); } } - await first.init(); + // Nothing is written yet: a failure to create the tables is one of a call which wrote nothing. + try { + await first.init(); + } catch (err) { + throw new PgWriteLtxFilesError('rolled-back', err); + } const results: (PgWriteLtxFileResult | null)[] = files.map(() => null); const timestamps: number[] = []; @@ -634,7 +641,14 @@ export class PgReplicaClient implements ReplicaClient { broken.add(client.prefix); timestamps.push(0); } else { - timestamps.push(Number(unmarshalHeader(body.subarray(0, HeaderSize)).timestamp)); + // A header which is not one leaves its file out, as a file too short to hold one. + try { + timestamps.push(Number(unmarshalHeader(body.subarray(0, HeaderSize)).timestamp)); + } catch (err) { + results[i] = { error: err instanceof Error ? err : new Error(String(err)) }; + broken.add(client.prefix); + timestamps.push(0); + } } } diff --git a/packages/backend-pg/test/write-ltx-files.test.ts b/packages/backend-pg/test/write-ltx-files.test.ts index 3d3ae8d..550875a 100644 --- a/packages/backend-pg/test/write-ltx-files.test.ts +++ b/packages/backend-pg/test/write-ltx-files.test.ts @@ -228,6 +228,40 @@ test('writeLtxFiles writes the files of a replica which come before one which is assert.deepEqual(await txIDs(a), [1n]); }); +test('writeLtxFiles leaves out a file whose header is not one', { skip }, async (t) => { + const { client } = setup(t); + const a = client(makePrefix()); + const b = client(makePrefix()); + // Long enough for a header, which it does not start with + const garbage = new Uint8Array(200).fill(7); + + const results = await PgReplicaClient.writeLtxFiles([ + { client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: garbage }, + { client: b, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }, + { client: a, level: 0, minTXID: 2n, maxTXID: 2n, body: makeBody(2n, 10) }, + ]); + + assert.ok(results[0].error instanceof Error); + assert.equal(results[1].error, undefined); + assert.match(String(results[2].error), /earlier file/); + assert.deepEqual(await txIDs(a), []); + assert.deepEqual(await txIDs(b), [1n]); +}); + +test('writeLtxFiles tells that nothing was written when the tables cannot be created', { skip }, async (t) => { + const { client } = setup(t); + await client(makePrefix()).init(); + // A connection which is closed before the client creates its tables + const closed = connectForTest(t); + await closed.end({ timeout: 1 }); + const a = new PgReplicaClient({ sql: closed, prefix: makePrefix(), tablePrefix }); + + await assert.rejects( + PgReplicaClient.writeLtxFiles([{ client: a, level: 0, minTXID: 1n, maxTXID: 1n, body: makeBody(1n, 10) }]), + (err: unknown) => err instanceof PgWriteLtxFilesError && err.outcome === 'rolled-back', + ); +}); + test('writeLtxFiles writes nothing when a file exists already', { skip }, async (t) => { const { client } = setup(t); const a = client(makePrefix()); From f2cf65e7546517f20fe169dc412e7d19e7ab7c82 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Wed, 2 Dec 2026 14:51:19 +0100 Subject: [PATCH 6/6] feat(s3): write several LTX files in one call --- packages/backend-s3/src/index.ts | 3 + packages/backend-s3/src/replica-client.ts | 176 +++++++- .../backend-s3/test/write-ltx-files.test.ts | 393 ++++++++++++++++++ 3 files changed, 566 insertions(+), 6 deletions(-) create mode 100644 packages/backend-s3/test/write-ltx-files.test.ts diff --git a/packages/backend-s3/src/index.ts b/packages/backend-s3/src/index.ts index b755f6c..588a43b 100644 --- a/packages/backend-s3/src/index.ts +++ b/packages/backend-s3/src/index.ts @@ -18,6 +18,9 @@ export { type S3ClientLike, type S3DeletePrefixOptions, type S3ReplicaClientOptions, + type S3WriteLtxFile, + type S3WriteLtxFileResult, + type S3WriteLtxFilesOptions, } from './replica-client.ts'; export { S3Leaser } from './leaser.ts'; diff --git a/packages/backend-s3/src/replica-client.ts b/packages/backend-s3/src/replica-client.ts index 0c57f41..6d57ca5 100644 --- a/packages/backend-s3/src/replica-client.ts +++ b/packages/backend-s3/src/replica-client.ts @@ -52,6 +52,7 @@ import { DefaultLeasePath, ErrGenerationSuperseded, HeaderSize, + InvalidArgumentError, LTXError, SnapshotLevel, formatFilename, @@ -79,6 +80,26 @@ export interface S3ClientLike { send(command: any): Promise; } +/** A file of {@link S3ReplicaClient.writeLtxFiles}: where it goes, and its bytes. */ +export interface S3WriteLtxFile { + /** The client of the replica the file belongs to: its bucket, its prefix and its generation are used. */ + client: S3ReplicaClient; + level: number; + minTXID: bigint; + maxTXID: bigint; + /** The whole file. */ + body: Uint8Array; +} + +/** The outcome of one file of {@link S3ReplicaClient.writeLtxFiles}. */ +export type S3WriteLtxFileResult = { info: FileInfo; error?: undefined } | { info?: undefined; error: Error }; + +/** Options of {@link S3ReplicaClient.writeLtxFiles}. */ +export interface S3WriteLtxFilesOptions { + /** How many replicas are written at the same time. Defaults to 16. */ + concurrency?: number; +} + /** Configuration for {@link S3ReplicaClient}. */ export interface S3ReplicaClientOptions { /** S3 bucket name. Required. */ @@ -393,12 +414,27 @@ export class S3ReplicaClient implements ReplicaClient { * Fails with {@link ErrGenerationSuperseded} if a generation higher than this * client's is registered. A no-op when fencing is disabled. */ - private async assertGeneration(): Promise { - if (this.generation === null) return; - if (this.supersededBy !== null) throw new ErrGenerationSuperseded(this.supersededBy); + private assertGeneration(): Promise { + return this.assertGenerationOf(this.generation); + } + + /** + * Fails with {@link ErrGenerationSuperseded} if a generation higher than + * `generation` is registered: the one a file was written under, which stays + * the same from the moment the file was handed over to its acknowledgement. + * The client may register another generation meanwhile, also while this + * reads the replica, and that one tells nothing of the file. + */ + private async assertGenerationOf(generation: bigint | null): Promise { + if (generation === null) return; + if (this.generation === generation && this.supersededBy !== null) { + throw new ErrGenerationSuperseded(this.supersededBy); + } const cur = await this.readGenerationObject(); - if (cur !== null && cur.state.generation > this.generation) { - throw this.superseded(cur.state.generation); + if (cur !== null && cur.state.generation > generation) { + // Only a client which is still under that generation is superseded from now on. + if (this.generation === generation) throw this.superseded(cur.state.generation); + throw new ErrGenerationSuperseded(cur.state.generation); } } @@ -576,7 +612,135 @@ export class S3ReplicaClient implements ReplicaClient { } } + /** + * Writes the files of several replicas in one call. S3 has no transaction + * to write them in: the replicas are written at the same time, `concurrency` + * of them at once, and the files of a replica one after the other, in the + * order of the call. What the call saves is the look at the generation + * after each file: a fenced replica is checked once, after the last of its + * files landed, which acknowledges them all. + * + * Returns one result for each file, in order: its `info`, or the `error` + * which left it out. **A file which is not written takes every later file + * of its replica with it**, whichever client they come from: a replica + * never gets a file whose predecessor in the call was not written, which + * would leave a hole in its history. The files of the other replicas are + * written all the same. When the generation of a replica is found + * superseded after its files landed, they all get + * {@link ErrGenerationSuperseded}: they are in the bucket, hidden from the + * restores by the fence of the newer generation. + * + * The files of a call use the same S3 client, and the files of a replica + * are written under one generation: the call rejects otherwise, before it + * writes anything. A client which registers another generation while the + * call runs has its later files left out. The call rejects for no file: + * unlike its Postgres counterpart, there is nothing to roll back, and each + * file has its own outcome. As with + * {@link writeLtxFile}, a fenced file which exists already is kept when + * it is part of the replica, and a file written without fencing replaces + * the one which was there. + */ + static async writeLtxFiles( + files: readonly S3WriteLtxFile[], + opts: S3WriteLtxFilesOptions = {}, + ): Promise { + const concurrency = opts.concurrency ?? 16; + if (!Number.isInteger(concurrency) || concurrency < 1) { + throw new InvalidArgumentError('S3 replica client: the concurrency of writeLtxFiles must be a positive integer'); + } + const results: S3WriteLtxFileResult[] = new Array(files.length); + if (files.length === 0) return results; + + // The files of each replica, in the order of the call. A replica is a prefix of a bucket: the store is the + // same for all, which is the only way to tell that two clients write the same replica. + // The generation of each replica is the one its client has now: it stays the one of its files until they are + // acknowledged, whatever the client registers while they wait for their turn or are written. + const store = files[0].client.client; + const byName = new Map(); + for (let i = 0; i < files.length; i++) { + const { client } = files[i]; + if (client.client !== store) { + throw new InvalidArgumentError('S3 replica client: the files of a call must use the same S3 client'); + } + const name = `${client.bucket}\u0000${client.prefix}`; + const replica = byName.get(name); + if (replica === undefined) { + byName.set(name, { generation: client.generation, indexes: [i] }); + } else { + // A file written under a generation is only acknowledged with the ones before it: under two generations, + // the later files could be acknowledged while the earlier ones are hidden by a fence. + if (client.generation !== replica.generation) { + throw new InvalidArgumentError('S3 replica client: the files of a replica must be written under one generation'); + } + replica.indexes.push(i); + } + } + const replicas = [...byName.values()]; + + const writeReplica = async ({ generation, indexes }: { generation: bigint | null; indexes: number[] }): Promise => { + let failed = false; + const first = files[indexes[0]].client; + // The files which were written, all under `generation`. + const written: number[] = []; + for (const i of indexes) { + const { client, level, minTXID, maxTXID, body } = files[i]; + if (failed) { + results[i] = { error: new InvalidArgumentError('write ltx file: an earlier file of the replica was not written') }; + continue; + } + // The client registered another generation since the call began: the file would be written under it, as + // one of the new owner. + if (client.generation !== generation) { + results[i] = { error: new InvalidArgumentError('write ltx file: the generation of the replica changed during the call') }; + failed = true; + continue; + } + try { + const info = await client.writeFile({ level, minTXID, maxTXID }, [body], false); + results[i] = { info }; + written.push(i); + } catch (err) { + results[i] = { error: err instanceof Error ? err : new Error(String(err)) }; + failed = true; + } + } + // The files are only acknowledged if the generation they were written under is still the latest after they + // landed: one look at the replica tells it for all of them. + if (generation !== null && written.length > 0) { + try { + await first.assertGenerationOf(generation); + } catch (err) { + const error = err instanceof Error ? err : new Error(String(err)); + for (const i of written) results[i] = { error }; + } + } + }; + + let next = 0; + const worker = async (): Promise => { + while (next < replicas.length) await writeReplica(replicas[next++]); + }; + const workers: Promise[] = []; + for (let i = 0; i < Math.min(concurrency, replicas.length); i++) workers.push(worker()); + await Promise.all(workers); + + return results; + } + async writeLtxFile(opts: WriteLTXFileOptions, body: AsyncIterable): Promise { + return this.writeFile(opts, body, true); + } + + /** + * Writes a file. With `acknowledge`, a fenced write is followed by the look + * at the generation which acknowledges it; without, that look is for the + * caller to take, once, after the last of the files it writes. + */ + private async writeFile( + opts: WriteLTXFileOptions, + body: AsyncIterable | Iterable, + acknowledge: boolean, + ): Promise { const key = this.fileKey(opts.level, opts.minTXID, opts.maxTXID); const generation = this.generation; if (generation !== null && this.supersededBy !== null) { @@ -718,7 +882,7 @@ export class S3ReplicaClient implements ReplicaClient { // The upload is only acknowledged if this generation is still the latest // after it landed: any generation registered later then sees the file. - await this.assertGeneration(); + if (acknowledge) await this.assertGenerationOf(generation); return existing ?? info; } catch (err) { if (err instanceof ErrGenerationSuperseded) throw err; diff --git a/packages/backend-s3/test/write-ltx-files.test.ts b/packages/backend-s3/test/write-ltx-files.test.ts new file mode 100644 index 0000000..d76adbd --- /dev/null +++ b/packages/backend-s3/test/write-ltx-files.test.ts @@ -0,0 +1,393 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; + +import { + ErrGenerationSuperseded, + InvalidArgumentError, + marshalHeader, + type Header, +} from '@platformatic/sqlite-js-stream'; + +import { GenerationObjectName, S3ReplicaClient } from '../src/index.ts'; +import { MemoryS3 } from './helpers/memory-s3.ts'; + +function makeBody(txID: bigint, size = 16, timestamp = 1700000000000): Uint8Array { + const hdr: Header = { + version: 3, + flags: 0, + pageSize: 4096, + commit: 1, + minTXID: txID, + maxTXID: txID, + timestamp: BigInt(timestamp), + preApplyChecksum: 0n, + walOffset: 0n, + walSize: 0n, + walSalt1: 0, + walSalt2: 0, + nodeID: 0n, + }; + const header = marshalHeader(hdr); + const body = new Uint8Array(header.length + size); + body.set(header, 0); + for (let i = 0; i < size; i++) body[header.length + i] = (i + Number(txID)) % 251; + return body; +} + +function file(client: S3ReplicaClient, txID: bigint, body = makeBody(txID)) { + return { client, level: 0, minTXID: txID, maxTXID: txID, body }; +} + +async function read(client: S3ReplicaClient, txID: bigint): Promise { + const chunks: Uint8Array[] = []; + for await (const chunk of await client.openLtxFile({ level: 0, minTXID: txID, maxTXID: txID, offset: 0, size: 0 })) { + chunks.push(chunk as Uint8Array); + } + return Buffer.concat(chunks); +} + +async function txIDs(client: S3ReplicaClient): Promise { + const ids: bigint[] = []; + for await (const info of client.ltxFiles({ level: 0, seek: 0n, useMetadata: false })) ids.push(info.minTXID); + return ids; +} + +function isGenerationRead(command: unknown, prefix: string): boolean { + return command instanceof GetObjectCommand && command.input.Key === `${prefix}/${GenerationObjectName}`; +} + +test('writeLtxFiles writes the files of several replicas in one call', async () => { + const s3 = new MemoryS3(); + const a = new S3ReplicaClient({ bucket: 'b', prefix: 'a', client: s3 }); + const b = new S3ReplicaClient({ bucket: 'b', prefix: 'b', client: s3, generation: 1n }); + await b.registerGeneration(1n); + + const files = [file(a, 1n), file(b, 1n), file(a, 2n), file(b, 2n, makeBody(2n, 4096, 1700000001000))]; + const results = await S3ReplicaClient.writeLtxFiles(files); + + assert.deepEqual(results, [ + { info: { level: 0, minTXID: 1n, maxTXID: 1n, size: files[0].body.length, createdAt: 1700000000000 } }, + { info: { level: 0, minTXID: 1n, maxTXID: 1n, size: files[1].body.length, createdAt: 1700000000000 } }, + { info: { level: 0, minTXID: 2n, maxTXID: 2n, size: files[2].body.length, createdAt: 1700000000000 } }, + { info: { level: 0, minTXID: 2n, maxTXID: 2n, size: files[3].body.length, createdAt: 1700000001000 } }, + ]); + assert.deepEqual(await txIDs(a), [1n, 2n]); + assert.deepEqual(await txIDs(b), [1n, 2n]); + assert.deepEqual(await read(a, 2n), Buffer.from(files[2].body)); + assert.deepEqual(await read(b, 2n), Buffer.from(files[3].body)); + + assert.deepEqual(await S3ReplicaClient.writeLtxFiles([]), []); +}); + +test('writeLtxFiles looks at the generation of a replica once, after the last of its files', async () => { + const s3 = new MemoryS3(); + const client = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: s3, generation: 1n }); + await client.registerGeneration(1n); + + const events: string[] = []; + s3.onSend = (command) => { + if (isGenerationRead(command, 'db')) events.push('generation'); + if (command instanceof PutObjectCommand && command.input.Key?.endsWith('.ltx')) events.push('file'); + }; + + const results = await S3ReplicaClient.writeLtxFiles([file(client, 1n), file(client, 2n), file(client, 3n)]); + assert.deepEqual( + results.map((result) => result.info?.minTXID), + [1n, 2n, 3n], + ); + assert.deepEqual(events, ['file', 'file', 'file', 'generation']); + + // One file at a time looks after each of them + events.length = 0; + await client.writeLtxFile( + { level: 0, minTXID: 4n, maxTXID: 4n }, + (async function* () { + yield makeBody(4n); + })(), + ); + assert.deepEqual(events, ['file', 'generation']); +}); + +test('writeLtxFiles does not acknowledge the files of a replica superseded while they were written', async () => { + const s3 = new MemoryS3(); + const old = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: s3, generation: 1n }); + const other = new S3ReplicaClient({ bucket: 'b', prefix: 'other', client: s3, generation: 1n }); + await old.registerGeneration(1n); + await other.registerGeneration(1n); + + // A new owner registers its generation once the first file of the old one landed + const owner = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: s3, generation: 2n }); + let registered = false; + s3.onSend = async (command) => { + if ( + !registered && + command instanceof PutObjectCommand && + /^db\/.*0000000000000002-0000000000000002\.ltx$/.test(command.input.Key ?? '') + ) { + registered = true; + await owner.registerGeneration(2n); + } + }; + + const results = await S3ReplicaClient.writeLtxFiles([file(old, 1n), file(other, 1n), file(old, 2n)]); + s3.onSend = null; + + assert.ok(registered, 'the key of a file is the one the test expects'); + assert.ok(results[0].error instanceof ErrGenerationSuperseded); + assert.ok(results[2].error instanceof ErrGenerationSuperseded); + assert.equal((results[0].error as ErrGenerationSuperseded).generation, 2n); + assert.equal(results[1].info?.minTXID, 1n); + + // The client knows it from then on: nothing else of it is sent + let sent = 0; + s3.onSend = () => { + sent++; + }; + const again = await S3ReplicaClient.writeLtxFiles([file(old, 3n), file(old, 4n)]); + assert.ok(again[0].error instanceof ErrGenerationSuperseded); + assert.ok(again[1].error instanceof InvalidArgumentError); + assert.equal(sent, 0); +}); + +test('writeLtxFiles leaves out the files of a replica which come after one which was not written', async () => { + const s3 = new MemoryS3(); + const a = new S3ReplicaClient({ bucket: 'b', prefix: 'a', client: s3 }); + const b = new S3ReplicaClient({ bucket: 'b', prefix: 'b', client: s3 }); + // Another client of the same replica: its files are after those of the first one all the same + const sameAsA = new S3ReplicaClient({ bucket: 'b', prefix: 'a', client: s3 }); + + const results = await S3ReplicaClient.writeLtxFiles([ + file(a, 1n), + file(a, 2n, new Uint8Array(10)), + file(b, 1n), + file(sameAsA, 3n), + file(b, 2n), + ]); + + assert.equal(results[0].info?.minTXID, 1n); + assert.match(results[1].error!.message, /too short to contain a header/); + assert.ok(results[3].error instanceof InvalidArgumentError); + assert.match(results[3].error.message, /an earlier file of the replica was not written/); + assert.equal(results[2].info?.minTXID, 1n); + assert.equal(results[4].info?.minTXID, 2n); + assert.deepEqual(await txIDs(a), [1n]); + assert.deepEqual(await txIDs(b), [1n, 2n]); +}); + +test('writeLtxFiles gives a failed upload as the result of its file, and writes the other replicas', async () => { + const s3 = new MemoryS3(); + const a = new S3ReplicaClient({ bucket: 'b', prefix: 'a', client: s3 }); + const b = new S3ReplicaClient({ bucket: 'b', prefix: 'b', client: s3 }); + s3.onSend = (command) => { + if (command instanceof PutObjectCommand && command.input.Key?.startsWith('a/')) { + throw new Error('the store is away'); + } + }; + + const results = await S3ReplicaClient.writeLtxFiles([file(a, 1n), file(b, 1n), file(a, 2n)]); + s3.onSend = null; + + assert.match( + String((results[0].error as Error & { cause?: unknown }).cause ?? results[0].error), + /the store is away/, + ); + assert.equal(results[1].info?.minTXID, 1n); + assert.match(results[2].error!.message, /an earlier file of the replica was not written/); + assert.deepEqual(await txIDs(a), []); +}); + +test('writeLtxFiles writes the files of a replica in order, and at most `concurrency` replicas at once', async () => { + const s3 = new MemoryS3(); + const clients: S3ReplicaClient[] = []; + for (let i = 0; i < 6; i++) clients.push(new S3ReplicaClient({ bucket: 'b', prefix: `db-${i}`, client: s3 })); + + let inFlight = 0; + let most = 0; + const order: string[] = []; + s3.onSend = async (command) => { + if (!(command instanceof PutObjectCommand)) return; + most = Math.max(most, ++inFlight); + order.push(command.input.Key!); + await new Promise((resolve) => setImmediate(resolve)); + inFlight--; + }; + + const files = []; + for (let txID = 1n; txID <= 3n; txID++) for (const client of clients) files.push(file(client, txID)); + const results = await S3ReplicaClient.writeLtxFiles(files, { concurrency: 2 }); + s3.onSend = null; + + assert.ok(results.every((result) => result.info !== undefined)); + assert.equal(most, 2); + for (let i = 0; i < 6; i++) { + const mine = order.filter((key) => key.startsWith(`db-${i}/`)); + assert.deepEqual(mine, [...mine].sort()); + assert.equal(mine.length, 3); + } + + await assert.rejects(S3ReplicaClient.writeLtxFiles(files, { concurrency: 0 }), InvalidArgumentError); +}); + +test('writeLtxFiles takes the files of a replica under one generation only', async () => { + const s3 = new MemoryS3(); + const stale = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: s3, generation: 1n }); + const current = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: s3, generation: 2n }); + await stale.registerGeneration(1n); + await current.registerGeneration(2n); + + // The file of the stale client would land and be hidden by the fence, and the one after it be acknowledged + let sent = 0; + s3.onSend = () => { + sent++; + }; + await assert.rejects( + S3ReplicaClient.writeLtxFiles([file(stale, 1n), file(current, 2n)]), + (err: Error) => err instanceof InvalidArgumentError && /under one generation/.test(err.message), + ); + assert.equal(sent, 0); + s3.onSend = null; + assert.deepEqual(await txIDs(current), []); + + // Two clients of the same generation are one writer + const same = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: s3, generation: 2n }); + const results = await S3ReplicaClient.writeLtxFiles([file(current, 1n), file(same, 2n)]); + assert.deepEqual( + results.map((result) => result.info?.minTXID), + [1n, 2n], + ); +}); + +test('writeLtxFiles takes the files of one S3 client only', async () => { + const one = new MemoryS3(); + const other = new MemoryS3(); + const a = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: one }); + // The same bucket and prefix through another client: nothing tells that it is the same replica + const b = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: other }); + + await assert.rejects( + S3ReplicaClient.writeLtxFiles([file(a, 1n, new Uint8Array(10)), file(b, 2n)]), + (err: Error) => err instanceof InvalidArgumentError && /the same S3 client/.test(err.message), + ); + assert.equal(one.objects.size, 0); + assert.equal(other.objects.size, 0); +}); + +test('writeLtxFiles acknowledges a file against the generation it was written under', async () => { + const s3 = new MemoryS3(); + const client = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: s3, generation: 1n }); + await client.registerGeneration(1n); + + // The client itself registers the next generation while its first file is on its way + let registered = false; + s3.onSend = async (command) => { + if (!registered && command instanceof PutObjectCommand && command.input.Key?.endsWith('.ltx')) { + registered = true; + await client.registerGeneration(2n); + } + }; + const results = await S3ReplicaClient.writeLtxFiles([file(client, 1n), file(client, 2n)]); + s3.onSend = null; + + // The file was written under the generation 1: the generation 2 of the client tells nothing of it + assert.ok(registered); + assert.ok(results[0].error instanceof ErrGenerationSuperseded); + assert.equal((results[0].error as ErrGenerationSuperseded).generation, 2n); + assert.match(results[1].error!.message, /the generation of the replica changed during the call/); + assert.deepEqual(await txIDs(client), []); + + // The client is the owner under its new generation + const again = await S3ReplicaClient.writeLtxFiles([file(client, 1n), file(client, 2n)]); + assert.deepEqual( + again.map((result) => result.info?.minTXID), + [1n, 2n], + ); + assert.deepEqual(await txIDs(client), [1n, 2n]); +}); + +test('writeLtxFiles writes nothing of a replica whose client changed generation while it waited', async () => { + const s3 = new MemoryS3(); + const a = new S3ReplicaClient({ bucket: 'b', prefix: 'a', client: s3, generation: 1n }); + const b = new S3ReplicaClient({ bucket: 'b', prefix: 'b', client: s3, generation: 1n }); + await a.registerGeneration(1n); + await b.registerGeneration(1n); + + // One replica at a time: while the first one is written, the client of the second registers the next generation + let registered = false; + const puts: string[] = []; + s3.onSend = async (command) => { + if (!(command instanceof PutObjectCommand) || !command.input.Key?.endsWith('.ltx')) return; + puts.push(command.input.Key); + if (!registered) { + registered = true; + await b.registerGeneration(2n); + } + }; + const results = await S3ReplicaClient.writeLtxFiles([file(a, 1n), file(b, 1n), file(b, 2n)], { concurrency: 1 }); + s3.onSend = null; + + // Its files were handed over under the generation 1: they are not written as the ones of the generation 2 + assert.equal(results[0].info?.minTXID, 1n); + assert.match(results[1].error!.message, /the generation of the replica changed during the call/); + assert.match(results[2].error!.message, /an earlier file of the replica was not written/); + assert.deepEqual( + puts.filter((key) => key.startsWith('b/')), + [], + ); + assert.deepEqual(await txIDs(b), []); +}); + +test('writeLtxFiles does not acknowledge a hidden file when its client changes generation during the last look', async () => { + const s3 = new MemoryS3(); + const client = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: s3, generation: 1n }); + const owner = new S3ReplicaClient({ bucket: 'b', prefix: 'db', client: s3, generation: 2n }); + await client.registerGeneration(1n); + + // A new owner registers before the file lands, which hides it. Then the client registers that generation too, + // while it reads the generation of the replica to acknowledge the file. + let stage = 0; + s3.onSend = async (command) => { + if (stage === 0 && command instanceof PutObjectCommand && command.input.Key?.endsWith('.ltx')) { + stage = 1; + await owner.registerGeneration(2n); + stage = 2; + } else if (stage === 2 && isGenerationRead(command, 'db')) { + stage = 3; + await client.registerGeneration(2n); + } + }; + const results = await S3ReplicaClient.writeLtxFiles([file(client, 1n)]); + s3.onSend = null; + + assert.equal(stage, 3); + assert.ok(results[0].error instanceof ErrGenerationSuperseded); + assert.equal((results[0].error as ErrGenerationSuperseded).generation, 2n); + assert.deepEqual(await txIDs(owner), []); + + // One file at a time, the same way + const single = new S3ReplicaClient({ bucket: 'b', prefix: 'single', client: s3, generation: 1n }); + const next = new S3ReplicaClient({ bucket: 'b', prefix: 'single', client: s3, generation: 2n }); + await single.registerGeneration(1n); + stage = 0; + s3.onSend = async (command) => { + if (stage === 0 && command instanceof PutObjectCommand && command.input.Key?.endsWith('.ltx')) { + stage = 1; + await next.registerGeneration(2n); + stage = 2; + } else if (stage === 2 && isGenerationRead(command, 'single')) { + stage = 3; + await single.registerGeneration(2n); + } + }; + await assert.rejects( + single.writeLtxFile( + { level: 0, minTXID: 1n, maxTXID: 1n }, + (async function* () { + yield makeBody(1n); + })(), + ), + ErrGenerationSuperseded, + ); + s3.onSend = null; + assert.equal(stage, 3); +});