Skip to content

Commit 1d58fb8

Browse files
committed
Merge remote-tracking branch 'origin/main' into claude/area-A5b-34199
2 parents 0f98ad4 + 35c9a30 commit 1d58fb8

19 files changed

Lines changed: 1747 additions & 157 deletions
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
'@objectstack/plugin-audit': patch
3+
'@objectstack/objectql': patch
4+
'@objectstack/cli': patch
5+
---
6+
7+
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`
8+
9+
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`.
10+
Metadata-protocol: none
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: the moved answer is whether an os migrate audit-* --apply run may proceed while a sealer could be sealing the rows it rewrites. The one-line fix for a refused run is in the body: stop the servers that seal the database and pass --sealer-stopped, or let the sealer pass finish. -->
13+
14+
**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.
15+
16+
**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).
17+
18+
- 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.
19+
- 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.
20+
- Two replicas with no cluster service now also keep their passes apart through this lock on Postgres and MySQL.
21+
- 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.
22+
- 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.
23+
24+
**`@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.

‎packages/cli/src/commands/migrate/audit-key-material.ts‎

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { absentTableReads } from '../../utils/absent-table-reads.js';
2424
import { exitOneShotCommand } from '../../utils/one-shot-exit.js';
2525
import { archiveFailureCount, examineArchiveTargets } from '../../utils/ledger-copy-archive.js';
2626
import { composeRedactionSeal } from '../../utils/audit-redaction-seal.js';
27+
import { sealerStoppedFlag, underAuditSealLock } from '../../utils/audit-seal-lock.js';
2728

2829
async function confirm(question: string): Promise<boolean> {
2930
if (!process.stdin.isTTY) return false; // non-interactive → require --yes
@@ -103,6 +104,7 @@ export default class MigrateAuditKeyMaterial extends Command {
103104
default: false,
104105
}),
105106
json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }),
107+
'sealer-stopped': sealerStoppedFlag,
106108
};
107109

108110
/**
@@ -227,24 +229,33 @@ export default class MigrateAuditKeyMaterial extends Command {
227229
};
228230

229231
const seal = redaction.seal(stack.kernel, engine);
230-
const report = await migrateKeyMaterialCopies(readView, logger, { apply, seal });
231-
232-
// Each copy table's declared archive target, then the same rewrite
233-
// through that datasource's driver.
234-
const archive = await examineArchiveTargets({
232+
// [ADR-0154 D3 amended] An --apply run holds the audit seal lock from before its first rewrite to after its
233+
// last, archive runs included, so no sealer pass seals a row it rewrites; where the database offers no session
234+
// lock, a run on a sealed object needs --sealer-stopped (seat ruling 6885005594, E + B).
235+
const { result: { report, archive }, lostLock } = await underAuditSealLock(
235236
engine,
236-
kernel: stack.kernel,
237-
reads: readView,
238-
tables: KEY_MATERIAL_COPY_TABLES,
239-
run: (driver, objects) => migrateArchivedKeyMaterialCopies(driver, logger, { apply, objects, seal }),
240-
});
237+
{ apply, sealerStopped: flags['sealer-stopped'], objects: KEY_MATERIAL_COPY_TABLES, warn: (line) => logger.warn(line) },
238+
async () => {
239+
const report = await migrateKeyMaterialCopies(readView, logger, { apply, seal });
240+
// Each copy table's declared archive target, then the same rewrite
241+
// through that datasource's driver.
242+
const archive = await examineArchiveTargets({
243+
engine,
244+
kernel: stack.kernel,
245+
reads: readView,
246+
tables: KEY_MATERIAL_COPY_TABLES,
247+
run: (driver, objects) => migrateArchivedKeyMaterialCopies(driver, logger, { apply, objects, seal }),
248+
});
249+
return { report, archive };
250+
},
251+
);
241252
const failures = report.failures + archiveFailureCount(archive);
242253
const refused = report.refused + archive.reduce((n, a) => n + (a.report?.refused ?? 0), 0);
243254

244255
if (flags.json) {
245256
reads.notice(true);
246-
await emitJson({ database: stack.dbLabel, apply, report, archive, duration: timer.elapsed() });
247-
if (failures > 0 || refused > 0) this.exit(1);
257+
await emitJson({ database: stack.dbLabel, apply, report, archive, ...(lostLock ? { sealLockLost: lostLock } : {}), duration: timer.elapsed() });
258+
if (failures > 0 || refused > 0 || lostLock) this.exit(1);
248259
return;
249260
}
250261

@@ -299,6 +310,7 @@ export default class MigrateAuditKeyMaterial extends Command {
299310

300311
const rewritten = report.rewritten + archive.reduce((n, a) => n + (a.report?.rewritten ?? 0), 0);
301312
if (refused > 0) printError(redaction.refusedLine(refused));
313+
if (lostLock) printError(lostLock);
302314
if (failures > 0) {
303315
printError(`${failures} read(s), row(s) or archive datasource(s) failed — re-run to finish them.`);
304316
} else if (apply && rewritten > 0) {
@@ -312,7 +324,7 @@ export default class MigrateAuditKeyMaterial extends Command {
312324
}
313325
console.log(chalk.dim(` ${timer.display()}`));
314326
console.log('');
315-
if (failures > 0 || refused > 0) this.exit(1);
327+
if (failures > 0 || refused > 0 || lostLock) this.exit(1);
316328
} catch (error: any) {
317329
if (isExitSignal(error)) throw error;
318330
if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); }

‎packages/cli/src/commands/migrate/audit-mail-bodies.ts‎

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { absentTableReads } from '../../utils/absent-table-reads.js';
2424
import { exitOneShotCommand } from '../../utils/one-shot-exit.js';
2525
import { archiveFailureCount, examineArchiveTargets } from '../../utils/ledger-copy-archive.js';
2626
import { composeRedactionSeal } from '../../utils/audit-redaction-seal.js';
27+
import { sealerStoppedFlag, underAuditSealLock } from '../../utils/audit-seal-lock.js';
2728

2829
async function confirm(question: string): Promise<boolean> {
2930
if (!process.stdin.isTTY) return false; // non-interactive → require --yes
@@ -110,6 +111,7 @@ export default class MigrateAuditMailBodies extends Command {
110111
default: false,
111112
}),
112113
json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }),
114+
'sealer-stopped': sealerStoppedFlag,
113115
};
114116

115117
/**
@@ -235,25 +237,34 @@ export default class MigrateAuditMailBodies extends Command {
235237
};
236238

237239
const seal = redaction.seal(stack.kernel, engine);
238-
const report = await migrateMailLogBodyCopies(readView, logger, { apply, seal });
239-
240-
// [#24899] Each copy table's declared archive target, then the same
241-
// runner through that datasource's driver (`examineArchiveTargets`).
242-
const archive = await examineArchiveTargets({
240+
// [ADR-0154 D3 amended] An --apply run holds the audit seal lock from before its first rewrite to after its
241+
// last, archive runs included, so no sealer pass seals a row it rewrites; where the database offers no session
242+
// lock, a run on a sealed object needs --sealer-stopped (seat ruling 6885005594, E + B).
243+
const { result: { report, archive }, lostLock } = await underAuditSealLock(
243244
engine,
244-
kernel: stack.kernel,
245-
reads: readView,
246-
tables: MAIL_LOG_BODY_COPY_OBJECTS,
247-
run: (driver, objects) => migrateArchivedMailLogBodyCopies(driver, logger, { apply, objects, seal }),
248-
});
245+
{ apply, sealerStopped: flags['sealer-stopped'], objects: MAIL_LOG_BODY_COPY_OBJECTS, warn: (line) => logger.warn(line) },
246+
async () => {
247+
const report = await migrateMailLogBodyCopies(readView, logger, { apply, seal });
248+
// [#24899] Each copy table's declared archive target, then the same
249+
// runner through that datasource's driver (`examineArchiveTargets`).
250+
const archive = await examineArchiveTargets({
251+
engine,
252+
kernel: stack.kernel,
253+
reads: readView,
254+
tables: MAIL_LOG_BODY_COPY_OBJECTS,
255+
run: (driver, objects) => migrateArchivedMailLogBodyCopies(driver, logger, { apply, objects, seal }),
256+
});
257+
return { report, archive };
258+
},
259+
);
249260
const archiveFailures = archiveFailureCount(archive);
250261
const failures = report.failures + archiveFailures;
251262
const refused = report.refused + archive.reduce((n, a) => n + (a.report?.refused ?? 0), 0);
252263

253264
if (flags.json) {
254265
reads.notice(true);
255-
await emitJson({ database: stack.dbLabel, apply, report, archive, duration: timer.elapsed() });
256-
if (failures > 0 || refused > 0) this.exit(1);
266+
await emitJson({ database: stack.dbLabel, apply, report, archive, ...(lostLock ? { sealLockLost: lostLock } : {}), duration: timer.elapsed() });
267+
if (failures > 0 || refused > 0 || lostLock) this.exit(1);
257268
return;
258269
}
259270

@@ -308,6 +319,7 @@ export default class MigrateAuditMailBodies extends Command {
308319

309320
const rewritten = report.rewritten + archive.reduce((n, a) => n + (a.report?.rewritten ?? 0), 0);
310321
if (refused > 0) printError(redaction.refusedLine(refused));
322+
if (lostLock) printError(lostLock);
311323
if (failures > 0) {
312324
printError(`${failures} read(s), row(s) or archive datasource(s) failed — re-run to finish them.`);
313325
} else if (apply && rewritten > 0) {
@@ -321,7 +333,7 @@ export default class MigrateAuditMailBodies extends Command {
321333
}
322334
console.log(chalk.dim(` ${timer.display()}`));
323335
console.log('');
324-
if (failures > 0 || refused > 0) this.exit(1);
336+
if (failures > 0 || refused > 0 || lostLock) this.exit(1);
325337
} catch (error: any) {
326338
if (isExitSignal(error)) throw error;
327339
if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); }

‎packages/cli/src/commands/migrate/audit-metadata-bodies.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { describeOccupancy, JOURNAL_MODE_SWITCH_NOTE } from '../../utils/sqlite-
2222
import { buildDataMigrationPlugins } from '../../utils/data-migration-plugins.js';
2323
import { absentTableReads } from '../../utils/absent-table-reads.js';
2424
import { composeRedactionSeal } from '../../utils/audit-redaction-seal.js';
25+
import { sealerStoppedFlag, underAuditSealLock } from '../../utils/audit-seal-lock.js';
2526

2627
async function confirm(question: string): Promise<boolean> {
2728
if (!process.stdin.isTTY) return false; // non-interactive → require --yes
@@ -88,6 +89,7 @@ export default class MigrateAuditMetadataBodies extends Command {
8889
default: false,
8990
}),
9091
json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to apply)' }),
92+
'sealer-stopped': sealerStoppedFlag,
9193
};
9294

9395
async run(): Promise<void> {
@@ -177,7 +179,7 @@ export default class MigrateAuditMetadataBodies extends Command {
177179
throw new Error('No ObjectQL engine on this stack — cannot rewrite audit rows.');
178180
}
179181

180-
const { migrateStoredMetadataBodyCopies } = await import('@objectstack/plugin-audit');
182+
const { migrateStoredMetadataBodyCopies, STORED_METADATA_BODY_REWRITTEN_OBJECTS } = await import('@objectstack/plugin-audit');
181183

182184
const logger = flags.json
183185
? { info: (m: string) => console.error(m), warn: (m: string) => console.error(m) }
@@ -207,12 +209,20 @@ export default class MigrateAuditMetadataBodies extends Command {
207209
update: (object, data, options) => engine.update(object, data, options),
208210
};
209211

210-
const report = await migrateStoredMetadataBodyCopies(readView, logger, { apply, seal: redaction.seal(stack.kernel, engine) });
212+
const seal = redaction.seal(stack.kernel, engine);
213+
// [ADR-0154 D3 amended] An --apply run holds the audit seal lock from before its first rewrite to after its
214+
// last, archive runs included, so no sealer pass seals a row it rewrites; where the database offers no session
215+
// lock, a run on a sealed object needs --sealer-stopped (seat ruling 6885005594, E + B).
216+
const { result: report, lostLock } = await underAuditSealLock(
217+
engine,
218+
{ apply, sealerStopped: flags['sealer-stopped'], objects: STORED_METADATA_BODY_REWRITTEN_OBJECTS, warn: (line) => logger.warn(line) },
219+
() => migrateStoredMetadataBodyCopies(readView, logger, { apply, seal }),
220+
);
211221

212222
if (flags.json) {
213223
reads.notice(true);
214-
await emitJson({ database: stack.dbLabel, apply, report, duration: timer.elapsed() });
215-
if (report.failures > 0 || report.refused > 0) this.exit(1);
224+
await emitJson({ database: stack.dbLabel, apply, report, ...(lostLock ? { sealLockLost: lostLock } : {}), duration: timer.elapsed() });
225+
if (report.failures > 0 || report.refused > 0 || lostLock) this.exit(1);
216226
return;
217227
}
218228

@@ -228,6 +238,7 @@ export default class MigrateAuditMetadataBodies extends Command {
228238
console.log('');
229239

230240
if (report.refused > 0) printError(redaction.refusedLine(report.refused));
241+
if (lostLock) printError(lostLock);
231242
if (report.failures > 0) {
232243
printError(`${report.failures} row(s) could not be rewritten — re-run to finish them.`);
233244
} else if (apply && report.rewritten > 0) {
@@ -243,7 +254,7 @@ export default class MigrateAuditMetadataBodies extends Command {
243254
}
244255
console.log(chalk.dim(` ${timer.display()}`));
245256
console.log('');
246-
if (report.failures > 0 || report.refused > 0) this.exit(1);
257+
if (report.failures > 0 || report.refused > 0 || lostLock) this.exit(1);
247258
} catch (error: any) {
248259
if (isExitSignal(error)) throw error;
249260
if (flags.json) { await emitJson({ error: error.message, ...errorCodeFields(error) }, 0, { compact: true }); this.exit(1); }

0 commit comments

Comments
 (0)