diff --git a/CHANGELOG.md b/CHANGELOG.md index 3314736..402bc1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- Message pruning is faster on large tables. + `runtime.retention.prune({ target: "messages" })` and scheduled retention + start each batch after the last message id of the previous batch, so they do + not read again the protected messages that an earlier batch passed. A batch + with fewer than `pruneBatchSize` messages ends the run without one more query. + Pruning removes the same messages as before on SQLite, PostgreSQL, and MySQL, + and `runtime.retention.preview({ target: "messages" })` reports the same + count. No migration is necessary. + ## 1.2.0 - 2026-11-30 - Add `runtime.reconciliation.outcomesFor()` and diff --git a/src/repository.ts b/src/repository.ts index 285acd1..806a3f1 100644 --- a/src/repository.ts +++ b/src/repository.ts @@ -1499,31 +1499,55 @@ export class Repository { } async pruneRetention(target: RetentionTarget): Promise { + if (target === "messages") return this.pruneMessagesByPage() let count = 0 while (true) { - const deleted = await this.settings.database.transaction(async (connection) => { - const now = await connection.nowMilliseconds() - const predicate = this.retentionPredicate({ target, now }) - const candidates = await connection.all<{ id: string }>( - `SELECT id FROM ${this.table(target)} WHERE ${predicate.sql} - ORDER BY id LIMIT ?`, - [...predicate.parameters, this.settings.pruneBatchSize], - ) - if (candidates.length === 0) return 0 - const candidateIds = candidates.map(({ id }) => id) - const result = await connection.run( - `DELETE FROM ${this.table(target)} - WHERE id IN (${parameterList(candidateIds.length)}) - AND ${predicate.sql}`, - [...candidateIds, ...predicate.parameters], - ) - return result.changes - }) - if (deleted === 0) return count - count += deleted + const batch = await this.pruneRetentionBatch({ target }) + if (batch.deleted === 0) return count + count += batch.deleted + } + } + + private async pruneMessagesByPage(): Promise { + let count = 0 + let after: string | undefined + while (true) { + const batch = await this.pruneRetentionBatch({ target: "messages", after }) + count += batch.deleted + if (batch.candidateIds.length < this.settings.pruneBatchSize) return count + after = batch.candidateIds.at(-1) } } + private async pruneRetentionBatch(options: { + target: RetentionTarget + after?: string | undefined + }): Promise<{ candidateIds: string[]; deleted: number }> { + const table = this.table(options.target) + return this.settings.database.transaction(async (connection) => { + const now = await connection.nowMilliseconds() + const predicate = this.retentionPredicate({ target: options.target, now }) + const cursor = + options.after === undefined + ? { sql: "", parameters: [] } + : { sql: ` AND ${table}.id > ?`, parameters: [options.after] } + const candidates = await connection.all<{ id: string }>( + `SELECT id FROM ${table} WHERE ${predicate.sql}${cursor.sql} + ORDER BY id LIMIT ?`, + [...predicate.parameters, ...cursor.parameters, this.settings.pruneBatchSize], + ) + const candidateIds = candidates.map(({ id }) => id) + if (candidateIds.length === 0) return { candidateIds, deleted: 0 } + const result = await connection.run( + `DELETE FROM ${table} + WHERE id IN (${parameterList(candidateIds.length)}) + AND ${predicate.sql}`, + [...candidateIds, ...predicate.parameters], + ) + return { candidateIds, deleted: result.changes } + }) + } + private retentionPredicate(options: { target: RetentionTarget; now: number }): { sql: string parameters: unknown[] diff --git a/test/message-pruning.test.ts b/test/message-pruning.test.ts new file mode 100644 index 0000000..ba22085 --- /dev/null +++ b/test/message-pruning.test.ts @@ -0,0 +1,633 @@ +import { afterEach, describe, expect, it } from "vitest" +import type { SolidObjectsConfiguration } from "../src/configuration.js" +import { sqlite } from "../src/database/sqlite.js" +import type { + Database, + DatabaseConnection, + DatabaseFamily, + DatabaseTransactionOptions, +} from "../src/database/types.js" +import { createRuntime, type SolidObjectsRuntime } from "../src/runtime.js" + +const DAY = 24 * 60 * 60 * 1_000 +const OLD = 31 * DAY +const ACTOR_TYPES = ["PruneActor", "ShortActor", "LongActor"] as const +const GUARDS = [ + "ready", + "claimed", + "deadLetter", + "retriedDeadLetter", + "unfinishedEffect", + "undeliveredBroadcast", +] as const + +type ActorType = (typeof ACTOR_TYPES)[number] +type Guard = (typeof GUARDS)[number] +type EffectStatus = "pending" | "processing" | "completed" | "dead" +type BroadcastStatus = "pending" | "processing" | "delivered" | "dead" +type BeforeDelete = ( + connection: DatabaseConnection, + candidateIds: readonly string[], +) => Promise + +interface MessageFixture { + id: string + actorType?: ActorType + completedAgo: number | null + ready?: "ready" + claimed?: "claimed" + deadLetter?: { retriedMessageId: string | null } + effects?: readonly EffectStatus[] + broadcasts?: readonly BroadcastStatus[] +} + +interface CandidatePage { + sql: string + parameters: readonly unknown[] + ids: string[] +} + +const runtimes: SolidObjectsRuntime[] = [] + +afterEach(async () => { + for (const runtime of runtimes.splice(0)) await runtime.close() +}) + +describe("message pruning", () => { + it("prunes only terminal unreferenced history for every guard and status", async () => { + const fixtures: MessageFixture[] = [ + { id: "plain", completedAgo: OLD }, + { id: "incomplete", completedAgo: null }, + { id: "recent", completedAgo: DAY }, + { id: "effect-completed", completedAgo: OLD, effects: ["completed"] }, + { id: "effect-pending", completedAgo: OLD, effects: ["pending"] }, + { id: "effect-processing", completedAgo: OLD, effects: ["processing"] }, + { id: "effect-dead", completedAgo: OLD, effects: ["dead"] }, + { id: "effect-mixed", completedAgo: OLD, effects: ["completed", "pending"] }, + { id: "broadcast-delivered", completedAgo: OLD, broadcasts: ["delivered"] }, + { id: "broadcast-pending", completedAgo: OLD, broadcasts: ["pending"] }, + { id: "broadcast-processing", completedAgo: OLD, broadcasts: ["processing"] }, + { id: "broadcast-dead", completedAgo: OLD, broadcasts: ["dead"] }, + { id: "broadcast-mixed", completedAgo: OLD, broadcasts: ["delivered", "pending"] }, + { + id: "all-terminal", + completedAgo: OLD, + effects: ["completed", "completed"], + broadcasts: ["delivered", "delivered"], + }, + { id: "retried-original", completedAgo: OLD, deadLetter: { retriedMessageId: "retry" } }, + { id: "retry", completedAgo: OLD }, + { id: "short-expired", actorType: "ShortActor", completedAgo: 2 * DAY }, + { id: "short-recent", actorType: "ShortActor", completedAgo: DAY / 2 }, + { id: "long-retained", actorType: "LongActor", completedAgo: OLD }, + { id: "long-expired", actorType: "LongActor", completedAgo: 61 * DAY }, + ...guardCombinations(), + ] + const pruned = [ + "all-terminal", + "broadcast-delivered", + "effect-completed", + "guards-none", + "long-expired", + "plain", + "short-expired", + ] + const database = await installedDatabase({ + pruneBatchSize: 2, + messageRetentionByActorType: { ShortActor: DAY, LongActor: 60 * DAY }, + }) + await seed(database, fixtures) + const runtime = currentRuntime() + + expect(await runtime.retention.preview({ target: "messages" })).toEqual({ + target: "messages", + count: pruned.length, + }) + expect(await runtime.retention.prune({ target: "messages" })).toEqual({ + target: "messages", + count: pruned.length, + }) + expect(await remainingIds(database)).toEqual( + allIds(fixtures) + .filter((id) => !pruned.includes(id)) + .sort(), + ) + expect(await runtime.retention.prune({ target: "messages" })).toEqual({ + target: "messages", + count: 0, + }) + }) + + it.each([ + { prunable: 0, pageSizes: [0] }, + { prunable: 1, pageSizes: [1] }, + { prunable: 2, pageSizes: [2] }, + { prunable: 3, pageSizes: [3, 0] }, + { prunable: 4, pageSizes: [3, 1] }, + { prunable: 5, pageSizes: [3, 2] }, + { prunable: 6, pageSizes: [3, 3, 0] }, + { prunable: 7, pageSizes: [3, 3, 1] }, + ])( + "pages through $prunable prunable messages between protected ones at batch size 3", + async ({ prunable, pageSizes }) => { + const fixtures = interleavedFixtures(prunable) + const prunableIds = fixtures + .filter((fixture) => fixture.effects === undefined) + .map(({ id }) => id) + const database = await installedDatabase({ pruneBatchSize: 3 }) + await seed(database, fixtures) + const runtime = currentRuntime() + + expect(await runtime.retention.prune({ target: "messages" })).toEqual({ + target: "messages", + count: prunable, + }) + expect(database.candidatePages.map(({ ids }) => ids.length)).toEqual(pageSizes) + expect(database.candidatePages.flatMap(({ ids }) => ids)).toEqual(prunableIds) + expectEachPageToResumeAfterThePreviousPage(database.candidatePages, allIds(fixtures)) + expect(await remainingIds(database)).toEqual( + allIds(fixtures).filter((id) => !prunableIds.includes(id)), + ) + expect(await runtime.retention.prune({ target: "messages" })).toEqual({ + target: "messages", + count: 0, + }) + }, + ) + + it("keeps paging when the rechecked delete removes fewer rows than a full page holds", async () => { + const fixtures = interleavedFixtures(5) + const prunableIds = fixtures + .filter((fixture) => fixture.effects === undefined) + .map(({ id }) => id) + const firstPage = prunableIds.slice(0, 3) + const database = await installedDatabase({ pruneBatchSize: 3 }, async (connection, ids) => { + await insertRows(connection, { + table: "ready_messages", + columns: ["message_id", "instance_id", "sequence", "available_at_ms"], + rows: ids.map((id, index) => [id, instanceId("PruneActor"), 10_000 + index, 0]), + }) + }) + await seed(database, fixtures) + const runtime = currentRuntime() + + expect(await runtime.retention.prune({ target: "messages" })).toEqual({ + target: "messages", + count: 2, + }) + expect(database.candidatePages.map(({ ids }) => ids)).toEqual([firstPage, prunableIds.slice(3)]) + expect(await remainingIds(database)).toEqual( + allIds(fixtures).filter((id) => !prunableIds.slice(3).includes(id)), + ) + }) + + it("prunes the same messages as one unpaged pass on a large table with leading protected rows", async () => { + const fixtures = largeFixtures() + const unpaged = await installedDatabase({ pruneBatchSize: 10_000 }) + await seed(unpaged, fixtures) + const unpagedCount = (await currentRuntime().retention.prune({ target: "messages" })).count + const unpagedRemaining = await remainingIds(unpaged) + expect(unpaged.candidatePages).toHaveLength(1) + + const paged = await installedDatabase({ pruneBatchSize: 25 }) + await seed(paged, fixtures) + const runtime = currentRuntime() + const preview = await runtime.retention.preview({ target: "messages" }) + + expect(await runtime.retention.prune({ target: "messages" })).toEqual({ + target: "messages", + count: unpagedCount, + }) + expect(preview.count).toBe(unpagedCount) + expect(unpagedCount).toBe(205) + expect(await remainingIds(paged)).toEqual(unpagedRemaining) + expect(paged.candidatePages.map(({ ids }) => ids.length)).toEqual([ + ...Array.from({ length: 8 }, () => 25), + 5, + ]) + expect(paged.candidatePages[0]?.ids[0]).toBe("message-0061") + expectEachPageToResumeAfterThePreviousPage(paged.candidatePages, allIds(fixtures)) + }, 30_000) + + it("rejects a fixture row whose value count does not match its columns", async () => { + const database = await installedDatabase({}) + await seed(database, [ + { id: "complete", completedAgo: OLD }, + { id: "short", completedAgo: OLD }, + { id: "retry", completedAgo: OLD }, + ]) + + await expect( + database.transaction((connection) => + insertRows(connection, { + table: "dead_letters", + columns: [ + "id", + "message_id", + "instance_id", + "attempts", + "error", + "created_at_ms", + "retried_message_id", + ], + rows: [ + ["dead-complete", "complete", instanceId("PruneActor"), 3, "{}", 0, "retry"], + ["dead-short", "short", instanceId("PruneActor"), 3, "{}", 0], + ], + }), + ), + ).rejects.toThrow("dead_letters fixture row 1 has 6 values for 7 columns") + expect(await remainingRowCount(database, "dead_letters")).toBe(0) + }) +}) + +function expectEachPageToResumeAfterThePreviousPage( + pages: readonly CandidatePage[], + messageIds: readonly string[], +): void { + const cursors = pages.map((page) => + page.parameters.find( + (parameter) => typeof parameter === "string" && messageIds.includes(parameter), + ), + ) + const previousLastIds = [undefined, ...pages.slice(0, -1).map(({ ids }) => ids.at(-1))] + expect(cursors).toEqual(previousLastIds) +} + +function guardCombinations(): MessageFixture[] { + return Array.from({ length: 2 ** GUARDS.length }, (_unused, mask) => { + const guards = GUARDS.filter((_guard, index) => (mask & (1 << index)) !== 0) + return guardedMessages(guards) + }).flat() +} + +function guardedMessages(guards: readonly Guard[]): MessageFixture[] { + const id = guards.length === 0 ? "guards-none" : `guards-${guards.join("-")}` + const message: MessageFixture = { + id, + completedAgo: OLD, + ...(guards.includes("ready") ? { ready: "ready" as const } : {}), + ...(guards.includes("claimed") ? { claimed: "claimed" as const } : {}), + ...(guards.includes("deadLetter") ? { deadLetter: { retriedMessageId: null } } : {}), + effects: guards.includes("unfinishedEffect") ? ["completed", "processing"] : ["completed"], + broadcasts: guards.includes("undeliveredBroadcast") + ? ["delivered", "processing"] + : ["delivered"], + } + if (!guards.includes("retriedDeadLetter")) return [message] + return [message, { id: `${id}-source`, completedAgo: OLD, deadLetter: { retriedMessageId: id } }] +} + +function interleavedFixtures(prunable: number): MessageFixture[] { + const protectedMessage = (position: number): MessageFixture => ({ + id: messageId(position), + completedAgo: OLD, + effects: ["pending"], + }) + const leading = [0, 1, 2].map(protectedMessage) + const interleaved = Array.from({ length: prunable }, (_unused, index) => [ + { id: messageId(3 + 2 * index), completedAgo: OLD }, + protectedMessage(4 + 2 * index), + ]).flat() + return [...leading, ...interleaved, protectedMessage(3 + 2 * prunable)] +} + +function largeFixtures(): MessageFixture[] { + return Array.from({ length: 300 }, (_unused, position) => { + const terminalEffects = Array.from({ length: 10 }, () => "completed" as const) + const terminalBroadcasts = Array.from({ length: 10 }, () => "delivered" as const) + const leadingProtected = position <= 60 + const interleavedProtected = position % 7 === 0 + return { + id: messageId(position), + completedAgo: OLD, + effects: leadingProtected ? [...terminalEffects, "pending"] : terminalEffects, + broadcasts: interleavedProtected ? [...terminalBroadcasts, "pending"] : terminalBroadcasts, + } + }) +} + +function messageId(position: number): string { + return `message-${String(position).padStart(4, "0")}` +} + +function allIds(fixtures: readonly MessageFixture[]): string[] { + return fixtures.map(({ id }) => id) +} + +function instanceId(actorType: ActorType): string { + return `instance-${actorType}` +} + +function table(name: string): string { + return `solid_objects_${name}` +} + +function currentRuntime(): SolidObjectsRuntime { + const runtime = runtimes.at(-1) + if (runtime === undefined) throw new Error("no runtime is installed") + return runtime +} + +async function installedDatabase( + configuration: Partial, + beforeFirstDelete?: BeforeDelete, +): Promise { + const database = new PruningDatabase(sqlite({ path: ":memory:" }), beforeFirstDelete) + const runtime = createRuntime({ + database, + authorizeAdministration: () => true, + ...configuration, + }) + runtimes.push(runtime) + await runtime.install() + return database +} + +async function remainingIds(database: Database): Promise { + const rows = await database.connection((connection) => + connection.all<{ id: string }>(`SELECT id FROM ${table("messages")} ORDER BY id`), + ) + return rows.map(({ id }) => id) +} + +async function remainingRowCount(database: Database, name: string): Promise { + const row = await database.connection((connection) => + connection.get<{ count: number }>(`SELECT COUNT(*) AS count FROM ${table(name)}`), + ) + return Number(row?.count) +} + +async function seed(database: Database, fixtures: readonly MessageFixture[]): Promise { + await database.transaction(async (connection) => { + const now = await connection.nowMilliseconds() + await insertRows(connection, { + table: "processes", + columns: ["id", "kind", "started_at_ms", "heartbeat_at_ms", "shutdown_state"], + rows: [["process", "worker", now, now, "running"]], + }) + await insertRows(connection, { + table: "instances", + columns: [ + "id", + "actor_type", + "actor_id", + "state", + "state_version", + "created_at_ms", + "updated_at_ms", + ], + rows: ACTOR_TYPES.map((actorType) => [ + instanceId(actorType), + actorType, + "actor", + "{}", + 1, + now, + now, + ]), + }) + await insertRows(connection, { + table: "messages", + columns: [ + "id", + "request_id", + "instance_id", + "actor_type", + "actor_id", + "sequence", + "operation", + "delivery_mode", + "arguments", + "max_attempts", + "completed_at_ms", + "created_at_ms", + "updated_at_ms", + ], + rows: fixtures.map((fixture, index) => { + const actorType = fixture.actorType ?? "PruneActor" + const completedAt = fixture.completedAgo === null ? null : now - fixture.completedAgo + return [ + fixture.id, + fixture.id, + instanceId(actorType), + actorType, + "actor", + index + 1, + "run", + "async", + "[]", + 3, + completedAt, + now - OLD * 3, + now, + ] + }), + }) + await insertRows(connection, { + table: "ready_messages", + columns: ["message_id", "instance_id", "sequence", "available_at_ms"], + rows: fixtures.flatMap((fixture, index) => + fixture.ready === undefined ? [] : [[fixture.id, instanceOf(fixture), index + 1, now]], + ), + }) + await insertRows(connection, { + table: "claimed_messages", + columns: [ + "message_id", + "instance_id", + "sequence", + "process_id", + "activation_token", + "activation_generation", + "claimed_at_ms", + ], + rows: fixtures.flatMap((fixture, index) => + fixture.claimed === undefined + ? [] + : [[fixture.id, instanceOf(fixture), index + 1, "process", "token", 1, now]], + ), + }) + await insertRows(connection, { + table: "dead_letters", + columns: [ + "id", + "message_id", + "instance_id", + "attempts", + "error", + "created_at_ms", + "retried_message_id", + ], + rows: fixtures.flatMap((fixture) => + fixture.deadLetter === undefined + ? [] + : [ + [ + `dead-${fixture.id}`, + fixture.id, + instanceOf(fixture), + 3, + "{}", + now, + fixture.deadLetter.retriedMessageId, + ], + ], + ), + }) + await insertRows(connection, { + table: "effects", + columns: [ + "id", + "message_id", + "instance_id", + "name", + "arguments", + "status", + "max_attempts", + "available_at_ms", + ], + rows: fixtures.flatMap((fixture) => + (fixture.effects ?? []).map((status, index) => [ + `effect-${fixture.id}-${index}`, + fixture.id, + instanceOf(fixture), + "effect", + "[]", + status, + 3, + now, + ]), + ), + }) + await insertRows(connection, { + table: "broadcasts", + columns: [ + "id", + "message_id", + "instance_id", + "actor_type", + "actor_id", + "state_revision", + "observables", + "status", + "available_at_ms", + ], + rows: fixtures.flatMap((fixture) => + (fixture.broadcasts ?? []).map((status, index) => [ + `broadcast-${fixture.id}-${index}`, + fixture.id, + instanceOf(fixture), + fixture.actorType ?? "PruneActor", + "actor", + 1, + "[]", + status, + now, + ]), + ), + }) + }) +} + +function instanceOf(fixture: MessageFixture): string { + return instanceId(fixture.actorType ?? "PruneActor") +} + +async function insertRows( + connection: DatabaseConnection, + options: { + table: string + columns: readonly string[] + rows: readonly (readonly (string | number | null)[])[] + }, +): Promise { + const mismatchedIndex = options.rows.findIndex((row) => row.length !== options.columns.length) + if (mismatchedIndex !== -1) { + const valueCount = options.rows[mismatchedIndex]?.length + throw new Error( + `${options.table} fixture row ${mismatchedIndex} has ${valueCount} values for ${options.columns.length} columns`, + ) + } + const placeholders = `(${options.columns.map(() => "?").join(", ")})` + for (let offset = 0; offset < options.rows.length; offset += 100) { + const chunk = options.rows.slice(offset, offset + 100) + await connection.run( + `INSERT INTO ${table(options.table)} (${options.columns.join(", ")}) + VALUES ${chunk.map(() => placeholders).join(", ")}`, + chunk.flat(), + ) + } +} + +class PruningDatabase implements Database { + readonly family: DatabaseFamily + readonly schemaIdentity: string + readonly candidatePages: CandidatePage[] = [] + private beforeFirstDelete: BeforeDelete | undefined + + constructor( + private readonly database: Database, + beforeFirstDelete?: BeforeDelete, + ) { + this.family = database.family + this.schemaIdentity = database.schemaIdentity + this.beforeFirstDelete = beforeFirstDelete + } + + connection( + callback: (connection: DatabaseConnection) => Promise, + ): Promise { + return this.database.connection((connection) => callback(this.recordingConnection(connection))) + } + + transaction( + callback: (connection: DatabaseConnection) => Promise, + options?: DatabaseTransactionOptions, + ): Promise { + return this.database.transaction( + (connection) => callback(this.recordingConnection(connection)), + options, + ) + } + + transactionActive(): boolean { + return this.database.transactionActive?.() ?? false + } + + close(): Promise { + return this.database.close() + } + + private recordingConnection(connection: DatabaseConnection): DatabaseConnection { + return { + run: async (sql, parameters) => { + await this.runBeforeFirstDelete({ connection, sql }) + return connection.run(sql, parameters) + }, + get: (sql, parameters) => connection.get(sql, parameters), + all: async (sql: string, parameters?: readonly unknown[]) => { + const rows = await connection.all(sql, parameters) + if (!sql.startsWith(`SELECT id FROM ${table("messages")} WHERE`)) return rows + this.candidatePages.push({ + sql, + parameters: [...(parameters ?? [])], + ids: rows.map((row) => String((row as { id: unknown }).id)), + }) + return rows + }, + nowMilliseconds: () => connection.nowMilliseconds(), + } + } + + private async runBeforeFirstDelete(options: { + connection: DatabaseConnection + sql: string + }): Promise { + const hook = this.beforeFirstDelete + if (hook === undefined) return + if (!options.sql.trimStart().startsWith(`DELETE FROM ${table("messages")}`)) return + this.beforeFirstDelete = undefined + await hook(options.connection, this.candidatePages.at(-1)?.ids ?? []) + } +}