From d41ddf57018a16bd50b1142626e585b8b9711a12 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:50:01 +0000 Subject: [PATCH 01/12] test(plugin-audit): pin the late re-read, the lost-sequence seed drop, the keyset tie arm, and one opening per checkpoint per run New pins, written before the fixes: a late checkpoint never lists a row another sealer sealed since the pass read the window's lists (N1); the seed of a checkpoint whose sequence another checkpoint holds is dropped (N2); rows of one created_at straddling the page boundary are each read once (S2 tie arm, N3); and one redaction run verifies each checkpoint and opens each seed once, while still refusing every row a checkpoint that does not verify, or whose seed does not open, lists. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- ...it-seal-redaction-live.integration.test.ts | 83 ++++++++++++++++++- .../src/audit-seal/audit-seal-sealer.test.ts | 64 ++++++++++++++ 2 files changed, 146 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-redaction-live.integration.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-redaction-live.integration.test.ts index 16acf8f950e..c7c6eb4be65 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-redaction-live.integration.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-redaction-live.integration.test.ts @@ -4,7 +4,7 @@ import { ObjectKernel } from '@objectstack/core'; import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import { SysSecret } from '@objectstack/platform-objects/system'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { AuditPlugin } from '../audit-plugin.js'; import { installDefaultOrganization } from '../default-organization.testkit.js'; import { migrateKeyMaterialCopies } from '../key-material-copy-migration.js'; @@ -18,6 +18,7 @@ import { bindingCrypto, recordingLogger } from './seal-store.testkit.js'; import type { AuditSealer } from './sealer.js'; import { amendmentRow, type RedactionAmendmentBody } from './signed-body.js'; import { LocalCheckpointSigner, readAuditSealSecret } from './signer.js'; +import { SigningKeyTrust } from './verifier.js'; /** * ADR-0154 D7 on a live engine over SQLite, with an `archive` datasource: @@ -296,6 +297,86 @@ describe('the redaction writer admits only inputs that verify under a trusted ke }); }); +describe('one run admits, rebuilds and opens each checkpoint once, however many rows it lists (ADR-0154 D6, D7)', () => { + const crypto = bindingCrypto(); + const plugin = new AuditPlugin({ cryptoProvider: crypto }); + const ROWS = 4; + const CHAINS = ['org_a', 'org_b', 'org_c'] as const; + let kernel: ObjectKernel; + let engine: ObjectQL; + let report: Awaited>; + const logger = recordingLogger(); + /** Each checkpoint's signature verifications, and each seed opened, during the one run. */ + const verified = new Map(); + const opened = new Map(); + const past = Math.floor(Date.now() / H) * H - 3 * H; + const iso = (ms: number) => new Date(ms).toISOString(); + const hot = () => engine.getDriverForObject(LOG) as unknown as Driver; + const idsOf = (tenant: string) => Array.from({ length: ROWS }, (_, i) => `${tenant}_${i}`); + const checkpointOf = async (tenant: string) => + ((await engine.find('sys_audit_checkpoint', { context: SYS })) as Row[]).find((r) => r.tenant_id === tenant)!; + + beforeAll(async () => { + ({ kernel, engine } = await bootSealedLog(plugin)); + for (const tenant of CHAINS) { + for (const [i, id] of idsOf(tenant).entries()) { + await hot().create(LOG, { + id, created_at: iso(past + (i + 1) * 60_000), action: 'create', object_name: 'sys_email', record_id: `${id}_rec`, tenant_id: tenant, + new_value: JSON.stringify({ id: `em_${id}`, body_text: MAIL_BODY }), + }); + } + } + const sealer = (plugin as unknown as { sealer: AuditSealer }).sealer; + await sealer.stop(); + expect(await sealer.runPass()).toBe(CHAINS.length); + // org_b's checkpoint no longer verifies; org_c's seed no longer opens. + await hot().update('sys_audit_checkpoint', String((await checkpointOf('org_b')).id), { signature: Buffer.alloc(64).toString('base64') }); + const seed = String((await checkpointOf('org_c')).seed_handle); + await (engine.getDriverForObject('sys_secret') as unknown as Driver).update('sys_secret', seed, { ciphertext: Buffer.alloc(60).toString('base64') }); + + // Both spies call through: they only count. + const signature = vi.spyOn(SigningKeyTrust.prototype, 'signature'); + const decrypt = vi.spyOn(crypto, 'decrypt'); + try { + report = await migrateMailLogBodyCopies(engine as never, logger, { apply: true, seal: { engine: engine as never, crypto }, objects: ['sys_audit_log'] }); + } finally { + for (const [, bytes] of signature.mock.calls) { + const body = JSON.parse(Buffer.from(bytes).toString('utf8')) as Row; + if (Array.isArray(body.row_ids)) verified.set(String(body.tenant_id), (verified.get(String(body.tenant_id)) ?? 0) + 1); + } + for (const [, ctx] of decrypt.mock.calls) if (ctx.namespace === LOG) opened.set(ctx.key, (opened.get(ctx.key) ?? 0) + 1); + signature.mockRestore(); + decrypt.mockRestore(); + } + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('verifies each checkpoint once (#32737)', () => { + expect(Object.fromEntries(verified)).toEqual({ org_a: 1, org_b: 1, org_c: 1 }); + }); + + it('opens each seed it reaches once, an answer that does not open included (#32737)', () => { + // org_b's seed is never reached: its checkpoint does not verify. + expect(Object.fromEntries(opened)).toEqual({ '["org_a",0]': 1, '["org_c",0]': 1 }); + }); + + it("amends every row of a checkpoint that verifies and opens, and the live check reads each redacted", async () => { + expect(report).toMatchObject({ scanned: CHAINS.length * ROWS, rewritten: ROWS, refused: 2 * ROWS, failures: 0 }); + const result = await verifyAuditLedger({ engine: engine as never, crypto }); + expect(verdicts(result)).toMatchObject(Object.fromEntries(idsOf('org_a').map((id) => [id, 'redacted']))); + }); + + it('still refuses every row a checkpoint that does not verify lists, and every row a seed that does not open sealed', async () => { + const refusals = (pattern: RegExp) => logger.lines.filter((l) => l.level === 'warn' && pattern.test(l.message)).map((l) => /sys_audit_log\/(\w+),/.exec(l.message)?.[1]); + expect(refusals(/a sealed row: checkpoint 0 that lists it does not verify under a trusted signing key/)).toEqual(idsOf('org_b')); + expect(refusals(/a sealed row: the seed of checkpoint 0 that sealed it does not open/)).toEqual(idsOf('org_c')); + for (const id of [...idsOf('org_b'), ...idsOf('org_c')]) expect(String((await hot().find(LOG, { where: { id } }))[0]!.new_value)).toContain(MAIL_BODY); + }); +}); + describe('a one-shot boot arms no sealer (ADR-0154 D3)', () => { it('starts no sealer with `armSealer: false`, whatever crypto provider it is handed', async () => { const plugin = new AuditPlugin({ cryptoProvider: bindingCrypto(), armSealer: 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 11d5dcd8ddf..995068dcd5d 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 @@ -106,6 +106,26 @@ describe('windows: the backlog oldest first, one checkpoint per chain per window expect(s.checkpoints().flatMap((c) => c.row_ids)).toEqual(rows.map((r) => r.id)); }); + it('reads each row of a window once when rows of one created_at straddle the page boundary: the keyset tie arm (S2)', async () => { + const s = setup(); + // 495 rows a second apart, then 15 rows of one instant: the first page of 500 ends inside the tie. + const tie = at(8, 30); + const rows = Array.from({ length: 510 }, (_, i) => + row(`r${String(i).padStart(3, '0')}`, i < 495 ? new Date(DAY0 + 8 * H + i * 1_000).toISOString() : tie)); + s.hot.table('ledger_probe').push(...rows); + const reads = new Map(); + const find = s.hot.find.bind(s.hot); + s.hot.find = async (object, query) => { + const page = await find(object, query); + if (object === 'ledger_probe' && query.limit === 500) for (const r of page) reads.set(String(r.id), (reads.get(String(r.id)) ?? 0) + 1); + return page; + }; + await s.sealer.runPass(); + expect(s.checkpoints().flatMap((c) => c.row_ids)).toEqual(rows.map((r) => r.id)); + expect(reads.size).toBe(510); + expect([...reads].filter(([, n]) => n !== 1)).toEqual([]); + }); + it('writes nothing on a second pass with nothing new', async () => { const s = setup(); s.hot.table('ledger_probe').push(row('r1', at(8, 10))); @@ -158,6 +178,30 @@ describe('late rows: re-counted and sealed as late, before the pass seals its wi expect(s.checkpoints().map((c) => [c.tenant_id, c.kind, c.row_ids])).toEqual([['org_a', 'window', ['a']], ['org_b', 'window', ['b']]]); expect(s.hot.table('sys_secret')).toHaveLength(4); // the key's half, two seeds, and the unstored write's seed kept as an orphan (M1) }); + + it("drops from a late checkpoint each row a checkpoint stored since the pass read the window's lists, so no row is sealed twice (N1)", async () => { + const cluster = grantingCluster(); + const s = setup({ cluster }); + const other = new AuditSealer({ engine: s.engine, crypto: s.crypto, signer: () => s.signer, cluster: () => cluster, logger: s.logger, now: () => s.clock.now }); + s.hot.table('ledger_probe').push(row('r1', at(10, 5))); + await s.sealer.runPass(); + s.hot.table('ledger_probe').push(row('late', at(10, 30))); + const find = s.hot.find.bind(s.hot); + let raced = false; + s.hot.find = async (object, query) => { + const page = await find(object, query); + // The pass's one read of the horizon's checkpoints; another sealer seals the late row right after it. + if (object === 'sys_audit_checkpoint' && !raced && (query.where as Record).window_start !== undefined) { + raced = true; + await other.runPass(); + } + return page; + }; + expect(await s.sealer.runPass()).toBe(0); + expect(s.checkpoints().filter((c) => c.row_ids.includes('late')).map((c) => [c.kind, c.sequence])).toEqual([['late', 1]]); + expect(s.hot.table('sys_secret').filter((r) => r.namespace === 'ledger_probe').map((r) => r.id).sort()) + .toEqual(s.checkpoints().map((c) => c.seed_handle).sort()); // nothing was sealed for the rows dropped + }); }); describe('the lock: audit.sealer, its fencing token on each checkpoint (D3, Q2 (a))', () => { @@ -300,6 +344,26 @@ describe('what the sealer writes, and where (ruling 3d)', () => { expect(await s.sealer.runPass()).toBe(0); }); + it('drops the seed of a checkpoint whose sequence another checkpoint holds: the unique index proves it can never be stored (N2)', async () => { + const cluster = grantingCluster(); + const s = setup({ cluster }); + const other = new AuditSealer({ engine: s.engine, crypto: s.crypto, signer: () => s.signer, cluster: () => cluster, logger: s.logger, now: () => s.clock.now }); + s.hot.table('ledger_probe').push(row('r1', at(8, 10))); + const insert = s.engine.insert.bind(s.engine); + let raced = false; + s.engine.insert = async (object, r, o) => { + if (object === 'sys_audit_checkpoint' && !raced) { + raced = true; + await other.runPass(); // stores this sequence first, past this pass's head re-read + } + return insert(object, r, o); + }; + expect(await s.sealer.runPass()).toBe(0); + expect(s.checkpoints().map((c) => c.sequence)).toEqual([0]); + expect(s.hot.table('sys_secret').filter((r) => r.namespace === 'ledger_probe').map((r) => r.id)).toEqual([s.checkpoints()[0].seed_handle]); + expect(s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message)).toEqual([expect.stringMatching(/UNIQUE constraint failed/)]); + }); + it('refuses an organization id too long for the seed coordinate before anything is sealed (Q6 (a))', async () => { const s = setup(); s.hot.table('ledger_probe').push(row('r1', at(8, 10), 'o'.repeat(130))); From 88a4abc22953ec060560b46d55c82891d7bcaee8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:51:18 +0000 Subject: [PATCH 02/12] fix(plugin-audit): admit and open each checkpoint once per redaction run; re-read a window's lists before a late checkpoint; drop a seed whose sequence another checkpoint holds The redaction amendment writer verified every listed checkpoint, rebuilt its root and opened its seed once per row (#32737). Each is now worked out once per checkpoint per run and reused for every row it lists, the answer that refuses included, so a checkpoint that does not verify, or whose seed does not open, still refuses every row it lists. The sealer re-read a chain's window head before a window insert only (S1). A late checkpoint now re-reads the window's checkpoints once the chain head is known and drops the rows already listed, so a row another sealer sealed in between is not listed twice (N1). When a rejected insert reads back a checkpoint at its sequence holding another seed, the seed it sealed can never be stored and is dropped rather than left an orphan (N2). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../src/audit-seal/amendment-writer.ts | 103 ++++++++++++++---- .../plugin-audit/src/audit-seal/sealer.ts | 22 +++- 2 files changed, 103 insertions(+), 22 deletions(-) diff --git a/packages/plugins/plugin-audit/src/audit-seal/amendment-writer.ts b/packages/plugins/plugin-audit/src/audit-seal/amendment-writer.ts index a5411b5a6fe..c298b773cac 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/amendment-writer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/amendment-writer.ts @@ -112,15 +112,38 @@ const NONE: RedactionDecision = Object.freeze({ kind: 'none' }); const messageOf = (err: unknown): string => String((err as Error)?.message ?? err); const refused = (reason: string): RedactionDecision => ({ kind: 'refused', reason }); -/** A stored checkpoint that lists a row, and its signed body. */ +/** A stored checkpoint and its signed body: one object per checkpoint, shared by every row it lists. */ interface ListedCheckpoint { readonly stored: Row; readonly body: CheckpointSignedBody; } +/** An opened checkpoint: the leaf hash it signed for each row it lists, and its salts; or why it does not open. */ +type OpenedCheckpoint = + | { readonly leafOf: ReadonlyMap; readonly saltOf: (rowId: string, column: string) => Buffer } + | string; + +/** An answer kept once it settles: a fault is kept too, and thrown again to each row that asks. */ +type Settled = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: unknown }; + +const settle = (pending: Promise): Promise> => + pending.then((value) => ({ ok: true as const, value }), (error: unknown) => ({ ok: false as const, error })); + +const unwrap = (settled: Settled): T => { + if (settled.ok) return settled.value; + throw settled.error; +}; + export class RedactionAmender { private sealedFields: Map | undefined; private readonly listings = new Map>>(); + /** + * Each listed checkpoint's admission and opening, worked out once per run + * and reused for every row it lists: its signature is verified once, its + * root rebuilt from `leaf_hashes` once, and its seed opened once. + */ + private readonly admissions = new Map>>(); + private readonly openings = new Map>>(); private trust: SigningKeyTrust | undefined; private signer: (IAuditCheckpointSigner & { activeKeyId?(): Promise }) | undefined; private keyId: string | null = null; @@ -175,6 +198,49 @@ export class RedactionAmender { return (await trust.signature(body.signing_key_id, signedBodyBytes(body), stored.signature)) === 'ok'; } + /** Whether a listed checkpoint is admitted ({@link admits}), answered once per run. */ + private admitted(trust: SigningKeyTrust, listed: ListedCheckpoint): Promise { + let pending = this.admissions.get(listed); + if (!pending) { + pending = settle(this.admits(trust, listed.body, listed.stored)); + this.admissions.set(listed, pending); + } + return pending.then(unwrap); + } + + /** + * A listed checkpoint, opened once per run: the leaf hashes it signed, + * matched against its signed root, and its seed. A seed that is missing or + * does not open is an answer too, given to every row the checkpoint lists; + * a re-run opens it again. + */ + private opened(crypto: ICryptoProvider, object: string, listed: ListedCheckpoint): Promise { + let pending = this.openings.get(listed); + if (!pending) { + pending = settle(this.open(crypto, object, listed)); + this.openings.set(listed, pending); + } + return pending.then(unwrap); + } + + private async open(crypto: ICryptoProvider, object: string, { stored, body }: ListedCheckpoint): Promise { + const hashes = checkpointLeafHashesFromRow(stored, body); + const handle = await readAuditSealSecret(this.seal.engine, body.seed_handle); + if (!handle) return `the seed of checkpoint ${body.sequence} that sealed it is missing`; + let seed: Buffer; + try { + seed = decodeCheckpointSeed(await crypto.decrypt(handle, checkpointSeedContext(object, body.tenant_id, body.sequence))); + } catch (err) { + return `the seed of checkpoint ${body.sequence} that sealed it does not open (${messageOf(err)})`; + } + // A row's leaf is the one at its first place in the list, as `row_ids.indexOf` reads it. + const leafOf = new Map(); + body.row_ids.forEach((id, at) => { + if (!leafOf.has(id)) leafOf.set(id, hashes[at]); + }); + return { leafOf, saltOf: columnSaltsOf(seed, object) }; + } + /** * The stored checkpoints of `object`, by each row id they list: a row is * located by its id, never by its own `created_at` or `tenant_id`, which an @@ -201,7 +267,8 @@ export class RedactionAmender { } catch { continue; // a malformed checkpoint holds nothing (D9) } - for (const id of body.row_ids) byRow.set(id, [...(byRow.get(id) ?? []), { stored, body }]); + const listed: ListedCheckpoint = { stored, body }; + for (const id of body.row_ids) byRow.set(id, [...(byRow.get(id) ?? []), listed]); } return byRow; })(); @@ -242,9 +309,9 @@ export class RedactionAmender { const crypto = this.seal.crypto; const trust = this.trustOf(); if (!crypto || !trust) return refused('no crypto provider is available to this run, so the seed of the checkpoint that sealed it cannot be opened'); - for (const { stored, body } of listing) { - if (!(await this.admits(trust, body, stored))) { - return refused(`checkpoint ${body.sequence} that lists it does not verify under a trusted signing key, so what it sealed cannot be shown`); + for (const listed of listing) { + if (!(await this.admitted(trust, listed))) { + return refused(`checkpoint ${listed.body.sequence} that lists it does not verify under a trusted signing key, so what it sealed cannot be shown`); } } const reader = rows ?? this.seal.engine.getDriverForObject(object); @@ -252,8 +319,9 @@ export class RedactionAmender { if (!row) return refused('the row could not be read whole, so whether it still matches its checkpoint cannot be told'); const prior = await this.admittedRedactions(trust, object, id); const drafts: RedactionDraft[] = []; - for (const { stored, body } of listing) { - const proven = await this.proveLeaf(crypto, object, id, row, fields, stored, body, prior); + for (const listed of listing) { + const { body } = listed; + const proven = await this.proveLeaf(crypto, object, id, row, fields, listed, prior); if (typeof proven === 'string') return refused(proven); for (const [column, value] of Object.entries(patch)) { if (body.columns.clear.includes(column)) { @@ -278,7 +346,7 @@ export class RedactionAmender { } /** - * The row's leaf under the admitted checkpoint `body`, rebuilt and matched + * The row's leaf under the admitted checkpoint `listed`, rebuilt and matched * against the leaf hash it signed, under the admitted redactions of the * row: the current commitments, the commitments it sealed, and the salts; * or why it does not match. @@ -289,20 +357,13 @@ export class RedactionAmender { id: string, row: Row, fields: SealedFieldTypes, - stored: Row, - body: CheckpointSignedBody, + listed: ListedCheckpoint, prior: readonly RedactionAmendmentBody[], ): Promise<{ current: Row; sealed: Row; saltOf: (rowId: string, column: string) => Buffer } | string> { - const hashes = checkpointLeafHashesFromRow(stored, body); - const handle = await readAuditSealSecret(this.seal.engine, body.seed_handle); - if (!handle) return `the seed of checkpoint ${body.sequence} that sealed it is missing`; - let seed: Buffer; - try { - seed = decodeCheckpointSeed(await crypto.decrypt(handle, checkpointSeedContext(object, body.tenant_id, body.sequence))); - } catch (err) { - return `the seed of checkpoint ${body.sequence} that sealed it does not open (${messageOf(err)})`; - } - const saltOf = columnSaltsOf(seed, object); + const { body } = listed; + const opened = await this.opened(crypto, object, listed); + if (typeof opened === 'string') return opened; + const { saltOf } = opened; const current = leafInput(row, body.columns, fields, saltOf); // The admitted redactions of this row: a column holding the commitment one rewrote to sealed the one it names. const sealed: Row = { ...current }; @@ -311,7 +372,7 @@ export class RedactionAmender { if (!body.columns.committed.includes(amendment.column_name)) continue; if (current[amendment.column_name] === amendment.rewritten_commitment) sealed[amendment.column_name] = amendment.sealed_commitment; } - if (leafHash(sealed).toString('hex') !== hashes[body.row_ids.indexOf(id)]) { + if (leafHash(sealed).toString('hex') !== opened.leafOf.get(id)) { return `it no longer matches checkpoint ${body.sequence} that sealed it, so the value that checkpoint sealed cannot be shown`; } return { current, sealed, saltOf }; diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index dd66d3fd705..03594ffc7e9 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -548,8 +548,17 @@ class ObjectPass { private async writeCheckpoint(chainKey: string, chain: ChainLeaves, start: number, kind: AuditCheckpointKind, watermark: number): Promise { const { engine, crypto } = this.options; - const ordered = [...chain.leaves].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); const head = await this.headOf(chainKey); + let leaves = chain.leaves; + if (kind === 'late') { + // N1: the window's checkpoints, re-read once this chain's head is known: a row another sealer listed + // since this pass read the window's lists is not sealed twice. One stored after the head was known + // takes a sequence at or past this one, so the unique index refuses whichever insert comes second. + const listed = await this.listedIn(start); + leaves = leaves.filter((leaf) => !listed.has(leaf.id)); + if (leaves.length === 0) return; + } + const ordered = [...leaves].sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); const sequence = head ? head.sequence + 1 : 0; // Q6: an over-long coordinate is refused here, before anything is encrypted or written. const context = checkpointSeedContext(this.plan.name, chain.tenantId, sequence); @@ -601,6 +610,9 @@ class ObjectPass { // never be recomputed. Unstored, the seed is an orphan for `os secret orphans`. const stored = await this.storedCheckpoint(chainKey, { sequence }).catch(() => undefined); if (stored?.seed_handle !== handle.id) { + // N2: another checkpoint holds this sequence, so the unique index proves this seed can never be + // stored: it is dropped. With no row read back, whether this insert stored is unknown, and it is kept. + if (stored !== undefined) await dropAuditSealSecret(engine, handle.id); this.heads.delete(chainKey); throw err; } @@ -613,6 +625,14 @@ class ObjectPass { await this.deliver(body, keyId, signature); } + /** The row ids the stored checkpoints of window `start` list, every chain's, as read now. */ + private async listedIn(start: number): Promise> { + const rows = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { + where: { sealed_object: this.plan.name, window_start: { $gte: iso(start), $lt: iso(start + AUDIT_SEAL_WINDOW_MS) } }, + }); + return new Set(rows.flatMap((r) => checkpointBodyFromRow(r).row_ids)); + } + /** This chain's stored checkpoint matching `where`, if any. */ private async storedCheckpoint(chainKey: string, where: Row): Promise { const [row] = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { where: { sealed_object: this.plan.name, chain_key: chainKey, ...where }, limit: 1 }); From 3bcc33204642288031b7f6b49d4dc23e734cbc9f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:52:25 +0000 Subject: [PATCH 03/12] docs(spec): the plugin-audit group of the platform object names says the package registers sys_audit_amendment too The comment still called sys_audit_amendment the one name in the group the package does not register; AuditPlugin registers and provisions it beside the checkpoints and the signing keys. Comment only. Adds the changeset for this slice. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .changeset/31908-p4a-audit-seal-once-per-run.md | 15 +++++++++++++++ .../src/system/constants/platform-object-names.ts | 7 +++---- 2 files changed, 18 insertions(+), 4 deletions(-) create mode 100644 .changeset/31908-p4a-audit-seal-once-per-run.md diff --git a/.changeset/31908-p4a-audit-seal-once-per-run.md b/.changeset/31908-p4a-audit-seal-once-per-run.md new file mode 100644 index 00000000000..f24037fbd40 --- /dev/null +++ b/.changeset/31908-p4a-audit-seal-once-per-run.md @@ -0,0 +1,15 @@ +--- +'@objectstack/plugin-audit': patch +'@objectstack/spec': patch +--- + +fix(plugin-audit): a redaction run admits and opens each checkpoint once; a late checkpoint never lists a row another sealer already sealed; a seed whose sequence another checkpoint holds is dropped + +Clause-②: no +Metadata-protocol: none + +**Redaction runs (`os migrate audit-mail-bodies`, `audit-key-material`, `audit-metadata-bodies`).** The redaction amendment writer verified a checkpoint's signature, rebuilt its root from `leaf_hashes` and opened its seed through the crypto provider once for every row the checkpoint lists. It now does each once per checkpoint per run (the hot run and the archive run are each one run) and reuses the answer for every row that checkpoint lists. With a KMS-backed provider that is one remote call per checkpoint instead of one per row. What a run decides is unchanged: a checkpoint that does not verify under a trusted signing key still refuses every row it lists, and a seed that is missing or does not open still refuses every row it sealed. A fault met while opening a checkpoint is now met once in a run and refuses every row that checkpoint lists; re-running the command tries it again. + +**The sealer.** A `late` checkpoint now re-reads its window's checkpoints once the chain's head is known, and leaves out every row a checkpoint stored in between already lists, so a row another sealer sealed while this pass ran is not listed by a second checkpoint. When a checkpoint insert is rejected and the read-back finds another checkpoint at that sequence, the seed the sealer just sealed can never be stored, so its `sys_secret` row is removed instead of being left for `os secret orphans`. A rejected insert with no row read back still keeps its seed, as before. + +`@objectstack/spec`: a source comment on the `plugin-audit` group of the platform object names now says that the package registers `sys_audit_amendment` too. No name, type or value changes. diff --git a/packages/spec/src/system/constants/platform-object-names.ts b/packages/spec/src/system/constants/platform-object-names.ts index 60b3f91c0f0..b66cf6552ab 100644 --- a/packages/spec/src/system/constants/platform-object-names.ts +++ b/packages/spec/src/system/constants/platform-object-names.ts @@ -114,10 +114,9 @@ export const PLATFORM_OBJECTS_BY_PACKAGE: Readonly Date: Sat, 14 Nov 2026 22:23:12 +0000 Subject: [PATCH 04/12] test(plugin-audit): pin per-chain sealer isolation: a chain-local fault skips only its chain, sealed_through holds, verify stays loud Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../src/audit-seal/audit-seal-sealer.test.ts | 73 ++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) 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 995068dcd5d..8f5ddc615bf 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 @@ -2,7 +2,7 @@ import type { IAuditCheckpointSigner, IClusterService, LockHandle } from '@objectstack/spec/contracts'; import { describe, expect, it } from 'vitest'; -import { checkpointBodyFromRow, checkpointDigest, signedBodyBytes } from './index.js'; +import { checkpointBodyFromRow, checkpointDigest, signedBodyBytes, verifyAuditLedger } from './index.js'; import { bindingCrypto, memoryEngine, recordingLogger } from './seal-store.testkit.js'; import { AUDIT_SEALER_LOCK, AuditSealer } from './sealer.js'; import { LocalCheckpointSigner } from './signer.js'; @@ -204,6 +204,77 @@ describe('late rows: re-counted and sealed as late, before the pass seals its wi }); }); +describe('per-chain isolation: only a chain-local fault skips a chain, and only that chain (S4, seat ruling 6884540128 item 2)', () => { + /** A row the canonical rule of its `payload` column (text) refuses: a number. */ + const refused = (id: string, created: string, tenant: string | null) => ({ ...row(id, created, tenant), payload: 42 }); + const errors = (s: ReturnType) => s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message); + + it('skips the chain of a row a canonical rule refuses, seals every other chain, and holds sealed_through at the skipped window', async () => { + const s = setup(); + s.hot.table('ledger_probe').push( + row('a1', at(8, 10)), refused('b1', at(8, 20), 'org_b'), row('d1', at(8, 30), null), + row('a2', at(9, 10)), row('b2', at(9, 20), 'org_b'), row('a3', at(10, 10)), + ); + expect(await s.sealer.runPass()).toBe(4); + expect(s.checkpoints().map((c) => [c.window_start, c.tenant_id, c.kind, c.row_ids, c.sealed_through])).toEqual([ + [at(8, 0), null, 'window', ['d1'], at(8, 0)], + [at(8, 0), 'org_a', 'window', ['a1'], at(8, 0)], + // org_b is out for the rest of the pass, so the 09:00 window has a skipped chain: no watermark past 08:00. + [at(9, 0), 'org_a', 'window', ['a2'], at(8, 0)], + [at(10, 0), 'org_a', 'window', ['a3'], at(8, 0)], + ]); + expect(errors(s)).toEqual([expect.stringMatching(/'ledger_probe'.*chain 'org:org_b'.*b1\.payload.*not text.*NOT being sealed/)]); + }); + + it('resumes a skipped chain from its own oldest unsealed window, as window checkpoints and not late ones', async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('a1', at(8, 10)), refused('b1', at(8, 20), 'org_b'), row('a2', at(9, 10)), row('b2', at(9, 20), 'org_b')); + expect(await s.sealer.runPass()).toBe(2); + s.hot.table('ledger_probe').find((r) => r.id === 'b1')!.payload = '{"v":"b1"}'; + expect(await s.sealer.runPass()).toBe(2); + expect(s.checkpoints().slice(2).map((c) => [c.window_start, c.tenant_id, c.kind, c.sequence, c.row_ids, c.sealed_through])).toEqual([ + [at(8, 0), 'org_b', 'window', 0, ['b1'], at(8, 0)], + [at(9, 0), 'org_b', 'window', 1, ['b2'], at(9, 0)], + ]); + expect(await s.sealer.runPass()).toBe(0); + }); + + it('skips the chain whose head checkpoint is malformed, and seals the others past it', async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('a1', at(8, 10)), row('b1', at(8, 20), 'org_b')); + expect(await s.sealer.runPass()).toBe(2); + s.hot.table('sys_audit_checkpoint').find((r) => r.tenant_id === 'org_b')!.root = 'not a digest'; + s.hot.table('ledger_probe').push(row('a2', at(9, 10)), row('b2', at(9, 20), 'org_b'), row('a3', at(10, 10))); + expect(await s.sealer.runPass()).toBe(2); + expect(s.hot.table('sys_audit_checkpoint').slice(2).map((r) => checkpointBodyFromRow(r)).map((c) => [c.tenant_id, c.sequence, c.row_ids, c.sealed_through])) + .toEqual([['org_a', 1, ['a2'], at(9, 0)], ['org_a', 2, ['a3'], at(9, 0)]]); + expect(errors(s)).toEqual([expect.stringMatching(/'ledger_probe'.*chain 'org:org_b'.*root.*NOT being sealed/)]); + }); + + it('still aborts the whole pass on a storage fault: no chain is skipped past it', async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('a1', at(8, 10)), row('b1', at(8, 20), 'org_b'), row('a2', at(9, 10))); + const insert = s.engine.insert.bind(s.engine); + s.engine.insert = async (object, r, o) => { + if (object === 'sys_audit_checkpoint' && r.tenant_id === 'org_a') throw new Error('connection reset'); + return insert(object, r, o); + }; + expect(await s.sealer.runPass()).toBe(0); + expect(s.hot.table('sys_audit_checkpoint')).toEqual([]); + expect(errors(s)).toEqual([expect.stringMatching(/sealing 'ledger_probe' FAILED \(connection reset\)/)]); + }); + + it("keeps verify loud: the skipped chain's rows read unsealed and the verdict is not ok", async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('a1', at(8, 10)), refused('b1', at(8, 20), 'org_b'), row('a2', at(9, 10)), row('b2', at(9, 20), 'org_b')); + await s.sealer.runPass(); + const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + expect(report.ok).toBe(false); + expect(report.totals).toMatchObject({ unmodified: 2, late: 2, unsealed: 2 }); + expect(report.chains.find((c) => c.chain === 'org:org_b')?.counts).toMatchObject({ late: 2, unsealed: 2 }); + }); +}); + describe('the lock: audit.sealer, its fencing token on each checkpoint (D3, Q2 (a))', () => { const lockedCluster = (token: bigint | null, onAcquire: (key: string) => void = () => {}) => { let held = token !== null; From 14873e941cc17155aa43eaecd75bf71d76ccfe79 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:29:39 +0000 Subject: [PATCH 05/12] fix(plugin-audit): isolate sealer faults per chain: a chain-local fault skips only its chain, each chain resumes from its own cursor, sealed_through holds at a skipped window Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../plugin-audit/src/audit-seal/sealer.ts | 220 ++++++++++++++---- 1 file changed, 179 insertions(+), 41 deletions(-) diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 03594ffc7e9..9cc93e6de0e 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -12,6 +12,7 @@ import type { import { isMissingTableError } from '@objectstack/types'; import { AUDIT_SEAL_CANON_VERSION, + CanonicalFormError, canonicalDatetime, leafHash, leafInput, @@ -35,6 +36,7 @@ import { checkpointDigest, checkpointRow, signedBodyBytes, + SignedBodyError, type AuditCheckpointKind, type CheckpointSignedBody, } from './signed-body.js'; @@ -61,6 +63,15 @@ import { dropAuditSealSecret, writeAuditSealSecret, type SealStorageDriver, type * Each checkpoint carries the sealed-through watermark: the end of the last * window the sealer had completed for every chain when it wrote it. * + * S4 (seat ruling 6884540128 item 2): a fault is isolated to the smallest + * thing it belongs to. A chain-local fault — a row a canonical rule refuses, + * or a malformed checkpoint of the chain (its head among them) — skips that + * chain for the rest of the pass; the other chains are sealed, and each chain + * resumes from its own oldest unsealed window, since every chain carries its + * own cursor. The watermark never advances past a window a skipped chain + * leaves unsealed. Every other fault — the lock, the signer, the crypto + * provider, the storage — stops the whole object's pass. + * * Nothing here writes the sealed object, and every secret row is written * below the hooks, so the sealer never seals its own writes. */ @@ -134,6 +145,19 @@ interface ChainLeaves { const iso = (ms: number): string => new Date(ms).toISOString(); +/** + * S4: a fault that belongs to one chain — a row of it a canonical rule + * refuses, or a malformed checkpoint of it. It skips that chain only. + */ +class ChainFault extends Error { + constructor(readonly chainKey: string, readonly fault: unknown) { + super(faultOf(fault)); + } +} + +/** Whether `err` is chain-local when it is thrown reading one chain's row or checkpoint (S4). */ +const isChainLocal = (err: unknown): boolean => err instanceof CanonicalFormError || err instanceof SignedBodyError; + /** * A fault as a report line may quote it: its code and the driver's own reason, * never the statement. A SQL driver's message leads with the statement and its @@ -216,6 +240,23 @@ export class AuditSealer { this.options.logger.error(message()); } + /** + * S4: each chain a chain-local fault skipped, at `error`, once per cause per + * {@link REPORT_REPEAT_MS} while it lasts; a chain sealed again is forgotten. + */ + private reportSkipped(object: string, skipped: ReadonlyMap): void { + for (const cause of this.reported.keys()) { + if (!cause.startsWith(`chain:${object}:`)) continue; + if (![...skipped.keys()].some((key) => cause.startsWith(`chain:${object}:${key}:`))) this.reported.delete(cause); + } + for (const [key, { fault, from }] of skipped) { + this.report(`chain:${object}:${key}:${fault}`, () => + `AuditSealer: '${object}' chain '${key}' is skipped (${fault}) — its rows from the window of ${iso(from)} on are ` + + 'NOT being sealed, and no checkpoint\'s sealed_through passes that window, so `os audit verify` reads them ' + + 'unsealed; every other chain is sealed. Each pass retries the chain from that window. Fix the fault named here.'); + } + } + /** The sealed objects the registry holds that can be sealed; each that cannot is reported. */ private plans(): SealPlan[] { const plans: SealPlan[] = []; @@ -301,6 +342,7 @@ export class AuditSealer { 'sealed until a pass gets past it; each pass retries. Fix the fault named here.'); } finally { written += pass?.written ?? 0; + if (pass) this.reportSkipped(plan.name, pass.skipped); } } return written; @@ -317,6 +359,12 @@ class ObjectPass { private readonly archive: SealStorageDriver | undefined; private readonly checkpoints: SealStorageDriver; private watermark: number | null = null; + /** The stored watermark when the pass began: every chain is complete before it. */ + private floor: number | null = null; + /** S4: each chain's own cursor, the start of the window after its last `window` checkpoint. */ + private readonly cursors = new Map(); + /** S4: the chains a chain-local fault put out for the rest of this pass, and the window each stays unsealed from. */ + readonly skipped = new Map(); /** Checkpoints this pass wrote, counted as each lands. */ written = 0; /** The key id the last checkpoint of this pass was signed under: the next body's expectation. */ @@ -351,43 +399,81 @@ class ObjectPass { limit: 1, }); this.watermark = top ? Date.parse(canonicalDatetime(top.sealed_through, 'sealed_through')) : null; - const [last] = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { - where: { sealed_object: this.plan.name, kind: 'window' }, - orderBy: [{ field: 'window_start', order: 'desc' }], - limit: 1, - }); - const lastWindow = last ? Date.parse(canonicalDatetime(last.window_start, 'window_start')) : null; + this.floor = this.watermark; + // S4: each chain's cursor, from its `window` checkpoints at or past the floor. A chain the floor passed with + // none there has the floor as its cursor; the latest `window` checkpoint is never below the floor. + let lastWindow: number | null = null; + if (this.floor !== null) { + const recent = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { + where: { sealed_object: this.plan.name, kind: 'window', window_start: { $gte: iso(this.floor) } }, + }); + for (const row of recent) { + const key = String(row.chain_key); + let start: number; + try { + start = Date.parse(canonicalDatetime(row.window_start, 'window_start')); + } catch (err) { + this.skip(key, err, this.floor); + continue; + } + this.cursors.set(key, Math.max(this.cursors.get(key) ?? start + AUDIT_SEAL_WINDOW_MS, start + AUDIT_SEAL_WINDOW_MS)); + lastWindow = Math.max(lastWindow ?? start, start); + } + } const due = windowOf(this.now - AUDIT_SEAL_SETTLE_MS); - let resumed: Set | null = null; - if (lastWindow !== null) resumed = await this.sealLate(lastWindow); + if (lastWindow !== null) await this.sealLate(lastWindow); - let cursor: number | null = lastWindow; + let cursor: number | null = this.floor; if (cursor === null) { const oldest = await this.firstRowAt(null, due); if (oldest === null) return this.written; cursor = windowOf(oldest); } - for (let n = 0; n < MAX_WINDOWS_PER_PASS; n++) { + // Windows oldest first from the floor; each chain is sealed from its own cursor. A window that only re-reads + // chains already sealed (or skipped) past it does not count toward the pass's windows. + for (let n = 0; n < MAX_WINDOWS_PER_PASS;) { const next = await this.firstRowAt(cursor, due); if (next === null) break; const start = windowOf(next); - const done = start === lastWindow ? resumed : null; - const chains = await this.readWindow(start, (row) => !done?.has(chainKeyOf(tenantOf(row)))); - await this.writeChains(chains, start, 'window', Math.max(this.watermark ?? start, start)); + const chains = await this.readWindow(start, (row) => start >= this.cursorOf(chainKeyOf(tenantOf(row)))); + if (chains.size > 0) n += 1; + await this.writeChains(chains, start, 'window', Math.max(this.watermark ?? Number.NEGATIVE_INFINITY, Math.min(start, this.stuckFrom()))); cursor = start + AUDIT_SEAL_WINDOW_MS; } return this.written; } + /** S4: the first window of chain `key` this pass may seal as a `window`; a row of it before is `late`. */ + private cursorOf(key: string): number { + return Math.max(this.floor ?? Number.NEGATIVE_INFINITY, this.cursors.get(key) ?? Number.NEGATIVE_INFINITY); + } + + /** S4: the earliest window a skipped chain leaves unsealed; no watermark passes it. */ + private stuckFrom(): number { + let from = Number.POSITIVE_INFINITY; + for (const skip of this.skipped.values()) from = Math.min(from, skip.from); + return from; + } + + /** + * S4: put chain `key` out for the rest of the pass over a chain-local fault + * met at window `at`. It stays unsealed from its own oldest unsealed window: + * its cursor, or `at` when the fault was met past it. + */ + private skip(key: string, fault: unknown, at: number): void { + if (this.skipped.has(key)) return; + this.skipped.set(key, { fault: faultOf(fault instanceof ChainFault ? fault.fault : fault), from: Math.max(this.cursorOf(key), at) }); + } + /** * Late rows (D3): each sealed window of the horizon whose stored count * differs from what its checkpoints list is read, and each unlisted row is - * sealed into a `late` checkpoint of its chain. In the last sealed window a - * chain with no `window` checkpoint yet is left to the window pass, which - * resumes it. Resolves to the chains that window already holds. + * sealed into a `late` checkpoint of its chain. A row is late only before its + * chain's own cursor; at or past it, the window pass seals it (S4), which is + * how a chain a stopped pass (or a skip) left behind resumes as `window`. */ - private async sealLate(lastWindow: number): Promise> { + private async sealLate(lastWindow: number): Promise { const from = windowOf(this.now - AUDIT_SEAL_LATE_HORIZON_MS); const to = lastWindow + AUDIT_SEAL_WINDOW_MS; const listed = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { @@ -395,22 +481,34 @@ class ObjectPass { }); const byWindow = new Map(); for (const row of listed) { - const start = Date.parse(canonicalDatetime(row.window_start, 'window_start')); + let start: number; + try { + start = Date.parse(canonicalDatetime(row.window_start, 'window_start')); + } catch (err) { + this.skip(String(row.chain_key), err, this.floor ?? from); + continue; + } byWindow.set(start, [...(byWindow.get(start) ?? []), row]); } - const resumed = new Set((byWindow.get(lastWindow) ?? []).filter((r) => r.kind === 'window').map((r) => String(r.chain_key))); const listedCount = (rows: readonly Row[]) => rows.reduce((sum, r) => sum + Number(r.leaf_count), 0); for (let start = from; start < to; start += AUDIT_SEAL_WINDOW_MS) { // S6: each window re-counted on its own, so a delete in one cannot hide a late row in another. await this.lock.renew(LOCK_TTL_MS); const holders = byWindow.get(start) ?? []; if ((await this.countRows(start, start + AUDIT_SEAL_WINDOW_MS)) === listedCount(holders)) continue; - const ids = new Set(holders.flatMap((r) => checkpointBodyFromRow(r).row_ids)); + const ids = new Set(); + for (const holder of holders) { + try { + for (const id of checkpointBodyFromRow(holder).row_ids) ids.add(id); + } catch (err) { + if (!isChainLocal(err)) throw err; + this.skip(String(holder.chain_key), err, start); // S4: a malformed checkpoint of its chain + } + } const chains = await this.readWindow(start, (row) => - !ids.has(rowIdOf(row)) && (start !== lastWindow || resumed.has(chainKeyOf(tenantOf(row))))); + !ids.has(rowIdOf(row)) && start < this.cursorOf(chainKeyOf(tenantOf(row)))); await this.writeChains(chains, start, 'late', this.watermark ?? start); } - return resumed; } /** The stores a pass reads: the hot store, then the archive. */ @@ -484,19 +582,27 @@ class ObjectPass { limit: PAGE_SIZE, }); for (const row of rows) { - const id = rowIdOf(row); - const at = canonicalDatetime(row.created_at, `${id}.created_at`); - if (seen.has(id) || windowOf(Date.parse(at)) !== start || !accept(row)) continue; - seen.add(id); const tenantId = tenantOf(row); const key = chainKeyOf(tenantId); - let chain = chains.get(key); - if (!chain) { - chain = { tenantId, seed: generateCheckpointSeed(), leaves: [] }; - chains.set(key, chain); + if (this.skipped.has(key)) continue; // S4: out for the rest of the pass + try { + const id = rowIdOf(row); + const at = canonicalDatetime(row.created_at, `${id}.created_at`); + if (seen.has(id) || windowOf(Date.parse(at)) !== start || !accept(row)) continue; + seen.add(id); + let chain = chains.get(key); + if (!chain) { + chain = { tenantId, seed: generateCheckpointSeed(), leaves: [] }; + chains.set(key, chain); + } + const leaf = leafInput(row, this.plan.columns, this.plan.fields, columnSaltsOf(chain.seed, this.plan.name)); + chain.leaves.push({ id, at, hash: leafHash(leaf) }); + } catch (err) { + // S4: a row a canonical rule refuses skips its chain, and only its chain. + if (!(err instanceof CanonicalFormError)) throw err; + this.skip(key, err, start); + chains.delete(key); } - const leaf = leafInput(row, this.plan.columns, this.plan.fields, columnSaltsOf(chain.seed, this.plan.name)); - chain.leaves.push({ id, at, hash: leafHash(leaf) }); } if (rows.length < PAGE_SIZE) break; after = rows[rows.length - 1]; @@ -512,17 +618,35 @@ class ObjectPass { orderBy: [{ field: 'sequence', order: 'desc' }], limit: 1, }); - const head = row ? (() => { - const body = checkpointBodyFromRow(row); - return { sequence: body.sequence, digest: checkpointDigest(body) }; - })() : null; + let head: ChainHead | null = null; + if (row) { + let body: CheckpointSignedBody; + try { + body = checkpointBodyFromRow(row); + } catch (err) { + if (!isChainLocal(err)) throw err; + throw new ChainFault(chainKey, err); // S4: a malformed chain head skips its chain + } + head = { sequence: body.sequence, digest: checkpointDigest(body) }; + } this.heads.set(chainKey, head); return head; } private async writeChains(chains: Map, start: number, kind: AuditCheckpointKind, watermark: number): Promise { // `readWindow` makes a chain only with its first leaf, so no checkpoint is empty (D3). - for (const key of [...chains.keys()].sort()) await this.writeCheckpoint(key, chains.get(key)!, start, kind, watermark); + for (const key of [...chains.keys()].sort()) { + if (this.skipped.has(key)) continue; + try { + await this.writeCheckpoint(key, chains.get(key)!, start, kind, watermark); + } catch (err) { + // S4: only a chain-local fault of this chain skips it; every other fault stops the object's pass. + if (!(err instanceof ChainFault) || err.chainKey !== key) throw err; + this.skip(key, err, start); + continue; + } + if (kind === 'window') this.cursors.set(key, start + AUDIT_SEAL_WINDOW_MS); + } if (kind === 'window') this.watermark = Math.max(this.watermark ?? watermark, watermark); } @@ -554,7 +678,7 @@ class ObjectPass { // N1: the window's checkpoints, re-read once this chain's head is known: a row another sealer listed // since this pass read the window's lists is not sealed twice. One stored after the head was known // takes a sequence at or past this one, so the unique index refuses whichever insert comes second. - const listed = await this.listedIn(start); + const listed = await this.listedIn(start, chainKey); leaves = leaves.filter((leaf) => !listed.has(leaf.id)); if (leaves.length === 0) return; } @@ -625,12 +749,26 @@ class ObjectPass { await this.deliver(body, keyId, signature); } - /** The row ids the stored checkpoints of window `start` list, every chain's, as read now. */ - private async listedIn(start: number): Promise> { + /** + * The row ids the stored checkpoints of window `start` list, every chain's, + * as read now. A malformed one skips its chain (S4): this chain's, with a + * {@link ChainFault}; another's, for the rest of the pass. + */ + private async listedIn(start: number, chainKey: string): Promise> { const rows = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { where: { sealed_object: this.plan.name, window_start: { $gte: iso(start), $lt: iso(start + AUDIT_SEAL_WINDOW_MS) } }, }); - return new Set(rows.flatMap((r) => checkpointBodyFromRow(r).row_ids)); + const ids = new Set(); + for (const row of rows) { + try { + for (const id of checkpointBodyFromRow(row).row_ids) ids.add(id); + } catch (err) { + if (!isChainLocal(err)) throw err; + if (String(row.chain_key) === chainKey) throw new ChainFault(chainKey, err); + this.skip(String(row.chain_key), err, start); + } + } + return ids; } /** This chain's stored checkpoint matching `where`, if any. */ From 03a059dad7108ad1d5cea97316cb2ba311f1ba2f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:31:18 +0000 Subject: [PATCH 06/12] test(plugin-audit): pin a host handing an app-composed AuditPlugin its crypto provider, never over an explicit one Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../plugin-audit/src/audit-plugin.test.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/packages/plugins/plugin-audit/src/audit-plugin.test.ts b/packages/plugins/plugin-audit/src/audit-plugin.test.ts index ae11b0cfa34..087572071d8 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.test.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.test.ts @@ -580,3 +580,47 @@ describe('AuditPlugin — sys_comment access gates are mounted', () => { expect(denials[0].reason).toMatchObject({ code: 'RECORD_NOT_ACCESSIBLE', status: 403 }); }); }); + +describe('AuditPlugin — a host hands an app-supplied instance its crypto provider (ADR-0154 D2, D6; seat ruling 6884540128 item 3)', () => { + const crypto = (label: string) => ({ label }) as never; + /** The sealer `startSealer` composes over a storage double whose registry holds no sealed object: its pass seals nothing. */ + const sealerOf = async (plugin: AuditPlugin): Promise<{ crypto?: unknown } | null> => { + const engine = { getDriverForObject: () => undefined, registry: { getAllObjects: () => [] } }; + const ctx = { logger: { info() {}, warn() {}, error() {}, debug() {} }, getService: () => undefined }; + (plugin as unknown as { startSealer(e: unknown, c: unknown): void }).startSealer(engine, ctx); + const sealer = (plugin as unknown as { sealer: { options: { crypto?: unknown }; stop(): Promise } | null }).sealer; + await sealer?.stop(); + return sealer && sealer.options; + }; + + it('takes the host provider when it was composed with none, and seals under it', async () => { + const plugin = new AuditPlugin({ readAudit: { objects: [] } }); + const host = crypto('host'); + expect(plugin.adoptHostCryptoProvider(() => host, { armSealer: true })).toBe(true); + expect((await sealerOf(plugin))?.crypto).toBe(host); + }); + + it('never overrides a provider the app composed it with', async () => { + const own = crypto('own'); + const plugin = new AuditPlugin({ cryptoProvider: own }); + expect(plugin.adoptHostCryptoProvider(() => crypto('host'), { armSealer: true })).toBe(false); + expect((await sealerOf(plugin))?.crypto).toBe(own); + }); + + it("keeps the sealer off on a host's one-shot boot, and an app's own `armSealer: false` stands", async () => { + const oneShot = new AuditPlugin(); + expect(oneShot.adoptHostCryptoProvider(() => crypto('host'), { armSealer: false })).toBe(true); + expect(await sealerOf(oneShot)).toBeNull(); + const off = new AuditPlugin({ armSealer: false }); + expect(off.adoptHostCryptoProvider(() => crypto('host'), { armSealer: true })).toBe(true); + expect(await sealerOf(off)).toBeNull(); + }); + + it('composes no provider when the host has none to hand: the sealer reports it once, at error (D3)', async () => { + const plugin = new AuditPlugin(); + expect(plugin.adoptHostCryptoProvider(() => undefined, { armSealer: true })).toBe(true); + const sealer = await sealerOf(plugin); + expect(sealer).not.toBeNull(); + expect(sealer?.crypto).toBeUndefined(); + }); +}); From a0650112bb7f45f0194ece793b0b293e6c05f94a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:31:18 +0000 Subject: [PATCH 07/12] feat(plugin-audit): AuditPlugin.adoptHostCryptoProvider takes a host's provider when the instance was composed with none Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../plugins/plugin-audit/src/audit-plugin.ts | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-audit/src/audit-plugin.ts b/packages/plugins/plugin-audit/src/audit-plugin.ts index 543a893a11c..698af38f964 100644 --- a/packages/plugins/plugin-audit/src/audit-plugin.ts +++ b/packages/plugins/plugin-audit/src/audit-plugin.ts @@ -325,9 +325,34 @@ export class AuditPlugin implements Plugin { * at `kernel:ready`; the activity door's writer reads it at each call. */ private actorSnapshotOf: ((api: unknown, userId: string) => Promise) | undefined; + /** [ADR-0154 D2, D6] The provider a host handed over, for an instance composed with none. */ + private hostCryptoProvider: (() => ICryptoProvider | undefined) | undefined; + /** [ADR-0154 D3] Set when a host that handed its provider over is a one-shot boot. */ + private hostDisarmsSealer = false; constructor(private readonly options: AuditPluginOptions = {}) {} + /** + * [ADR-0154 D2, D6; seat ruling 6884540128 item 3] A host hands an instance + * the app composed (a stack `plugins` entry) the host's own crypto provider, + * which the sealer then seals under. It is taken only when this instance was + * composed with no `cryptoProvider`: one the app composed is never + * overridden. `armSealer: false` — the host's one-shot boot — keeps the + * sealer off; `true` leaves this instance's own `armSealer` standing, so an + * app's `armSealer: false` is never turned on. + * + * The provider is read when the sealer starts (`kernel:ready`), so a host + * hands it over before then. Resolves whether it was taken. A provider that + * answers `undefined` is an absent one: the sealer reports it once, at + * `error`, and seals nothing; the boot is never refused. + */ + adoptHostCryptoProvider(provider: () => ICryptoProvider | undefined, host: { armSealer: boolean }): boolean { + if (this.options.cryptoProvider !== undefined) return false; + this.hostCryptoProvider = provider; + if (!host.armSealer) this.hostDisarmsSealer = true; + return true; + } + async init(ctx: PluginContext): Promise { // Register audit system objects via the manifest service. ctx.getService<{ register(m: any): void }>('manifest').register({ @@ -768,11 +793,11 @@ export class AuditPlugin implements Plugin { * command's boot (`armSealer: false`). */ private startSealer(engine: IDataEngine, ctx: PluginContext): void { - if (this.options.armSealer === false) return; + if (this.options.armSealer === false || this.hostDisarmsSealer) return; const storage = engine as unknown as Partial; if (typeof storage.getDriverForObject !== 'function' || typeof storage.registry?.getAllObjects !== 'function') return; const sealEngine = storage as AuditSealerEngine; - const option = this.options.cryptoProvider; + const option = this.options.cryptoProvider ?? this.hostCryptoProvider; const crypto = typeof option === 'function' ? option() : option; const localSigner = crypto ? new LocalCheckpointSigner({ engine: sealEngine, crypto }) : undefined; const optional = (name: string): T | undefined => { From e1b0acc471aa783bf65df129d1fba87d55c7841a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:32:12 +0000 Subject: [PATCH 08/12] test(cli): pin os serve handing its crypto provider to an app-supplied AuditPlugin, real class only Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../serve-audit-registration.contract.test.ts | 12 +++++ .../app-audit-plugin-host-crypto.test.ts | 45 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 packages/cli/src/utils/app-audit-plugin-host-crypto.test.ts diff --git a/packages/cli/src/commands/serve-audit-registration.contract.test.ts b/packages/cli/src/commands/serve-audit-registration.contract.test.ts index aeae20498f1..eb3785a2786 100644 --- a/packages/cli/src/commands/serve-audit-registration.contract.test.ts +++ b/packages/cli/src/commands/serve-audit-registration.contract.test.ts @@ -249,6 +249,18 @@ describe('os serve registers AuditPlugin with no config-derived options, above t expect(SERVE).toMatch(/cap === 'audit' && hostCrypto\s*\?\s*\{ \.\.\.\(arg \?\? \{\}\), cryptoProvider: hostCrypto\.provider, armSealer: !migrateAndExit \}/); }); + it('hands the host crypto provider to an app-supplied AuditPlugin in the stack `plugins` loop, before the kernel takes it (seat ruling 6884540128 item 3)', () => { + // The app's `plugins` entry supersedes the CLI's instance (last one wins), so without this hand-over an app + // that composed its own AuditPlugin seals nothing. The same provider function, the same one-shot posture. + const HAND = 'handHostCryptoToAppAuditPlugin(pluginToLoad, RealAuditPlugin, () => hostCrypto?.provider, !migrateAndExit)'; + const loop = soleOffset(SERVE, PLUGINS_LOOP, 'stack-plugins-loop'); + const hand = soleOffset(SERVE, HAND, 'app AuditPlugin hand-over'); + expect(hand).toBeGreaterThan(loop); + expect(hand).toBeLessThan(soleOffset(SERVE, 'await kernel.use(pluginToLoad);', 'stack-plugin registration')); + // Judged against the real class, loaded once ahead of the loop: never by name, so a lookalike is never fed. + expect(soleOffset(SERVE, '({ AuditPlugin: RealAuditPlugin } = await import(', 'real AuditPlugin class')).toBeLessThan(loop); + }); + it('arms no sealer on an `OS_MIGRATE_AND_EXIT=1` boot, a one-shot job (ADR-0154 D3)', () => { // One reading of the variable, ahead of both constructions; the exit reads the same constant. const reading = "const migrateAndExit = process.env.OS_MIGRATE_AND_EXIT === '1';"; diff --git a/packages/cli/src/utils/app-audit-plugin-host-crypto.test.ts b/packages/cli/src/utils/app-audit-plugin-host-crypto.test.ts new file mode 100644 index 00000000000..f4c74e9b5d2 --- /dev/null +++ b/packages/cli/src/utils/app-audit-plugin-host-crypto.test.ts @@ -0,0 +1,45 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { AuditPlugin } from '@objectstack/plugin-audit'; +import { handHostCryptoToAppAuditPlugin } from './app-audit-plugin-host-crypto.js'; + +/** + * [ADR-0154 D2, D6; seat ruling 6884540128 item 3] `os serve` hands its one + * crypto provider to an AuditPlugin the app put in its stack `plugins`: only + * to an instance of the real class, only when the app composed it with none. + */ +describe('os serve hands its crypto provider to an app-supplied AuditPlugin', () => { + const host = () => ({ label: 'host' }) as never; + + it('hands it to a real AuditPlugin composed with no provider', () => { + const plugin = new AuditPlugin({ readAudit: { objects: [] } }); + expect(handHostCryptoToAppAuditPlugin(plugin, AuditPlugin, host, true)).toBe(true); + expect((plugin as unknown as { hostCryptoProvider: unknown }).hostCryptoProvider).toBe(host); + }); + + it('never overrides a provider the app composed it with', () => { + const own = { label: 'own' } as never; + const plugin = new AuditPlugin({ cryptoProvider: own }); + expect(handHostCryptoToAppAuditPlugin(plugin, AuditPlugin, host, true)).toBe(false); + expect((plugin as unknown as { hostCryptoProvider: unknown }).hostCryptoProvider).toBeUndefined(); + }); + + it('never feeds a same-named lookalike, whatever it answers to', () => { + const calls: unknown[] = []; + const lookalike = { name: 'com.objectstack.audit', adoptHostCryptoProvider: (...args: unknown[]) => (calls.push(args), true) }; + expect(handHostCryptoToAppAuditPlugin(lookalike, AuditPlugin, host, true)).toBe(false); + expect(calls).toEqual([]); + }); + + it('feeds nothing when the class could not be loaded, and never throws', () => { + expect(handHostCryptoToAppAuditPlugin(new AuditPlugin(), undefined, host, true)).toBe(false); + expect(handHostCryptoToAppAuditPlugin(undefined, AuditPlugin, host, true)).toBe(false); + }); + + it("keeps the sealer off on a one-shot boot (`armSealer: false`)", () => { + const plugin = new AuditPlugin(); + expect(handHostCryptoToAppAuditPlugin(plugin, AuditPlugin, host, false)).toBe(true); + expect((plugin as unknown as { hostDisarmsSealer: boolean }).hostDisarmsSealer).toBe(true); + }); +}); From 574c27c1be8845e167fa20d40f7cbf2b12172e49 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:32:43 +0000 Subject: [PATCH 09/12] fix(cli): os serve hands its crypto provider to an app-supplied AuditPlugin composed with none Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- packages/cli/src/commands/serve.ts | 20 ++++++++++++ .../src/utils/app-audit-plugin-host-crypto.ts | 32 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 packages/cli/src/utils/app-audit-plugin-host-crypto.ts diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index 609f719fa2b..c1f45d9c7e7 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -10,6 +10,7 @@ import { loadConfig, bundleConfigModule } from '../utils/config.js'; import { mergeBootConfig } from '../utils/merge-boot-config.js'; import { provisionTelemetryDatasource, standaloneTelemetryPrimary } from '../utils/telemetry-datasource.js'; import { isHostConfig, shouldBootWithLibrary } from '../utils/plugin-detection.js'; +import { handHostCryptoToAppAuditPlugin } from '../utils/app-audit-plugin-host-crypto.js'; import { mountsAiServicePlugin, resolveAiServiceLoad, resolveOptionalPluginLoad } from '../utils/ai-service-auto-inject.js'; import { registerInstalledPlugins } from '../utils/installed-plugins-boot.js'; import { readInternalArtifactPath, readInternalConfigOutputPath } from '../utils/internal-artifact-channel.js'; @@ -4978,6 +4979,17 @@ export default class Serve extends Command { // got that far), for `refuseUnloadedCryptoProviderPlugins` below. const unloadedStackPlugins: UnloadedStackPlugin[] = []; if (plugins.length > 0) { + // [ADR-0154 D2, D6; seat ruling 6884540128 item 3] The class an app's + // own AuditPlugin is judged by, loaded as this host loads it: only an + // instance of it is handed the host's crypto provider below, never a + // plugin that merely carries its name. Optional, as at 5d. + let RealAuditPlugin: typeof import('@objectstack/plugin-audit').AuditPlugin | undefined; + try { + const auditPkg = '@objectstack/plugin-audit'; + ({ AuditPlugin: RealAuditPlugin } = await import(/* webpackIgnore: true */ auditPkg)); + } catch { + RealAuditPlugin = undefined; + } let index = -1; for (const plugin of plugins) { index += 1; @@ -5014,6 +5026,14 @@ export default class Serve extends Command { // declared contract (`packages/core/src/plugin-registration.ts`), // with a `warn` naming both versions. That is how an app supplies // options to a plugin this CLI mounts without them. + // + // [ADR-0154 D2, D6; seat ruling 6884540128 item 3] An app's own + // AuditPlugin composed with no crypto provider is handed the + // host's — the same provider function, and the same one-shot + // posture, as the instance at 5d and the `requires: ['audit']` + // resolver — so superseding the CLI's instance does not leave the + // sealed objects unsealed. An explicit provider is never replaced. + handHostCryptoToAppAuditPlugin(pluginToLoad, RealAuditPlugin, () => hostCrypto?.provider, !migrateAndExit); await kernel.use(pluginToLoad); stackMountedPlugins.push(pluginToLoad); const pluginName = plugin.name || plugin.constructor?.name || 'unnamed'; diff --git a/packages/cli/src/utils/app-audit-plugin-host-crypto.ts b/packages/cli/src/utils/app-audit-plugin-host-crypto.ts new file mode 100644 index 00000000000..d89cf674c76 --- /dev/null +++ b/packages/cli/src/utils/app-audit-plugin-host-crypto.ts @@ -0,0 +1,32 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { AuditPlugin } from '@objectstack/plugin-audit'; +import type { ICryptoProvider } from '@objectstack/spec/contracts'; + +/** + * [ADR-0154 D2, D6; seat ruling 6884540128 item 3] Hand `os serve`'s one + * crypto provider to an AuditPlugin the app put in its stack `plugins`. + * + * The app's entry supersedes the instance the CLI composes (the declared + * last-one-wins registration), and an app composing its own instance for + * `readAudit` rarely spells a crypto provider, so without this its sealer + * seals nothing. The hand-over matches the capability resolver's + * `requires: ['audit']` path: the same provider, and no sealer on a one-shot + * boot (`armSealer: false`). + * + * Only an instance of the real class (`RealAuditPlugin`, as this host loads + * it) is handed anything — never a plugin that merely carries its name — and + * only one the app composed with no provider of its own (the class's + * `adoptHostCryptoProvider` decides that). Nothing here throws or refuses the + * boot: an instance left without a provider reports that once, at `error`, + * from its sealer (ADR-0154 D3). Resolves whether the provider was handed. + */ +export function handHostCryptoToAppAuditPlugin( + plugin: unknown, + RealAuditPlugin: typeof AuditPlugin | undefined, + provider: () => ICryptoProvider | undefined, + armSealer: boolean, +): boolean { + if (RealAuditPlugin === undefined || !(plugin instanceof RealAuditPlugin)) return false; + return plugin.adoptHostCryptoProvider(provider, { armSealer }); +} From 812588a2c79d48d4ebb70835093d5643e9b9ec1a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:33:10 +0000 Subject: [PATCH 10/12] chore(changeset): plugin-audit and cli patch for per-chain sealer isolation and the app AuditPlugin hand-over Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .changeset/31908-p4b1-sealer-chain-isolation.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .changeset/31908-p4b1-sealer-chain-isolation.md diff --git a/.changeset/31908-p4b1-sealer-chain-isolation.md b/.changeset/31908-p4b1-sealer-chain-isolation.md new file mode 100644 index 00000000000..dfe247fe84c --- /dev/null +++ b/.changeset/31908-p4b1-sealer-chain-isolation.md @@ -0,0 +1,13 @@ +--- +'@objectstack/plugin-audit': patch +'@objectstack/cli': patch +--- + +fix(plugin-audit, cli): the audit sealer skips only the chain a chain-local fault belongs to; `os serve` hands its crypto provider to an AuditPlugin the app composed with none + +Clause-②: yes (widening) +Metadata-protocol: none + +**The sealer (ADR-0154 D3, S4).** A fault that belongs to one chain of a sealed object — a row a canonical rule refuses, or a malformed checkpoint of that chain (its head among them) — now skips that chain for the rest of the pass instead of stopping the whole object. Every other chain is still sealed. Each chain now resumes from its own oldest unsealed window, as `window` checkpoints, so a skipped chain catches up once its fault is fixed. No checkpoint's `sealed_through` passes a window a skipped chain leaves unsealed. The sealer reports each skipped chain once at `error`, naming the object, the chain, the fault and the window it is unsealed from, and again each hour while it lasts. A lock lapse, a signer, crypto-provider or storage fault still stops the object's pass, as before. `os audit verify` reads the skipped chain's rows in a window another chain sealed as `late` and unsealed, and fails. + +**An app-supplied AuditPlugin (ADR-0154 D2, D6).** An app that puts its own `AuditPlugin` in its stack `plugins` (to turn on `readAudit`, for example) supersedes the one `os serve` composes, and so lost the host's crypto provider: its sealer sealed nothing and said so at `error`. `os serve` now hands it the host's provider when the app composed it with no `cryptoProvider`, and keeps its sealer off on an `OS_MIGRATE_AND_EXIT=1` boot, as for the instance it composes itself. A provider the app composed is never replaced, an app's `armSealer: false` stays off, and a plugin that only carries the AuditPlugin name is never handed anything. The new `AuditPlugin.adoptHostCryptoProvider(provider, { armSealer })` is the method a host calls to do this. From 4cbd2fca9faeaa5e7ab0116e5ff068ad3ed46b13 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:34:10 +0000 Subject: [PATCH 11/12] fix(plugin-audit): the skipped-chain report claims only what the sealer holds back Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- packages/plugins/plugin-audit/src/audit-seal/sealer.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 9cc93e6de0e..5e40b5178ea 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -252,8 +252,8 @@ export class AuditSealer { for (const [key, { fault, from }] of skipped) { this.report(`chain:${object}:${key}:${fault}`, () => `AuditSealer: '${object}' chain '${key}' is skipped (${fault}) — its rows from the window of ${iso(from)} on are ` + - 'NOT being sealed, and no checkpoint\'s sealed_through passes that window, so `os audit verify` reads them ' + - 'unsealed; every other chain is sealed. Each pass retries the chain from that window. Fix the fault named here.'); + 'NOT being sealed, and no checkpoint\'s sealed_through passes that window; every other chain is sealed. ' + + 'Each pass retries the chain from that window. Fix the fault named here.'); } } From 22d4da3f6ea47cf704793e3012f02a5050f5f7ba Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:54:06 +0000 Subject: [PATCH 12/12] test(plugin-audit): pin the window-major pass and that a lagging chain recovers into window checkpoints, never late ones Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../src/audit-seal/audit-seal-sealer.test.ts | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) 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 8f5ddc615bf..8c54358618a 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 @@ -251,6 +251,36 @@ describe('per-chain isolation: only a chain-local fault skips a chain, and only expect(errors(s)).toEqual([expect.stringMatching(/'ledger_probe'.*chain 'org:org_b'.*root.*NOT being sealed/)]); }); + it('seals window-major: on a healthy backlog past the per-pass budget, every chain ends each pass at the same window, a sparse one included', async () => { + const s = setup(); + s.clock.now = DAY0 + 40 * H; // windows up to 39:00 are due + // org_a writes every hour for 30 hours, more windows than one pass seals; org_b only at hours 0, 11, 23 and 29. + for (let h = 0; h < 30; h++) s.hot.table('ledger_probe').push(row(`a${h}`, at(h, 10))); + for (const h of [0, 11, 23, 29]) s.hot.table('ledger_probe').push(row(`b${h}`, at(h, 20), 'org_b')); + const newest = () => { + const by: Record = {}; + for (const c of s.checkpoints()) if (c.kind === 'window' && !(by[String(c.tenant_id)] > c.window_start)) by[String(c.tenant_id)] = c.window_start; + return by; + }; + expect(await s.sealer.runPass()).toBe(24 + 3); + expect(newest()).toEqual({ org_a: at(23, 0), org_b: at(23, 0) }); + expect(await s.sealer.runPass()).toBe(6 + 1); + expect(newest()).toEqual({ org_a: at(29, 0), org_b: at(29, 0) }); + expect(s.checkpoints().filter((c) => c.kind === 'late')).toEqual([]); + }); + + it("never seals a lagging chain's rows as late: skipped where another chain sealed, it recovers into window checkpoints, while that chain's own late row is sealed late", async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('y1', at(8, 10)), refused('x1', at(8, 20), 'org_x'), row('y2', at(9, 10)), row('x2', at(9, 20), 'org_x')); + expect(await s.sealer.runPass()).toBe(2); // org_a seals 08:00 and 09:00; org_x is skipped at 08:00 + s.hot.table('ledger_probe').find((r) => r.id === 'x1')!.payload = '{"v":"x1"}'; + s.hot.table('ledger_probe').push(row('y-late', at(8, 40))); // so the late pass reads the 08:00 window + expect(await s.sealer.runPass()).toBe(3); + expect(s.checkpoints().filter((c) => c.tenant_id === 'org_x').map((c) => [c.kind, c.window_start, c.sequence, c.row_ids])) + .toEqual([['window', at(8, 0), 0, ['x1']], ['window', at(9, 0), 1, ['x2']]]); + expect(s.checkpoints().filter((c) => c.kind === 'late').map((c) => [c.tenant_id, c.window_start, c.row_ids])).toEqual([['org_a', at(8, 0), ['y-late']]]); + }); + it('still aborts the whole pass on a storage fault: no chain is skipped past it', async () => { const s = setup(); s.hot.table('ledger_probe').push(row('a1', at(8, 10)), row('b1', at(8, 20), 'org_b'), row('a2', at(9, 10)));