From d41ddf57018a16bd50b1142626e585b8b9711a12 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:50:01 +0000 Subject: [PATCH 01/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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))); From 4827322fef43a45212e757427511361775de927e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 03:00:57 +0000 Subject: [PATCH 13/23] test(plugin-audit): pin bounded checkpoint parts, the duplicate-listing fault and the bounded idle re-walk (S7, review#3 S1) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../src/audit-seal/audit-seal-core.test.ts | 18 ++- .../src/audit-seal/audit-seal-sealer.test.ts | 124 +++++++++++++++++- .../audit-seal/audit-seal-verifier.test.ts | 21 ++- .../src/audit-seal/seal-store.testkit.ts | 1 + 4 files changed, 159 insertions(+), 5 deletions(-) diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-core.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-core.test.ts index a30efe3d6f4..8ab1890e6c9 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-core.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-core.test.ts @@ -253,6 +253,8 @@ describe('signed bodies (D4, D7, D8)', () => { tenant_id: 'org_1', sequence: 3, kind: 'window', + part_index: 0, + final_part: true, window_start: '2026-11-10T04:00:00.000Z', window_end: '2026-11-10T05:00:00.000Z', sealed_through: '2026-11-10T05:00:00.000Z', @@ -279,6 +281,8 @@ describe('signed bodies (D4, D7, D8)', () => { window_end: '2026-11-10 05:00:00', sealed_at: Date.parse(body.sealed_at), fencing_token: 17, + part_index: '0', + final_part: 1, // a driver with no boolean column hands back 1 / 0 }; const back = checkpointBodyFromRow(driverRow); expect(back).toEqual(body); @@ -304,6 +308,8 @@ describe('signed bodies (D4, D7, D8)', () => { { ...body, tenant_id: 'org_2' }, { ...body, sealed_through: '2026-11-10T06:00:00.000Z' }, { ...body, seed_handle: 'sec_other' }, + { ...body, part_index: 1 }, + { ...body, final_part: false }, ]) { expect(checkpointDigest(checkpointBodyFromRow(changed))).not.toBe(digest); } @@ -323,6 +329,10 @@ describe('signed bodies (D4, D7, D8)', () => { { ...body, columns: { clear: ['id', 'created_at'], committed: [] } }, { ...body, columns: { clear: ['id'], committed: ['id'] } }, { ...body, fencing_token: '-1' }, + { ...body, part_index: -1 }, + { ...body, part_index: undefined }, + { ...body, final_part: undefined }, + { ...body, final_part: 'yes' }, ]) { expect(() => checkpointBodyFromRow(bad as unknown as Record), JSON.stringify(bad).slice(0, 80)).toThrow(SignedBodyError); } @@ -400,6 +410,8 @@ describe('the deployment chain signs a NULL organization (D5)', () => { tenant_id: null, sequence: 0, kind: 'window', + part_index: 0, + final_part: true, window_start: '2026-11-10T04:00:00.000Z', window_end: '2026-11-10T05:00:00.000Z', sealed_through: '2026-11-10T05:00:00.000Z', @@ -467,7 +479,7 @@ describe('a redaction names its checkpoint by the signed sequence (D7)', () => { it('declares one checkpoint column per stored field, the sequence a redaction refers to among them', () => { const body: CheckpointSignedBody = { - sealed_object: 'sys_audit_log', tenant_id: null, sequence: 0, kind: 'window', + sealed_object: 'sys_audit_log', tenant_id: null, sequence: 0, kind: 'window', part_index: 0, final_part: true, window_start: '2026-11-10T04:00:00.000Z', window_end: '2026-11-10T05:00:00.000Z', sealed_through: '2026-11-10T05:00:00.000Z', leaf_count: 1, row_ids: ['r1'], root: 'a'.repeat(64), previous_digest: null, columns: { clear: ['created_at', 'id'], committed: [] }, @@ -482,7 +494,7 @@ describe('a redaction names its checkpoint by the signed sequence (D7)', () => { describe('NULL names the deployment chain only when it is stated (D5)', () => { const checkpoint: CheckpointSignedBody = { - sealed_object: 'sys_audit_log', tenant_id: null, sequence: 0, kind: 'window', + sealed_object: 'sys_audit_log', tenant_id: null, sequence: 0, kind: 'window', part_index: 0, final_part: true, window_start: '2026-11-10T04:00:00.000Z', window_end: '2026-11-10T05:00:00.000Z', sealed_through: '2026-11-10T05:00:00.000Z', leaf_count: 1, row_ids: ['r1'], root: 'a'.repeat(64), previous_digest: null, columns: { clear: ['created_at', 'id'], committed: [] }, @@ -530,6 +542,8 @@ describe('the leaf hashes beside a checkpoint are trusted only through its signe tenant_id: 'org_1', sequence: 0, kind: 'window', + part_index: 0, + final_part: true, window_start: '2026-11-10T04:00:00.000Z', window_end: '2026-11-10T05:00:00.000Z', sealed_through: '2026-11-10T05:00:00.000Z', 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 8c54358618a..942e8c26e07 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 @@ -4,7 +4,7 @@ import type { IAuditCheckpointSigner, IClusterService, LockHandle } from '@objec import { describe, expect, it } from 'vitest'; 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 { AUDIT_SEAL_MAX_IDLE_WINDOWS_PER_PASS, AUDIT_SEAL_MAX_LEAVES, AUDIT_SEALER_LOCK, AuditSealer } from './sealer.js'; import { LocalCheckpointSigner } from './signer.js'; /** @@ -25,7 +25,7 @@ const LEDGER = { const row = (id: string, created: string, tenant: string | null = 'org_a') => ({ id, created_at: created, action: 'update', tenant_id: tenant, payload: `{"v":"${id}"}` }); -function setup(options: { objects?: unknown[]; crypto?: boolean; signer?: IAuditCheckpointSigner; cluster?: IClusterService } = {}) { +function setup(options: { objects?: unknown[]; crypto?: boolean; signer?: IAuditCheckpointSigner; cluster?: IClusterService; maxLeaves?: number } = {}) { const store = memoryEngine((options.objects ?? [LEDGER]) as never); const crypto = bindingCrypto(); const logger = recordingLogger(); @@ -38,6 +38,7 @@ function setup(options: { objects?: unknown[]; crypto?: boolean; signer?: IAudit cluster: () => options.cluster, logger, now: () => clock.now, + ...(options.maxLeaves === undefined ? {} : { maxLeaves: options.maxLeaves }), }); const checkpoints = () => store.hot.table('sys_audit_checkpoint').map((r) => checkpointBodyFromRow(r)); return { ...store, crypto, logger, signer, clock, sealer, checkpoints }; @@ -305,6 +306,125 @@ describe('per-chain isolation: only a chain-local fault skips a chain, and only }); }); +describe('bounded checkpoints: a window seals into consecutive parts of at most N leaves (S7, ADR-0154 D4 amended)', () => { + const parts = (s: ReturnType) => + s.checkpoints().map((c) => [c.tenant_id, c.kind, c.window_start, c.sequence, c.part_index, c.final_part, c.row_ids]); + + it('fixes N at 10,000 leaves', () => { + expect(AUDIT_SEAL_MAX_LEAVES).toBe(10_000); + }); + + it('cuts a window into consecutive parts in D1 order (created_at, id), the last one final, each chained after the one before', async () => { + const s = setup({ maxLeaves: 2 }); + // Pushed out of order, with a created_at tie broken by id. + s.hot.table('ledger_probe').push(row('r5', at(8, 50)), row('r2', at(8, 20)), row('r3b', at(8, 30)), row('r1', at(8, 10)), row('r3a', at(8, 30))); + expect(await s.sealer.runPass()).toBe(3); + expect(parts(s)).toEqual([ + ['org_a', 'window', at(8, 0), 0, 0, false, ['r1', 'r2']], + ['org_a', 'window', at(8, 0), 1, 1, false, ['r3a', 'r3b']], + ['org_a', 'window', at(8, 0), 2, 2, true, ['r5']], + ]); + const [p0, p1, p2] = s.checkpoints(); + expect([p1.previous_digest, p2.previous_digest]).toEqual([checkpointDigest(p0), checkpointDigest(p1)]); + expect(new Set(s.checkpoints().map((c) => c.seed_handle)).size).toBe(3); // one seed per checkpoint (D2) + const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + expect(report.ok).toBe(true); + expect(report.totals).toMatchObject({ unmodified: 5, unsealed: 0 }); + expect(await s.sealer.runPass()).toBe(0); + }); + + it('seals a window of at most N rows as one part, index 0 and final: the single-part checkpoint, which still verifies', async () => { + const s = setup({ maxLeaves: 2 }); + s.hot.table('ledger_probe').push(row('r1', at(8, 10)), row('r2', at(8, 20)), row('r3', at(9, 10))); + expect(await s.sealer.runPass()).toBe(2); + expect(parts(s)).toEqual([ + ['org_a', 'window', at(8, 0), 0, 0, true, ['r1', 'r2']], + ['org_a', 'window', at(9, 0), 1, 0, true, ['r3']], + ]); + expect((await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now })).ok).toBe(true); + }); + + it('resumes a window a stopped pass left mid-way as further window parts, never late ones', async () => { + const s = setup({ maxLeaves: 2 }); + s.hot.table('ledger_probe').push(row('r1', at(8, 10)), row('r2', at(8, 20)), row('r3', at(8, 30)), row('r4', at(8, 40)), row('r5', at(8, 50)), row('n1', at(9, 10))); + const insert = s.engine.insert.bind(s.engine); + let inserts = 0; + s.engine.insert = async (object, r, o) => { + if (object === 'sys_audit_checkpoint' && ++inserts === 2) throw new Error('connection reset'); + return insert(object, r, o); + }; + expect(await s.sealer.runPass()).toBe(1); // part 0 stored; the pass stops at part 1 + expect(await s.sealer.runPass()).toBe(3); + expect(parts(s)).toEqual([ + ['org_a', 'window', at(8, 0), 0, 0, false, ['r1', 'r2']], + ['org_a', 'window', at(8, 0), 1, 1, false, ['r3', 'r4']], + ['org_a', 'window', at(8, 0), 2, 2, true, ['r5']], + ['org_a', 'window', at(9, 0), 3, 0, true, ['n1']], + ]); + expect((await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now })).ok).toBe(true); + expect(await s.sealer.runPass()).toBe(0); + }); + + it('caps late checkpoints the same way: late rows of a window seal into late parts of at most N', async () => { + const s = setup({ maxLeaves: 2 }); + s.hot.table('ledger_probe').push(row('r1', at(10, 5))); + expect(await s.sealer.runPass()).toBe(1); + s.hot.table('ledger_probe').push(row('l3', at(10, 40)), row('l1', at(10, 20)), row('l2', at(10, 30))); + expect(await s.sealer.runPass()).toBe(2); + expect(parts(s).slice(1)).toEqual([ + ['org_a', 'late', at(10, 0), 1, 0, false, ['l1', 'l2']], + ['org_a', 'late', at(10, 0), 2, 1, true, ['l3']], + ]); + const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + expect(report.totals).toMatchObject({ unmodified: 1, late: 3, unsealed: 0 }); + }); + + it('refuses a window part the chain, re-read under the lease, already holds at that index or past it (S1, relaxed for parts)', async () => { + const cluster = grantingCluster(); + const s = setup({ cluster, maxLeaves: 2 }); + const other = new AuditSealer({ engine: s.engine, crypto: s.crypto, signer: () => s.signer, cluster: () => cluster, logger: s.logger, now: () => s.clock.now, maxLeaves: 2 }); + s.hot.table('ledger_probe').push(row('r1', at(8, 10)), row('r2', at(8, 20)), row('r3', at(8, 30))); + const sign = s.signer.sign.bind(s.signer); + let raced = false; + s.signer.sign = async (bytes) => { + const signed = await sign(bytes); + if (!raced) { + raced = true; + await other.runPass(); // seals both parts of the window while this pass signs its part 0 + } + return signed; + }; + await s.sealer.runPass(); + expect(parts(s)).toEqual([ + ['org_a', 'window', at(8, 0), 0, 0, false, ['r1', 'r2']], + ['org_a', 'window', at(8, 0), 1, 1, true, ['r3']], + ]); + expect(s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message)).toEqual([expect.stringMatching(/not sealed twice/)]); + }); +}); + +describe('the uncounted re-walk is bounded while a chain stays skipped (review#3 S1)', () => { + it('walks at most MAX_IDLE_WINDOWS_PER_PASS windows that seal nothing, and says so at error', async () => { + const s = setup(); + const HOURS = 200; + s.clock.now = DAY0 + (HOURS + 1) * H; // windows up to HOURS:00 are due + s.hot.table('ledger_probe').push({ ...row('stuck', at(0, 20), 'org_s'), payload: 42 }); + for (let h = 0; h <= HOURS - 1; h++) s.hot.table('ledger_probe').push(row(`a${h}`, at(h, 10))); + // org_a catches up 24 windows a pass while org_s stays skipped at 00:00, so the floor stays there. + for (let pass = 0; pass < 12 && (await s.sealer.runPass()) > 0; pass++); + const windowsRead = new Set(); + const find = s.hot.find.bind(s.hot); + s.hot.find = async (object, query) => { + if (object === 'ledger_probe' && query.limit === 500) windowsRead.add(JSON.stringify((query.where as Record).created_at ?? (query.where as { $and: Array> }).$and[0].created_at)); + return find(object, query); + }; + expect(await s.sealer.runPass()).toBe(0); + expect(windowsRead.size).toBe(1 + AUDIT_SEAL_MAX_IDLE_WINDOWS_PER_PASS); // the floor window, then the cap + expect(s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message)) + .toContainEqual(expect.stringMatching(/'ledger_probe'.*walked .* windows that seal nothing.*chain 'org:org_s'/)); + }); +}); + 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; diff --git a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-verifier.test.ts b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-verifier.test.ts index 77b9d2a7e8e..59b202fa4a3 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/audit-seal-verifier.test.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/audit-seal-verifier.test.ts @@ -11,6 +11,7 @@ import { canonicalValue, checkpointBodyFromRow, checkpointDigest, + checkpointRow, checkpointSeedContext, columnSaltsOf, commitValue, @@ -27,7 +28,7 @@ import { } from './index.js'; import { bindingCrypto, memoryEngine, recordingLogger } from './seal-store.testkit.js'; import { AuditSealer } from './sealer.js'; -import { LocalCheckpointSigner, readAuditSealSecret } from './signer.js'; +import { LocalCheckpointSigner, readAuditSealSecret, writeAuditSealSecret } from './signer.js'; /** * ADR-0154 D9 — the live check over an in-memory engine double: per-row @@ -252,6 +253,24 @@ describe('trust: only keys the anchor vouches for (D6)', () => { expect(verdicts(report)).toEqual({ r5: 'late!' }); }); + it('faults a row id two checkpoints list, though each is signed and linked: the second listing holds nothing (S7)', async () => { + const s = await sealedLedger(); + // A second, validly signed and linked checkpoint of org_b re-listing r5, under its own sealed seed. + const first = checkpointBodyFromRow(s.checkpoint('org:org_b', 0)); + const handle = await readAuditSealSecret(s.engine, first.seed_handle); + const seed = await s.crypto.decrypt(handle!, checkpointSeedContext('ledger_probe', 'org_b', 0)); + const context = checkpointSeedContext('ledger_probe', 'org_b', 1); + const resealed = await s.crypto.encrypt(seed, context); + await writeAuditSealSecret(s.engine, resealed, context); + const body: CheckpointSignedBody = { ...first, sequence: 1, previous_digest: checkpointDigest(first), seed_handle: resealed.id }; + const { signature } = await s.signer.sign(signedBodyBytes(body)); + s.checkpoints().push(checkpointRow(body, { id: 'again', signature, leafHashes: JSON.parse(String(s.checkpoint('org:org_b', 0).leaf_hashes)) })); + const report = await s.verifyNow(); + expect(faultKinds(report)).toEqual(['org:org_b#1:listed_twice']); + expect(report.ok).toBe(false); + expect(report.totals).toMatchObject({ unmodified: 5 }); + }); + it('reports a checkpoint row that is not a signed body as malformed: the run fails', async () => { const s = await sealedLedger(); s.checkpoint('org:org_b', 0).row_ids = '["r5","r5"]'; diff --git a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts index 4065dc8dc56..84595101fcf 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts @@ -24,6 +24,7 @@ function matches(row: Row, where: Record = {}): boolean { if ('$gte' in ops && !((value as number) >= (comparable(ops.$gte) as number))) return false; if ('$gt' in ops && !((value as number) > (comparable(ops.$gt) as number))) return false; if ('$lt' in ops && !((value as number) < (comparable(ops.$lt) as number))) return false; + if ('$in' in ops && !(ops.$in as unknown[]).some((v) => comparable(v) === value)) return false; return true; } return value === comparable(cond); From b080e65aebaa3b2f63f5b86b3fab37e3492df08e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 03:03:36 +0000 Subject: [PATCH 14/23] feat(plugin-audit): seal a window into consecutive checkpoints of at most 10,000 leaves, and bound the idle re-walk (S7, review#3 S1) A chain's window seals into parts cut in D1 order, each with its own seed; the signed body carries part_index and final_part. A pass that stopped mid-window resumes it as further window parts. Late sealings split the same way. The verifier faults a row id two checkpoints list. Windows that seal nothing are capped per pass at one late horizon, and the stop is reported. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .../src/audit-seal/audit-seal-sealer.test.ts | 2 +- .../plugin-audit/src/audit-seal/sealer.ts | 222 +++++++++++++++--- .../src/audit-seal/signed-body.ts | 31 +++ .../plugin-audit/src/audit-seal/verifier.ts | 13 +- .../objects/sys-audit-checkpoint.object.ts | 18 +- 5 files changed, 245 insertions(+), 41 deletions(-) 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 942e8c26e07..4bd9ce80b83 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 @@ -421,7 +421,7 @@ describe('the uncounted re-walk is bounded while a chain stays skipped (review#3 expect(await s.sealer.runPass()).toBe(0); expect(windowsRead.size).toBe(1 + AUDIT_SEAL_MAX_IDLE_WINDOWS_PER_PASS); // the floor window, then the cap expect(s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message)) - .toContainEqual(expect.stringMatching(/'ledger_probe'.*walked .* windows that seal nothing.*chain 'org:org_s'/)); + .toContainEqual(expect.stringMatching(/'ledger_probe'.*walked .* windows that seal nothing.*chain\(s\) 'org:org_s'/)); }); }); diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 5e40b5178ea..8bb5374f7ce 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -34,6 +34,7 @@ import { chainKeyOf, checkpointBodyFromRow, checkpointDigest, + checkpointPartOf, checkpointRow, signedBodyBytes, SignedBodyError, @@ -44,8 +45,10 @@ import { dropAuditSealSecret, writeAuditSealSecret, type SealStorageDriver, type /** * ADR-0154 D3 — the sealer: after a settle lag, one window at a time, under - * the cluster lock `audit.sealer`, it seals each sealed object's rows into one - * signed checkpoint per chain (organization, or the deployment) per window. + * the cluster lock `audit.sealer`, it seals each sealed object's rows into + * signed checkpoints per chain (organization, or the deployment) per window: + * consecutive parts of at most {@link AUDIT_SEAL_MAX_LEAVES} leaves each + * (S7, D4 as amended 2026-11-14), cut in D1 order, the last one final. * * A pass, per sealed object: * @@ -63,6 +66,13 @@ 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. * + * S7: a pass that stops mid-window leaves the chain's last `window` part + * non-final; the next pass resumes that window as further `window` parts, + * counting on from that part's index, so the rest is never sealed as `late`. + * A window is read twice: once for the ids and instants of its rows, then + * each part's rows by id, hashed under that part's own seed (D2) — so one + * checkpoint's work is bounded by N, whatever its window holds. + * * 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 @@ -91,6 +101,19 @@ const REPORT_REPEAT_MS = 60 * 60 * 1000; const PAGE_SIZE = 500; /** Windows sealed per object per pass; a backlog continues on the next pass, which follows at once. */ const MAX_WINDOWS_PER_PASS = 24; +/** + * S7 (ADR-0154 D4 amended): the most leaves one checkpoint holds. A window + * holding more seals into consecutive parts. A fixed constant, not a knob. + */ +export const AUDIT_SEAL_MAX_LEAVES = 10_000; +/** + * review#3 S1: windows a pass may walk that seal nothing — every row of them + * belongs to a chain sealed past them, or to a chain skipped in this pass — + * before it stops walking. Only a skipped chain holds the floor back so that + * such windows recur; this bounds what each pass re-reads while it stays + * skipped. One late horizon's worth of windows. + */ +export const AUDIT_SEAL_MAX_IDLE_WINDOWS_PER_PASS = AUDIT_SEAL_LATE_HORIZON_MS / AUDIT_SEAL_WINDOW_MS; /** Sign attempts of one checkpoint before the pass gives up (the S1 loop). */ const MAX_SIGN_ATTEMPTS = 3; /** The key id a body is built with before the signer has named one. */ @@ -121,6 +144,12 @@ export interface AuditSealerOptions { cluster?: () => IClusterService | undefined; logger: AuditSealerLogger; now?: () => number; + /** + * Test seam, like `now`: a smaller {@link AUDIT_SEAL_MAX_LEAVES}, so a test + * can cut a window into parts with a handful of rows. `AuditPlugin` never + * passes it, and nothing an operator or a tenant sets reaches it. + */ + maxLeaves?: number; } /** A sealed object, as a pass reads it. */ @@ -136,13 +165,23 @@ interface ChainHead { readonly digest: string; } -/** One chain's rows of one window, as leaves. */ -interface ChainLeaves { +/** One chain's rows of one window, as read: each row's id and canonical `created_at`, not yet hashed. */ +interface ChainRows { readonly tenantId: string | null; - readonly seed: Buffer; - readonly leaves: Array<{ id: string; at: string; hash: Buffer }>; + readonly rows: Array<{ id: string; at: string }>; +} + +/** A row as a leaf of one checkpoint, under that checkpoint's seed. */ +interface Leaf { + readonly id: string; + readonly at: string; + readonly hash: Buffer; } +/** D1 leaf order: `(created_at, id)`. */ +const leafOrder = (a: { id: string; at: string }, b: { id: string; at: string }): number => + a.at < b.at ? -1 : a.at > b.at ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0; + const iso = (ms: number): string => new Date(ms).toISOString(); /** @@ -257,6 +296,19 @@ export class AuditSealer { } } + /** + * review#3 S1: the walk stopped on its bound of windows that seal nothing. + * While a skipped chain holds the floor back, windows past that bound wait + * for it; this says so at `error`, once per {@link REPORT_REPEAT_MS}. + */ + private reportIdleStop(object: string, stop: { at: number; windows: number }, skipped: ReadonlyMap): void { + const chains = [...skipped.keys()].map((key) => `'${key}'`).join(', ') || 'none in this pass'; + this.report(`idle:${object}`, () => + `AuditSealer: '${object}' walked ${stop.windows} windows that seal nothing in one pass and stopped there — ` + + `its rows from the window of ${iso(stop.at)} on are NOT being sealed while the skipped chain(s) ${chains} ` + + 'hold its sealed-through watermark back. Fix the chain fault reported for it; sealing then catches up.'); + } + /** The sealed objects the registry holds that can be sealed; each that cannot is reported. */ private plans(): SealPlan[] { const plans: SealPlan[] = []; @@ -343,6 +395,7 @@ export class AuditSealer { } finally { written += pass?.written ?? 0; if (pass) this.reportSkipped(plan.name, pass.skipped); + if (pass?.idleStop) this.reportIdleStop(plan.name, pass.idleStop, pass.skipped); } } return written; @@ -365,6 +418,10 @@ class ObjectPass { 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(); + /** S7: the chains whose newest `window` part is not final — the window they resume, and its next part. */ + private readonly resume = new Map(); + /** review#3 S1: where the walk stopped on its bound of windows that seal nothing, if it did. */ + idleStop: { at: number; windows: number } | null = null; /** 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. */ @@ -407,18 +464,30 @@ class ObjectPass { const recent = await this.checkpoints.find(AUDIT_CHECKPOINT_OBJECT, { where: { sealed_object: this.plan.name, kind: 'window', window_start: { $gte: iso(this.floor) } }, }); + // S7: a chain whose newest `window` part is not final resumes that window, from the next part. + const newest = new Map(); for (const row of recent) { const key = String(row.chain_key); let start: number; + let part: { part_index: number; final_part: boolean }; try { start = Date.parse(canonicalDatetime(row.window_start, 'window_start')); + part = checkpointPartOf(row); } 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)); + const seen = newest.get(key); + if (!seen || start > seen.start || (start === seen.start && part.part_index > seen.part)) { + newest.set(key, { start, part: part.part_index, final: part.final_part }); + } lastWindow = Math.max(lastWindow ?? start, start); } + for (const [key, { start, part, final }] of newest) { + if (this.skipped.has(key)) continue; + this.cursors.set(key, final ? start + AUDIT_SEAL_WINDOW_MS : start); + if (!final) this.resume.set(key, { window: start, next: part + 1 }); + } } const due = windowOf(this.now - AUDIT_SEAL_SETTLE_MS); @@ -431,13 +500,19 @@ class ObjectPass { cursor = windowOf(oldest); } // 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;) { + // chains already sealed (or skipped) past it does not count toward the pass's windows, but toward its own + // bound (review#3 S1): a chain that stays skipped holds the floor, and every pass walks on from there. + for (let n = 0, idle = 0; n < MAX_WINDOWS_PER_PASS;) { const next = await this.firstRowAt(cursor, due); if (next === null) break; + if (idle >= AUDIT_SEAL_MAX_IDLE_WINDOWS_PER_PASS) { + this.idleStop = { at: windowOf(next), windows: idle }; + break; + } const start = windowOf(next); const chains = await this.readWindow(start, (row) => start >= this.cursorOf(chainKeyOf(tenantOf(row)))); if (chains.size > 0) n += 1; + else idle += 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; } @@ -564,8 +639,8 @@ class ObjectPass { * is read once though both stores hold it (between the archive's copy and * its hot delete), and only in the window its canonical `created_at` names. */ - private async readWindow(start: number, accept: (row: Row) => boolean): Promise> { - const chains = new Map(); + private async readWindow(start: number, accept: (row: Row) => boolean): Promise> { + const chains = new Map(); const seen = new Set(); const range = { created_at: { $gte: iso(start), $lt: iso(start + AUDIT_SEAL_WINDOW_MS) } }; for (const store of this.stores()) { @@ -592,11 +667,11 @@ class ObjectPass { seen.add(id); let chain = chains.get(key); if (!chain) { - chain = { tenantId, seed: generateCheckpointSeed(), leaves: [] }; + chain = { tenantId, rows: [] }; 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) }); + // S7: ids and instants only; each part's rows are read again by id and hashed under its own seed. + chain.rows.push({ id, at }); } catch (err) { // S4: a row a canonical rule refuses skips its chain, and only its chain. if (!(err instanceof CanonicalFormError)) throw err; @@ -633,23 +708,91 @@ class ObjectPass { 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). + private async writeChains(chains: Map, start: number, kind: AuditCheckpointKind, watermark: number): Promise { + // `readWindow` makes a chain only with its first row, so no checkpoint is empty (D3). for (const key of [...chains.keys()].sort()) { if (this.skipped.has(key)) continue; try { - await this.writeCheckpoint(key, chains.get(key)!, start, kind, watermark); + await this.writeChain(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; + // S4: only a chain-local fault of this chain skips it — a malformed checkpoint of it, or a row of it a + // canonical rule refuses as its part is hashed; every other fault stops the object's pass. + if (!(err instanceof CanonicalFormError) && !(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.cursors.set(key, start + AUDIT_SEAL_WINDOW_MS); + this.resume.delete(key); + } } if (kind === 'window') this.watermark = Math.max(this.watermark ?? watermark, watermark); } + /** + * S7: one chain's rows of window `start` as consecutive checkpoints of at + * most N leaves, cut in D1 order, the last one final. A `window` sealing + * that resumes a window a stopped pass left continues its part count and + * seals only the rows no checkpoint lists yet. + */ + private async writeChain(key: string, chain: ChainRows, start: number, kind: AuditCheckpointKind, watermark: number): Promise { + await this.headOf(key); + const resumed = kind === 'window' ? this.resume.get(key) : undefined; + let rows = chain.rows; + if (kind === 'late' || resumed?.window === start) { + // 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. + // A resumed window drops the rows its earlier parts list the same way. + const listed = await this.listedIn(start, key); + rows = rows.filter((r) => !listed.has(r.id)); + } + const ordered = [...rows].sort(leafOrder); + const size = Math.max(1, Math.floor(this.options.maxLeaves ?? AUDIT_SEAL_MAX_LEAVES)); + const first = resumed?.window === start ? resumed.next : 0; + for (let at = 0; at < ordered.length; at += size) { + const seed = generateCheckpointSeed(); + const leaves = await this.leavesOf(key, seed, ordered.slice(at, at + size), start); + if (leaves.length === 0) continue; // every row of the part went since the window was read + await this.writeCheckpoint(key, chain.tenantId, seed, leaves, start, kind, watermark, { + part_index: first + at / size, + final_part: at + size >= ordered.length, + }); + } + } + + /** + * The leaves of one part: its rows read again by id, from the hot store and + * then the archive, hashed under the part's seed, in D1 order. A row gone + * since the window was read, or whose `created_at` or chain moved since, is + * left out: it is no longer a row of this chain's window. + */ + private async leavesOf(key: string, seed: Buffer, part: ReadonlyArray<{ id: string }>, start: number): Promise { + const ids = part.map((r) => r.id); + const byId = new Map(); + for (const store of this.stores()) { + for (let i = 0; i < ids.length; i += PAGE_SIZE) { + const batch = ids.slice(i, i + PAGE_SIZE).filter((id) => !byId.has(id)); + if (batch.length === 0) continue; + await this.lock.renew(LOCK_TTL_MS); + for (const row of await this.find(store, { where: { id: { $in: batch } } })) { + const id = rowIdOf(row); + if (!byId.has(id)) byId.set(id, row); + } + } + } + const saltOf = columnSaltsOf(seed, this.plan.name); + const leaves: Leaf[] = []; + for (const id of ids) { + const row = byId.get(id); + if (!row) continue; + const at = canonicalDatetime(row.created_at, `${id}.created_at`); + if (windowOf(Date.parse(at)) !== start || chainKeyOf(tenantOf(row)) !== key) continue; + leaves.push({ id, at, hash: leafHash(leafInput(row, this.plan.columns, this.plan.fields, saltOf)) }); + } + return leaves.sort(leafOrder); + } + /** * Sign `build`'s body under the S1 loop: built with the key id the signer is * expected to use, signed, and when the signer answers with another key id, @@ -670,33 +813,34 @@ class ObjectPass { throw new Error(`the checkpoint signer answered a different key id on each of ${MAX_SIGN_ATTEMPTS} attempts`); } - private async writeCheckpoint(chainKey: string, chain: ChainLeaves, start: number, kind: AuditCheckpointKind, watermark: number): Promise { + private async writeCheckpoint( + chainKey: string, + tenantId: string | null, + seed: Buffer, + ordered: readonly Leaf[], + start: number, + kind: AuditCheckpointKind, + watermark: number, + part: { readonly part_index: number; readonly final_part: boolean }, + ): Promise { const { engine, crypto } = this.options; 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, chainKey); - 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); + const context = checkpointSeedContext(this.plan.name, tenantId, sequence); await this.lock.renew(LOCK_TTL_MS); - const handle = await crypto!.encrypt(encodeCheckpointSeed(chain.seed), context); + const handle = await crypto!.encrypt(encodeCheckpointSeed(seed), context); await writeAuditSealSecret(engine, handle, context); let signed: { body: CheckpointSignedBody; keyId: string; signature: string }; try { const sealedAt = iso((this.options.now ?? Date.now)()); signed = await this.signBody((signingKeyId) => ({ sealed_object: this.plan.name, - tenant_id: chain.tenantId, + tenant_id: tenantId, sequence, kind, + part_index: part.part_index, + final_part: part.final_part, window_start: iso(start), window_end: iso(start + AUDIT_SEAL_WINDOW_MS), sealed_through: iso(watermark), @@ -713,9 +857,13 @@ class ObjectPass { })); if (!this.lock.isHeld()) throw new Error('the audit.sealer lock lapsed before the checkpoint was written'); // S1: the chain's window head, re-read under the lease: a window another sealer sealed (or passed) - // since this pass began is not sealed again. Windows of a chain are sealed oldest first. - if (kind === 'window' && (await this.storedCheckpoint(chainKey, { kind: 'window', window_start: { $gte: iso(start) } }))) { - throw new Error(`chain '${chainKey}' already holds a window checkpoint at or after ${iso(start)}; it is not sealed twice`); + // since this pass began is not sealed again. Windows of a chain are sealed oldest first, and the parts of + // one window in order (S7), so only a later window or a part of this one at this index or past it refuses. + if (kind === 'window' && (await this.storedCheckpoint(chainKey, { kind: 'window', $or: [ + { window_start: { $gte: iso(start + AUDIT_SEAL_WINDOW_MS) } }, + { window_start: { $gte: iso(start), $lt: iso(start + AUDIT_SEAL_WINDOW_MS) }, part_index: { $gte: part.part_index } }, + ] }))) { + throw new Error(`chain '${chainKey}' already holds a window checkpoint at or after part ${part.part_index} of ${iso(start)}; it is not sealed twice`); } } catch (err) { // No insert was attempted, so nothing names the seed. diff --git a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts index 66cff064f8b..51e4593c6d2 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts @@ -65,6 +65,16 @@ export interface CheckpointSignedBody { readonly tenant_id: string | null; readonly sequence: number; readonly kind: AuditCheckpointKind; + /** + * ADR-0154 D4 amended (S7): a chain's window seals into consecutive + * checkpoints of at most N leaves. This one's place among them, from 0 — for + * a `window` part, its place in the window's `window` parts (a pass that + * resumes a window it left mid-way continues the count); for a `late` part, + * its place in the one late sealing of the window that wrote it. + */ + readonly part_index: number; + /** Whether this is the last part of its sealing: a window, or one late sealing of it. */ + readonly final_part: boolean; readonly window_start: string; readonly window_end: string; /** The sealed-through watermark (D3). */ @@ -191,6 +201,26 @@ function fencingToken(raw: unknown): string { return value; } +/** + * A flag in its one meaning: `true` or `false`, or the `1` / `0` (number or + * text) a driver with no boolean column hands back. Absent is refused, never + * read as either. + */ +function flag(row: Readonly>, field: string): boolean { + const value = row[field]; + if (value === true || value === 1 || value === '1' || value === 'true') return true; + if (value === false || value === 0 || value === '0' || value === 'false') return false; + throw new SignedBodyError(`${field}: true or false is required`); +} + +/** + * A stored checkpoint's place among its window's parts (S7), read alone — the + * sealer's resume reads it without judging the whole body. + */ +export function checkpointPartOf(row: Readonly>): { readonly part_index: number; readonly final_part: boolean } { + return { part_index: count(row, 'part_index'), final_part: flag(row, 'final_part') }; +} + /** A JSON column: stored as JCS text, or handed back already parsed by a driver with JSON columns. */ function json(row: Readonly>, field: string): unknown { const value = row[field]; @@ -240,6 +270,7 @@ export function checkpointBodyFromRow(row: Readonly>): C tenant_id: nullableText(row, 'tenant_id'), sequence: count(row, 'sequence'), kind: oneOf(row, 'kind', AUDIT_CHECKPOINT_KINDS), + ...checkpointPartOf(row), window_start: instant(row, 'window_start'), window_end: instant(row, 'window_end'), sealed_through: instant(row, 'sealed_through'), diff --git a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts index 10931a980fe..1bb8c22d765 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/verifier.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/verifier.ts @@ -79,6 +79,8 @@ export type AuditChainFaultKind = | 'chain_key' /** Two checkpoints at one sequence of one chain. */ | 'duplicate' + /** A row id another checkpoint already lists (S7: the parts of a window never overlap). */ + | 'listed_twice' /** Sequences no checkpoint holds and no honoured expiry covers. */ | 'gap' /** A `previous_digest` that is not the digest of what precedes it. */ @@ -763,6 +765,13 @@ export abstract class ChainCheck { this.holdsNothing(head, body); return; } + // S7 (ADR-0154 D4 amended): no row is sealed twice, whatever cut a window into parts. A row another + // checkpoint already holds is a fault here, and this listing holds nothing more for it. + const again = new Set(body.row_ids.filter((id) => this.held.has(id))); + if (again.size > 0) { + const named = [...again].slice(0, 5).join(', ') + (again.size > 5 ? ` and ${again.size - 5} more` : ''); + this.check.fault({ ...at, kind: 'listed_twice', sequence: body.sequence, message: `checkpoint ${body.sequence}: lists row(s) ${named} that another checkpoint already lists` }); + } let hashes: string[]; try { hashes = checkpointLeafHashesFromRow(row, body); @@ -779,6 +788,7 @@ export abstract class ChainCheck { } const redactions = this.redactions.get(this.key(head.chain, body.sequence)) ?? []; for (const [i, id] of body.row_ids.entries()) { + if (again.has(id)) continue; this.held.add(id); const leaf = leaves[i]; if (leaf === null) { @@ -816,7 +826,8 @@ export abstract class ChainCheck { /** The columns of a stored checkpoint and amendment a proof bundle copies of a row that is not a signed body. */ const CHECKPOINT_COLUMNS = [ - 'id', 'chain_key', 'signature', 'leaf_hashes', 'sealed_object', 'tenant_id', 'sequence', 'kind', 'window_start', 'window_end', + 'id', 'chain_key', 'signature', 'leaf_hashes', 'sealed_object', 'tenant_id', 'sequence', 'kind', 'part_index', 'final_part', + 'window_start', 'window_end', 'sealed_through', 'leaf_count', 'row_ids', 'root', 'previous_digest', 'columns', 'canon_version', 'seed_handle', 'fencing_token', 'sealed_at', 'signing_key_id', ]; diff --git a/packages/plugins/plugin-audit/src/objects/sys-audit-checkpoint.object.ts b/packages/plugins/plugin-audit/src/objects/sys-audit-checkpoint.object.ts index c9c5733a36e..de7be447d69 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-audit-checkpoint.object.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-audit-checkpoint.object.ts @@ -3,8 +3,10 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; /** - * sys_audit_checkpoint — one Merkle root per chain per window, chained and - * signed (ADR-0154 D4). + * sys_audit_checkpoint — one Merkle root per checkpoint, chained and signed + * (ADR-0154 D4, amended 2026-11-14: a chain's window seals into consecutive + * checkpoints of at most 10,000 rows, each carrying its `part_index` and + * `final_part` under the signature). * * A checkpoint seals one chain's rows of one window of a sealed object: the * chain is that object × one organization, or × the deployment for rows about @@ -91,6 +93,18 @@ export const SysAuditCheckpoint = ObjectSchema.create({ description: 'A window sealed on time, or rows that arrived after their window was sealed', }, ), + part_index: Field.number({ + label: 'Part', + required: true, + readonly: true, + description: 'Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0', + }), + final_part: Field.boolean({ + label: 'Final Part', + required: true, + readonly: true, + description: 'Whether this is the last part of its window (or late sealing)', + }), window_start: Field.datetime({ label: 'Window Start', required: true, readonly: true }), window_end: Field.datetime({ label: 'Window End', required: true, readonly: true }), sealed_through: Field.datetime({ From 0dd58a80e3121d6eb7cd343b67506099f3e3321d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 03:09:41 +0000 Subject: [PATCH 15/23] fix(plugin-audit): a checkpoint written before the parts amendment reads as one final part, and the checkpoint part columns are nullable Also regenerates the plugin-audit translation bundles for the two new checkpoint columns, and adds the changeset. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --- .changeset/31908-p4b2-bounded-checkpoints.md | 14 ++++++++++++ .../src/audit-seal/audit-seal-sealer.test.ts | 22 ++++++++++++++++++- .../plugin-audit/src/audit-seal/sealer.ts | 3 ++- .../src/audit-seal/signed-body.ts | 21 +++++++++++++----- .../objects/sys-audit-checkpoint.object.ts | 4 ++-- .../src/translations/ar.objects.generated.ts | 8 +++++++ .../ar.source-hashes.generated.ts | 4 ++++ .../src/translations/de.objects.generated.ts | 8 +++++++ .../de.source-hashes.generated.ts | 4 ++++ .../src/translations/en.objects.generated.ts | 8 +++++++ .../translations/es-ES.objects.generated.ts | 8 +++++++ .../es-ES.source-hashes.generated.ts | 4 ++++ .../src/translations/fr.objects.generated.ts | 8 +++++++ .../fr.source-hashes.generated.ts | 4 ++++ .../translations/ja-JP.objects.generated.ts | 8 +++++++ .../ja-JP.source-hashes.generated.ts | 4 ++++ .../src/translations/ko.objects.generated.ts | 8 +++++++ .../ko.source-hashes.generated.ts | 4 ++++ .../translations/pt-BR.objects.generated.ts | 8 +++++++ .../pt-BR.source-hashes.generated.ts | 4 ++++ .../src/translations/ru.objects.generated.ts | 8 +++++++ .../ru.source-hashes.generated.ts | 4 ++++ .../translations/zh-CN.objects.generated.ts | 8 +++++++ .../zh-CN.source-hashes.generated.ts | 4 ++++ .../translations/zh-Hant.objects.generated.ts | 8 +++++++ .../zh-Hant.source-hashes.generated.ts | 4 ++++ 26 files changed, 182 insertions(+), 10 deletions(-) create mode 100644 .changeset/31908-p4b2-bounded-checkpoints.md diff --git a/.changeset/31908-p4b2-bounded-checkpoints.md b/.changeset/31908-p4b2-bounded-checkpoints.md new file mode 100644 index 00000000000..4c2d9b60979 --- /dev/null +++ b/.changeset/31908-p4b2-bounded-checkpoints.md @@ -0,0 +1,14 @@ +--- +'@objectstack/plugin-audit': patch +--- + +fix(plugin-audit): the audit sealer seals a window into checkpoints of at most 10,000 rows each, and bounds what a pass re-reads while a chain stays skipped + +Clause-②: yes (widening) +Metadata-protocol: none + +**Bounded checkpoints (ADR-0154 D4, as amended 2026-11-14).** A chain's rows of one window now seal into consecutive checkpoints of at most 10,000 rows each, cut in `(created_at, id)` order, instead of one checkpoint however many rows the window holds. Each checkpoint has its own seed. Its signed body carries two new fields, `part_index` (from 0) and `final_part`, and `sys_audit_checkpoint` stores them in two new nullable columns. A pass that stops in the middle of a window resumes it on the next pass as further `window` checkpoints, never as `late` ones. Late rows split into checkpoints of at most 10,000 rows the same way. The work and memory of one checkpoint no longer grow with the window. A checkpoint written before this release has neither field. It still verifies, reads as one final part, and its chain goes on. + +**`os audit verify`.** A row id that two checkpoints list is now a fault of the new kind `listed_twice`, and the run fails. The second listing holds nothing for that row. + +**Skipped chains.** While a chain stays skipped by a chain-local fault, it holds back the sealed-through watermark, so each pass walked every window from there and re-read all of them. A pass now walks at most 168 windows that seal nothing (one late horizon) and then stops. When it stops, the sealer says so at `error`, naming the skipped chains. Sealing catches up once the chain fault is fixed. 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 4bd9ce80b83..405a3608b9f 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, verifyAuditLedger } from './index.js'; +import { checkpointBodyFromRow, checkpointDigest, signedBodyBytes, verifyAuditLedger, type CheckpointSignedBody } from './index.js'; import { bindingCrypto, memoryEngine, recordingLogger } from './seal-store.testkit.js'; import { AUDIT_SEAL_MAX_IDLE_WINDOWS_PER_PASS, AUDIT_SEAL_MAX_LEAVES, AUDIT_SEALER_LOCK, AuditSealer } from './sealer.js'; import { LocalCheckpointSigner } from './signer.js'; @@ -344,6 +344,26 @@ describe('bounded checkpoints: a window seals into consecutive parts of at most expect((await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now })).ok).toBe(true); }); + it('reads a checkpoint written before the amendment (no part index, no final flag) as one final part: it verifies, and its chain goes on', async () => { + const s = setup(); + s.hot.table('ledger_probe').push(row('r1', at(8, 10))); + await s.sealer.runPass(); + const stored = s.hot.table('sys_audit_checkpoint')[0]; + const { part_index: _part, final_part: _final, ...legacy } = checkpointBodyFromRow(stored); + const { signature } = await s.signer.sign(signedBodyBytes(legacy as CheckpointSignedBody)); + Object.assign(stored, { part_index: null, final_part: null, signature }); + expect(Object.keys(checkpointBodyFromRow(stored))).not.toContain('part_index'); + s.hot.table('ledger_probe').push(row('r2', at(9, 10))); + expect(await s.sealer.runPass()).toBe(1); + expect(parts(s)).toEqual([ + ['org_a', 'window', at(8, 0), 0, undefined, undefined, ['r1']], + ['org_a', 'window', at(9, 0), 1, 0, true, ['r2']], + ]); + const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + expect(report.ok).toBe(true); + expect(report.totals).toMatchObject({ unmodified: 2 }); + }); + it('resumes a window a stopped pass left mid-way as further window parts, never late ones', async () => { const s = setup({ maxLeaves: 2 }); s.hot.table('ledger_probe').push(row('r1', at(8, 10)), row('r2', at(8, 20)), row('r3', at(8, 30)), row('r4', at(8, 40)), row('r5', at(8, 50)), row('n1', at(9, 10))); diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index 8bb5374f7ce..efa320c0319 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -472,7 +472,8 @@ class ObjectPass { let part: { part_index: number; final_part: boolean }; try { start = Date.parse(canonicalDatetime(row.window_start, 'window_start')); - part = checkpointPartOf(row); + // A checkpoint written before the amendment is one part, final. + part = checkpointPartOf(row) ?? { part_index: 0, final_part: true }; } catch (err) { this.skip(key, err, this.floor); continue; diff --git a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts index 51e4593c6d2..ab2d542afc4 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts @@ -71,10 +71,15 @@ export interface CheckpointSignedBody { * a `window` part, its place in the window's `window` parts (a pass that * resumes a window it left mid-way continues the count); for a `late` part, * its place in the one late sealing of the window that wrote it. + * + * Absent, with `final_part`, from a checkpoint written before the amendment: + * such a body signed neither key, so it is read back without them and reads + * as one part, final. A body holding one of the two and not the other is + * refused. */ - readonly part_index: number; - /** Whether this is the last part of its sealing: a window, or one late sealing of it. */ - readonly final_part: boolean; + readonly part_index?: number; + /** Whether this is the last part of its sealing: a window, or one late sealing of it. Absent with `part_index`. */ + readonly final_part?: boolean; readonly window_start: string; readonly window_end: string; /** The sealed-through watermark (D3). */ @@ -215,9 +220,13 @@ function flag(row: Readonly>, field: string): boolean { /** * A stored checkpoint's place among its window's parts (S7), read alone — the - * sealer's resume reads it without judging the whole body. + * sealer's resume reads it without judging the whole body. `null` for a + * checkpoint written before the amendment, which carries neither key (NULL + * columns, or a body without them): one part, final. */ -export function checkpointPartOf(row: Readonly>): { readonly part_index: number; readonly final_part: boolean } { +export function checkpointPartOf(row: Readonly>): { readonly part_index: number; readonly final_part: boolean } | null { + const absent = (field: string) => row[field] === undefined || row[field] === null; + if (absent('part_index') && absent('final_part')) return null; return { part_index: count(row, 'part_index'), final_part: flag(row, 'final_part') }; } @@ -270,7 +279,7 @@ export function checkpointBodyFromRow(row: Readonly>): C tenant_id: nullableText(row, 'tenant_id'), sequence: count(row, 'sequence'), kind: oneOf(row, 'kind', AUDIT_CHECKPOINT_KINDS), - ...checkpointPartOf(row), + ...checkpointPartOf(row), // absent from a body written before the amendment, so its signed bytes stand window_start: instant(row, 'window_start'), window_end: instant(row, 'window_end'), sealed_through: instant(row, 'sealed_through'), diff --git a/packages/plugins/plugin-audit/src/objects/sys-audit-checkpoint.object.ts b/packages/plugins/plugin-audit/src/objects/sys-audit-checkpoint.object.ts index de7be447d69..66f3de03f7c 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-audit-checkpoint.object.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-audit-checkpoint.object.ts @@ -93,15 +93,15 @@ export const SysAuditCheckpoint = ObjectSchema.create({ description: 'A window sealed on time, or rows that arrived after their window was sealed', }, ), + // Not required: a checkpoint written before ADR-0154's 2026-11-14 amendment holds NULL in both and reads as + // one part, final — its signed body never carried them. part_index: Field.number({ label: 'Part', - required: true, readonly: true, description: 'Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0', }), final_part: Field.boolean({ label: 'Final Part', - required: true, readonly: true, description: 'Whether this is the last part of its window (or late sealing)', }), diff --git a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts index 47ac16a6ffb..fcff01a766a 100644 --- a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts @@ -329,6 +329,14 @@ export const arObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts index d522f37ec99..dfcd43b515e 100644 --- a/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ar.source-hashes.generated.ts @@ -59,6 +59,8 @@ export const arGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -67,6 +69,8 @@ export const arGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", diff --git a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts index 0725a5e71dc..41c17cc1bd9 100644 --- a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts @@ -329,6 +329,14 @@ export const deObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts index 1814d471e76..6de7d547ab1 100644 --- a/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/de.source-hashes.generated.ts @@ -59,6 +59,8 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -67,6 +69,8 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", diff --git a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts index c1a082de590..3f6441a64fa 100644 --- a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts @@ -329,6 +329,14 @@ export const enObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts index 9d5c070662d..f137aad58a1 100644 --- a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts @@ -329,6 +329,14 @@ export const esESObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts index 71aa5710371..c90dd3fdadb 100644 --- a/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/es-ES.source-hashes.generated.ts @@ -61,6 +61,8 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -69,6 +71,8 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", diff --git a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts index 27e32b6c708..d4e0eab7570 100644 --- a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts @@ -329,6 +329,14 @@ export const frObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts index 2de189384cb..f6c9388915a 100644 --- a/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/fr.source-hashes.generated.ts @@ -60,6 +60,8 @@ export const frGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -68,6 +70,8 @@ export const frGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", diff --git a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts index 72b0316c262..6e1d2831f64 100644 --- a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts @@ -329,6 +329,14 @@ export const jaJPObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts index 1f01fb8981b..ca768fe241f 100644 --- a/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ja-JP.source-hashes.generated.ts @@ -60,6 +60,8 @@ export const jaJPGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -68,6 +70,8 @@ export const jaJPGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", diff --git a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts index 7f833047ed1..ca765f6c6fc 100644 --- a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts @@ -329,6 +329,14 @@ export const koObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts index b3eb442b766..4664e99c854 100644 --- a/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ko.source-hashes.generated.ts @@ -59,6 +59,8 @@ export const koGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -67,6 +69,8 @@ export const koGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", diff --git a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts index 5513611c149..832b4c98808 100644 --- a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts @@ -329,6 +329,14 @@ export const ptBRObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts index 03b424f62a3..37a0720daff 100644 --- a/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/pt-BR.source-hashes.generated.ts @@ -59,6 +59,8 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -67,6 +69,8 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", diff --git a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts index ab5582b88b8..2622a4e2366 100644 --- a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts @@ -329,6 +329,14 @@ export const ruObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts index d28c39ad2c6..24358d64b24 100644 --- a/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ru.source-hashes.generated.ts @@ -59,6 +59,8 @@ export const ruGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -67,6 +69,8 @@ export const ruGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", diff --git a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts index b649ae4ae23..3ca4806bb8c 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts @@ -329,6 +329,14 @@ export const zhCNObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts index e5e21a0d8a6..5d0b20a169f 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-CN.source-hashes.generated.ts @@ -60,6 +60,8 @@ export const zhCNGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -68,6 +70,8 @@ export const zhCNGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", diff --git a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts index 3d3dfead628..a4e8aa63d6f 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts @@ -329,6 +329,14 @@ export const zhHantObjects: NonNullable = { late: "Late" } }, + part_index: { + label: "Part", + help: "Place among the consecutive checkpoints of at most 10,000 rows its window (or late sealing) is cut into, from 0" + }, + final_part: { + label: "Final Part", + help: "Whether this is the last part of its window (or late sealing)" + }, window_start: { label: "Window Start" }, diff --git a/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts index a09d064c7e8..1680ecc8112 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-Hant.source-hashes.generated.ts @@ -59,6 +59,8 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.columns.help": "789c1b1b474161a1", "objects.sys_audit_checkpoint.fields.columns.label": "c849ea0a39dedbb6", "objects.sys_audit_checkpoint.fields.fencing_token.label": "7e206dcd4b8d3ffc", + "objects.sys_audit_checkpoint.fields.final_part.help": "dd2ea0abf9d27fa3", + "objects.sys_audit_checkpoint.fields.final_part.label": "accc721e7bff52c3", "objects.sys_audit_checkpoint.fields.id.label": "6ace5d591b082096", "objects.sys_audit_checkpoint.fields.kind.help": "893a956c8c781ed6", "objects.sys_audit_checkpoint.fields.kind.label": "3acd2ee4b0e7f2cf", @@ -67,6 +69,8 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "objects.sys_audit_checkpoint.fields.leaf_count.label": "3879d38d4e5176e5", "objects.sys_audit_checkpoint.fields.leaf_hashes.help": "8c59d342be41804c", "objects.sys_audit_checkpoint.fields.leaf_hashes.label": "74230d1d6453537c", + "objects.sys_audit_checkpoint.fields.part_index.help": "37552741e590bfa1", + "objects.sys_audit_checkpoint.fields.part_index.label": "049d919558de58bd", "objects.sys_audit_checkpoint.fields.previous_digest.help": "f1e76ab5745fa68b", "objects.sys_audit_checkpoint.fields.previous_digest.label": "c0df1553d55fcdd6", "objects.sys_audit_checkpoint.fields.root.label": "2a87592c30d680bc", From b189644b95e192084fdd646e2766a4082145128d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:07:37 +0000 Subject: [PATCH 16/23] test(plugin-audit): pin the part cut across a tie, rows that go between the two reads, an emptied last part and its resume, removed parts, the pre-amendment S1 refusal, and re-sealing after the idle cap The seal-store testkit now judges a where the way a SQL driver does: a comparison with a NULL column is never true, where JavaScript's null >= 0 is true, and { $null: true } is IS NULL. Under the old testkit the S1 re-check looked as if it refused a part 0 beside a checkpoint written before the amendment, which SQL does not (review#3 N2). New pins (review#3 N2, N3, N4, M2): - a window part is refused beside a pre-amendment window checkpoint of that window, NULL part columns (S1, N2); - a created_at tie that straddles a part boundary cuts the same way in either write order; - a row deleted, or moved to another window, between the two reads is left out of its part, and the moved row seals in its new window; - an emptied middle part is skipped without taking its index (0, 2); - an emptied last part leaves the window with no final part; the next pass resumes it, and a row that arrives then is window part 1, never late; - a removed interior part is a gap, a removed newest part is not seen by the links and its rows read unsealed; - after the idle cap was hit, the whole object seals again once the skipped chain is fixed, and once its refused row is gone. Claude-Session: https://claude.ai/code/session_016WV4cyNkH7W7e89m6j4aQq Co-authored-by: Claude --- .../src/audit-seal/audit-seal-sealer.test.ts | 171 +++++++++++++++++- .../src/audit-seal/seal-store.testkit.ts | 8 + 2 files changed, 176 insertions(+), 3 deletions(-) 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 405a3608b9f..a6aba14b3f9 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 @@ -50,6 +50,26 @@ function grantingCluster() { return cluster as unknown as IClusterService & { renews: number }; } +/** Runs `change` once, right after the first page read of a window's rows: between the sealer's two reads of it (S7). */ +function betweenReads(s: ReturnType, change: () => void) { + const find = s.hot.find.bind(s.hot); + let changed = false; + s.hot.find = async (object, query) => { + const page = await find(object, query); + if (!changed && object === 'ledger_probe' && query.limit === 500) { + changed = true; + change(); + } + return page; + }; +} + +/** Deletes a row of the sealed object from the hot store. */ +function drop(s: ReturnType, id: string) { + const table = s.hot.table('ledger_probe'); + table.splice(table.findIndex((r) => r.id === id), 1); +} + describe('windows: the backlog oldest first, one checkpoint per chain per window (D3, D5)', () => { it('seals every due window that holds a row, skips the empty one and the one not yet settled', async () => { const s = setup(); @@ -421,17 +441,139 @@ describe('bounded checkpoints: a window seals into consecutive parts of at most ]); expect(s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message)).toEqual([expect.stringMatching(/not sealed twice/)]); }); + + it('refuses a window part when the chain, re-read under the lease, holds a checkpoint of that window written before the amendment: on SQL a NULL part index is not at or past part 0 (S1, N2)', async () => { + const cluster = grantingCluster(); + const s = setup({ cluster }); + // A sealer of the release before the amendment, running beside this one in a rolling upgrade. + const older = 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 find = s.hot.find.bind(s.hot); + let raced = false; + s.hot.find = async (object, query) => { + const page = await find(object, query); + if (object === 'ledger_probe' && query.limit === 500 && !raced) { + raced = true; + await older.runPass(); // seals the window this pass has just read, before this pass reads the chain head + const stored = s.hot.table('sys_audit_checkpoint')[0]; + const { part_index: _part, final_part: _final, ...legacy } = checkpointBodyFromRow(stored); + const { signature } = await s.signer.sign(signedBodyBytes(legacy as CheckpointSignedBody)); + Object.assign(stored, { part_index: null, final_part: null, signature }); // what that release stores + } + return page; + }; + expect(await s.sealer.runPass()).toBe(0); + expect(parts(s)).toEqual([['org_a', 'window', at(8, 0), 0, undefined, undefined, ['r1']]]); + expect(s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message)).toEqual([expect.stringMatching(/at or after part 0 .*not sealed twice/)]); + expect((await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now })).ok).toBe(true); + }); + + it('cuts the same way whatever order the rows were written in, when a created_at tie straddles a part boundary: the id decides the side', async () => { + const tie = [row('r1', at(8, 10)), row('t-b', at(8, 20)), row('t-a', at(8, 20)), row('r4', at(8, 30))]; + for (const written of [tie, [...tie].reverse()]) { + const s = setup({ maxLeaves: 2 }); + s.hot.table('ledger_probe').push(...written.map((r) => ({ ...r }))); + expect(await s.sealer.runPass()).toBe(2); + expect(parts(s)).toEqual([ + ['org_a', 'window', at(8, 0), 0, 0, false, ['r1', 't-a']], + ['org_a', 'window', at(8, 0), 1, 1, true, ['t-b', 'r4']], + ]); + expect((await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now })).ok).toBe(true); + } + }); + + it('leaves out of its part a row deleted, or moved to another window, between the two reads; the moved row seals in its new window', async () => { + const s = setup({ maxLeaves: 2 }); + s.hot.table('ledger_probe').push(row('r1', at(8, 10)), row('r2', at(8, 20)), row('r3', at(8, 30)), row('r4', at(8, 40))); + betweenReads(s, () => { + drop(s, 'r2'); + s.hot.table('ledger_probe').find((r) => r.id === 'r3')!.created_at = at(9, 15); + }); + expect(await s.sealer.runPass()).toBe(3); + expect(parts(s)).toEqual([ + ['org_a', 'window', at(8, 0), 0, 0, false, ['r1']], + ['org_a', 'window', at(8, 0), 1, 1, true, ['r4']], + ['org_a', 'window', at(9, 0), 2, 0, true, ['r3']], + ]); + const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + expect(report.ok).toBe(true); + expect(report.totals).toMatchObject({ unmodified: 3, unsealed: 0 }); + expect(await s.sealer.runPass()).toBe(0); + }); + + it('skips a middle part whose rows all went between the two reads without taking its index: part_index may jump, and the window verifies', async () => { + const s = setup({ maxLeaves: 2 }); + s.hot.table('ledger_probe').push(row('r1', at(8, 10)), row('r2', at(8, 20)), row('r3', at(8, 30)), row('r4', at(8, 40)), row('r5', at(8, 50))); + betweenReads(s, () => (drop(s, 'r3'), drop(s, 'r4'))); + expect(await s.sealer.runPass()).toBe(2); + expect(parts(s)).toEqual([ + ['org_a', 'window', at(8, 0), 0, 0, false, ['r1', 'r2']], + ['org_a', 'window', at(8, 0), 1, 2, true, ['r5']], + ]); + expect((await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now })).ok).toBe(true); + }); + + it('leaves the window with no final part when its last part empties between the two reads; the next pass resumes it, so a row that arrives then is a window part, never a late one', async () => { + const s = setup({ maxLeaves: 2 }); + s.hot.table('ledger_probe').push(row('r1', at(8, 10)), row('r2', at(8, 20)), row('r3', at(8, 30))); + betweenReads(s, () => drop(s, 'r3')); + expect(await s.sealer.runPass()).toBe(1); + expect(parts(s)).toEqual([['org_a', 'window', at(8, 0), 0, 0, false, ['r1', 'r2']]]); + expect((await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now })).ok).toBe(true); + expect(await s.sealer.runPass()).toBe(0); // the resume finds every row listed + s.hot.table('ledger_probe').push(row('r6', at(8, 55))); + expect(await s.sealer.runPass()).toBe(1); + expect(parts(s).slice(1)).toEqual([['org_a', 'window', at(8, 0), 1, 1, true, ['r6']]]); + const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + expect(report.ok).toBe(true); + expect(report.totals).toMatchObject({ unmodified: 3, late: 0, unsealed: 0 }); + }); + + it('shows a removed interior part through the links (a gap); a removed newest part is not seen by the links, and its rows read unsealed (M2)', async () => { + const without = async (sequence: number) => { + const s = setup({ maxLeaves: 2 }); + s.hot.table('ledger_probe').push(row('r1', at(8, 10)), row('r2', at(8, 20)), row('r3', at(8, 30)), row('r4', at(8, 40)), row('r5', at(8, 50))); + expect(await s.sealer.runPass()).toBe(3); + const table = s.hot.table('sys_audit_checkpoint'); + table.splice(table.findIndex((r) => Number(r.sequence) === sequence), 1); + return verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + }; + const interior = await without(1); + expect(interior.ok).toBe(false); + expect(interior.faults.map((f) => [f.kind, f.sequence])).toEqual([['gap', 1]]); + expect(interior.rows.map((r) => [r.row, r.verdict, r.sealed])).toEqual([['r3', 'late', false], ['r4', 'late', false]]); + const newest = await without(2); + expect(newest.ok).toBe(false); + expect(newest.faults).toEqual([]); + expect(newest.rows.map((r) => [r.row, r.verdict, r.sealed])).toEqual([['r5', 'late', false]]); + }); }); describe('the uncounted re-walk is bounded while a chain stays skipped (review#3 S1)', () => { - it('walks at most MAX_IDLE_WINDOWS_PER_PASS windows that seal nothing, and says so at error', async () => { + const HOURS = 200; + /** + * org_s skipped at 00:00 by a row its canonical rule refuses, while org_a + * writes every hour: org_a catches up 24 windows a pass while org_s holds + * the floor at 00:00, until the cap stops the walk. + */ + async function stalled() { const s = setup(); - const HOURS = 200; s.clock.now = DAY0 + (HOURS + 1) * H; // windows up to HOURS:00 are due s.hot.table('ledger_probe').push({ ...row('stuck', at(0, 20), 'org_s'), payload: 42 }); for (let h = 0; h <= HOURS - 1; h++) s.hot.table('ledger_probe').push(row(`a${h}`, at(h, 10))); - // org_a catches up 24 windows a pass while org_s stays skipped at 00:00, so the floor stays there. for (let pass = 0; pass < 12 && (await s.sealer.runPass()) > 0; pass++); + return s; + } + const catchUp = async (s: ReturnType) => { + for (let pass = 0; pass < 6 && (await s.sealer.runPass()) > 0; pass++); + }; + const sealedOnce = (s: ReturnType) => { + const listed = s.checkpoints().flatMap((c) => c.row_ids).sort(); + return { listed, rows: s.hot.table('ledger_probe').map((r) => String(r.id)).sort(), late: s.checkpoints().filter((c) => c.kind === 'late') }; + }; + + it('walks at most MAX_IDLE_WINDOWS_PER_PASS windows that seal nothing, and says so at error', async () => { + const s = await stalled(); const windowsRead = new Set(); const find = s.hot.find.bind(s.hot); s.hot.find = async (object, query) => { @@ -443,6 +585,29 @@ describe('the uncounted re-walk is bounded while a chain stays skipped (review#3 expect(s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message)) .toContainEqual(expect.stringMatching(/'ledger_probe'.*walked .* windows that seal nothing.*chain\(s\) 'org:org_s'/)); }); + + it('seals the whole object again once the skipped chain is fixed: its window and the windows past the cap seal as window checkpoints, none late', async () => { + const s = await stalled(); + expect(sealedOnce(s).listed).toHaveLength(168); // org_a up to the cap; org_s and the rest wait + s.hot.table('ledger_probe').find((r) => r.id === 'stuck')!.payload = '{"v":"stuck"}'; + await catchUp(s); + const { listed, rows, late } = sealedOnce(s); + expect(listed).toEqual(rows); + expect(late).toEqual([]); + expect(s.checkpoints().filter((c) => c.tenant_id === 'org_s').map((c) => [c.kind, c.window_start, c.row_ids])).toEqual([['window', at(0, 0), ['stuck']]]); + }); + + it('seals the whole object again once the skipped chain has nothing left to seal (its refused row gone): no chain is skipped, so the walk past the cap is not cut', async () => { + const s = await stalled(); + drop(s, 'stuck'); + await catchUp(s); + const { listed, rows, late } = sealedOnce(s); + expect(listed).toEqual(rows); + expect(late).toEqual([]); + const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); + expect(report.ok).toBe(true); + expect(report.totals).toMatchObject({ unmodified: HOURS, unsealed: 0 }); + }); }); describe('the lock: audit.sealer, its fencing token on each checkpoint (D3, Q2 (a))', () => { diff --git a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts index 84595101fcf..72435a2ad28 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/seal-store.testkit.ts @@ -14,6 +14,11 @@ function comparable(value: unknown): unknown { return value; } +/** + * A `where` judged the way a SQL driver judges it: a comparison with a NULL + * column is never true (`NULL >= 0` is unknown, where JavaScript's + * `null >= 0` is `true`), and `{ $null: true }` is `IS NULL`. + */ function matches(row: Row, where: Record = {}): boolean { return Object.entries(where).every(([field, cond]) => { if (field === '$and') return (cond as Row[]).every((w) => matches(row, w)); @@ -21,6 +26,9 @@ function matches(row: Row, where: Record = {}): boolean { const value = comparable(row[field]); if (cond !== null && typeof cond === 'object' && !Array.isArray(cond)) { const ops = cond as Record; + const isNull = value === null || value === undefined; + if ('$null' in ops && ops.$null !== isNull) return false; + if (isNull && ['$gte', '$gt', '$lt', '$in'].some((op) => op in ops)) return false; if ('$gte' in ops && !((value as number) >= (comparable(ops.$gte) as number))) return false; if ('$gt' in ops && !((value as number) > (comparable(ops.$gt) as number))) return false; if ('$lt' in ops && !((value as number) < (comparable(ops.$lt) as number))) return false; From e9302166d85d425d68c1e0235142b6621e2df683 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:24:03 +0000 Subject: [PATCH 17/23] test(plugin-audit): the re-seal pin's precondition is that the cap holds rows back, not a measured count of them Claude-Session: https://claude.ai/code/session_016WV4cyNkH7W7e89m6j4aQq Co-authored-by: Claude --- .../plugin-audit/src/audit-seal/audit-seal-sealer.test.ts | 2 +- 1 file changed, 1 insertion(+), 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 a6aba14b3f9..a10be1ab5d1 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 @@ -588,7 +588,7 @@ describe('the uncounted re-walk is bounded while a chain stays skipped (review#3 it('seals the whole object again once the skipped chain is fixed: its window and the windows past the cap seal as window checkpoints, none late', async () => { const s = await stalled(); - expect(sealedOnce(s).listed).toHaveLength(168); // org_a up to the cap; org_s and the rest wait + expect(sealedOnce(s).listed.length).toBeLessThan(HOURS); // org_a up to the cap; org_s and the rest wait s.hot.table('ledger_probe').find((r) => r.id === 'stuck')!.payload = '{"v":"stuck"}'; await catchUp(s); const { listed, rows, late } = sealedOnce(s); From 6bb7f49080f1ae9bd5f02767f3aeaa2731536284 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:25:07 +0000 Subject: [PATCH 18/23] fix(plugin-audit): the idle cap counts only while a chain is skipped, and the S1 re-check refuses a part beside a pre-amendment checkpoint of its window The idle cap (review#3 S1) counted every window that sealed nothing, whether or not a chain was skipped. Once the skipped chain was fixed, or had nothing left to seal, the windows the cap had left behind still counted: the walk stopped short of the next window that seals something, no checkpoint was written, and the floor never moved, so the object never sealed past the cap again. It now counts only while a chain is skipped in the pass; with none skipped the walk reaches the next window that seals something and the floor moves past the rest. The relaxed S1 re-check matched part_index >= n. On SQL a NULL part index (a checkpoint written before the amendment) matches no comparison, so a part 0 beside such a checkpoint of the same window was not refused. A third arm matches it as NULL (review#3 N2). The part_index and final_part docblocks say that the count may skip an emptied part, that a window whose last part emptied has no final part, and what the links do and do not show of a removed part (review#3 N4, M2). Claude-Session: https://claude.ai/code/session_016WV4cyNkH7W7e89m6j4aQq Co-authored-by: Claude --- .../plugin-audit/src/audit-seal/sealer.ts | 31 +++++++++++++------ .../src/audit-seal/signed-body.ts | 13 +++++++- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts index efa320c0319..e6877d87bee 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/sealer.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/sealer.ts @@ -109,9 +109,14 @@ export const AUDIT_SEAL_MAX_LEAVES = 10_000; /** * review#3 S1: windows a pass may walk that seal nothing — every row of them * belongs to a chain sealed past them, or to a chain skipped in this pass — - * before it stops walking. Only a skipped chain holds the floor back so that - * such windows recur; this bounds what each pass re-reads while it stays - * skipped. One late horizon's worth of windows. + * while a chain is skipped, before it stops walking. Only a skipped chain + * holds the floor back so that such windows recur; this bounds what each pass + * re-reads while it stays skipped. One late horizon's worth of windows. + * + * With no chain skipped the walk is not cut: such windows are then only what + * a chain skipped before (fixed since, or with nothing left to seal) left + * behind, and walking on to the next window that seals something is what + * moves the floor past them. Cut there, the floor would never move again. */ export const AUDIT_SEAL_MAX_IDLE_WINDOWS_PER_PASS = AUDIT_SEAL_LATE_HORIZON_MS / AUDIT_SEAL_WINDOW_MS; /** Sign attempts of one checkpoint before the pass gives up (the S1 loop). */ @@ -302,7 +307,7 @@ export class AuditSealer { * for it; this says so at `error`, once per {@link REPORT_REPEAT_MS}. */ private reportIdleStop(object: string, stop: { at: number; windows: number }, skipped: ReadonlyMap): void { - const chains = [...skipped.keys()].map((key) => `'${key}'`).join(', ') || 'none in this pass'; + const chains = [...skipped.keys()].map((key) => `'${key}'`).join(', '); // never empty: the bound counts only while one is skipped this.report(`idle:${object}`, () => `AuditSealer: '${object}' walked ${stop.windows} windows that seal nothing in one pass and stopped there — ` + `its rows from the window of ${iso(stop.at)} on are NOT being sealed while the skipped chain(s) ${chains} ` + @@ -501,8 +506,10 @@ class ObjectPass { cursor = windowOf(oldest); } // 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, but toward its own - // bound (review#3 S1): a chain that stays skipped holds the floor, and every pass walks on from there. + // chains already sealed (or skipped) past it does not count toward the pass's windows; while a chain is + // skipped it counts toward its own bound (review#3 S1): a chain that stays skipped holds the floor, and every + // pass walks on from there. With none skipped it counts toward nothing, so the walk reaches the next window + // that seals something and the floor moves on. for (let n = 0, idle = 0; n < MAX_WINDOWS_PER_PASS;) { const next = await this.firstRowAt(cursor, due); if (next === null) break; @@ -513,7 +520,7 @@ class ObjectPass { const start = windowOf(next); const chains = await this.readWindow(start, (row) => start >= this.cursorOf(chainKeyOf(tenantOf(row)))); if (chains.size > 0) n += 1; - else idle += 1; + else if (this.skipped.size > 0) idle += 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; } @@ -754,7 +761,9 @@ class ObjectPass { for (let at = 0; at < ordered.length; at += size) { const seed = generateCheckpointSeed(); const leaves = await this.leavesOf(key, seed, ordered.slice(at, at + size), start); - if (leaves.length === 0) continue; // every row of the part went since the window was read + // Every row of the part went since the window was read: nothing is written, and its index is not reused, so + // part_index may skip one, and a window whose last part emptied has no final part. Nothing reads either. + if (leaves.length === 0) continue; await this.writeCheckpoint(key, chain.tenantId, seed, leaves, start, kind, watermark, { part_index: first + at / size, final_part: at + size >= ordered.length, @@ -860,9 +869,13 @@ class ObjectPass { // S1: the chain's window head, re-read under the lease: a window another sealer sealed (or passed) // since this pass began is not sealed again. Windows of a chain are sealed oldest first, and the parts of // one window in order (S7), so only a later window or a part of this one at this index or past it refuses. + // A checkpoint of this window written before the amendment is the whole window; its part index is NULL, + // which no comparison matches on SQL (`NULL >= 0` is not true), so it is matched as NULL. + const thisWindow = { $gte: iso(start), $lt: iso(start + AUDIT_SEAL_WINDOW_MS) }; if (kind === 'window' && (await this.storedCheckpoint(chainKey, { kind: 'window', $or: [ { window_start: { $gte: iso(start + AUDIT_SEAL_WINDOW_MS) } }, - { window_start: { $gte: iso(start), $lt: iso(start + AUDIT_SEAL_WINDOW_MS) }, part_index: { $gte: part.part_index } }, + { window_start: thisWindow, part_index: { $gte: part.part_index } }, + { window_start: thisWindow, part_index: { $null: true } }, ] }))) { throw new Error(`chain '${chainKey}' already holds a window checkpoint at or after part ${part.part_index} of ${iso(start)}; it is not sealed twice`); } diff --git a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts index ab2d542afc4..6cc14de7493 100644 --- a/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts +++ b/packages/plugins/plugin-audit/src/audit-seal/signed-body.ts @@ -72,13 +72,24 @@ export interface CheckpointSignedBody { * resumes a window it left mid-way continues the count); for a `late` part, * its place in the one late sealing of the window that wrote it. * + * The count may skip a number: a part whose rows were all deleted or moved + * between the sealer's two reads of the window is not written and takes no + * index (parts 0 and 2, say). Nothing reads continuity, and nothing requires + * a final part, since a window whose last part emptied has none. A removed + * interior part still shows in the chain links (`gap`, `link`); a removed + * newest part does not, and its rows read unsealed. + * * Absent, with `final_part`, from a checkpoint written before the amendment: * such a body signed neither key, so it is read back without them and reads * as one part, final. A body holding one of the two and not the other is * refused. */ readonly part_index?: number; - /** Whether this is the last part of its sealing: a window, or one late sealing of it. Absent with `part_index`. */ + /** + * Whether this is the last part of its sealing: a window, or one late + * sealing of it. Absent with `part_index`. A window whose last part emptied + * between the two reads has no final part (see `part_index`). + */ readonly final_part?: boolean; readonly window_start: string; readonly window_end: string; From ff13294fa38ecdb17c266c6c798ce030438858bd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 04:25:25 +0000 Subject: [PATCH 19/23] =?UTF-8?q?docs(changeset):=20P4b2=20declares=20Clau?= =?UTF-8?q?se-=E2=91=A1=20yes=20(narrowing)=20with=20the=20BREAKING=20bann?= =?UTF-8?q?er=20and=20its=20ADR-0087=20disposition,=20and=20states=20the?= =?UTF-8?q?=20one-way=20upgrade?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit review#3 M1: listed_twice refuses a chain the released 18.4.0 sealer could write when two late sealings overlapped and the 18.4.0 verifier accepted, so the arm is (narrowing). Metadata-protocol stays none, so the level stays patch. The disposition is not-required (no-migration-prescription): nothing stored is rewritten and no tolerance or repair ships. review#3 M2: what verify's links show of a removed part, interior and newest. N1: the one-way upgrade note. The skipped-chain paragraph states the idle cap as it now counts, only while a chain is skipped. Claude-Session: https://claude.ai/code/session_016WV4cyNkH7W7e89m6j4aQq Co-authored-by: Claude --- .changeset/31908-p4b2-bounded-checkpoints.md | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/.changeset/31908-p4b2-bounded-checkpoints.md b/.changeset/31908-p4b2-bounded-checkpoints.md index 4c2d9b60979..98824e38acd 100644 --- a/.changeset/31908-p4b2-bounded-checkpoints.md +++ b/.changeset/31908-p4b2-bounded-checkpoints.md @@ -2,13 +2,19 @@ '@objectstack/plugin-audit': patch --- -fix(plugin-audit): the audit sealer seals a window into checkpoints of at most 10,000 rows each, and bounds what a pass re-reads while a chain stays skipped +fix(plugin-audit)!: the audit sealer seals a window into checkpoints of at most 10,000 rows each, `os audit verify` fails on a row two checkpoints list, and a pass bounds what it re-reads while a chain stays skipped -Clause-②: yes (widening) +Clause-②: yes (narrowing) — narrowed: `os audit verify` reports a row id that two checkpoints list as the new chain fault `listed_twice` and fails the run, where the 18.4.0 verifier accepted it, and the 18.4.0 sealer could write such a chain when two of its late sealings overlapped. Widened: the checkpoint's signed body gains two optional fields, `part_index` and `final_part`; `sys_audit_checkpoint` gains two nullable columns for them; and the exported `AuditChainFaultKind` union gains `listed_twice`. Metadata-protocol: none -**Bounded checkpoints (ADR-0154 D4, as amended 2026-11-14).** A chain's rows of one window now seal into consecutive checkpoints of at most 10,000 rows each, cut in `(created_at, id)` order, instead of one checkpoint however many rows the window holds. Each checkpoint has its own seed. Its signed body carries two new fields, `part_index` (from 0) and `final_part`, and `sys_audit_checkpoint` stores them in two new nullable columns. A pass that stops in the middle of a window resumes it on the next pass as further `window` checkpoints, never as `late` ones. Late rows split into checkpoints of at most 10,000 rows the same way. The work and memory of one checkpoint no longer grow with the window. A checkpoint written before this release has neither field. It still verifies, reads as one final part, and its chain goes on. + -**`os audit verify`.** A row id that two checkpoints list is now a fault of the new kind `listed_twice`, and the run fails. The second listing holds nothing for that row. +**BREAKING** for `os audit verify` on a chain that an 18.4.0 sealer wrote while two of its late sealings overlapped (two replicas with no cluster service, whose lock is in-process only, or a lease that lapsed). Such a chain lists one late row in two checkpoints. Verify now reports it as a `listed_twice` fault and fails, where it passed. No tolerance and no repair ships for it. A chain one sealer wrote at a time is not affected. -**Skipped chains.** While a chain stays skipped by a chain-local fault, it holds back the sealed-through watermark, so each pass walked every window from there and re-read all of them. A pass now walks at most 168 windows that seal nothing (one late horizon) and then stops. When it stops, the sealer says so at `error`, naming the skipped chains. Sealing catches up once the chain fault is fixed. +**Bounded checkpoints (ADR-0154 D4, as amended 2026-11-14).** A chain's rows of one window now seal into consecutive checkpoints of at most 10,000 rows each, cut in `(created_at, id)` order, instead of one checkpoint however many rows the window holds. Each checkpoint has its own seed. Its signed body carries two new fields, `part_index` (from 0) and `final_part`, and `sys_audit_checkpoint` stores them in two new nullable columns. A pass that stops in the middle of a window resumes it on the next pass as further `window` checkpoints, never as `late` ones. Late rows split into checkpoints of at most 10,000 rows the same way. The work and memory of one checkpoint no longer grow with the window. A checkpoint written before this release has neither field. It still verifies, reads as one final part, and its chain goes on. `part_index` can skip a number, and a window can end with no final part: a part whose rows were all deleted or moved between the sealer's two reads of the window is not written. + +**`os audit verify`.** A row id that two checkpoints list is now a fault of the new kind `listed_twice`, and the run fails. The second listing holds nothing for that row. Verify does not check that a window's parts are continuous or that it ends in a final part. The chain links show a removed interior part, as a `gap` or a `link` fault. They do not show a removed newest part; that part's rows read as late and unsealed instead. + +**Skipped chains.** While a chain stays skipped by a chain-local fault, it holds back the sealed-through watermark, so each pass walked every window from there and re-read all of them. Now, while a chain is skipped, a pass walks at most 168 windows that seal nothing (one late horizon) and then stops. When it stops, the sealer says so at `error`, naming the skipped chains. Once no chain is skipped, the walk is not cut, so sealing catches up whether the chain's fault was fixed or the chain has nothing left to seal. + +**Upgrading is one way once this release writes a checkpoint.** An 18.4.0 reader does not know `part_index` and `final_part`. The 18.4.0 verifier drops them and then fails the signature of every checkpoint that carries them. An 18.4.0 sealer computes the chain head's digest without them, so the checkpoint it writes next is a `link` fault. Roll back to 18.4.0 only before this release seals its first checkpoint. A host's checkpoint sink receives the two fields in each body. From f08afcaffe37f59edcbfb4f09cc7bc57b82b51a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 06:43:41 +0000 Subject: [PATCH 20/23] docs(audit): an hour seals into checkpoints of at most 10,000 rows, verify fails on a row two checkpoints list, and what a removed checkpoint shows objects.mdx said each hour seals into one checkpoint per organization, and cli.mdx's exit code 1 named no duplicate listing: both stopped being true with the parts and the listed_twice fault. cli.mdx also says what verify shows of a removed checkpoint, interior and newest (review#3 M2). The changeset carries the Skills-docs line the (narrowing) arm owes. Claude-Session: https://claude.ai/code/session_016WV4cyNkH7W7e89m6j4aQq Co-authored-by: Claude --- .changeset/31908-p4b2-bounded-checkpoints.md | 1 + content/docs/data-modeling/objects.mdx | 8 +++++--- content/docs/deployment/cli.mdx | 11 +++++++++-- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/.changeset/31908-p4b2-bounded-checkpoints.md b/.changeset/31908-p4b2-bounded-checkpoints.md index 98824e38acd..f5a1b41d688 100644 --- a/.changeset/31908-p4b2-bounded-checkpoints.md +++ b/.changeset/31908-p4b2-bounded-checkpoints.md @@ -6,6 +6,7 @@ fix(plugin-audit)!: the audit sealer seals a window into checkpoints of at most Clause-②: yes (narrowing) — narrowed: `os audit verify` reports a row id that two checkpoints list as the new chain fault `listed_twice` and fails the run, where the 18.4.0 verifier accepted it, and the 18.4.0 sealer could write such a chain when two of its late sealings overlapped. Widened: the checkpoint's signed body gains two optional fields, `part_index` and `final_part`; `sys_audit_checkpoint` gains two nullable columns for them; and the exported `AuditChainFaultKind` union gains `listed_twice`. Metadata-protocol: none +Skills-docs: none — no skill under `skills/**` teaches how a sealed hour is cut into checkpoints or what `os audit verify` faults (`skills/objectstack-data/rules/lifecycle.md` teaches authoring `lifecycle.seal`, which does not change); `content/docs/data-modeling/objects.mdx` and `content/docs/deployment/cli.mdx` gain the parts, the new fault and what a removed checkpoint shows in this change. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 2e950a76f66..9ac2f014c3e 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -222,9 +222,11 @@ lifecycle: { } ``` -- Each hour of `created_at` is sealed ten minutes after it ends: one - checkpoint per organization (and one for rows about no organization), - holding a Merkle root over the rows, signed with the deployment's Ed25519 +- Each hour of `created_at` is sealed ten minutes after it ends, per + organization (and once for rows about no organization): into one + checkpoint, or, when the hour holds more than 10,000 such rows, into + consecutive checkpoints of at most 10,000 rows each. Each checkpoint holds a + Merkle root over its rows and is signed with the deployment's Ed25519 key. A row that arrives later in a sealed hour is sealed as a `late` checkpoint; rows that already exist when sealing starts are sealed oldest first, archived rows included. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 9c5bfc30230..0f4b58dd311 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -800,6 +800,12 @@ Each row a checkpoint lists reads as one of: A row in a sealed window that no checkpoint lists is reported `late` and **unsealed**: on the host alone it cannot be told from a forged insert. +A checkpoint removed from a chain shows as a gap in the chain's links, unless it was the +chain's newest: the links cannot see that one. Its rows then read `late` and unsealed +while their window still counts as sealed (another checkpoint of the object names that +window, or one's sealed-through passes it); otherwise the removal does not show. A row +that two checkpoints list is a fault of its own. + Trust comes only from the deployment's own signing key. A key is trusted only when its wrapped private half opens with the crypto provider `os serve` seals with (the declaring plugin's, or the existing data key from `OS_SECRET_KEY` or the persisted key file; this @@ -811,8 +817,9 @@ Exit codes: - **0**: every chain, link and signature verifies under a trusted key, and every row is `unmodified`, `late` (sealed), `redacted` or `expired`. Also 0 when nothing is sealed. -- **1**: a row is `modified`, `missing` or `late` and unsealed, or a link or signature - fails. The report names every row that is not `unmodified` and every fault. +- **1**: a row is `modified`, `missing` or `late` and unsealed, a link or signature + fails, or two checkpoints list the same row. The report names every row that is not + `unmodified` and every fault. - **2**: no verdict is given. The cause is one of these: a usage error, a stack that would not boot, a crypto provider that cannot open what is sealed, an archive datasource a sealed object declares that this run did not connect (every archived row would read From b234eee59250fb5f9a6ab12596de7fc1c4f1608e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 06:46:49 +0000 Subject: [PATCH 21/23] test(plugin-audit): state a 30 s budget on the three stalled-chain re-walk tests Each drives stalled(): some 200 windows sealed and signed over a dozen passes. On the green Test Core (8/8) shard at ff13294f they took 1891, 3663 and 4587 ms against vitest's 5 s default; on the loaded shard after the main merge (suite test time 140 s -> 204 s) two of them took 5596 and 6754 ms and timed out. Nothing in their import closure changed in that merge; the budget is now stated instead of borrowed from the default. Claude-Session: https://claude.ai/code/session_016WV4cyNkH7W7e89m6j4aQq Co-authored-by: Claude --- .../src/audit-seal/audit-seal-sealer.test.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) 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 a10be1ab5d1..7d42252aa73 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 @@ -551,6 +551,12 @@ describe('bounded checkpoints: a window seals into consecutive parts of at most describe('the uncounted re-walk is bounded while a chain stays skipped (review#3 S1)', () => { const HOURS = 200; + /** + * Each of these tests first drives `stalled()`: some 200 windows sealed and + * signed over a dozen passes. That costs 2-5 s on a quiet CI shard and more + * on a loaded one, against vitest's 5 s default, so the budget is stated. + */ + const STALLED_TIMEOUT_MS = 30_000; /** * org_s skipped at 00:00 by a row its canonical rule refuses, while org_a * writes every hour: org_a catches up 24 windows a pass while org_s holds @@ -584,7 +590,7 @@ describe('the uncounted re-walk is bounded while a chain stays skipped (review#3 expect(windowsRead.size).toBe(1 + AUDIT_SEAL_MAX_IDLE_WINDOWS_PER_PASS); // the floor window, then the cap expect(s.logger.lines.filter((l) => l.level === 'error').map((l) => l.message)) .toContainEqual(expect.stringMatching(/'ledger_probe'.*walked .* windows that seal nothing.*chain\(s\) 'org:org_s'/)); - }); + }, STALLED_TIMEOUT_MS); it('seals the whole object again once the skipped chain is fixed: its window and the windows past the cap seal as window checkpoints, none late', async () => { const s = await stalled(); @@ -595,7 +601,7 @@ describe('the uncounted re-walk is bounded while a chain stays skipped (review#3 expect(listed).toEqual(rows); expect(late).toEqual([]); expect(s.checkpoints().filter((c) => c.tenant_id === 'org_s').map((c) => [c.kind, c.window_start, c.row_ids])).toEqual([['window', at(0, 0), ['stuck']]]); - }); + }, STALLED_TIMEOUT_MS); it('seals the whole object again once the skipped chain has nothing left to seal (its refused row gone): no chain is skipped, so the walk past the cap is not cut', async () => { const s = await stalled(); @@ -607,7 +613,7 @@ describe('the uncounted re-walk is bounded while a chain stays skipped (review#3 const report = await verifyAuditLedger({ engine: s.engine, crypto: s.crypto, now: () => s.clock.now }); expect(report.ok).toBe(true); expect(report.totals).toMatchObject({ unmodified: HOURS, unsealed: 0 }); - }); + }, STALLED_TIMEOUT_MS); }); describe('the lock: audit.sealer, its fencing token on each checkpoint (D3, Q2 (a))', () => { From 5ef334ececf85ba4345b879b4723455b533210de Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:20:54 +0000 Subject: [PATCH 22/23] docs(changeset): name the two skills/objectstack-data files a follow-up owes in Skills-docs The eval objects-fields-relationships.json and rules/lifecycle.md still teach one checkpoint per organization per hour; skills/** changes only on a domain:skills PR, so the line reads follow-up owed instead of none. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cyNkH7W7e89m6j4aQq --- .changeset/31908-p4b2-bounded-checkpoints.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/31908-p4b2-bounded-checkpoints.md b/.changeset/31908-p4b2-bounded-checkpoints.md index f5a1b41d688..2e7df06ff2e 100644 --- a/.changeset/31908-p4b2-bounded-checkpoints.md +++ b/.changeset/31908-p4b2-bounded-checkpoints.md @@ -6,7 +6,7 @@ fix(plugin-audit)!: the audit sealer seals a window into checkpoints of at most Clause-②: yes (narrowing) — narrowed: `os audit verify` reports a row id that two checkpoints list as the new chain fault `listed_twice` and fails the run, where the 18.4.0 verifier accepted it, and the 18.4.0 sealer could write such a chain when two of its late sealings overlapped. Widened: the checkpoint's signed body gains two optional fields, `part_index` and `final_part`; `sys_audit_checkpoint` gains two nullable columns for them; and the exported `AuditChainFaultKind` union gains `listed_twice`. Metadata-protocol: none -Skills-docs: none — no skill under `skills/**` teaches how a sealed hour is cut into checkpoints or what `os audit verify` faults (`skills/objectstack-data/rules/lifecycle.md` teaches authoring `lifecycle.seal`, which does not change); `content/docs/data-modeling/objects.mdx` and `content/docs/deployment/cli.mdx` gain the parts, the new fault and what a removed checkpoint shows in this change. +Skills-docs: follow-up owed — skills/objectstack-data/evals/objects-fields-relationships.json, skills/objectstack-data/rules/lifecycle.md — both still teach that the sealer signs each `created_at` hour into one checkpoint per organization, where this change cuts a window into checkpoints of at most 10,000 rows each (the eval's graded `expected_output`, and `lifecycle.md` § Sealing); the card also carries their older stale claim that no verifier exists, which `os audit verify` already contradicts. `skills/**` is changed only on a `domain:skills` PR, so this one does not edit them; `content/docs/data-modeling/objects.mdx` and `content/docs/deployment/cli.mdx` gain the parts, the new fault and what a removed checkpoint shows in this change. From 55dfebcfc26c1eacf0085e9813a43598222d1b10 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 10:11:16 +0000 Subject: [PATCH 23/23] docs(changeset): name follow-up #33773 in the P4b2 Skills-docs line review#3 M1 (record 6891899947): the `Skills-docs:` declaration names the filed follow-up card instead of `follow-up owed`. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cyNkH7W7e89m6j4aQq --- .changeset/31908-p4b2-bounded-checkpoints.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/31908-p4b2-bounded-checkpoints.md b/.changeset/31908-p4b2-bounded-checkpoints.md index 2e7df06ff2e..a59be52889b 100644 --- a/.changeset/31908-p4b2-bounded-checkpoints.md +++ b/.changeset/31908-p4b2-bounded-checkpoints.md @@ -6,7 +6,7 @@ fix(plugin-audit)!: the audit sealer seals a window into checkpoints of at most Clause-②: yes (narrowing) — narrowed: `os audit verify` reports a row id that two checkpoints list as the new chain fault `listed_twice` and fails the run, where the 18.4.0 verifier accepted it, and the 18.4.0 sealer could write such a chain when two of its late sealings overlapped. Widened: the checkpoint's signed body gains two optional fields, `part_index` and `final_part`; `sys_audit_checkpoint` gains two nullable columns for them; and the exported `AuditChainFaultKind` union gains `listed_twice`. Metadata-protocol: none -Skills-docs: follow-up owed — skills/objectstack-data/evals/objects-fields-relationships.json, skills/objectstack-data/rules/lifecycle.md — both still teach that the sealer signs each `created_at` hour into one checkpoint per organization, where this change cuts a window into checkpoints of at most 10,000 rows each (the eval's graded `expected_output`, and `lifecycle.md` § Sealing); the card also carries their older stale claim that no verifier exists, which `os audit verify` already contradicts. `skills/**` is changed only on a `domain:skills` PR, so this one does not edit them; `content/docs/data-modeling/objects.mdx` and `content/docs/deployment/cli.mdx` gain the parts, the new fault and what a removed checkpoint shows in this change. +Skills-docs: follow-up #33773 — skills/objectstack-data/evals/objects-fields-relationships.json, skills/objectstack-data/rules/lifecycle.md — both still teach that the sealer signs each `created_at` hour into one checkpoint per organization, where this change cuts a window into checkpoints of at most 10,000 rows each (the eval's graded `expected_output`, and `lifecycle.md` § Sealing); the card also carries their older stale claim that no verifier exists, which `os audit verify` already contradicts. `skills/**` is changed only on a `domain:skills` PR, so this one does not edit them; `content/docs/data-modeling/objects.mdx` and `content/docs/deployment/cli.mdx` gain the parts, the new fault and what a removed checkpoint shows in this change.