diff --git a/.changeset/31908-p4b3-audit-seal-lock.md b/.changeset/31908-p4b3-audit-seal-lock.md new file mode 100644 index 00000000000..092faaa6c9b --- /dev/null +++ b/.changeset/31908-p4b3-audit-seal-lock.md @@ -0,0 +1,24 @@ +--- +'@objectstack/plugin-audit': patch +'@objectstack/objectql': patch +'@objectstack/cli': patch +--- + +feat(plugin-audit, cli)!: an `os migrate audit-* --apply` run holds the audit seal lock for its whole run, each sealer pass skips while it is held, and where the database offers no session lock a run on a sealed object needs `--sealer-stopped` + +Clause-②: yes (narrowing) — narrowed: `os migrate audit-key-material`, `os migrate audit-mail-bodies` and `os migrate audit-metadata-bodies` with `--apply` now refuse a run that rewrites an object declaring `lifecycle.seal` when that object's database offers no session lock (SQLite, Turso) unless `--sealer-stopped` is passed, and on Postgres or MySQL refuse when a sealer pass or another run still holds the audit seal lock after ten minutes; 18.4.0 ran both. `os migrate audit-side-copies`, new in this release, holds the lock and takes the flag from its first release. Widened: the `--sealer-stopped` flag, and new exports — `@objectstack/objectql` `acquireDatabaseSessionLock`, `tryDatabaseSessionLock`, `databaseSessionLockPgKey` and the types `DatabaseSessionLock`, `DatabaseSessionLockRunOptions`, `DatabaseSessionLockWait`; `@objectstack/plugin-audit` `holdAuditSealLock`, `AUDIT_SEAL_LOCK_NAME`, `AUDIT_SEAL_LOCK_WAIT_MS`, `STORED_METADATA_BODY_REWRITTEN_OBJECTS` and the types `AuditSealLockEngine`, `AuditSealLockFinish`, `AuditSealLockHold`. +Metadata-protocol: none + + + +**BREAKING** for an `os migrate audit-* --apply` run on a deployment where an app declared `lifecycle.seal`. On SQLite or Turso the run now stops before writing anything and names the flag: stop every server that seals the database, then re-run with `--sealer-stopped`. On Postgres or MySQL the run waits up to ten minutes for a sealer pass in flight, then refuses, having changed nothing: run it again once that pass has finished. A run that rewrites no sealed object is unchanged on every database, and so is every dry run. No object declares `lifecycle.seal` by default, so a deployment that did not opt in sees no change. + +**The audit seal lock (ADR-0154 D3, as amended 2026-11-14).** A sealer pass and an `os migrate audit-*` rewrite no longer work on a sealed object at the same time. That race let a pass seal a row's old value while the rewrite redacted it, and `os audit verify` then reported the sanctioned redaction as a modified row. The lock is a database session lock named `objectstack:audit-seal`, a Postgres advisory lock or a MySQL `GET_LOCK` on a connection of its own, taken on the database that holds each sealed object's rows (its hot store, where that differs from the primary database). + +- Each sealer pass takes it beside the cluster lock `audit.sealer`. While another session holds it, the pass seals nothing and says so at `info`, once an hour while it lasts; the next pass tries again. A checkpoint is written only while both locks still stand: a lock whose database session ended fails the object's pass, and the seed it had sealed is dropped. +- An `--apply` rewrite (`os migrate audit-key-material`, `audit-mail-bodies`, `audit-metadata-bodies` and `audit-side-copies`) holds it from before its first write to after its last, archive runs included. A run whose lock's database session ended before it finished says so, names `os audit verify`, and exits non-zero. +- Two replicas with no cluster service now also keep their passes apart through this lock on Postgres and MySQL. +- Two datasources that reach one lock namespace — one Postgres database, or two schemas of one MySQL server — share one lock: a pass or a run takes it once there and never waits on itself. +- On MySQL, lock names are server-wide: a rewrite on one database of a server makes the sealer of another database on that server skip its passes while it runs. + +**`@objectstack/objectql`.** The schema-migration lock and the audit seal lock share one implementation of a named database session lock, now exported: `acquireDatabaseSessionLock` (wait, then refuse), `tryDatabaseSessionLock` (once, never waiting: the lock, `'held'`, or `null` where the database offers none) and `databaseSessionLockPgKey`. A held lock's `isHeld()` asks its own session whether it still stands. With `ownLocks` (`DatabaseSessionLockRunOptions`), a run that locks several datasources marks each session it opens, and a lock it finds held by one of its own sessions in the same database answers that lock instead of `'held'` or a wait. `acquireSchemaMigrationLock` takes the same statements, prints the same lines and refuses with the same message as before. diff --git a/packages/cli/src/commands/migrate/audit-key-material.ts b/packages/cli/src/commands/migrate/audit-key-material.ts index a9f8b6e110d..7d1da6d7dc0 100644 --- a/packages/cli/src/commands/migrate/audit-key-material.ts +++ b/packages/cli/src/commands/migrate/audit-key-material.ts @@ -24,6 +24,7 @@ import { absentTableReads } from '../../utils/absent-table-reads.js'; import { exitOneShotCommand } from '../../utils/one-shot-exit.js'; import { archiveFailureCount, examineArchiveTargets } from '../../utils/ledger-copy-archive.js'; import { composeRedactionSeal } from '../../utils/audit-redaction-seal.js'; +import { sealerStoppedFlag, underAuditSealLock } from '../../utils/audit-seal-lock.js'; async function confirm(question: string): Promise { if (!process.stdin.isTTY) return false; // non-interactive → require --yes @@ -103,6 +104,7 @@ export default class MigrateAuditKeyMaterial extends Command { default: false, }), json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }), + 'sealer-stopped': sealerStoppedFlag, }; /** @@ -227,24 +229,33 @@ export default class MigrateAuditKeyMaterial extends Command { }; const seal = redaction.seal(stack.kernel, engine); - const report = await migrateKeyMaterialCopies(readView, logger, { apply, seal }); - - // Each copy table's declared archive target, then the same rewrite - // through that datasource's driver. - const archive = await examineArchiveTargets({ + // [ADR-0154 D3 amended] An --apply run holds the audit seal lock from before its first rewrite to after its + // last, archive runs included, so no sealer pass seals a row it rewrites; where the database offers no session + // lock, a run on a sealed object needs --sealer-stopped (seat ruling 6885005594, E + B). + const { result: { report, archive }, lostLock } = await underAuditSealLock( engine, - kernel: stack.kernel, - reads: readView, - tables: KEY_MATERIAL_COPY_TABLES, - run: (driver, objects) => migrateArchivedKeyMaterialCopies(driver, logger, { apply, objects, seal }), - }); + { apply, sealerStopped: flags['sealer-stopped'], objects: KEY_MATERIAL_COPY_TABLES, warn: (line) => logger.warn(line) }, + async () => { + const report = await migrateKeyMaterialCopies(readView, logger, { apply, seal }); + // Each copy table's declared archive target, then the same rewrite + // through that datasource's driver. + const archive = await examineArchiveTargets({ + engine, + kernel: stack.kernel, + reads: readView, + tables: KEY_MATERIAL_COPY_TABLES, + run: (driver, objects) => migrateArchivedKeyMaterialCopies(driver, logger, { apply, objects, seal }), + }); + return { report, archive }; + }, + ); const failures = report.failures + archiveFailureCount(archive); const refused = report.refused + archive.reduce((n, a) => n + (a.report?.refused ?? 0), 0); if (flags.json) { reads.notice(true); - await emitJson({ database: stack.dbLabel, apply, report, archive, duration: timer.elapsed() }); - if (failures > 0 || refused > 0) this.exit(1); + await emitJson({ database: stack.dbLabel, apply, report, archive, ...(lostLock ? { sealLockLost: lostLock } : {}), duration: timer.elapsed() }); + if (failures > 0 || refused > 0 || lostLock) this.exit(1); return; } @@ -299,6 +310,7 @@ export default class MigrateAuditKeyMaterial extends Command { const rewritten = report.rewritten + archive.reduce((n, a) => n + (a.report?.rewritten ?? 0), 0); if (refused > 0) printError(redaction.refusedLine(refused)); + if (lostLock) printError(lostLock); if (failures > 0) { printError(`${failures} read(s), row(s) or archive datasource(s) failed — re-run to finish them.`); } else if (apply && rewritten > 0) { @@ -312,7 +324,7 @@ export default class MigrateAuditKeyMaterial extends Command { } console.log(chalk.dim(` ${timer.display()}`)); console.log(''); - if (failures > 0 || refused > 0) this.exit(1); + if (failures > 0 || refused > 0 || lostLock) this.exit(1); } catch (error: any) { if (isExitSignal(error)) throw error; if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); } diff --git a/packages/cli/src/commands/migrate/audit-mail-bodies.ts b/packages/cli/src/commands/migrate/audit-mail-bodies.ts index 318e57ca1c0..1a7a5a19f98 100644 --- a/packages/cli/src/commands/migrate/audit-mail-bodies.ts +++ b/packages/cli/src/commands/migrate/audit-mail-bodies.ts @@ -24,6 +24,7 @@ import { absentTableReads } from '../../utils/absent-table-reads.js'; import { exitOneShotCommand } from '../../utils/one-shot-exit.js'; import { archiveFailureCount, examineArchiveTargets } from '../../utils/ledger-copy-archive.js'; import { composeRedactionSeal } from '../../utils/audit-redaction-seal.js'; +import { sealerStoppedFlag, underAuditSealLock } from '../../utils/audit-seal-lock.js'; async function confirm(question: string): Promise { if (!process.stdin.isTTY) return false; // non-interactive → require --yes @@ -110,6 +111,7 @@ export default class MigrateAuditMailBodies extends Command { default: false, }), json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }), + 'sealer-stopped': sealerStoppedFlag, }; /** @@ -235,25 +237,34 @@ export default class MigrateAuditMailBodies extends Command { }; const seal = redaction.seal(stack.kernel, engine); - const report = await migrateMailLogBodyCopies(readView, logger, { apply, seal }); - - // [#24899] Each copy table's declared archive target, then the same - // runner through that datasource's driver (`examineArchiveTargets`). - const archive = await examineArchiveTargets({ + // [ADR-0154 D3 amended] An --apply run holds the audit seal lock from before its first rewrite to after its + // last, archive runs included, so no sealer pass seals a row it rewrites; where the database offers no session + // lock, a run on a sealed object needs --sealer-stopped (seat ruling 6885005594, E + B). + const { result: { report, archive }, lostLock } = await underAuditSealLock( engine, - kernel: stack.kernel, - reads: readView, - tables: MAIL_LOG_BODY_COPY_OBJECTS, - run: (driver, objects) => migrateArchivedMailLogBodyCopies(driver, logger, { apply, objects, seal }), - }); + { apply, sealerStopped: flags['sealer-stopped'], objects: MAIL_LOG_BODY_COPY_OBJECTS, warn: (line) => logger.warn(line) }, + async () => { + const report = await migrateMailLogBodyCopies(readView, logger, { apply, seal }); + // [#24899] Each copy table's declared archive target, then the same + // runner through that datasource's driver (`examineArchiveTargets`). + const archive = await examineArchiveTargets({ + engine, + kernel: stack.kernel, + reads: readView, + tables: MAIL_LOG_BODY_COPY_OBJECTS, + run: (driver, objects) => migrateArchivedMailLogBodyCopies(driver, logger, { apply, objects, seal }), + }); + return { report, archive }; + }, + ); const archiveFailures = archiveFailureCount(archive); const failures = report.failures + archiveFailures; const refused = report.refused + archive.reduce((n, a) => n + (a.report?.refused ?? 0), 0); if (flags.json) { reads.notice(true); - await emitJson({ database: stack.dbLabel, apply, report, archive, duration: timer.elapsed() }); - if (failures > 0 || refused > 0) this.exit(1); + await emitJson({ database: stack.dbLabel, apply, report, archive, ...(lostLock ? { sealLockLost: lostLock } : {}), duration: timer.elapsed() }); + if (failures > 0 || refused > 0 || lostLock) this.exit(1); return; } @@ -308,6 +319,7 @@ export default class MigrateAuditMailBodies extends Command { const rewritten = report.rewritten + archive.reduce((n, a) => n + (a.report?.rewritten ?? 0), 0); if (refused > 0) printError(redaction.refusedLine(refused)); + if (lostLock) printError(lostLock); if (failures > 0) { printError(`${failures} read(s), row(s) or archive datasource(s) failed — re-run to finish them.`); } else if (apply && rewritten > 0) { @@ -321,7 +333,7 @@ export default class MigrateAuditMailBodies extends Command { } console.log(chalk.dim(` ${timer.display()}`)); console.log(''); - if (failures > 0 || refused > 0) this.exit(1); + if (failures > 0 || refused > 0 || lostLock) this.exit(1); } catch (error: any) { if (isExitSignal(error)) throw error; if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); } diff --git a/packages/cli/src/commands/migrate/audit-metadata-bodies.ts b/packages/cli/src/commands/migrate/audit-metadata-bodies.ts index 0ce7034f43c..32cf4f063f8 100644 --- a/packages/cli/src/commands/migrate/audit-metadata-bodies.ts +++ b/packages/cli/src/commands/migrate/audit-metadata-bodies.ts @@ -22,6 +22,7 @@ import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite- import { buildDataMigrationPlugins } from '../../utils/data-migration-plugins.js'; import { absentTableReads } from '../../utils/absent-table-reads.js'; import { composeRedactionSeal } from '../../utils/audit-redaction-seal.js'; +import { sealerStoppedFlag, underAuditSealLock } from '../../utils/audit-seal-lock.js'; async function confirm(question: string): Promise { if (!process.stdin.isTTY) return false; // non-interactive → require --yes @@ -88,6 +89,7 @@ export default class MigrateAuditMetadataBodies extends Command { default: false, }), json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }), + 'sealer-stopped': sealerStoppedFlag, }; async run(): Promise { @@ -177,7 +179,7 @@ export default class MigrateAuditMetadataBodies extends Command { throw new Error('No ObjectQL engine on this stack — cannot rewrite audit rows.'); } - const { migrateStoredMetadataBodyCopies } = await import('@objectstack/plugin-audit'); + const { migrateStoredMetadataBodyCopies, STORED_METADATA_BODY_REWRITTEN_OBJECTS } = await import('@objectstack/plugin-audit'); const logger = flags.json ? { info: (m: string) => console.error(m), warn: (m: string) => console.error(m) } @@ -207,12 +209,20 @@ export default class MigrateAuditMetadataBodies extends Command { update: (object, data, options) => engine.update(object, data, options), }; - const report = await migrateStoredMetadataBodyCopies(readView, logger, { apply, seal: redaction.seal(stack.kernel, engine) }); + const seal = redaction.seal(stack.kernel, engine); + // [ADR-0154 D3 amended] An --apply run holds the audit seal lock from before its first rewrite to after its + // last, archive runs included, so no sealer pass seals a row it rewrites; where the database offers no session + // lock, a run on a sealed object needs --sealer-stopped (seat ruling 6885005594, E + B). + const { result: report, lostLock } = await underAuditSealLock( + engine, + { apply, sealerStopped: flags['sealer-stopped'], objects: STORED_METADATA_BODY_REWRITTEN_OBJECTS, warn: (line) => logger.warn(line) }, + () => migrateStoredMetadataBodyCopies(readView, logger, { apply, seal }), + ); if (flags.json) { reads.notice(true); - await emitJson({ database: stack.dbLabel, apply, report, duration: timer.elapsed() }); - if (report.failures > 0 || report.refused > 0) this.exit(1); + await emitJson({ database: stack.dbLabel, apply, report, ...(lostLock ? { sealLockLost: lostLock } : {}), duration: timer.elapsed() }); + if (report.failures > 0 || report.refused > 0 || lostLock) this.exit(1); return; } @@ -228,6 +238,7 @@ export default class MigrateAuditMetadataBodies extends Command { console.log(''); if (report.refused > 0) printError(redaction.refusedLine(report.refused)); + if (lostLock) printError(lostLock); if (report.failures > 0) { printError(`${report.failures} row(s) could not be rewritten — re-run to finish them.`); } else if (apply && report.rewritten > 0) { @@ -243,7 +254,7 @@ export default class MigrateAuditMetadataBodies extends Command { } console.log(chalk.dim(` ${timer.display()}`)); console.log(''); - if (report.failures > 0 || report.refused > 0) this.exit(1); + if (report.failures > 0 || report.refused > 0 || lostLock) this.exit(1); } catch (error: any) { if (isExitSignal(error)) throw error; if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); } diff --git a/packages/cli/src/commands/migrate/audit-redaction-seal.contract.test.ts b/packages/cli/src/commands/migrate/audit-redaction-seal.contract.test.ts index 52f33f6bb9b..4bc10a8535a 100644 --- a/packages/cli/src/commands/migrate/audit-redaction-seal.contract.test.ts +++ b/packages/cli/src/commands/migrate/audit-redaction-seal.contract.test.ts @@ -9,6 +9,13 @@ // is an EDIT that drops the option from one call, which reads as a run that // rewrites a sealed row unamended. A source scan, comments masked, as // `../serve-audit-registration.contract.test.ts` reads `serve.ts`. +// +// [ADR-0154 D3 amended, seat ruling 6885005594] And every rewrite run sits +// inside the one `underAuditSealLock` call, which holds the audit seal lock for +// an `--apply` run's whole length, on the objects the command rewrites, with the +// operator's `--sealer-stopped`. What the hold does is pinned in plugin-audit +// (`audit-seal/audit-seal-lock.test.ts`); here, an EDIT that moves a run out of +// the hold, or drops the flag, reads as a run a sealer pass can seal under. import { describe, expect, it } from 'vitest'; import { readFileSync } from 'node:fs'; @@ -26,6 +33,18 @@ const COMMANDS: Record = { 'audit-metadata-bodies.ts': ['migrateStoredMetadataBodyCopies'], }; +/** + * Each command's list of the objects it rewrites, as plugin-audit exports it — + * or, for `audit-side-copies`, the run's selection of `SIDE_COPY_TABLES` + * (`--object` narrows it), the same list its hot and archive runs are handed. + */ +const REWRITTEN: Record = { + 'audit-mail-bodies.ts': 'MAIL_LOG_BODY_COPY_OBJECTS', + 'audit-key-material.ts': 'KEY_MATERIAL_COPY_TABLES', + 'audit-side-copies.ts': 'objects', + 'audit-metadata-bodies.ts': 'STORED_METADATA_BODY_REWRITTEN_OBJECTS', +}; + /** The argument text of every `name(` call in `source`, parentheses walked. */ function calls(source: string, name: string): string[] { const found: string[] = []; @@ -59,8 +78,22 @@ describe('os migrate audit-* amend a sealed row first (ADR-0154 D7)', () => { } }); - it(`${file}: exits non-zero when a sealed row was refused, as for a failure`, () => { - expect(source.match(/failures > 0 \|\| (report\.)?refused > 0\) this\.exit\(1\)/g)).toHaveLength(2); + it(`${file}: exits non-zero when a sealed row was refused, or the seal lock was lost, as for a failure`, () => { + expect(source.match(/failures > 0 \|\| (report\.)?refused > 0 \|\| lostLock\) this\.exit\(1\)/g)).toHaveLength(2); + }); + + it(`${file}: declares --sealer-stopped, the one shared flag (D3 amended, B)`, () => { + expect(source).toMatch(/'sealer-stopped': sealerStoppedFlag,/); + }); + + it(`${file}: runs every rewrite inside one hold of the audit seal lock, on its objects, with the flag (D3 amended, E)`, () => { + const holds = calls(source, 'underAuditSealLock'); + expect(holds).toHaveLength(1); + const [hold] = holds; + // The warn channel is called through its receiver (`check:logger-receiver-detach`), never handed on bare. + expect(hold).toMatch(/\{ apply, sealerStopped: flags\['sealer-stopped'\], objects: (\w+), warn: \(line\) => logger\.warn\(line\) \}/); + expect(/objects: (\w+)/.exec(hold)?.[1]).toBe(REWRITTEN[file]); + for (const run of runs) expect(calls(hold, run), run).toHaveLength(1); }); } }); diff --git a/packages/cli/src/commands/migrate/audit-side-copies.ts b/packages/cli/src/commands/migrate/audit-side-copies.ts index 9b5c5468855..80f79f0b8eb 100644 --- a/packages/cli/src/commands/migrate/audit-side-copies.ts +++ b/packages/cli/src/commands/migrate/audit-side-copies.ts @@ -24,6 +24,7 @@ import { absentTableReads } from '../../utils/absent-table-reads.js'; import { exitOneShotCommand } from '../../utils/one-shot-exit.js'; import { archiveFailureCount, examineArchiveTargets } from '../../utils/ledger-copy-archive.js'; import { composeRedactionSeal } from '../../utils/audit-redaction-seal.js'; +import { sealerStoppedFlag, underAuditSealLock } from '../../utils/audit-seal-lock.js'; import { objectNotFoundError } from '@objectstack/core'; async function confirm(question: string): Promise { @@ -110,6 +111,7 @@ export default class MigrateAuditSideCopies extends Command { multiple: true, }), json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }), + 'sealer-stopped': sealerStoppedFlag, }; /** @@ -253,24 +255,34 @@ export default class MigrateAuditSideCopies extends Command { }; const seal = redaction.seal(stack.kernel, engine); - const report = await migrateSideCopies(readView, logger, { apply, objects, seal }); - - // Each copy table's declared archive target, then the same rewrite - // through that datasource's driver. - const archive = await examineArchiveTargets({ + // [ADR-0154 D3 amended] An --apply run holds the audit seal lock from before its first rewrite to after its + // last, archive runs included, on the copy tables it rewrites (`--object` narrows them), so no sealer pass + // seals a row it rewrites; where the database offers no session lock, a run on a sealed object needs + // --sealer-stopped (seat ruling 6885005594, E + B), as for its twins. + const { result: { report, archive }, lostLock } = await underAuditSealLock( engine, - kernel: stack.kernel, - reads: readView, - tables: objects, - run: (driver, archived) => migrateArchivedSideCopies(driver, logger, { apply, objects: archived, seal }), - }); + { apply, sealerStopped: flags['sealer-stopped'], objects: objects, warn: (line) => logger.warn(line) }, + async () => { + const report = await migrateSideCopies(readView, logger, { apply, objects, seal }); + // Each copy table's declared archive target, then the same rewrite + // through that datasource's driver. + const archive = await examineArchiveTargets({ + engine, + kernel: stack.kernel, + reads: readView, + tables: objects, + run: (driver, archived) => migrateArchivedSideCopies(driver, logger, { apply, objects: archived, seal }), + }); + return { report, archive }; + }, + ); const failures = report.failures + archiveFailureCount(archive); const refused = report.refused + archive.reduce((n, a) => n + (a.report?.refused ?? 0), 0); if (flags.json) { reads.notice(true); - await emitJson({ database: stack.dbLabel, apply, objects, report, archive, duration: timer.elapsed() }); - if (failures > 0 || refused > 0) this.exit(1); + await emitJson({ database: stack.dbLabel, apply, objects, report, archive, ...(lostLock ? { sealLockLost: lostLock } : {}), duration: timer.elapsed() }); + if (failures > 0 || refused > 0 || lostLock) this.exit(1); return; } @@ -325,6 +337,7 @@ export default class MigrateAuditSideCopies extends Command { const rewritten = report.rewritten + archive.reduce((n, a) => n + (a.report?.rewritten ?? 0), 0); if (refused > 0) printError(redaction.refusedLine(refused)); + if (lostLock) printError(lostLock); if (failures > 0) { printError(`${failures} read(s), row(s) or archive datasource(s) failed — re-run to finish them.`); } else if (apply && rewritten > 0) { @@ -338,7 +351,7 @@ export default class MigrateAuditSideCopies extends Command { } console.log(chalk.dim(` ${timer.display()}`)); console.log(''); - if (failures > 0 || refused > 0) this.exit(1); + if (failures > 0 || refused > 0 || lostLock) this.exit(1); } catch (error: any) { if (isExitSignal(error)) throw error; if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); } diff --git a/packages/cli/src/utils/audit-seal-lock.ts b/packages/cli/src/utils/audit-seal-lock.ts new file mode 100644 index 00000000000..4e9b93d9875 --- /dev/null +++ b/packages/cli/src/utils/audit-seal-lock.ts @@ -0,0 +1,65 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { Flags } from '@oclif/core'; +import type { AuditSealLockEngine, AuditSealLockFinish } from '@objectstack/plugin-audit'; + +/** + * [ADR-0154 D3 as amended, seat ruling 6885005594] What an `os migrate audit-*` + * ledger-copy rewrite holds so that no sealer pass seals a row while it + * rewrites it: the audit seal lock (`holdAuditSealLock` in + * `@objectstack/plugin-audit`), from before the run's first write to after its + * last, its archive runs included. + * + * - E: on Postgres and MySQL the `--apply` run takes the lock on the database + * of each sealed object it rewrites, waits for a sealer pass in flight, and + * refuses when the wait runs out, having changed nothing. + * - B: where that database offers no session lock (SQLite, Turso), an + * `--apply` run that rewrites a sealed object is refused unless the operator + * passes {@link sealerStoppedFlag}, and with it says on whose word it runs. + * + * A dry run writes nothing and takes nothing. A run whose lock's session ended + * before it finished is told so ({@link AuditSealLockRun.lostLock}), and the + * command prints that line and exits non-zero. + */ + +/** `--sealer-stopped`: the operator's word that no server seals the database while the run lasts (B). */ +export const sealerStoppedFlag = Flags.boolean({ + description: + 'With --apply on a database that offers no session lock (SQLite, Turso): rewrite objects declaring ' + + 'lifecycle.seal anyway, on your word that every server sealing this database is stopped. Postgres and MySQL ' + + 'take the audit seal lock instead.', + default: false, +}); + +export interface AuditSealLockRun { + readonly result: T; + /** The line to print, and exit non-zero on, when the lock's session ended before the run finished; else `null`. */ + readonly lostLock: string | null; +} + +/** + * Run `rewrite` under the audit seal lock when `apply`; a dry run runs it bare. + * A refusal (contention past the wait, or B without `sealerStopped`) is thrown + * before `rewrite` starts. + */ +export async function underAuditSealLock( + engine: unknown, + options: { apply: boolean; sealerStopped: boolean; objects: readonly string[]; warn(line: string): void }, + rewrite: () => Promise, +): Promise> { + if (!options.apply) return { result: await rewrite(), lostLock: null }; + const { holdAuditSealLock } = await import('@objectstack/plugin-audit'); + const hold = await holdAuditSealLock(engine as AuditSealLockEngine, { + objects: options.objects, + sealerStopped: options.sealerStopped, + warn: options.warn, + }); + let finished: AuditSealLockFinish | undefined; + try { + const result = await rewrite(); + finished = await hold.finish(); + return { result, lostLock: finished.lost ? finished.line : null }; + } finally { + if (!finished) await hold.finish(); + } +} diff --git a/packages/objectql/src/database-session-lock.test.ts b/packages/objectql/src/database-session-lock.test.ts new file mode 100644 index 00000000000..a3eae65407a --- /dev/null +++ b/packages/objectql/src/database-session-lock.test.ts @@ -0,0 +1,237 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The database session lock both named locks ride on + * (`database-session-lock.ts`): the schema-migration lock, and the audit seal + * lock of ADR-0154 D3 as amended (seat ruling 6885005594, E). What the + * schema-migration lock's own pins do not reach: a lock of ANOTHER name, the + * try-once form a sealer pass takes (no wait, never a line), and the probe a + * holder asks whether its session — and so its lock — still stands. + * + * Every statement runs against a fake Knex at the seams a real database cannot + * stage on demand; two sessions on one live Postgres are the CLI's live file. + */ + +import { describe, expect, it, vi } from 'vitest'; +import { createHash } from 'node:crypto'; +import { + acquireDatabaseSessionLock, + databaseSessionLockPgKey, + tryDatabaseSessionLock, +} from './database-session-lock.js'; +import { SCHEMA_MIGRATION_LOCK_NAME, SCHEMA_MIGRATION_PG_LOCK_KEY } from './schema-migration-lock.js'; + +interface Statement { + sql: string; + bindings: readonly unknown[]; + connection: unknown; +} + +/** A driver whose knex records every statement and the session it ran on, answered by `answer`. */ +function fakeDriver(dialect: string, answer: (sql: string, bindings: readonly unknown[]) => unknown) { + const statements: Statement[] = []; + const connection = { id: 'raw-1' }; + const opened: unknown[] = []; + const destroyed: unknown[] = []; + const shape = (row: unknown) => (dialect === 'mysql' ? [[row], []] : { rows: [row] }); + const knex = { + client: { + acquireRawConnection: vi.fn(async () => { opened.push(connection); return connection; }), + destroyRawConnection: vi.fn(async (c: unknown) => { destroyed.push(c); }), + }, + raw: (sql: string, bindings: readonly unknown[] = []) => ({ + connection: async (c: unknown) => { + statements.push({ sql, bindings, connection: c }); + const out = answer(sql, bindings); + if (out instanceof Error) throw out; + return shape(out); + }, + }), + }; + const getKnex = vi.fn(() => knex); + return { driver: { dialectName: dialect, getKnex }, getKnex, statements, opened, destroyed, connection }; +} + +const NAME = 'objectstack:probe-lock'; +const KEY = databaseSessionLockPgKey(NAME); + +describe('the Postgres key of a named lock', () => { + it('is the derivation the schema-migration lock was pinned to: the first 8 bytes of SHA-256, signed 64-bit', () => { + expect(databaseSessionLockPgKey(SCHEMA_MIGRATION_LOCK_NAME)).toBe(SCHEMA_MIGRATION_PG_LOCK_KEY); + const hex = createHash('sha256').update(NAME).digest('hex').slice(0, 16); + expect(KEY).toBe(BigInt.asIntN(64, BigInt(`0x${hex}`)).toString()); + expect(KEY).not.toBe(SCHEMA_MIGRATION_PG_LOCK_KEY); + }); +}); + +describe('tryDatabaseSessionLock: once, never waiting, never a line', () => { + it.each(['sqlite', 'mssql', 'unknown'])('dialectName %s: null, Knex never asked for, no session opened', async (dialect) => { + const f = fakeDriver(dialect, () => ({})); + await expect(tryDatabaseSessionLock(f.driver, NAME)).resolves.toBeNull(); + expect(f.getKnex).not.toHaveBeenCalled(); + expect(f.opened).toEqual([]); + }); + + it('Postgres, free: one try-lock under the name\'s own key, on a session of its own', async () => { + const f = fakeDriver('postgres', () => ({ locked: true })); + const lock = await tryDatabaseSessionLock(f.driver, NAME); + expect(lock).not.toBeNull(); + expect(lock).not.toBe('held'); + expect(f.statements.map((s) => [s.sql, s.bindings])).toEqual([['select pg_try_advisory_lock(?::bigint) as locked', [KEY]]]); + expect(f.statements[0].connection).toBe(f.connection); + expect(f.destroyed).toEqual([]); + }); + + it('Postgres, held by another session: answers "held", issues no wait, and closes its session', async () => { + const f = fakeDriver('postgres', () => ({ locked: false })); + await expect(tryDatabaseSessionLock(f.driver, NAME)).resolves.toBe('held'); + expect(f.statements.map((s) => s.sql)).toEqual(['select pg_try_advisory_lock(?::bigint) as locked']); + expect(f.destroyed).toEqual([f.connection]); + }); + + it('MySQL: GET_LOCK under the name with no wait; held answers "held"', async () => { + const free = fakeDriver('mysql', () => ({ locked: 1 })); + const lock = await tryDatabaseSessionLock(free.driver, NAME); + expect(lock).not.toBe('held'); + expect(free.statements.map((s) => [s.sql, s.bindings])).toEqual([['select GET_LOCK(?, 0) as locked', [NAME]]]); + const held = fakeDriver('mysql', () => ({ locked: 0 })); + await expect(tryDatabaseSessionLock(held.driver, NAME)).resolves.toBe('held'); + expect(held.destroyed).toEqual([held.connection]); + }); + + it('a failed try is handed on as it is, its session closed — never read as "free" or "held"', async () => { + const reset = Object.assign(new Error('connection reset'), { code: 'ECONNRESET' }); + const f = fakeDriver('postgres', () => reset); + await expect(tryDatabaseSessionLock(f.driver, NAME)).rejects.toBe(reset); + expect(f.destroyed).toEqual([f.connection]); + }); +}); + +describe('isHeld: a holder asks whether its session still stands', () => { + it('probes the SAME session the lock was taken on, and reads true while it answers', async () => { + const f = fakeDriver('postgres', () => ({ locked: true, held: 1 })); + const lock = await tryDatabaseSessionLock(f.driver, NAME); + if (lock === null || lock === 'held') throw new Error('expected a lock'); + await expect(lock.isHeld()).resolves.toBe(true); + expect(f.statements.map((s) => s.sql)).toEqual(['select pg_try_advisory_lock(?::bigint) as locked', 'select 1 as held']); + expect(new Set(f.statements.map((s) => s.connection))).toEqual(new Set([f.connection])); + }); + + it('reads false once the session is gone — the database released the lock with it — and never throws', async () => { + let ended = false; + const f = fakeDriver('postgres', (sql) => (sql === 'select 1 as held' && ended ? new Error('Connection terminated unexpectedly') : { locked: true, held: 1 })); + const lock = await tryDatabaseSessionLock(f.driver, NAME); + if (lock === null || lock === 'held') throw new Error('expected a lock'); + ended = true; + await expect(lock.isHeld()).resolves.toBe(false); + }); + + it('reads false after release, without a statement', async () => { + const f = fakeDriver('mysql', () => ({ locked: 1, held: 1 })); + const lock = await tryDatabaseSessionLock(f.driver, NAME); + if (lock === null || lock === 'held') throw new Error('expected a lock'); + await lock.release(); + const before = f.statements.length; + await expect(lock.isHeld()).resolves.toBe(false); + expect(f.statements).toHaveLength(before); + expect(f.statements.map((s) => s.sql)).toEqual(['select GET_LOCK(?, 0) as locked', 'select RELEASE_LOCK(?)']); + }); +}); + +describe('acquireDatabaseSessionLock: a lock of another name waits and refuses in its own words', () => { + it('contended: the caller\'s one wait line, then the bounded wait under the name\'s key', async () => { + const f = fakeDriver('postgres', (sql) => (sql.startsWith('select pg_try') ? { locked: false } : {})); + const onWait = vi.fn(); + const lock = await acquireDatabaseSessionLock(f.driver, { name: NAME, waitMs: 2_000, onWait, refuse: () => new Error('refused') }); + expect(lock).not.toBeNull(); + expect(onWait).toHaveBeenCalledTimes(1); + expect(f.statements.map((s) => [s.sql, s.bindings])).toEqual([ + ['select pg_try_advisory_lock(?::bigint) as locked', [KEY]], + ['set lock_timeout = 2000', []], + ['select pg_advisory_lock(?::bigint)', [KEY]], + ]); + }); + + it('⛔ a wait that runs out throws the caller\'s refusal and closes the session', async () => { + const timedOut = Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' }); + const f = fakeDriver('postgres', (sql) => (sql.startsWith('select pg_try') ? { locked: false } : sql.startsWith('select pg_advisory_lock') ? timedOut : {})); + const refusal = new Error('the caller\'s refusal'); + await expect(acquireDatabaseSessionLock(f.driver, { name: NAME, waitMs: 1_000, onWait: () => {}, refuse: () => refusal })).rejects.toBe(refusal); + expect(f.destroyed).toEqual([f.connection]); + }); + + it('MySQL: a wait that runs out throws the caller\'s refusal', async () => { + let tries = 0; + const f = fakeDriver('mysql', () => ({ locked: tries++ === 0 ? 0 : 0 })); + const refusal = new Error('refused'); + await expect(acquireDatabaseSessionLock(f.driver, { name: NAME, waitMs: 1_000, onWait: () => {}, refuse: () => refusal })).rejects.toBe(refusal); + expect(f.statements.map((s) => [s.sql, s.bindings])).toEqual([ + ['select GET_LOCK(?, 0) as locked', [NAME]], + ['select GET_LOCK(?, ?) as locked', [NAME, 1]], + ]); + }); +}); + +describe('ownLocks: a run that locks several datasources never contends with itself (review 6894679963 M1)', () => { + /** A key's `pg_locks` `classid` and `objid`: its high and low 32 bits, unsigned. */ + const halves = (key: string) => { + const unsigned = BigInt.asUintN(64, BigInt(key)); + return [(unsigned >> 32n).toString(), (unsigned & 0xffffffffn).toString()]; + }; + const SEEN_PG = /^select exists \(select 1 from pg_locks m join pg_locks l on l\.pid = m\.pid and l\.database = m\.database where /; + + it('without it, no marker: the schema-migration lock\'s statements are unchanged', async () => { + const f = fakeDriver('postgres', () => ({ locked: false })); + await expect(tryDatabaseSessionLock(f.driver, NAME)).resolves.toBe('held'); + expect(f.statements.map((s) => s.sql)).toEqual(['select pg_try_advisory_lock(?::bigint) as locked']); + }); + + it('Postgres: the run\'s session takes a marker of its own before the lock; a later session finding the lock held asks whether the marked session holds it in THIS database, and answers that lock', async () => { + const first = fakeDriver('postgres', (sql) => (sql.endsWith('as marked') ? { marked: true } : { locked: true })); + const own = await tryDatabaseSessionLock(first.driver, NAME, { ownLocks: [] }); + const [mark, lock] = first.statements; + expect([mark.sql, lock.sql]).toEqual(['select pg_try_advisory_lock(?::bigint) as marked', 'select pg_try_advisory_lock(?::bigint) as locked']); + const markerKey = String(mark.bindings[0]); + expect(markerKey).not.toBe(KEY); + + const second = fakeDriver('postgres', (sql) => (sql.endsWith('as marked') ? { marked: true } : SEEN_PG.test(sql) ? { seen: true } : { locked: false })); + await expect(tryDatabaseSessionLock(second.driver, NAME, { ownLocks: [own as never] })).resolves.toBe(own); + const seen = second.statements.find((s) => SEEN_PG.test(s.sql))!; + expect(seen.sql).toContain('m.database = (select oid from pg_database where datname = current_database())'); + expect(seen.bindings).toEqual([...halves(markerKey), ...halves(KEY)]); + expect(second.destroyed).toEqual([second.connection]); + }); + + it('⛔ a held lock the marked session does not hold is contention, as before: "held", and the wait for acquire', async () => { + const first = fakeDriver('postgres', (sql) => (sql.endsWith('as marked') ? { marked: true } : { locked: true })); + const own = await tryDatabaseSessionLock(first.driver, NAME, { ownLocks: [] }); + const other = fakeDriver('postgres', (sql) => (sql.endsWith('as marked') ? { marked: true } : SEEN_PG.test(sql) ? { seen: false } : { locked: false })); + await expect(tryDatabaseSessionLock(other.driver, NAME, { ownLocks: [own as never] })).resolves.toBe('held'); + const timedOut = Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' }); + const waiting = fakeDriver('postgres', (sql) => + sql.endsWith('as marked') ? { marked: true } : SEEN_PG.test(sql) ? { seen: false } : sql.startsWith('select pg_try') ? { locked: false } : sql.startsWith('select pg_advisory_lock') ? timedOut : {}); + const onWait = vi.fn(); + const refusal = new Error('refused'); + await expect(acquireDatabaseSessionLock(waiting.driver, { name: NAME, waitMs: 1_000, onWait, refuse: () => refusal, ownLocks: [own as never] })) + .rejects.toBe(refusal); + expect(onWait).toHaveBeenCalledTimes(1); + }); + + it('MySQL: the connection holding the run\'s marker holds the name, server-wide — acquire answers the run\'s lock with no wait and no line', async () => { + const first = fakeDriver('mysql', (sql) => (sql.endsWith('as marked') ? { marked: 1 } : { locked: 1 })); + const own = await tryDatabaseSessionLock(first.driver, NAME, { ownLocks: [] }); + const markerName = String(first.statements[0].bindings[0]); + expect(first.statements[0].sql).toBe('select GET_LOCK(?, 0) as marked'); + expect(markerName.length).toBeLessThanOrEqual(64); + const second = fakeDriver('mysql', (sql) => (sql.endsWith('as marked') ? { marked: 1 } : sql.endsWith('as seen') ? { seen: 1 } : { locked: 0 })); + const onWait = vi.fn(); + await expect(acquireDatabaseSessionLock(second.driver, { name: NAME, waitMs: 1_000, onWait, refuse: () => new Error('no'), ownLocks: [own as never] })) + .resolves.toBe(own); + expect(second.statements.map((s) => [s.sql, s.bindings]).slice(1)).toEqual([ + ['select GET_LOCK(?, 0) as locked', [NAME]], + ['select IS_USED_LOCK(?) = IS_USED_LOCK(?) as seen', [markerName, NAME]], + ]); + expect(onWait).not.toHaveBeenCalled(); + expect(second.destroyed).toEqual([second.connection]); + }); +}); diff --git a/packages/objectql/src/database-session-lock.ts b/packages/objectql/src/database-session-lock.ts new file mode 100644 index 00000000000..a1054e3af1c --- /dev/null +++ b/packages/objectql/src/database-session-lock.ts @@ -0,0 +1,336 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A named database session lock: a Postgres advisory lock or a MySQL + * `GET_LOCK`, on a connection of its own outside the driver's pool. Two named + * locks ride on it, each with its own name and key: + * + * - the schema-migration lock (`schema-migration-lock.ts`), one migrator per + * database at a time (#31598, #31715); + * - the audit seal lock (`@objectstack/plugin-audit`, ADR-0154 D3 as amended + * by seat ruling 6885005594), so a sealer pass and an + * `os migrate audit-* --apply` run never work on a sealed object at once. + * + * [ADR-0154 D3 amended] It lives HERE, below both callers, because the second + * lock follows the first one's pattern exactly and ⛔ the dialect statements + * are never copied: one module says how a session lock is taken, waited for, + * probed and released on each dialect, and each named lock says only its name, + * its wait and its words. + * + * Its own module, importing nothing but `node:crypto`, so the pins on it load + * the lock and not the engine around it. + */ +import { createHash, randomUUID } from 'node:crypto'; + +/** + * The Postgres advisory-lock key of a lock named `name`: the first 8 bytes of + * SHA-256 of the name, as the signed 64-bit integer `pg_advisory_lock(bigint)` + * takes. In `pg_locks` it appears with `locktype = 'advisory'`, its high 32 + * bits as `classid` and its low 32 as `objid`. A string, so no JavaScript + * number rounds it on the way to the bind. + * + * ⛔ Never derived from anything but the name: every version that takes a lock + * must take the SAME one, or an old and a new process run side by side. + */ +export function databaseSessionLockPgKey(name: string): string { + return BigInt.asIntN(64, BigInt(`0x${createHash('sha256').update(name).digest('hex').slice(0, 16)}`)).toString(); +} + +/** The slice of knex the lock uses, typed structurally. */ +interface LockKnex { + client: { + acquireRawConnection(): Promise; + destroyRawConnection(connection: unknown): Promise; + }; + raw(sql: string, bindings?: readonly unknown[]): { connection(connection: unknown): Promise }; +} + +/** A held database session lock. `release()` is idempotent and never throws. */ +export interface DatabaseSessionLock { + release(): Promise; + /** + * Whether the lock still stands: its session answers a probe on the very + * connection it was taken on. A session that ended — a dropped connection, + * a terminated backend — took the lock with it, so a probe that fails reads + * `false`, never throws. Always `false` after `release()`. + */ + isHeld(): Promise; +} + +/** + * The options of a lock that one run takes on several datasources under one + * name ({@link tryDatabaseSessionLock}, {@link acquireDatabaseSessionLock}). + */ +export interface DatabaseSessionLockRunOptions { + /** + * The locks of the same name this run already holds on other datasources, + * each taken with this option too. Passing it — empty for the run's first — + * marks the new session as the run's, so that a later lock of the run can + * tell it from another holder. + * + * Two datasources can reach one lock namespace: a Postgres advisory lock is + * database-wide and a MySQL `GET_LOCK` name server-wide, so two datasources + * on one Postgres database, or on two schemas of one MySQL server, share the + * lock while each opens its own session. Without this, the run's second + * session finds the lock held — by the run's first — and the run contends + * with itself for good. With it, a lock found held is first checked against + * these: when one of them holds it in the same namespace, the new session is + * closed and THAT lock is answered, the database already being under it. + * The check proves the namespace and never guesses it (see `heldAmong`), so + * a holder it cannot prove its own is contention, as before. + */ + readonly ownLocks?: readonly DatabaseSessionLock[]; +} + +/** + * The marker a session of a run holds beside its named lock: a second session + * lock under a name no other session can know. Seen held from another + * session, it proves that session shares the marked session's namespace. + */ +interface LockMarker { + readonly name: string; + readonly pgKey: string; +} + +/** The marker of each lock taken with {@link DatabaseSessionLockRunOptions.ownLocks}. */ +const markers = new WeakMap(); + +/** A Postgres key's `classid` and `objid` in `pg_locks`: its high and low 32 bits, unsigned. */ +function pgLockHalves(pgKey: string): [string, string] { + const unsigned = BigInt.asUintN(64, BigInt(pgKey)); + return [(unsigned >> 32n).toString(), (unsigned & 0xffffffffn).toString()]; +} + +/** + * Whether the session that holds a marker (its key's two halves, granted in + * the CURRENT database) also holds the named lock (its two halves) there. + */ +const PG_HELD_BY_MARKED = + 'select exists (select 1 from pg_locks m join pg_locks l on l.pid = m.pid and l.database = m.database ' + + "where m.locktype = 'advisory' and m.granted and m.objsubid = 1 " + + 'and m.database = (select oid from pg_database where datname = current_database()) ' + + 'and m.classid::bigint = ?::bigint and m.objid::bigint = ?::bigint ' + + "and l.locktype = 'advisory' and l.granted and l.objsubid = 1 " + + 'and l.classid::bigint = ?::bigint and l.objid::bigint = ?::bigint) as seen'; + +/** The same on MySQL, server-wide: the connection holding the marker holds the named lock (`NULL` when either is free). */ +const MYSQL_HELD_BY_MARKED = 'select IS_USED_LOCK(?) = IS_USED_LOCK(?) as seen'; + +/** The single row a lock statement answers, whichever client shaped the result. */ +function lockRow(result: unknown): Record | undefined { + // pg answers `{ rows }`; mysql2 answers `[rows, fields]`. + const rows = Array.isArray(result) ? result[0] : (result as { rows?: unknown } | null)?.rows; + return Array.isArray(rows) ? (rows[0] as Record | undefined) : undefined; +} + +/** A session opened for a lock named `name` on a Postgres or MySQL database. */ +interface LockSession { + readonly pg: boolean; + run(sql: string, bindings: readonly unknown[]): Promise | undefined>; + close(): Promise; + /** Try once, without waiting. */ + tryLock(): Promise; + /** + * Take this session's marker, BEFORE its named lock: a MySQL older than + * 5.7.5 keeps one `GET_LOCK` per session and lets the earlier go, so there + * the marker is the one dropped — the run then reads its own lock as + * contention, as without markers — and never the named lock. `null` when + * the marker could not be taken; the lock is then simply unmarked. + */ + mark(): Promise; + /** The lock of `own` whose session this session sees holding the named lock here: it already covers this namespace. */ + heldAmong(own: readonly DatabaseSessionLock[]): Promise; + held(marker: LockMarker | null): DatabaseSessionLock; +} + +/** + * Open a session for the lock named `name` on `driver`'s database, or `null` + * when the lock does not apply there. Postgres and MySQL, by the driver's + * `dialectName`; every other dialect, and a driver that names none, answers + * `null`, runs no statement and never asks the driver for its Knex — SQLite + * (and the Turso / WASM drivers on it) serializes writers in the database file + * itself. + * + * The session is a connection of its own, opened through the driver's own + * client (its configuration, credentials and TLS) but OUTSIDE its pool: both + * locks are session-scoped, so the lock and its release must run on one + * session, which a pool does not promise; a pooled connection idle past the + * pool's reaper would be closed and the lock released with it; and a pool of + * one would have none left for the work the lock guards. A session lock + * excludes every other session on the database, so the guarded work's own + * pooled connections are serialized by it all the same. + */ +async function openLockSession(driver: unknown, name: string): Promise { + // [#31715] The dialect is the driver's own answer (`SqlDriver#dialectName`, + // its one public "which SQL do I speak"), read BEFORE the driver is asked + // for its Knex: a face that refuses to hand out Knex (the Turso remote + // transport) throws from `getKnex()` rather than answering `undefined`, and + // a dialect this lock does not cover must never reach that call. A Postgres + // or MySQL driver whose Knex cannot be handed out still throws here, loudly. + const dialect = (driver as { dialectName?: unknown } | null)?.dialectName; + if (dialect !== 'postgres' && dialect !== 'mysql') return null; + const knex = (driver as { getKnex?: () => LockKnex }).getKnex?.(); + if (!knex) return null; + const pg = dialect === 'postgres'; + const pgKey = pg ? databaseSessionLockPgKey(name) : ''; + const connection = await knex.client.acquireRawConnection(); + const run = async (sql: string, bindings: readonly unknown[]): Promise | undefined> => + lockRow(await knex.raw(sql, bindings).connection(connection)); + const close = async (): Promise => { + try { await knex.client.destroyRawConnection(connection); } catch { /* closing releases the lock anyway */ } + }; + return { + pg, + run, + close, + async tryLock() { + const tried = pg + ? await run('select pg_try_advisory_lock(?::bigint) as locked', [pgKey]) + : await run('select GET_LOCK(?, 0) as locked', [name]); + return tried?.locked === true || Number(tried?.locked) === 1; + }, + async mark() { + // A name of its own per session, the same length every time (MySQL caps a name at 64 characters). + const marker = { name: `objectstack:lock-session:${randomUUID()}`, pgKey: '' }; + marker.pgKey = databaseSessionLockPgKey(marker.name); + const tried = pg + ? await run('select pg_try_advisory_lock(?::bigint) as marked', [marker.pgKey]) + : await run('select GET_LOCK(?, 0) as marked', [marker.name]); + return tried?.marked === true || Number(tried?.marked) === 1 ? marker : null; + }, + async heldAmong(own) { + // Exact, never a guess: the database itself answers that the session holding the named lock in + // THIS namespace holds the marker only `lock`'s session took — on Postgres in this database + // (`pg_locks` lists every database of the cluster), on MySQL on this server. Session ids are never + // compared across sessions of the run: two servers number their sessions alike. + for (const lock of own) { + const marker = markers.get(lock); + if (!marker) continue; + const seen = pg + ? await run(PG_HELD_BY_MARKED, [...pgLockHalves(marker.pgKey), ...pgLockHalves(pgKey)]) + : await run(MYSQL_HELD_BY_MARKED, [marker.name, name]); + if (seen?.seen === true || Number(seen?.seen) === 1) return lock; + } + return undefined; + }, + held(marker) { + let held = true; + const lock: DatabaseSessionLock = { + release: async () => { + if (!held) return; + held = false; + try { + if (pg) await run('select pg_advisory_unlock(?::bigint)', [pgKey]); + else await run('select RELEASE_LOCK(?)', [name]); + } catch { /* closing the session below releases it */ } + await close(); + }, + isHeld: async () => { + if (!held) return false; + try { + await run('select 1 as held', []); + return true; + } catch { + return false; + } + }, + }; + if (marker) markers.set(lock, marker); + return lock; + }, + }; +} + +/** + * Take the lock named `name` on `driver`'s database if it is free, once, + * never waiting and never printing: the lock, `'held'` when another session + * holds it (this session is closed again), or `null` when the database offers + * no session lock ({@link openLockSession}). With `options.ownLocks`, a lock + * found held by one of those in this database's namespace answers that lock + * ({@link DatabaseSessionLockRunOptions}). A statement that fails is handed + * on as it is, the session closed — never read as free or as held. + */ +export async function tryDatabaseSessionLock( + driver: unknown, + name: string, + options: DatabaseSessionLockRunOptions = {}, +): Promise { + const session = await openLockSession(driver, name); + if (!session) return null; + let marker: LockMarker | null = null; + let own: DatabaseSessionLock | undefined; + let locked: boolean; + try { + if (options.ownLocks) marker = await session.mark(); + locked = await session.tryLock(); + if (!locked && options.ownLocks) own = await session.heldAmong(options.ownLocks); + } catch (error) { + await session.close(); + throw error; + } + if (!locked) { + await session.close(); + return own ?? 'held'; + } + return session.held(marker); +} + +/** How a waiting lock speaks: its one wait line and its refusal are the caller's words. */ +export interface DatabaseSessionLockWait extends DatabaseSessionLockRunOptions { + /** The lock's name: MySQL's `GET_LOCK` name, and the source of its Postgres key. */ + readonly name: string; + /** How long to wait for another session to let go before refusing. */ + readonly waitMs: number; + /** Called once, when the lock is found held and the wait begins. */ + onWait(): void; + /** The error thrown when the wait runs out; this run then did nothing under the lock. */ + refuse(): Error; +} + +/** + * Take the lock named `wait.name` on `driver`'s database, waiting up to + * `wait.waitMs` for another session to let go, or `null` when the database + * offers no session lock ({@link openLockSession}). With `wait.ownLocks`, a + * lock found held by one of those in this database's namespace answers that + * lock at once, with no wait and no line ({@link DatabaseSessionLockRunOptions}). + * + * Uncontended, it is silent: one statement, no output. Contended, it calls + * `onWait` ONCE, then waits up to `waitMs` and throws `refuse()` on timeout. + * Any other failure is handed on as it is. Either way the session is closed. + */ +export async function acquireDatabaseSessionLock(driver: unknown, wait: DatabaseSessionLockWait): Promise { + const session = await openLockSession(driver, wait.name); + if (!session) return null; + const { pg, run } = session; + const { waitMs } = wait; + let marker: LockMarker | null = null; + try { + if (wait.ownLocks) marker = await session.mark(); + if (!(await session.tryLock())) { + const own = wait.ownLocks ? await session.heldAmong(wait.ownLocks) : undefined; + if (own) { + await session.close(); + return own; + } + wait.onWait(); + if (pg) { + await run(`set lock_timeout = ${Math.max(1, Math.trunc(waitMs))}`, []); + try { + await run('select pg_advisory_lock(?::bigint)', [databaseSessionLockPgKey(wait.name)]); + } catch (error) { + // 55P03 lock_not_available: `lock_timeout` ran out. + if ((error as { code?: unknown } | null)?.code === '55P03') throw wait.refuse(); + throw error; + } + } else { + // GET_LOCK answers 1 (taken), 0 (timed out) or NULL (an error). + const waited = await run('select GET_LOCK(?, ?) as locked', [wait.name, Math.max(1, Math.ceil(waitMs / 1000))]); + if (Number(waited?.locked) !== 1) throw wait.refuse(); + } + } + } catch (error) { + await session.close(); + throw error; + } + return session.held(marker); +} diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index fe7d449c9f2..d806a61819a 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -915,3 +915,12 @@ export { SCHEMA_MIGRATION_PG_LOCK_KEY, } from './schema-migration-lock.js'; export type { SchemaMigrationLock } from './schema-migration-lock.js'; +// [ADR-0154 D3 amended] The database session lock both named locks ride on: +// `@objectstack/plugin-audit`'s audit seal lock takes it under its own name, +// so a sealer pass and an `os migrate audit-* --apply` run exclude each other. +export { + acquireDatabaseSessionLock, + databaseSessionLockPgKey, + tryDatabaseSessionLock, +} from './database-session-lock.js'; +export type { DatabaseSessionLock, DatabaseSessionLockRunOptions, DatabaseSessionLockWait } from './database-session-lock.js'; diff --git a/packages/objectql/src/schema-migration-lock.ts b/packages/objectql/src/schema-migration-lock.ts index eb8701611b0..b99c406762a 100644 --- a/packages/objectql/src/schema-migration-lock.ts +++ b/packages/objectql/src/schema-migration-lock.ts @@ -12,10 +12,13 @@ * the lock; the CLI re-exports it from `utils/schema-migration-lock.ts`. One * module, one name, one key: ⛔ never a second copy. * - * Its own module, importing nothing but `node:crypto`, so the pins on it load - * the lock and not the migration stack around it. + * [ADR-0154 D3 amended] How a session lock is taken, waited for and released + * on each dialect is `database-session-lock.ts`'s, which the audit seal lock + * rides on too; this module says only this lock's name, key, wait and words. + * It imports nothing but that module, so the pins on it load the lock and not + * the migration stack around it. */ -import { createHash } from 'node:crypto'; +import { acquireDatabaseSessionLock, databaseSessionLockPgKey } from './database-session-lock.js'; /** * The one name every migrator locks on (#31598): two `os migrate apply` runs @@ -39,10 +42,7 @@ export const SCHEMA_MIGRATION_LOCK_NAME = 'objectstack:schema-migrate'; * 'advisory'`, its high 32 bits as `classid` and its low 32 as `objid`. * A string, so no JavaScript number rounds it on the way to the bind. */ -export const SCHEMA_MIGRATION_PG_LOCK_KEY = BigInt.asIntN( - 64, - BigInt(`0x${createHash('sha256').update(SCHEMA_MIGRATION_LOCK_NAME).digest('hex').slice(0, 16)}`), -).toString(); +export const SCHEMA_MIGRATION_PG_LOCK_KEY = databaseSessionLockPgKey(SCHEMA_MIGRATION_LOCK_NAME); /** * How long a migrator waits for another to finish before it refuses. No @@ -50,27 +50,11 @@ export const SCHEMA_MIGRATION_PG_LOCK_KEY = BigInt.asIntN( */ export const SCHEMA_MIGRATION_LOCK_WAIT_MS = 10 * 60_000; -/** The slice of knex the lock uses, typed structurally. */ -interface LockKnex { - client: { - acquireRawConnection(): Promise; - destroyRawConnection(connection: unknown): Promise; - }; - raw(sql: string, bindings?: readonly unknown[]): { connection(connection: unknown): Promise }; -} - /** A held schema-migration lock. `release()` is idempotent and never throws. */ export interface SchemaMigrationLock { release(): Promise; } -/** The single row a lock statement answers, whichever client shaped the result. */ -function lockRow(result: unknown): Record | undefined { - // pg answers `{ rows }`; mysql2 answers `[rows, fields]`. - const rows = Array.isArray(result) ? result[0] : (result as { rows?: unknown } | null)?.rows; - return Array.isArray(rows) ? (rows[0] as Record | undefined) : undefined; -} - /** * Take the schema-migration lock on `driver`'s database (#31598): Postgres * `pg_advisory_lock`, MySQL `GET_LOCK`, by the driver's `dialectName`. Every @@ -83,83 +67,27 @@ function lockRow(result: unknown): Record | undefined { * ONE line through `warn`, then waits up to `waitMs` and refuses on timeout — * this run then migrates nothing, and says so. * - * The lock lives on a connection of its own, opened through the driver's own - * client (its configuration, credentials and TLS) but OUTSIDE its pool: both - * locks are session-scoped, so the lock and its release must run on one - * session, which a pool does not promise; a pooled connection idle past the - * pool's reaper would be closed and the lock released with it; and an - * `OS_DATABASE_POOL_MAX=1` pool would have none left for the migration. A - * session lock excludes every other session on the database, so the - * migration's own pooled connections are serialized by it all the same. + * The lock lives on a connection of its own, outside the driver's pool (an + * `OS_DATABASE_POOL_MAX=1` pool would have none left for the migration); + * `database-session-lock.ts` says why, and its session lock excludes every + * other session on the database, the migration's own pooled ones included. */ export async function acquireSchemaMigrationLock( driver: unknown, opts: { database: string; warn: (line: string) => void; waitMs?: number }, ): Promise { - // [#31715] The dialect is the driver's own answer (`SqlDriver#dialectName`, - // its one public "which SQL do I speak"), read BEFORE the driver is asked - // for its Knex: a face that refuses to hand out Knex (the Turso remote - // transport) throws from `getKnex()` rather than answering `undefined`, and - // a dialect this lock does not cover must never reach that call. A Postgres - // or MySQL driver whose Knex cannot be handed out still throws here, loudly. - const dialect = (driver as { dialectName?: unknown } | null)?.dialectName; - if (dialect !== 'postgres' && dialect !== 'mysql') return null; - const knex = (driver as { getKnex?: () => LockKnex }).getKnex?.(); - if (!knex) return null; - const pg = dialect === 'postgres'; const waitMs = opts.waitMs ?? SCHEMA_MIGRATION_LOCK_WAIT_MS; - const connection = await knex.client.acquireRawConnection(); - const run = async (sql: string, bindings: readonly unknown[]): Promise | undefined> => - lockRow(await knex.raw(sql, bindings).connection(connection)); - const close = async (): Promise => { - try { await knex.client.destroyRawConnection(connection); } catch { /* closing releases the lock anyway */ } - }; - const refuse = (): Error => new Error( - `Refusing to migrate ${opts.database}: another schema migration still held the migration lock ` - + `('${SCHEMA_MIGRATION_LOCK_NAME}') after ${waitMs} ms, so this run changed nothing. ` - + 'Run it again once that migration has finished.', - ); - try { - const tried = pg - ? await run('select pg_try_advisory_lock(?::bigint) as locked', [SCHEMA_MIGRATION_PG_LOCK_KEY]) - : await run('select GET_LOCK(?, 0) as locked', [SCHEMA_MIGRATION_LOCK_NAME]); - if (!(tried?.locked === true || Number(tried?.locked) === 1)) { - opts.warn( - `Another schema migration is running on ${opts.database}; waiting up to ` - + `${Math.ceil(waitMs / 1000)} s for it to finish…`, - ); - if (pg) { - await run(`set lock_timeout = ${Math.max(1, Math.trunc(waitMs))}`, []); - try { - await run('select pg_advisory_lock(?::bigint)', [SCHEMA_MIGRATION_PG_LOCK_KEY]); - } catch (error) { - // 55P03 lock_not_available: `lock_timeout` ran out. - if ((error as { code?: unknown } | null)?.code === '55P03') throw refuse(); - throw error; - } - } else { - // GET_LOCK answers 1 (taken), 0 (timed out) or NULL (an error). - const waited = await run('select GET_LOCK(?, ?) as locked', [ - SCHEMA_MIGRATION_LOCK_NAME, - Math.max(1, Math.ceil(waitMs / 1000)), - ]); - if (Number(waited?.locked) !== 1) throw refuse(); - } - } - } catch (error) { - await close(); - throw error; - } - let held = true; - return { - release: async () => { - if (!held) return; - held = false; - try { - if (pg) await run('select pg_advisory_unlock(?::bigint)', [SCHEMA_MIGRATION_PG_LOCK_KEY]); - else await run('select RELEASE_LOCK(?)', [SCHEMA_MIGRATION_LOCK_NAME]); - } catch { /* closing the session below releases it */ } - await close(); - }, - }; + return acquireDatabaseSessionLock(driver, { + name: SCHEMA_MIGRATION_LOCK_NAME, + waitMs, + onWait: () => opts.warn( + `Another schema migration is running on ${opts.database}; waiting up to ` + + `${Math.ceil(waitMs / 1000)} s for it to finish…`, + ), + refuse: () => new Error( + `Refusing to migrate ${opts.database}: another schema migration still held the migration lock ` + + `('${SCHEMA_MIGRATION_LOCK_NAME}') after ${waitMs} ms, so this run changed nothing. ` + + 'Run it again once that migration has finished.', + ), + }); } diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-lock.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-lock.test.ts new file mode 100644 index 00000000000..49ba14f74f7 --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-lock.test.ts @@ -0,0 +1,312 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it, vi } from 'vitest'; +import { AUDIT_SEAL_LOCK_NAME, AUDIT_SEAL_LOCK_WAIT_MS, AUDIT_SEAL_PG_LOCK_KEY, holdAuditSealLock, type AuditSealLockEngine } from './seal-lock.js'; +import { AuditSealer } from './sealer.js'; +import { LocalCheckpointSigner } from './signer.js'; +import { bindingCrypto, lockableStore, memoryEngine, MemoryStore, recordingLogger, sessionLockDatabase } from './seal-store.testkit.js'; + +/** + * ADR-0154 D3 as amended (seat ruling 6885005594, E + B): what an + * `os migrate audit-* --apply` run holds for its whole run so that no sealer + * pass seals a row it rewrites — the audit seal lock, a database session lock + * on the datasource that holds the audit rows — and what it does where the + * database offers no such lock. The sealer's side (each pass try-locks it and + * skips while it is held) is pinned with the sealer, in + * `audit-seal-sealer.test.ts`; the two meet here, on one database. + */ + +const SEALED = { + name: 'sys_audit_log', + fields: { id: { type: 'text' }, created_at: { type: 'datetime' }, tenant_id: { type: 'lookup' }, new_value: { type: 'textarea' } }, + lifecycle: { class: 'audit', seal: { valueFields: ['new_value'] } }, +}; +const PLAIN = { name: 'sys_activity', fields: {}, lifecycle: { class: 'audit' } }; + +/** An engine whose registry holds `objects`, each routed to the datasource `routes` names. */ +const engineOf = (objects: ReadonlyArray<{ name: string; lifecycle?: unknown }>, routes: Record): AuditSealLockEngine => ({ + registry: { getAllObjects: () => objects }, + getDriverForObject: (name: string) => routes[name], +}); + +const RUN = ['sys_audit_log', 'sys_activity'] as const; + +describe('the lock: one name, one key, one wait (D3 amended)', () => { + it('is pinned, so every version that seals or rewrites a sealed object takes the SAME lock', () => { + expect(AUDIT_SEAL_LOCK_NAME).toBe('objectstack:audit-seal'); + expect(AUDIT_SEAL_PG_LOCK_KEY).toBe('-5564991198496822599'); + }); + + it('waits ten minutes by default: a normal sealer pass — the windows newly due — seals in seconds (ruling item 6)', () => { + expect(AUDIT_SEAL_LOCK_WAIT_MS).toBe(10 * 60_000); + }); +}); + +describe('an --apply run holds it on the datasource that holds the audit rows (E)', () => { + it('on a sealed object\'s hot store — not the primary, where they differ — until it finishes', async () => { + const hotDb = sessionLockDatabase(); + const primaryDb = sessionLockDatabase(); + const hot = lockableStore(new MemoryStore(), hotDb); + const primary = lockableStore(new MemoryStore(), primaryDb); + const warn = vi.fn(); + const hold = await holdAuditSealLock(engineOf([SEALED, PLAIN], { sys_audit_log: hot, sys_activity: primary }), { + objects: RUN, sealerStopped: false, warn, + }); + const taken = hotDb.statements.find((st) => st.sql === 'select pg_try_advisory_lock(?::bigint) as locked')!; + expect(taken.bindings).toEqual([AUDIT_SEAL_PG_LOCK_KEY]); + expect(hotDb.holder(AUDIT_SEAL_PG_LOCK_KEY)).toBe(taken.session); + expect(primaryDb.statements).toEqual([]); + expect(warn).not.toHaveBeenCalled(); + await expect(hold.finish()).resolves.toEqual({ lost: false }); + expect(hotDb.holder(AUDIT_SEAL_PG_LOCK_KEY)).toBeUndefined(); + expect(hotDb.open()).toEqual([]); + }); + + it('takes one lock per database: two sealed objects on one datasource share a session', async () => { + const db = sessionLockDatabase(); + const hot = lockableStore(new MemoryStore(), db); + const both = [SEALED, { ...PLAIN, lifecycle: { class: 'audit', seal: {} } }]; + const hold = await holdAuditSealLock(engineOf(both, { sys_audit_log: hot, sys_activity: hot }), { objects: RUN, sealerStopped: false, warn: vi.fn() }); + // The session's marker of the run, then the one lock. + expect(db.statements.map((st) => st.sql)).toEqual([ + 'select pg_try_advisory_lock(?::bigint) as marked', + 'select pg_try_advisory_lock(?::bigint) as locked', + ]); + await hold.finish(); + }); + + it('a run whose objects declare no lifecycle.seal takes none and refuses nothing — on any database', async () => { + const db = sessionLockDatabase(); + const hold = await holdAuditSealLock( + engineOf([{ ...SEALED, lifecycle: { class: 'audit' } }, PLAIN], { sys_audit_log: lockableStore(new MemoryStore(), db), sys_activity: new MemoryStore() }), + { objects: RUN, sealerStopped: false, warn: vi.fn() }, + ); + expect(db.statements).toEqual([]); + await expect(hold.finish()).resolves.toEqual({ lost: false }); + }); + + it('⛔ a failure to take it on a database that offers one is handed on — never read as "no lock"', async () => { + const refused = new Error('postgres: Knex cannot be handed out'); + const hot = { dialectName: 'postgres', getKnex: () => { throw refused; } }; + await expect(holdAuditSealLock(engineOf([SEALED], { sys_audit_log: hot }), { objects: RUN, sealerStopped: true, warn: vi.fn() })) + .rejects.toBe(refused); + }); + + it('a run whose lock\'s session ended before it finished says it lost it, and why that matters', async () => { + const db = sessionLockDatabase(); + const hold = await holdAuditSealLock(engineOf([SEALED], { sys_audit_log: lockableStore(new MemoryStore(), db) }), { + objects: RUN, sealerStopped: false, warn: vi.fn(), + }); + db.kill(db.holder(AUDIT_SEAL_PG_LOCK_KEY)!); + const finished = await hold.finish(); + expect(finished.lost).toBe(true); + expect(finished.lost && finished.line).toMatch(/audit seal lock on the database of 'sys_audit_log' was lost.*os audit verify/); + }); +}); + +describe('two datasources on one database: the run locks it once and never waits on itself (review 6894679963 M1)', () => { + // Two datasources over ONE lock namespace: one Postgres database, or two schemas of one MySQL server, whose + // GET_LOCK names are server-wide. Each opens its own session; the lock is the namespace's, not the session's. + const BOTH_SEALED = [SEALED, { ...PLAIN, lifecycle: { class: 'audit', seal: {} } }]; + const LOCK_KEY = { postgres: AUDIT_SEAL_PG_LOCK_KEY, mysql: AUDIT_SEAL_LOCK_NAME } as const; + + for (const dialect of ['postgres', 'mysql'] as const) { + it(`${dialect}: the --apply hold takes the lock on the first datasource, and the second is under it — no wait, no line`, async () => { + const db = sessionLockDatabase(dialect); + const audit = lockableStore(new MemoryStore(), db); + const activity = lockableStore(new MemoryStore(), db); + const warn = vi.fn(); + const hold = await holdAuditSealLock(engineOf(BOTH_SEALED, { sys_audit_log: audit, sys_activity: activity }), { + objects: RUN, sealerStopped: false, warn, waitMs: 50, + }); + expect(warn).not.toHaveBeenCalled(); + expect(db.statements.map((st) => st.sql)).not.toContain('set lock_timeout = 50'); + expect(db.statements.map((st) => st.sql)).not.toContain('select GET_LOCK(?, ?) as locked'); + // One session holds the lock; the second datasource's session was closed once it proved itself covered. + const holder = db.holder(LOCK_KEY[dialect]); + expect(holder).toBeDefined(); + expect(db.open()).toEqual([holder]); + await expect(hold.finish()).resolves.toEqual({ lost: false }); + expect(db.holder(LOCK_KEY[dialect])).toBeUndefined(); + expect(db.open()).toEqual([]); + }); + } + + it('a lost shared lock is reported for every object it covered', async () => { + const db = sessionLockDatabase(); + const hold = await holdAuditSealLock( + engineOf(BOTH_SEALED, { sys_audit_log: lockableStore(new MemoryStore(), db), sys_activity: lockableStore(new MemoryStore(), db) }), + { objects: RUN, sealerStopped: false, warn: vi.fn(), waitMs: 50 }, + ); + db.kill(db.holder(AUDIT_SEAL_PG_LOCK_KEY)!); + const finished = await hold.finish(); + expect(finished.lost && finished.line).toMatch(/database of 'sys_audit_log', 'sys_activity' was lost/); + }); + + it('⛔ the run\'s own lock on ANOTHER database is never read as cover: a held lock there is contention, waited for and refused', async () => { + const mine = sessionLockDatabase(); + const theirs = sessionLockDatabase(); + const sealerPass = await theirs.hold(AUDIT_SEAL_PG_LOCK_KEY); + const warn = vi.fn(); + const refusal = await holdAuditSealLock( + engineOf(BOTH_SEALED, { sys_audit_log: lockableStore(new MemoryStore(), mine), sys_activity: lockableStore(new MemoryStore(), theirs) }), + { objects: RUN, sealerStopped: false, warn, waitMs: 20 }, + ).then(() => null, (e: unknown) => e); + expect((refusal as Error).message).toMatch(/^Refusing to rewrite 'sys_activity'.*after 20 ms/); + expect(warn).toHaveBeenCalledTimes(1); + expect(mine.open()).toEqual([]); + expect(theirs.open()).toEqual([sealerPass.session]); + }); + + it('a pass of the sealer seals both objects, where the lock per datasource skipped every pass', async () => { + const H = 60 * 60 * 1000; + const DAY0 = Date.UTC(2026, 10, 10); + const store = memoryEngine(BOTH_SEALED.map((o) => ({ ...o, fields: SEALED.fields }))); + const db = sessionLockDatabase(); + lockableStore(store.hot, db); + // A second datasource over the same tables, on the same database. + const activity = lockableStore({ + find: (object: string, query: Record) => store.hot.find(object, query), + count: (object: string, query?: Record) => store.hot.count(object, query), + create: (object: string, data: Record) => store.hot.create(object, data), + delete: (object: string, id: string) => store.hot.delete(object, id), + }, db); + store.engine.getDriverForObject = (object: string) => (object === 'sys_activity' ? activity : store.hot); + const crypto = bindingCrypto(); + const logger = recordingLogger(); + const sealer = new AuditSealer({ + engine: store.engine, crypto, signer: () => new LocalCheckpointSigner({ engine: store.engine, crypto }), logger, now: () => DAY0 + 12 * H, + }); + for (const object of RUN) { + store.hot.table(object).push({ id: `${object}-r1`, created_at: new Date(DAY0 + 8 * H).toISOString(), tenant_id: 'org_a', new_value: '{}' }); + } + expect(await sealer.runPass()).toBe(2); + expect(new Set(store.hot.table('sys_audit_checkpoint').map((r) => r.sealed_object))).toEqual(new Set(RUN)); + expect(logger.lines.filter((l) => /audit seal lock/.test(l.message))).toEqual([]); + expect(db.open()).toEqual([]); + }); +}); + +describe('N2: a database that offers no lock is refused before any wait on another', () => { + it('⛔ refuses at once, with no wait line, when one sealed object is lockless and another\'s lock is held', async () => { + const held = sessionLockDatabase(); + const sealerPass = await held.hold(AUDIT_SEAL_PG_LOCK_KEY); + const lockless = lockableStore(new MemoryStore(), { ...sessionLockDatabase(), face: { dialectName: 'sqlite', getKnex: () => { throw new Error('never asked'); } } }); + const warn = vi.fn(); + const refusal = await holdAuditSealLock( + engineOf([SEALED, { ...PLAIN, lifecycle: { class: 'audit', seal: {} } }], { sys_audit_log: lockableStore(new MemoryStore(), held), sys_activity: lockless }), + { objects: RUN, sealerStopped: false, warn }, + ).then(() => null, (e: unknown) => e); + expect((refusal as Error).message).toMatch(/^Refusing to rewrite 'sys_activity'.*--sealer-stopped/); + expect(warn).not.toHaveBeenCalled(); + expect(held.statements.map((st) => st.sql)).not.toContain(`set lock_timeout = ${AUDIT_SEAL_LOCK_WAIT_MS}`); + expect(held.open()).toEqual([sealerPass.session]); + }); +}); + +describe('contention: the run waits for a sealer pass in flight, then refuses (E)', () => { + it('waits out a sealer pass in flight, with its default wait, and holds the lock only once the pass let it go', async () => { + const H = 60 * 60 * 1000; + const DAY0 = Date.UTC(2026, 10, 10); + const store = memoryEngine([SEALED]); + const db = sessionLockDatabase(); + lockableStore(store.hot, db); + const crypto = bindingCrypto(); + const sealer = new AuditSealer({ + engine: store.engine, crypto, signer: () => new LocalCheckpointSigner({ engine: store.engine, crypto }), + logger: recordingLogger(), now: () => DAY0 + 12 * H, + }); + store.hot.table('sys_audit_log').push({ id: 'r1', created_at: new Date(DAY0 + 8 * H).toISOString(), tenant_id: 'org_a', new_value: '{}' }); + const events: string[] = []; + const insert = store.engine.insert.bind(store.engine); + store.engine.insert = async (...args: Parameters) => { + if (args[0] === 'sys_audit_checkpoint') events.push('checkpoint written'); + return insert(...args); + }; + const warn = vi.fn(); + let holding: Promise | undefined; + const find = store.hot.find.bind(store.hot); + store.hot.find = async (object, query) => { + // The pass has the lock and is reading the window: the run starts now. + if (!holding && object === 'sys_audit_log' && query.limit === 500) { + holding = holdAuditSealLock(engineOf([SEALED], { sys_audit_log: store.hot }), { objects: RUN, sealerStopped: false, warn }) + .then((hold) => (events.push('run holds the lock'), hold)); + } + return find(object, query); + }; + expect(await sealer.runPass()).toBe(1); + const hold = (await holding) as Awaited>; + expect(events).toEqual(['checkpoint written', 'run holds the lock']); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0][0]).toMatch(/holds the audit seal lock on the database of 'sys_audit_log'; waiting up to 600 s/); + expect(db.statements.map((st) => st.sql)).toContain(`set lock_timeout = ${AUDIT_SEAL_LOCK_WAIT_MS}`); + await hold.finish(); + }); + + it('⛔ a wait that runs out refuses, naming the lock, and the run changed nothing', async () => { + const db = sessionLockDatabase(); + const sealerPass = await db.hold(AUDIT_SEAL_PG_LOCK_KEY); + const refusal = await holdAuditSealLock(engineOf([SEALED], { sys_audit_log: lockableStore(new MemoryStore(), db) }), { + objects: RUN, sealerStopped: false, warn: vi.fn(), waitMs: 20, + }).then(() => null, (e: unknown) => e); + expect(refusal).toBeInstanceOf(Error); + expect((refusal as Error).message).toMatch(/^Refusing to rewrite .*'sys_audit_log'.*'objectstack:audit-seal'.*after 20 ms, so this run changed nothing/); + expect(db.open()).toEqual([sealerPass.session]); + }); + + it('a sealer pass skips while a run holds it, and seals once the run has finished', async () => { + const H = 60 * 60 * 1000; + const DAY0 = Date.UTC(2026, 10, 10); + const store = memoryEngine([SEALED]); + const db = sessionLockDatabase(); + lockableStore(store.hot, db); + const crypto = bindingCrypto(); + const sealer = new AuditSealer({ + engine: store.engine, crypto, signer: () => new LocalCheckpointSigner({ engine: store.engine, crypto }), + logger: recordingLogger(), now: () => DAY0 + 12 * H, + }); + store.hot.table('sys_audit_log').push({ id: 'r1', created_at: new Date(DAY0 + 8 * H).toISOString(), tenant_id: 'org_a', new_value: '{}' }); + const hold = await holdAuditSealLock(engineOf([SEALED], { sys_audit_log: store.hot }), { objects: RUN, sealerStopped: false, warn: vi.fn() }); + expect(await sealer.runPass()).toBe(0); + await hold.finish(); + expect(await sealer.runPass()).toBe(1); + }); +}); + +describe('B: where the database offers no session lock, an --apply run on a sealed object needs --sealer-stopped', () => { + const lockless = () => lockableStore(new MemoryStore(), { ...sessionLockDatabase(), face: { dialectName: 'sqlite', getKnex: () => { throw new Error('never asked'); } } }); + + it('⛔ is refused without it, before anything is written, naming the object and the flag', async () => { + const warn = vi.fn(); + const refusal = await holdAuditSealLock(engineOf([SEALED, PLAIN], { sys_audit_log: lockless(), sys_activity: lockless() }), { + objects: RUN, sealerStopped: false, warn, + }).then(() => null, (e: unknown) => e); + expect(refusal).toBeInstanceOf(Error); + expect((refusal as Error).message).toMatch(/^Refusing to rewrite 'sys_audit_log'.*no session lock.*--sealer-stopped.*changed nothing/); + expect(warn).not.toHaveBeenCalled(); + }); + + it('a driver with no Knex at all (a memory store) is a database with no session lock too', async () => { + await expect(holdAuditSealLock(engineOf([SEALED], { sys_audit_log: new MemoryStore() }), { objects: RUN, sealerStopped: false, warn: vi.fn() })) + .rejects.toThrow(/--sealer-stopped/); + }); + + it('only a SEALED object on such a database needs it: unsealed ones there, with the sealed one locked elsewhere, go ahead', async () => { + const db = sessionLockDatabase(); + const hold = await holdAuditSealLock(engineOf([SEALED, PLAIN], { sys_audit_log: lockableStore(new MemoryStore(), db), sys_activity: lockless() }), { + objects: RUN, sealerStopped: false, warn: vi.fn(), + }); + expect(db.holder(AUDIT_SEAL_PG_LOCK_KEY)).toBeDefined(); + await hold.finish(); + }); + + it('with --sealer-stopped it goes ahead, saying once that it rests on the operator\'s word', async () => { + const warn = vi.fn(); + const hold = await holdAuditSealLock(engineOf([SEALED, PLAIN], { sys_audit_log: lockless(), sys_activity: lockless() }), { + objects: RUN, sealerStopped: true, warn, + }); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0][0]).toMatch(/^--sealer-stopped: 'sys_audit_log' is rewritten without the audit seal lock/); + await expect(hold.finish()).resolves.toEqual({ lost: false }); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-sealer.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-sealer.test.ts index 7d42252aa73..bd23db6b357 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-sealer.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-sealer.test.ts @@ -3,7 +3,8 @@ import type { IAuditCheckpointSigner, IClusterService, LockHandle } from '@objectstack/spec/contracts'; import { describe, expect, it } from 'vitest'; import { checkpointBodyFromRow, checkpointDigest, signedBodyBytes, verifyAuditLedger, type CheckpointSignedBody } from './index.js'; -import { bindingCrypto, memoryEngine, recordingLogger } from './seal-store.testkit.js'; +import { bindingCrypto, lockableStore, memoryEngine, recordingLogger, sessionLockDatabase } from './seal-store.testkit.js'; +import { AUDIT_SEAL_PG_LOCK_KEY } from './seal-lock.js'; import { AUDIT_SEAL_MAX_IDLE_WINDOWS_PER_PASS, AUDIT_SEAL_MAX_LEAVES, AUDIT_SEALER_LOCK, AuditSealer } from './sealer.js'; import { LocalCheckpointSigner } from './signer.js'; @@ -861,3 +862,87 @@ describe('when it cannot seal it says so at error, again each hour while it last expect(s.logger.lines).toEqual([]); }); }); + +describe('the audit seal lock: each pass try-locks it beside audit.sealer, and skips while it is held (D3 amended, seat ruling 6885005594)', () => { + /** A setup whose hot store is a datasource of a database that keeps session locks. */ + const lockable = (options: Parameters[0] = {}) => { + const s = setup(options); + const db = sessionLockDatabase(); + lockableStore(s.hot, db); + return { ...s, db }; + }; + const tries = (db: ReturnType) => + db.statements.filter((st) => st.sql === 'select pg_try_advisory_lock(?::bigint) as locked'); + + it('takes it on the sealed object\'s hot store for the whole pass, under its own name, and lets it go when the pass ends', async () => { + const s = lockable(); + s.hot.table('ledger_probe').push(row('r1', at(8, 10)), row('r2', at(9, 10))); + const heldAtWrite: Array = []; + const insert = s.engine.insert.bind(s.engine); + s.engine.insert = async (...args: Parameters) => { + if (args[0] === 'sys_audit_checkpoint') heldAtWrite.push(s.db.holder(AUDIT_SEAL_PG_LOCK_KEY)); + return insert(...args); + }; + expect(await s.sealer.runPass()).toBe(2); + expect(tries(s.db).map((st) => st.bindings)).toEqual([[AUDIT_SEAL_PG_LOCK_KEY]]); + const session = tries(s.db)[0].session; + expect(heldAtWrite).toEqual([session, session]); + expect(s.db.holder(AUDIT_SEAL_PG_LOCK_KEY)).toBeUndefined(); + expect(s.db.open()).toEqual([]); + }); + + it('takes it on the datasource that holds the audit rows: the hot store, where it differs from the primary', async () => { + const s = setup(); + const hotDb = sessionLockDatabase(); + const primaryDb = sessionLockDatabase(); + lockableStore(s.hot, hotDb); + // The checkpoints, the seeds and the signing key are on the primary: one more datasource, of another database. + const primary = lockableStore({ + find: (object: string, query: Record) => s.hot.find(object, query), + count: (object: string, query?: Record) => s.hot.count(object, query), + create: (object: string, data: Record) => s.hot.create(object, data), + delete: (object: string, id: string) => s.hot.delete(object, id), + }, primaryDb); + s.engine.getDriverForObject = (object: string) => (object === 'ledger_probe' ? s.hot : primary); + s.hot.table('ledger_probe').push(row('r1', at(8, 10))); + expect(await s.sealer.runPass()).toBe(1); + expect(tries(hotDb)).toHaveLength(1); + expect(primaryDb.statements).toEqual([]); + }); + + it('skips the pass while another session holds it — an os migrate audit-* run — says so once, and seals on the first pass after', async () => { + const s = lockable(); + s.hot.table('ledger_probe').push(row('r1', at(8, 10))); + const migration = await s.db.hold(AUDIT_SEAL_PG_LOCK_KEY); + expect(await s.sealer.runPass()).toBe(0); + expect(await s.sealer.runPass()).toBe(0); + expect(s.hot.table('sys_audit_checkpoint')).toEqual([]); + expect(s.hot.table('sys_secret')).toEqual([]); + expect(s.db.open()).toEqual([migration.session]); + const skipped = s.logger.lines.filter((l) => /audit seal lock/.test(l.message)); + expect(skipped.map((l) => l.level)).toEqual(['info']); + expect(skipped[0].message).toMatch(/'ledger_probe'.*held by another session.*skipped/); + migration.release(); + // The skipped passes let audit.sealer go as well: the next pass takes both. + expect(await s.sealer.runPass()).toBe(1); + }); + + it('stores nothing once its session ends mid-pass, drops the seed it sealed, and fails the object\'s pass at error (a lock lapse)', async () => { + const s = lockable(); + s.hot.table('ledger_probe').push(row('r1', at(8, 10))); + betweenReads(s, () => s.db.kill(s.db.holder(AUDIT_SEAL_PG_LOCK_KEY)!)); + expect(await s.sealer.runPass()).toBe(0); + expect(s.hot.table('sys_audit_checkpoint')).toEqual([]); + expect(s.hot.table('sys_secret').filter((r) => r.namespace === 'ledger_probe')).toEqual([]); + expect(s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message)) + .toEqual([expect.stringMatching(/sealing 'ledger_probe' FAILED \(the audit seal lock .*lapsed/)]); + }); + + it('on a datasource that offers no session lock, takes none and seals as before: B is the migrations\' to enforce', async () => { + const s = setup(); + lockableStore(s.hot, { ...sessionLockDatabase(), face: { dialectName: 'sqlite', getKnex: () => { throw new Error('never asked'); } } }); + s.hot.table('ledger_probe').push(row('r1', at(8, 10))); + expect(await s.sealer.runPass()).toBe(1); + expect(s.logger.lines.filter((l) => /audit seal lock/.test(l.message))).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-audit/src/audit-seal/index.ts b/packages/plugins/plugin-audit/src/audit-seal/index.ts index 552cc4e9f05..27cfa7573b7 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/index.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/index.ts @@ -92,3 +92,6 @@ export type { } from './verifier.js'; export { AuditProofBundleError, verifyAuditProofBundle } from './bundle.js'; export type { AuditProofBundleVerifyOptions } from './bundle.js'; +// D3 amended (seat ruling 6885005594): the audit seal lock an `os migrate audit-* --apply` run holds for its whole run. +export { AUDIT_SEAL_LOCK_NAME, AUDIT_SEAL_LOCK_WAIT_MS, AUDIT_SEAL_PG_LOCK_KEY, holdAuditSealLock } from './seal-lock.js'; +export type { AuditSealLockEngine, AuditSealLockFinish, AuditSealLockHold, AuditSealLockHoldOptions } from './seal-lock.js'; diff --git a/packages/plugins/plugin-audit/src/audit-seal/seal-lock.ts b/packages/plugins/plugin-audit/src/audit-seal/seal-lock.ts new file mode 100644 index 00000000000..2df37a24c68 --- /dev/null +++ b/packages/plugins/plugin-audit/src/audit-seal/seal-lock.ts @@ -0,0 +1,278 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { + acquireDatabaseSessionLock, + databaseSessionLockPgKey, + tryDatabaseSessionLock, + type DatabaseSessionLock, +} from '@objectstack/objectql'; + +/** + * ADR-0154 D3 as amended (seat ruling 6885005594, E + B) — the audit seal + * lock: a database session lock, so a sealer pass and an + * `os migrate audit-* --apply` run never work on a sealed object at once. The + * sealer and a migration share the database on every topology, so the two + * exclude each other with no cluster driver; the cluster lock `audit.sealer` + * and the unique `(sealed_object, chain_key, sequence)` index stay as they are. + * + * It rides on `@objectstack/objectql`'s database session lock, the pattern of + * the schema-migration lock: a Postgres advisory lock or a MySQL `GET_LOCK`, + * on a connection of its own outside the pool. It is taken on the datasource + * that holds the audit rows — each sealed object's hot store, which is not the + * primary where the object routes elsewhere — by both sides: + * + * - **The sealer** try-locks it on every pass, beside `audit.sealer`, and + * skips the pass while another session holds it (`sealer.ts`). + * - **A migration** holds it for its whole run ({@link holdAuditSealLock}): + * it waits up to {@link AUDIT_SEAL_LOCK_WAIT_MS}, then refuses. + * - **B, the residual.** Where the database offers no session lock (SQLite, + * Turso, every dialect but Postgres and MySQL), an `--apply` run on an + * object declaring `lifecycle.seal` is refused unless the operator passes + * `--sealer-stopped`. + * + * ⛔ Red line: never take a lock that excludes nothing and then proceed + * silently. Where no lock can be taken, the run says so and refuses, or goes + * ahead only on the operator's explicit word, and says that too. + */ + +/** + * The one name the sealer and every migration lock on. ⛔ Never derived from + * the database name, the project or the release: every version that can seal + * or rewrite a sealed object must take the SAME lock, or a rolling upgrade runs + * an old migration beside a new sealer. The unit pin holds its key to its value + * for that reason. + */ +export const AUDIT_SEAL_LOCK_NAME = 'objectstack:audit-seal'; + +/** Its Postgres advisory-lock key (`databaseSessionLockPgKey`). */ +export const AUDIT_SEAL_PG_LOCK_KEY = databaseSessionLockPgKey(AUDIT_SEAL_LOCK_NAME); + +/** + * How long an `--apply` run waits for a sealer pass (or another run) to let + * go before it refuses: ten minutes, the schema-migration lock's own wait. It + * outlasts a normal sealer pass by orders of magnitude (seat ruling item 6): a + * pass in step with the clock seals the one window newly due and re-counts the + * late horizon, a few hundred reads; a backlog pass is cut at + * `MAX_WINDOWS_PER_PASS` windows of at most `AUDIT_SEAL_MAX_LEAVES` leaves per + * checkpoint, and the passes after it follow at once — between two of them the + * lock is free, and the waiting run takes it. No environment override. + */ +export const AUDIT_SEAL_LOCK_WAIT_MS = 10 * 60_000; + +/** + * The four rewrites that hold the lock, spelled as an operator types them, for + * the lines that tell an operator what else may hold it. Each is a full + * command id, so `check:cli-command-ids` holds every one to a real command. + */ +export const AUDIT_SEAL_LOCK_REWRITE_COMMANDS = + '`os migrate audit-key-material`, `os migrate audit-mail-bodies`, `os migrate audit-metadata-bodies` or ' + + '`os migrate audit-side-copies`'; + +/** The engine surface a hold reads: which objects are sealed, and where each one's rows live. */ +export interface AuditSealLockEngine { + registry: { getAllObjects(): ReadonlyArray<{ name: string; lifecycle?: unknown }> }; + getDriverForObject(name: string): unknown; +} + +export interface AuditSealLockHoldOptions { + /** The objects the run rewrites, hot. A sealed one's archive rows are covered by the lock on its hot store. */ + readonly objects: readonly string[]; + /** The operator's `--sealer-stopped`: their word that no sealer runs against the database. */ + readonly sealerStopped: boolean; + /** Where the hold's one line goes: the wait, or the run going ahead on `--sealer-stopped`. */ + warn(line: string): void; + /** Test seam: a shorter wait. The command never passes it. */ + readonly waitMs?: number; +} + +/** What {@link AuditSealLockHold.finish} found. */ +export type AuditSealLockFinish = { readonly lost: false } | { readonly lost: true; readonly line: string }; + +export interface AuditSealLockHold { + /** + * Let every lock of the hold go, once the run's last write is done, and say + * whether each one still stood at that moment: a lock whose session ended + * mid-run (a dropped connection) excluded nothing from then on. + */ + finish(): Promise; +} + +/** Whether `object` declares `lifecycle.seal` in `engine`'s registry. */ +function sealedObjects(engine: AuditSealLockEngine, objects: readonly string[]): string[] { + const sealed = new Set(); + for (const o of engine.registry.getAllObjects()) { + if ((o.lifecycle as { seal?: unknown } | undefined)?.seal) sealed.add(o.name); + } + return objects.filter((name) => sealed.has(name)); +} + +/** `'a', 'b'` for a line. */ +const named = (objects: readonly string[]): string => objects.map((o) => `'${o}'`).join(', '); + +/** + * `objects` grouped by the driver that holds each one's hot rows. A group is a + * datasource, not yet a database: two datasources can reach one lock + * namespace — one Postgres database, or two schemas of one MySQL server, whose + * `GET_LOCK` names are server-wide — and there they share ONE lock, the one + * this run or pass took first ({@link LockCover}). + */ +function byDriver(engine: AuditSealLockEngine, objects: readonly string[]): Map { + const groups = new Map(); + for (const object of objects) { + const driver = engine.getDriverForObject(object); + groups.set(driver, [...(groups.get(driver) ?? []), object]); + } + return groups; +} + +/** + * The locks one run or pass holds, each with the objects it covers. Every lock + * is taken with the ones before it as `ownLocks`, so a datasource whose + * database another datasource of the same run already locked is answered that + * lock, never `'held'`: a run or pass never contends with itself (review + * 6894679963 M1). Covering more than one datasource, a lock is still one + * session, released once. + */ +class LockCover { + private readonly covered = new Map(); + + /** The locks taken so far: the `ownLocks` of the next. */ + get own(): DatabaseSessionLock[] { + return [...this.covered.keys()]; + } + + add(lock: DatabaseSessionLock, objects: readonly string[]): void { + this.covered.set(lock, [...(this.covered.get(lock) ?? []), ...objects]); + } + + entries(): Array<{ objects: string[]; lock: DatabaseSessionLock }> { + return [...this.covered].map(([lock, objects]) => ({ objects, lock })); + } + + async releaseAll(): Promise { + for (const lock of this.covered.keys()) await lock.release(); + } +} + +/** + * Hold the audit seal lock for an `os migrate audit-* --apply` run (E), on + * each database that holds the hot rows of a sealed object the run rewrites; + * call it before the run's first write and {@link AuditSealLockHold.finish} + * after its last. A run whose objects declare no `lifecycle.seal` takes no + * lock: no sealer pass reads its rows, so there is nothing to exclude. + * + * Each database is locked once, however many of the run's datasources reach + * it ({@link LockCover}). Contended, it says so once through `warn` and waits + * up to {@link AUDIT_SEAL_LOCK_WAIT_MS}, then refuses. Where a sealed object's + * database offers no session lock (B), the run is refused unless + * `sealerStopped` — before any wait on another database — and with it the run + * goes ahead and says on whose word. Every refusal comes before anything is + * written, and lets go of every lock the hold had already taken. + */ +export async function holdAuditSealLock(engine: AuditSealLockEngine, options: AuditSealLockHoldOptions): Promise { + const waitMs = options.waitMs ?? AUDIT_SEAL_LOCK_WAIT_MS; + const cover = new LockCover(); + const contended: Array<[unknown, string[]]> = []; + const unlocked: string[] = []; + const refuseUnlocked = (): void => { + if (unlocked.length === 0 || options.sealerStopped) return; + throw new Error( + `Refusing to rewrite ${named(unlocked)}: ${unlocked.length === 1 ? 'it declares' : 'they declare'} ` + + 'lifecycle.seal, and the database that holds its rows offers no session lock to exclude the audit sealer ' + + 'with (only Postgres and MySQL do), so a sealer pass of a running server could seal a row while this run ' + + 'rewrites it. Stop every server that seals this database, then re-run with --sealer-stopped. ' + + 'This run changed nothing.', + ); + }; + try { + // First one try on every database, never waiting: a database that offers no lock is refused (B) before + // any wait on another, and a database another datasource of this run already locked is found covered. + for (const [driver, objects] of byDriver(engine, sealedObjects(engine, options.objects))) { + const lock = await tryDatabaseSessionLock(driver, AUDIT_SEAL_LOCK_NAME, { ownLocks: cover.own }); + if (lock === null) unlocked.push(...objects); + else if (lock === 'held') contended.push([driver, objects]); + else cover.add(lock, objects); + } + refuseUnlocked(); + // Then the wait, where another session holds it. + for (const [driver, objects] of contended) { + const where = `the database of ${named(objects)}`; + const lock = await acquireDatabaseSessionLock(driver, { + name: AUDIT_SEAL_LOCK_NAME, + waitMs, + ownLocks: cover.own, + onWait: () => options.warn( + `A sealer pass or another run of ${AUDIT_SEAL_LOCK_REWRITE_COMMANDS} holds the audit seal lock on ${where}; ` + + `waiting up to ${Math.ceil(waitMs / 1000)} s for it to finish…`, + ), + refuse: () => new Error( + `Refusing to rewrite ${named(objects)}: a sealer pass or another run of ${AUDIT_SEAL_LOCK_REWRITE_COMMANDS} ` + + `still held the audit seal lock ('${AUDIT_SEAL_LOCK_NAME}') on ${where} after ${waitMs} ms, so this run ` + + 'changed nothing. Run it again once that has finished.', + ), + }); + if (lock) cover.add(lock, objects); + else unlocked.push(...objects); + } + refuseUnlocked(); + } catch (error) { + await cover.releaseAll(); + throw error; + } + if (unlocked.length > 0) { + options.warn( + `--sealer-stopped: ${named(unlocked)} ${unlocked.length === 1 ? 'is' : 'are'} rewritten without the audit seal ` + + 'lock, which the database that holds its rows cannot take — on your word that no server seals it while this ' + + 'run lasts.', + ); + } + return { + async finish() { + const lost: string[] = []; + for (const { objects, lock } of cover.entries()) { + if (!(await lock.isHeld())) lost.push(...objects); + await lock.release(); + } + if (lost.length === 0) return { lost: false }; + return { + lost: true, + line: + `The audit seal lock on the database of ${named(lost)} was lost during this run (its database session ` + + 'ended), so a sealer pass may have sealed a row this run rewrote. Run `os audit verify`: a row it reports ' + + 'modified was rewritten under such a pass.', + }; + }, + }; +} + +/** What a sealer pass got when it try-locked the audit seal lock on its sealed objects' databases. */ +export type AuditSealPassLocks = + | { readonly held: true; readonly objects: readonly string[] } + | { readonly held: false; readonly locks: ReadonlyArray<{ readonly objects: readonly string[]; readonly lock: DatabaseSessionLock }> }; + +/** + * A sealer pass's try (E): the audit seal lock on each database that holds the + * hot rows of `objects`, once, never waiting, and once per database however + * many datasources reach it ({@link LockCover}). `held` names the objects of + * the first database where another session holds it — every lock already taken is + * let go again, and the pass is skipped. A database that offers no session + * lock adds none: there, B is the migrations' to enforce. A failure to try is + * handed on, every lock already taken let go. + */ +export async function trySealPassLocks(engine: Pick, objects: readonly string[]): Promise { + const cover = new LockCover(); + try { + for (const [driver, group] of byDriver(engine as AuditSealLockEngine, objects)) { + const lock = driver === undefined ? null : await tryDatabaseSessionLock(driver, AUDIT_SEAL_LOCK_NAME, { ownLocks: cover.own }); + if (lock === 'held') { + await cover.releaseAll(); + return { held: true, objects: group }; + } + if (lock) cover.add(lock, group); + } + } catch (error) { + await cover.releaseAll(); + throw error; + } + return { held: false, locks: cover.entries() }; +} diff --git a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts index 72435a2ad28..e8cc3a75719 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts @@ -155,3 +155,136 @@ export function recordingLogger() { error: (message: string) => void lines.push({ level: 'error', message }), }; } + +/** A statement one session of a {@link sessionLockDatabase} ran. */ +export interface SessionStatement { + readonly session: number; + readonly sql: string; + readonly bindings: readonly unknown[]; +} + +/** + * A database that keeps session locks the way Postgres keeps advisory locks + * (and MySQL `GET_LOCK`): held by the session that took them, until that + * session unlocks or ends. A blocking lock really waits, until the lock is + * free or the session's `lock_timeout` runs out (`55P03`). It answers the + * statements `@objectstack/objectql`'s database session lock runs, and + * nothing else. + * + * `face` is what a SQL driver adds to a store (`dialectName`, `getKnex()`): + * on a {@link MemoryStore} ({@link lockableStore}), that store is a datasource + * the lock can be taken on. `kill(session)` ends a session as a dropped + * connection would, which releases every lock it held. + */ +export function sessionLockDatabase(dialect: 'postgres' | 'mysql' = 'postgres') { + const holders = new Map(); + const sessions = new Map(); + const statements: SessionStatement[] = []; + let next = 1; + const shape = (row: Row) => (dialect === 'mysql' ? [[row], []] : { rows: [row] }); + const end = (id: number) => { + const session = sessions.get(id); + if (session) session.alive = false; + for (const [key, holder] of holders) if (holder === id) holders.delete(key); + }; + const take = (id: number, key: string): boolean => { + const holder = holders.get(key); + if (holder !== undefined && holder !== id) return false; + holders.set(key, id); + return true; + }; + const wait = async (id: number, key: string, timeoutMs: number): Promise => { + const until = Date.now() + timeoutMs; + for (;;) { + if (!sessions.get(id)?.alive) throw new Error('Connection terminated unexpectedly'); + if (take(id, key)) return true; + if (Date.now() >= until) return false; + await new Promise((resolve) => setTimeout(resolve, 2)); + } + }; + const run = async (id: number, sql: string, bindings: readonly unknown[]): Promise => { + const session = sessions.get(id); + if (!session?.alive) throw new Error('Connection terminated unexpectedly'); + statements.push({ session: id, sql, bindings }); + const key = String(bindings[0]); + switch (sql) { + case 'select pg_try_advisory_lock(?::bigint) as locked': + return shape({ locked: take(id, key) }); + case 'select GET_LOCK(?, 0) as locked': + return shape({ locked: take(id, key) ? 1 : 0 }); + // A run's session marker, and the check that the session holding a lock here holds a marker. + case 'select pg_try_advisory_lock(?::bigint) as marked': + return shape({ marked: take(id, key) }); + case 'select GET_LOCK(?, 0) as marked': + return shape({ marked: take(id, key) ? 1 : 0 }); + case 'select IS_USED_LOCK(?) = IS_USED_LOCK(?) as seen': { + const [marker, lock] = [holders.get(key), holders.get(String(bindings[1]))]; + return shape({ seen: marker === undefined || lock === undefined ? null : Number(marker === lock) }); + } + case 'select pg_advisory_lock(?::bigint)': + if (await wait(id, key, session.lockTimeoutMs)) return shape({}); + throw Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' }); + case 'select GET_LOCK(?, ?) as locked': + return shape({ locked: (await wait(id, key, Number(bindings[1]) * 1000)) ? 1 : 0 }); + case 'select pg_advisory_unlock(?::bigint)': + case 'select RELEASE_LOCK(?)': + if (holders.get(key) === id) holders.delete(key); + return shape({}); + case 'select 1 as held': + return shape({ held: 1 }); + default: { + if (sql.startsWith('select exists (select 1 from pg_locks m join pg_locks l on l.pid = m.pid')) { + // classid and objid, the high and low 32 bits of each key, back to the key. + const keyOf = (high: unknown, low: unknown) => BigInt.asIntN(64, (BigInt(String(high)) << 32n) | BigInt(String(low))).toString(); + const [marker, lock] = [holders.get(keyOf(bindings[0], bindings[1])), holders.get(keyOf(bindings[2], bindings[3]))]; + return shape({ seen: marker !== undefined && marker === lock }); + } + const timeout = /^set lock_timeout = (\d+)$/.exec(sql); + if (timeout) { + session.lockTimeoutMs = Number(timeout[1]); + return shape({}); + } + throw new Error(`sessionLockDatabase: no answer for ${sql}`); + } + } + }; + const knex = { + client: { + async acquireRawConnection(): Promise<{ id: number }> { + const id = next++; + sessions.set(id, { alive: true, lockTimeoutMs: Number.POSITIVE_INFINITY }); + return { id }; + }, + async destroyRawConnection(connection: unknown): Promise { + end((connection as { id: number }).id); + }, + }, + raw: (sql: string, bindings: readonly unknown[] = []) => ({ + connection: (connection: unknown) => run((connection as { id: number }).id, sql, bindings), + }), + }; + return { + statements, + face: { dialectName: dialect, getKnex: () => knex }, + /** The session holding the lock under `key` (a Postgres key, or a MySQL name), if any. */ + holder: (key: string): number | undefined => holders.get(key), + /** Every session opened and not yet ended. */ + open: (): number[] => [...sessions].filter(([, s]) => s.alive).map(([id]) => id), + kill: end, + /** Take the lock under `key` on a session of the test's own, as another process would. */ + async hold(key: string): Promise<{ session: number; release(): void }> { + const { id } = await knex.client.acquireRawConnection(); + if (!take(id, key)) throw new Error(`sessionLockDatabase: '${key}' is already held`); + return { session: id, release: () => end(id) }; + }, + }; +} + +/** + * `store`, made a datasource the database session lock can be taken on: `db`'s + * `face` on it. A face naming another dialect (`'sqlite'`) makes a datasource + * that offers no session lock. + */ +export function lockableStore(store: T, db: { face: { dialectName: string; getKnex(): unknown } }): T { + return Object.assign(store, db.face); +} diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index e6877d87bee..c5ecd5f39b3 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -42,6 +42,12 @@ import { type CheckpointSignedBody, } from './signed-body.js'; import { dropAuditSealSecret, writeAuditSealSecret, type SealStorageDriver, type SealStorageEngine } from './signer.js'; +import { + AUDIT_SEAL_LOCK_NAME, + AUDIT_SEAL_LOCK_REWRITE_COMMANDS, + trySealPassLocks, + type AuditSealPassLocks, +} from './seal-lock.js'; /** * ADR-0154 D3 — the sealer: after a settle lag, one window at a time, under @@ -82,6 +88,15 @@ import { dropAuditSealSecret, writeAuditSealSecret, type SealStorageDriver, type * leaves unsealed. Every other fault — the lock, the signer, the crypto * provider, the storage — stops the whole object's pass. * + * D3 as amended (seat ruling 6885005594, E): beside `audit.sealer`, each + * pass try-locks the audit seal lock (`seal-lock.ts`), a database session lock + * on each sealed object's hot store, and skips the pass while another session + * holds it — an `os migrate audit-* --apply` run holds it for its whole run. + * A checkpoint is written only while both still stand; a lapse of either + * fails the object's pass, as any lock lapse does (S4). A database that offers + * no session lock adds none: there the migrations refuse to run on a sealed + * object without the operator's `--sealer-stopped` (B). + * * Nothing here writes the sealed object, and every secret row is written * below the hooks, so the sealer never seals its own writes. */ @@ -219,6 +234,32 @@ function faultOf(err: unknown): string { const windowOf = (ms: number): number => Math.floor(ms / AUDIT_SEAL_WINDOW_MS) * AUDIT_SEAL_WINDOW_MS; const tenantOf = (row: Row): string | null => (typeof row.tenant_id === 'string' && row.tenant_id !== '' ? row.tenant_id : null); +/** + * The locks a pass holds (D3 amended): the lease `audit.sealer`, whose fencing + * token each checkpoint records, and the audit seal lock on each sealed + * object's database. + */ +interface PassLock { + readonly fencingToken: bigint; + renew(ttlMs: number): Promise; + /** The lock guarding `object`'s checkpoints that lapsed, named for a line; `null` while each still stands. */ + lapsed(object: string): Promise; +} + +function passLockOf(lease: LockHandle, session: Extract['locks']): PassLock { + return { + fencingToken: lease.fencingToken, + renew: (ttlMs) => lease.renew(ttlMs), + async lapsed(object) { + if (!lease.isHeld()) return 'the audit.sealer lock'; + for (const { objects, lock } of session) { + if (objects.includes(object) && !(await lock.isHeld())) return `the audit seal lock on the database of '${object}'`; + } + return null; + }, + }; +} + /** Q2 (a): with no cluster service the lock is this process's, with its own fencing counter. */ let inProcessHeld = false; let inProcessFencing = 0n; @@ -361,8 +402,10 @@ export class AuditSealer { this.reported.set('in-process-lock', this.now()); this.options.logger.info( 'AuditSealer: no cluster service is registered, so the audit.sealer lock is held in-process only — ' + - 'cross-replica exclusion is off by the host\'s declaration. The checkpoint table\'s unique ' + - '(sealed_object, chain_key, sequence) index still refuses a second checkpoint at a taken sequence.', + 'its cross-replica exclusion is off by the host\'s declaration. The database session lock each pass ' + + 'also takes, where the database offers one (Postgres, MySQL), still keeps two replicas\' passes apart, and ' + + 'the checkpoint table\'s unique (sealed_object, chain_key, sequence) index still refuses a second ' + + 'checkpoint at a taken sequence.', ); } return acquireInProcessLock(); @@ -383,13 +426,28 @@ export class AuditSealer { } const lock = await this.acquireLock(); if (!lock) return 0; + // D3 amended (E): the audit seal lock beside audit.sealer, on each sealed object's database, or no pass. + let session: AuditSealPassLocks; + try { + session = await trySealPassLocks(this.options.engine, plans.map((p) => p.name)); + } catch (err) { + await lock.release(); + throw err; + } + if (session.held) { + await lock.release(); + this.reportSealLockHeld(session.objects); + return 0; + } + this.reported.delete('seal-lock-held'); + const passLock = passLockOf(lock, session.locks); try { let written = 0; for (const plan of plans) { // One object's fault never stops another's sealing; it is reported while it lasts. let pass: ObjectPass | undefined; try { - pass = new ObjectPass(this.options, plan, lock, signer, this.now()); + pass = new ObjectPass(this.options, plan, passLock, signer, this.now()); await pass.run(); for (const cause of this.reported.keys()) if (cause.startsWith(`object:${plan.name}:`)) this.reported.delete(cause); } catch (err) { @@ -405,9 +463,28 @@ export class AuditSealer { } return written; } finally { + for (const held of session.locks) await held.lock.release(); await lock.release(); } } + + /** + * D3 amended (E): another session holds the audit seal lock, so the pass was + * skipped. Expected while an `os migrate audit-*` run lasts (or another + * server's pass), so at `info`, once per {@link REPORT_REPEAT_MS} while it + * lasts; a pass that takes the lock forgets it. + */ + private reportSealLockHeld(objects: readonly string[]): void { + const last = this.reported.get('seal-lock-held'); + if (last !== undefined && this.now() - last < REPORT_REPEAT_MS) return; + this.reported.set('seal-lock-held', this.now()); + this.options.logger.info( + `AuditSealer: the audit seal lock ('${AUDIT_SEAL_LOCK_NAME}') on the database of ` + + `${objects.map((o) => `'${o}'`).join(', ')} is held by another session — a run of ` + + `${AUDIT_SEAL_LOCK_REWRITE_COMMANDS}, or another server's sealer pass — so this pass is skipped and seals ` + + 'nothing until it lets go; each pass tries again.', + ); + } } /** One pass over one sealed object. */ @@ -435,7 +512,7 @@ class ObjectPass { constructor( private readonly options: AuditSealerOptions, private readonly plan: SealPlan, - private readonly lock: LockHandle, + private readonly lock: PassLock, private readonly signer: IAuditCheckpointSigner & { activeKeyId?(): Promise }, private readonly now: number, ) { @@ -865,7 +942,8 @@ class ObjectPass { sealed_at: sealedAt, signing_key_id: signingKeyId, })); - if (!this.lock.isHeld()) throw new Error('the audit.sealer lock lapsed before the checkpoint was written'); + const lapsed = await this.lock.lapsed(this.plan.name); + if (lapsed) throw new Error(`${lapsed} lapsed before the checkpoint was written`); // S1: the chain's window head, re-read under the lease: a window another sealer sealed (or passed) // since this pass began is not sealed again. Windows of a chain are sealed oldest first, and the parts of // one window in order (S7), so only a later window or a part of this one at this index or past it refuses. diff --git a/packages/plugins/plugin-audit/src/index.ts b/packages/plugins/plugin-audit/src/index.ts index 8476e22a271..8ccd3f4eb80 100644 --- a/packages/plugins/plugin-audit/src/index.ts +++ b/packages/plugins/plugin-audit/src/index.ts @@ -138,6 +138,7 @@ export { planActivityRowPatch, redactLedgerSnapshotBody, STORED_METADATA_BODY_AUDIT_OBJECTS, + STORED_METADATA_BODY_REWRITTEN_OBJECTS, } from './stored-metadata-body-migration.js'; export type { MigrationLogger, @@ -233,18 +234,30 @@ export type { // this one reads: the `sys_secret` reference union (`@objectstack/cli`) finds // the sealer's secrets through the holder list, the coordinate predicate and // the two sealing contexts, and `os audit verify` runs the live check (D9), -// writes its proof bundle, and checks one offline. +// writes its proof bundle, and checks one offline. The `os migrate audit-*` +// rewrites hold the audit seal lock for their whole `--apply` run (D3 as +// amended by seat ruling 6885005594). // The rest of the pure core (`./audit-seal/`) is reached by path inside this // package. export { AUDIT_PROOF_BUNDLE_FORMAT, AUDIT_ROW_VERDICTS, + AUDIT_SEAL_LOCK_NAME, + AUDIT_SEAL_LOCK_WAIT_MS, AUDIT_SEAL_SECRET_HOLDERS, AuditProofBundleError, checkpointSeedContext, + holdAuditSealLock, isAuditSealSecretCoordinate, signingKeyContext, verifyAuditLedger, verifyAuditProofBundle, } from './audit-seal/index.js'; -export type { AuditProofBundle, AuditRowVerdict, AuditVerifyReport } from './audit-seal/index.js'; +export type { + AuditProofBundle, + AuditRowVerdict, + AuditSealLockEngine, + AuditSealLockFinish, + AuditSealLockHold, + AuditVerifyReport, +} from './audit-seal/index.js'; diff --git a/packages/plugins/plugin-audit/src/stored-metadata-body-migration.ts b/packages/plugins/plugin-audit/src/stored-metadata-body-migration.ts index 9159d5f3147..de448e4ae35 100644 --- a/packages/plugins/plugin-audit/src/stored-metadata-body-migration.ts +++ b/packages/plugins/plugin-audit/src/stored-metadata-body-migration.ts @@ -108,6 +108,14 @@ export function withheldStoredHashTokens(text: string): string { /** [#21207] The decision-audit table whose conflict notes named both stored hashes. */ export const METADATA_DECISION_AUDIT_OBJECT = 'sys_metadata_audit'; +/** + * Every table {@link migrateStoredMetadataBodyCopies} rewrites: the two copy + * tables and the decision-audit table. The one list its run reads, and the + * objects `os migrate audit-metadata-bodies --apply` holds the audit seal lock + * for (ADR-0154 D3 as amended). + */ +export const STORED_METADATA_BODY_REWRITTEN_OBJECTS = [...STORED_METADATA_BODY_AUDIT_OBJECTS, METADATA_DECISION_AUDIT_OBJECT] as const; + /** The persisted code of an optimistic-concurrency refusal's decision-audit row. */ // adr0112-ok: D6b — the persisted audit column's own vocabulary, not a wire code const CONFLICT_NOTE_CODE = 'metadata_conflict'; @@ -434,13 +442,13 @@ export async function migrateStoredMetadataBodyCopies( // [#21207] The copies of a decision-audit row are read too (its conflict // note named both stored hashes), and so is the decision-audit table itself. const copiedObjects = [...STORED_METADATA_BODY_OBJECTS, METADATA_DECISION_AUDIT_OBJECT]; - const tables: ReadonlyArray<{ object: string; where: Record }> = [ - ...STORED_METADATA_BODY_AUDIT_OBJECTS.map((object) => ({ object, where: { object_name: { $in: copiedObjects } } })), - // A PREDICATE on the persisted `code` column (ADR-0112 D6b, the audit - // column's own vocabulary), written in operator form: it reads rows by the - // code they carry and stamps none. - { object: METADATA_DECISION_AUDIT_OBJECT, where: { code: { $eq: CONFLICT_NOTE_CODE } } }, - ]; + // A decision-audit row is read by a PREDICATE on the persisted `code` column + // (ADR-0112 D6b, the audit column's own vocabulary), written in operator form: + // it reads rows by the code they carry and stamps none. + const tables: ReadonlyArray<{ object: string; where: Record }> = STORED_METADATA_BODY_REWRITTEN_OBJECTS.map((object) => ({ + object, + where: object === METADATA_DECISION_AUDIT_OBJECT ? { code: { $eq: CONFLICT_NOTE_CODE } } : { object_name: { $in: copiedObjects } }, + })); for (const { object, where } of tables) { report.byObject[object] = { scanned: 0, rewritten: 0, refused: 0 }; const sealed = amender?.isSealed(object) === true;