From dbf8752d24e08502a20fa483de0bf389048f0e9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 08:04:02 +0100 Subject: [PATCH 01/33] feat!: retire event types and seal what they stored by the marks every start records Squashed from the PR 2 sessions so far, to rebase onto the merged PR 1: - feat(core): retire event types, refuse types no module names and reach a retired event's process - feat(cli): generate retired event types - feat(core): export and redact a retired event type's personal data by its envelopes - test(core): close every connection before restoring a SQLite backup in the retired personal data tests - feat(core): record event type marks, the kinds that opened a stream and each process letter's instance - test(core): restore the marks and the kinds that opened a stream with a copy, and migrate a SQLite copy taken before them - feat(core): seal retired event types by the marks every start records - fix(core): never write back in the clear what an upcast carries or makes from a sealed value under a key no schema declares - test(core): seal retired types end to end across rolling deploys, A to B to A marks, frozen and forgotten tenants - test(core): refuse a rebuild and a ledger prune over a retired type no start recorded marks for --- docs/src/content/docs/adapters/index.mdx | 5 +- packages/cli/src/generate/discover.test.ts | 76 ++ packages/cli/src/generate/discover.ts | 122 +++- packages/cli/src/generate/emit/emit.test.ts | 43 ++ packages/cli/src/generate/emit/registry.ts | 9 + packages/cli/src/generate/fingerprint.test.ts | 29 + packages/cli/src/generate/model.ts | 8 + .../cloudflare/test/bounda-object.test.ts | 2 +- packages/core/src/adapter/index.ts | 5 + packages/core/src/adapter/sql/dead-letters.ts | 27 + .../core/src/adapter/sql/event-marks.test.ts | 154 ++++ packages/core/src/adapter/sql/event-marks.ts | 171 +++++ .../core/src/adapter/sql/event-types.test.ts | 80 ++- packages/core/src/adapter/sql/event-types.ts | 62 +- packages/core/src/adapter/sql/index.ts | 20 + packages/core/src/adapter/sqlite/adapter.ts | 1 + .../src/adapter/sqlite/dead-letter-store.ts | 8 +- .../core/src/adapter/sqlite/event-store.ts | 35 +- .../core/src/adapter/sqlite/migrations.ts | 51 +- .../src/adapter/sqlite/restore-copy.test.ts | 74 +- packages/core/src/adapter/sqlite/schema.ts | 5 +- .../core/src/adapter/sqlite/sqlite.test.ts | 11 +- .../core/src/adapter/staged-event-store.ts | 41 +- .../src/adapter/storage/dead-letter-store.ts | 5 + .../core/src/adapter/storage/event-store.ts | 72 +- .../core/src/adapter/storage/inspection.ts | 2 + .../testing/dead-letter-store.contract.ts | 28 + .../src/adapter/testing/documented-tables.ts | 1 + .../core/src/adapter/testing/earlier-rows.ts | 21 +- .../adapter/testing/event-store.contract.ts | 285 +++++++- .../adapter/testing/inspection.contract.ts | 5 + .../src/adapter/testing/restore.contract.ts | 67 ++ .../testing/storage-schema.contract.ts | 124 +++- .../src/kernel/aggregate/build-aggregates.ts | 4 +- .../src/kernel/aggregate/fold-state.test.ts | 40 ++ .../core/src/kernel/aggregate/fold-state.ts | 10 +- packages/core/src/kernel/aggregate/runtime.ts | 10 + .../src/kernel/aggregate/stored-types.test.ts | 167 ++++- .../core/src/kernel/aggregate/stored-types.ts | 124 +++- .../src/kernel/aggregate/upcasting.test.ts | 56 +- .../core/src/kernel/aggregate/upcasting.ts | 6 +- packages/core/src/kernel/app.ts | 79 +- .../core/src/kernel/dead-letters/retry.ts | 1 + .../dispatch/subscriber-failures-app.test.ts | 4 +- packages/core/src/kernel/migrate.test.ts | 2 +- .../personal-data/backfill-walk.test.ts | 5 + .../kernel/personal-data/event-store.test.ts | 129 ++++ .../src/kernel/personal-data/event-store.ts | 39 +- .../src/kernel/personal-data/export-stream.ts | 37 +- .../src/kernel/personal-data/export.test.ts | 4 +- .../personal-data/key-hierarchy.test.ts | 2 +- .../src/kernel/personal-data/key-hierarchy.ts | 5 +- .../kernel/personal-data/ledger-in-force.ts | 5 + .../kernel/personal-data/ledger-prune.test.ts | 2 + .../src/kernel/personal-data/ledger-prune.ts | 38 +- .../src/kernel/personal-data/marks.test.ts | 2 + .../core/src/kernel/personal-data/marks.ts | 19 +- .../src/kernel/personal-data/persons.test.ts | 20 + .../core/src/kernel/personal-data/persons.ts | 33 +- .../core/src/kernel/personal-data/redact.ts | 21 +- .../personal-data/redaction-details.test.ts | 7 +- .../personal-data/redaction-targets.test.ts | 41 +- .../kernel/personal-data/redaction-targets.ts | 58 +- .../src/kernel/personal-data/redaction.ts | 70 +- .../personal-data/reseal-batches.test.ts | 11 +- .../kernel/personal-data/reseal-batches.ts | 5 +- .../kernel/personal-data/resealing.test.ts | 239 ++++++- .../src/kernel/personal-data/resealing.ts | 161 ++++- .../personal-data/retired-marks-app.test.ts | 674 ++++++++++++++++++ .../retired-personal-data-app.test.ts | 629 ++++++++++++++++ .../schema-ahead-readers.test.ts | 1 + .../kernel/personal-data/stored-marks.test.ts | 244 +++++++ .../src/kernel/personal-data/stored-marks.ts | 214 ++++++ .../core/src/kernel/personal-data/stranded.ts | 8 +- .../tenant-export-stream.test.ts | 40 +- .../personal-data/tenant-export-stream.ts | 55 +- .../personal-data/tenant-keys-app.test.ts | 2 +- .../core/src/kernel/policy/build-policies.ts | 12 +- packages/core/src/kernel/policy/delayed.ts | 15 +- .../core/src/kernel/policy/runner.test.ts | 39 + .../src/kernel/process/build-processes.ts | 60 +- .../src/kernel/process/dead-letter-retry.ts | 12 +- .../core/src/kernel/process/failures.test.ts | 27 +- packages/core/src/kernel/process/failures.ts | 5 + .../core/src/kernel/process/runner.test.ts | 66 ++ packages/core/src/kernel/reactive-harness.ts | 1 + .../core/src/kernel/read-model/rebuild.ts | 26 +- .../src/kernel/retired-events-app.test.ts | 436 +++++++++++ .../src/kernel/shared/committed-events.ts | 2 + .../src/kernel/unit-of-work/unit-of-work.ts | 10 +- packages/core/src/memory/event-store.ts | 62 +- packages/core/src/memory/index.ts | 5 + packages/core/src/memory/tenant-fence.test.ts | 2 + packages/core/src/memory/tenant-fence.ts | 2 +- packages/core/src/memory/transaction.ts | 1 + packages/core/src/modules/event.ts | 5 + packages/core/src/modules/redaction.ts | 16 +- packages/core/src/modules/registry.ts | 8 +- packages/core/src/modules/validate.test.ts | 55 ++ packages/core/src/modules/validate.ts | 34 +- .../order-app-inferred/.bounda/registry.ts | 2 + .../app/domain/order/order-note-added.ts | 1 + .../fixtures/order-app/.bounda/registry.ts | 2 + .../app/domain/order/order-note-added.ts | 1 + packages/core/test-types/inference.test-d.ts | 1 + .../core/test-types/retired-events.test-d.ts | 49 ++ .../test-types/schema-evolution.test-d.ts | 35 +- packages/postgresql/src/dead-letter-store.ts | 8 +- packages/postgresql/src/event-store.ts | 37 +- packages/postgresql/src/index.ts | 1 + packages/postgresql/src/migrations.ts | 49 ++ packages/postgresql/src/postgresql.test.ts | 3 + packages/postgresql/src/schema.ts | 5 +- packages/sqlite/src/libsql-server.test.ts | 2 +- packages/sqlite/src/sqlite.test.ts | 2 + 115 files changed, 5740 insertions(+), 331 deletions(-) create mode 100644 packages/core/src/adapter/sql/event-marks.test.ts create mode 100644 packages/core/src/adapter/sql/event-marks.ts create mode 100644 packages/core/src/kernel/personal-data/retired-marks-app.test.ts create mode 100644 packages/core/src/kernel/personal-data/retired-personal-data-app.test.ts create mode 100644 packages/core/src/kernel/personal-data/stored-marks.test.ts create mode 100644 packages/core/src/kernel/personal-data/stored-marks.ts create mode 100644 packages/core/src/kernel/retired-events-app.test.ts create mode 100644 packages/core/test-types/fixtures/order-app-inferred/app/domain/order/order-note-added.ts create mode 100644 packages/core/test-types/fixtures/order-app/app/domain/order/order-note-added.ts create mode 100644 packages/core/test-types/retired-events.test-d.ts diff --git a/docs/src/content/docs/adapters/index.mdx b/docs/src/content/docs/adapters/index.mdx index 9c91cea28..bc7fd77db 100644 --- a/docs/src/content/docs/adapters/index.mdx +++ b/docs/src/content/docs/adapters/index.mdx @@ -89,11 +89,12 @@ it brings them up to the version the installed Bounda expects | Table | Holds | | --- | --- | | `bounda_events` | Every event, with its stream version, a global position and the person it names, if any, which [`exportPersonalData`](/guides/personal-data/#exporting-a-persons-data) reads by | -| `bounda_event_types` | Each kind of event the store holds, by aggregate type, type and schema version, which every append records in its own transaction and a start [checks against the code](/guides/changing-events/#what-the-runtime-checks) | +| `bounda_event_types` | Each kind of event the store holds, by aggregate type, type and schema version, and whether an event of it opened a stream, which every append records in its own transaction and a start [checks against the code](/guides/changing-events/#what-the-runtime-checks) | +| `bounda_event_marks` | Each set of [personal marks](/guides/personal-data/) an event type had, by aggregate type, type and a fingerprint of the marks, in the order first recorded and with when: written once and never changed, so a type's marks outlive its module | | `bounda_checkpoints` | How far each projection, the policy runner, the process runner, the retention and the [forget ledger](/guides/personal-data/#backups)'s copy have read, where a paused rebuild stands, the time of the last ledger entry the database applied, when the last reconciliation ran and the wait of one that failed, when the [key rotation](/guides/personal-data/#rotating-the-tenants-key) was last found complete, the leases of the [background jobs](/guides/deployment/#more-than-one-instance), the counters that tell a [restore](/guides/personal-data/#restores), and, for a read model in a database of its own, the event each of its checkpoints stands at, there, and how far it reached, in the storage's | | `bounda_inbox` | Which handler already completed for which event, so a retry does not run it again | | `bounda_scheduled_commands` | Scheduled commands, process deadlines and timeouts, and delayed policy runs, each with when it was scheduled | -| `bounda_dead_letters` | Handler runs that gave up, with the error, the attempt count and the persons the work names, removed once retried or discarded longer ago than [`runtime.deadLetters.retention`](/reference/configuration/#dead-letters) | +| `bounda_dead_letters` | Handler runs that gave up, with the error, the attempt count, the persons the work names and, for a process, the instance it failed in, removed once retried or discarded longer ago than [`runtime.deadLetters.retention`](/reference/configuration/#dead-letters) | | `bounda_idempotency_keys` | What a command dispatched with an `idempotencyKey` answered, the key with it, sealed under the keys of the persons it names, or under the database's key when it names nobody, and filed under an HMAC of the key until it expires; an answer erased with a person's data leaves that HMAC alone | | `bounda_personal_keys` | One key per person, which their [personal fields](/guides/personal-data/) are encrypted with, wrapped under the [tenant's key](/guides/personal-data/#where-the-keys-live) whose version it names, and the key's fingerprint, and the wait of a rewrap that failed; `forget` deletes it | | `bounda_index_keys` | The database's key, which derives the [blind indexes](/guides/personal-data/#sealed-at-rest) of the database's read models and seals snapshots and the remembered answers that name nobody, wrapped as a person's key is, and its fingerprint | diff --git a/packages/cli/src/generate/discover.test.ts b/packages/cli/src/generate/discover.test.ts index 7d5d5e858..157aa2744 100644 --- a/packages/cli/src/generate/discover.test.ts +++ b/packages/cli/src/generate/discover.test.ts @@ -66,6 +66,7 @@ const relativePaths = (model: ProjectModel): Record => ({ event.relativePath, event.upcasts?.relativePath ?? null, ]), + retired: aggregate.retired.map((event) => [event.key, event.relativePath]), ports: aggregate.ports.map((port) => ({ key: port.key, typeName: port.typeName, @@ -135,6 +136,7 @@ describe("discoverProject on the order-app fixture", () => { null, ], ], + retired: [], ports: [], commands: [ [ @@ -159,6 +161,7 @@ describe("discoverProject on the order-app fixture", () => { "app/domain/order/order-placed.upcast.ts", ], ], + retired: [["orderNoteAdded", "app/domain/order/order-note-added.ts"]], ports: [ { key: "auditLog", @@ -465,6 +468,79 @@ describe("discoverProject and the files at the project root", () => { }); }); +describe("discoverProject and retired event types", () => { + const RETIRED = "export const retired = true;\n"; + + it("takes a module at the aggregate's root that exports only retired as a retired event, named by no type", async () => { + const root = await project([ + "app/domain/order/order-placed.ts", + ["app/domain/order/order-note-added.ts", RETIRED], + ["app/domain/order/order-lost.ts", "const retired = true;\nexport { retired };\n"], + ]); + const model = await discoverProject({ root }); + const [order] = model.aggregates; + expect(order?.events.map((event) => event.key)).toEqual(["orderPlaced"]); + expect(order?.retired.map((event) => [event.key, event.typeName, event.relativePath])).toEqual([ + ["orderLost", "OrderLost", "app/domain/order/order-lost.ts"], + ["orderNoteAdded", "OrderNoteAdded", "app/domain/order/order-note-added.ts"], + ]); + expect(model.warnings).toEqual([]); + }); + + it("rejects a retired event that exports anything else, a misnamed one, and the upcasts of one", async () => { + const root = await project([ + "app/domain/order/order-placed.ts", + ["app/domain/order/order-note-added.ts", RETIRED], + "app/domain/order/order-note-added.upcast.ts", + ["app/domain/order/order-lost.ts", `${RETIRED}export const evolve = () => ({});\n`], + ["app/domain/order/status.ts", `${RETIRED}export const active = true;\n`], + ["app/domain/order/Order_Gone.ts", RETIRED], + ]); + expect(await problemsOf(root)).toEqual([ + "app/domain/order/Order_Gone.ts: Event names must be kebab-case (lower-case letters, digits and dashes)", + 'app/domain/order/order-lost.ts: exports "retired" and "evolve" besides: a retired event exports only retired', + 'app/domain/order/status.ts: exports "retired" and "active" besides: a retired event exports only retired', + "app/domain/order/order-note-added.upcast.ts: order-note-added.ts is retired, and a retired event is read as stored; delete its upcasts", + ]); + }); + + it("rejects a policy, a projection and a process handler whose file name names a retired event, unless it exports on", async () => { + const ON_PLACED = 'export const on = "OrderPlaced";\nexport const handler = () => {};\n'; + const root = await project([ + "app/domain/order/order-placed.ts", + "app/domain/order/note-added.ts", + ["app/domain/order/order-note-added.ts", RETIRED], + "app/domain/payment/payment-failed.ts", + ["app/domain/payment/payment-captured.ts", RETIRED], + "app/domain/order/policies/remind-on-order-note-added.ts", + ["app/domain/order/policies/ring-on-order-note-added.ts", ON_PLACED], + "app/domain/order/policies/ping-on-note-added.ts", + "app/domain/order/policies/payment/chase-on-payment-captured.ts", + "app/domain/order/processes/checkout/index.ts", + "app/domain/order/processes/checkout/on-order-placed.ts", + "app/domain/order/processes/checkout/on-order-note-added.ts", + "app/domain/order/processes/checkout/payment/on-payment-captured.ts", + "app/read/orders/view.ts", + ["app/read/orders/projections/order/order-placed.ts", "export const project = () => {};\n"], + [ + "app/read/orders/projections/order/order-note-added.ts", + "export const project = () => {};\n", + ], + [ + "app/read/orders/projections/payment/payment-captured.ts", + 'export const on = "PaymentFailed";\nexport const project = () => {};\n', + ], + ]); + expect(await problemsOf(root)).toEqual([ + 'app/domain/order/processes/checkout/on-order-note-added.ts: "orderNoteAdded" is a retired event of this aggregate, which nothing reacts to; delete the handler', + 'app/domain/order/processes/checkout/payment/on-payment-captured.ts: "paymentCaptured" is a retired event of the aggregate "payment", which nothing reacts to; delete the handler', + 'app/domain/order/policies/payment/chase-on-payment-captured.ts: its name ends with "paymentCaptured", a retired event of "payment", which nothing reacts to; delete the policy or export "on"', + 'app/domain/order/policies/remind-on-order-note-added.ts: its name ends with "orderNoteAdded", a retired event of "order", which nothing reacts to; delete the policy or export "on"', + 'app/read/orders/projections/order/order-note-added.ts: "orderNoteAdded" is a retired event of "order", which nothing projects; delete the projection or export "on"', + ]); + }); +}); + describe("discoverProject convention problems", () => { it("fails when the application directory is missing", async () => { const root = await project([]); diff --git a/packages/cli/src/generate/discover.ts b/packages/cli/src/generate/discover.ts index 981192060..20e1198b4 100644 --- a/packages/cli/src/generate/discover.ts +++ b/packages/cli/src/generate/discover.ts @@ -35,6 +35,7 @@ import type { ProjectModel, QueryModel, ReadModelModel, + RetiredEventModel, } from "./model.ts"; import { compareNames, @@ -278,12 +279,19 @@ const discoverPolicies = async ( return policies.sort(byKey); }; +// What a handler `on-.ts` of the aggregate's own events reports when no event is named so. +const ownEventProblem = (eventKey: string, retiredKeys: ReadonlySet): string => + retiredKeys.has(eventKey) + ? `"${eventKey}" is a retired event of this aggregate, which nothing reacts to; delete the handler` + : `"${eventKey}" is not an event of this aggregate`; + const discoverProcess = async ( context: Context, directory: string, name: string, aggregate: string, eventKeys: ReadonlySet, + retiredKeys: ReadonlySet, ): Promise => { const index = join(directory, `${INDEX}.ts`); if (!(await exists(index))) { @@ -342,7 +350,7 @@ const discoverProcess = async ( continue; } if (!eventKeys.has(eventKey)) { - context.problems.add(path, `"${eventKey}" is not an event of this aggregate`); + context.problems.add(path, ownEventProblem(eventKey, retiredKeys)); continue; } handlers.push({ ...moduleRef(context, path), aggregate, eventKey }); @@ -367,6 +375,7 @@ const discoverProcesses = async ( directory: string, aggregate: string, eventKeys: ReadonlySet, + retiredKeys: ReadonlySet, ): Promise => { const listing = await list(directory); rejectOthers(context, directory, listing); @@ -380,7 +389,14 @@ const discoverProcesses = async ( for (const name of listing.directories) { const processDirectory = join(directory, name); if (!checkName(context, processDirectory, name, "Process")) continue; - const process = await discoverProcess(context, processDirectory, name, aggregate, eventKeys); + const process = await discoverProcess( + context, + processDirectory, + name, + aggregate, + eventKeys, + retiredKeys, + ); if (process !== null) processes.push(process); } return processes.sort(byKey); @@ -502,6 +518,9 @@ const PORT_DECLARATION = (typeName: string): RegExp => // makes one. const EVENT_EXPORTS: ReadonlySet = new Set(["payload", "begin", "evolve"]); +// What a module at the aggregate's root exports, and only that, for an event type it retires. +const RETIRED_EXPORT = "retired"; + // What makes a port's module declare a recipient. const RECIPIENT_EXPORT = "recipient"; // What a port's module says its calls return of whom with. @@ -671,6 +690,7 @@ const discoverAggregate = async ( const listing = await list(directory); rejectOthers(context, directory, listing); const events: EventModel[] = []; + const retired: RetiredEventModel[] = []; const others = new Map(); const upcasts: string[] = []; let state: ModuleRef | null = null; @@ -686,9 +706,25 @@ const discoverAggregate = async ( for (const [index, module] of rest.entries()) { const path = join(directory, `${module}.ts`); const text = texts[index] ?? ""; + const exported = runtimeExportsOf(text); + if (exported.includes(RETIRED_EXPORT)) { + const besides = exported.filter((name) => name !== RETIRED_EXPORT); + if (besides.length > 0) { + context.problems.add( + path, + `exports "${RETIRED_EXPORT}" and ${quoted(besides)} besides: a retired event exports only retired`, + ); + } else if (checkName(context, path, module, "Event")) { + retired.push({ + ...moduleRef(context, path), + key: keyOf(module), + typeName: typeNameOf(keyOf(module)), + }); + } + continue; + } if (!isEvent(context, path, text)) { // A port imports its own types for what it declares. - const exported = runtimeExportsOf(text); if ( OWN_TYPES_IMPORT(module).test(text) && !exported.includes(RECIPIENT_EXPORT) && @@ -720,6 +756,7 @@ const discoverAggregate = async ( }); } const eventNames = new Set(events.map((event) => basename(event.path, ".ts"))); + const retiredNames = new Set(retired.map((event) => basename(event.path, ".ts"))); const upcastOf = new Map(); for (const module of upcasts) { const path = join(directory, `${module}.ts`); @@ -727,6 +764,11 @@ const discoverAggregate = async ( if (!checkName(context, path, eventName, "Event")) continue; if (eventNames.has(eventName)) { upcastOf.set(keyOf(eventName), moduleRef(context, path)); + } else if (retiredNames.has(eventName)) { + context.problems.add( + path, + `${eventName}.ts is retired, and a retired event is read as stored; delete its upcasts`, + ); } else if (others.has(eventName)) { context.problems.add( path, @@ -746,6 +788,7 @@ const discoverAggregate = async ( events: events .map((event) => ({ ...event, upcasts: upcastOf.get(event.key) ?? null })) .sort(byKey), + retired: retired.sort(byKey), ports: has(INFRASTRUCTURE) ? await discoverPorts(context, AGGREGATE, directory, others, eventNames) : [], @@ -754,7 +797,13 @@ const discoverAggregate = async ( ? await discoverPolicies(context, join(directory, "policies"), name) : [], processes: has("processes") - ? await discoverProcesses(context, join(directory, "processes"), name, eventKeys) + ? await discoverProcesses( + context, + join(directory, "processes"), + name, + eventKeys, + new Set(retired.map((event) => event.key)), + ) : [], }; }; @@ -916,26 +965,66 @@ const discoverGroup = async ( }; const checkForeignHandlers = (context: Context, aggregates: readonly AggregateModel[]): void => { - const eventsOf = new Map( - aggregates.map((aggregate) => [ - aggregate.name, - new Set(aggregate.events.map((event) => event.key)), - ]), - ); + const byName = new Map(aggregates.map((aggregate) => [aggregate.name, aggregate])); for (const aggregate of aggregates) { for (const process of aggregate.processes) { for (const handler of process.handlers) { - if (eventsOf.get(handler.aggregate)?.has(handler.eventKey) !== true) { - context.problems.add( - handler.path, - `"${handler.eventKey}" is not an event of the aggregate "${handler.aggregate}"`, - ); - } + const source = byName.get(handler.aggregate); + if (source?.events.some((event) => event.key === handler.eventKey) === true) continue; + context.problems.add( + handler.path, + source?.retired.some((event) => event.key === handler.eventKey) === true + ? `"${handler.eventKey}" is a retired event of the aggregate "${handler.aggregate}", which nothing reacts to; delete the handler` + : `"${handler.eventKey}" is not an event of the aggregate "${handler.aggregate}"`, + ); } } } }; +const exportsOn = async (path: string): Promise => + runtimeExportsOf(await readFile(path, "utf8")).includes("on"); + +/** + * A policy or a projection whose file name triggers it on a retired event, which nothing reacts + * to: one that exports `on` is triggered by that instead, which boot checks. + */ +const checkRetiredTriggers = async ( + context: Context, + aggregates: readonly AggregateModel[], + readModels: readonly ReadModelModel[], +): Promise => { + const byName = new Map(aggregates.map((aggregate) => [aggregate.name, aggregate])); + for (const aggregate of aggregates) { + for (const policy of aggregate.policies) { + const source = byName.get(policy.source ?? aggregate.name); + if (source === undefined || source.retired.length === 0) continue; + const type = policyTrigger({ + key: policy.key, + events: [...source.events, ...source.retired].map((event) => event.typeName), + }); + const retired = source.retired.find((event) => event.typeName === type); + if (retired === undefined || (await exportsOn(policy.path))) continue; + context.problems.add( + policy.path, + `its name ends with "${retired.key}", a retired event of "${source.name}", which nothing reacts to; delete the policy or export "on"`, + ); + } + } + for (const readModel of readModels) { + for (const projection of readModel.projections) { + const retired = byName + .get(projection.aggregate) + ?.retired.some((event) => event.key === projection.eventKey); + if (retired !== true || (await exportsOn(projection.path))) continue; + context.problems.add( + projection.path, + `"${projection.eventKey}" is a retired event of "${projection.aggregate}", which nothing projects; delete the projection or export "on"`, + ); + } + } +}; + // A reaction's qualified name is its identity in the inbox, which records that it handled an event, // so two reactions of one aggregate sharing a key would each skip what the other handled. const checkUniqueReactions = (context: Context, aggregate: AggregateModel): void => { @@ -1173,6 +1262,7 @@ export const discoverProject: DiscoverProjectFunction = async ({ root, appDir = ); checkForeignHandlers(context, aggregates); checkUniqueNames(context, aggregates, readModels); + await checkRetiredTriggers(context, aggregates, readModels); problems.throwIfAny(); await checkProjectionEvents(context, aggregates, readModels); const audit = join(root, AUDIT_FILE); diff --git a/packages/cli/src/generate/emit/emit.test.ts b/packages/cli/src/generate/emit/emit.test.ts index c6b1cda24..fb455069e 100644 --- a/packages/cli/src/generate/emit/emit.test.ts +++ b/packages/cli/src/generate/emit/emit.test.ts @@ -62,6 +62,7 @@ const model: ProjectModel = { name: "order", directory: "/project/app/domain/order", state: null, + retired: [], events: [], ports: [], commands: [], @@ -90,6 +91,7 @@ const model: ProjectModel = { name: "shipment", directory: "/project/app/domain/shipment", state: null, + retired: [], events: [ { key: "created", @@ -108,6 +110,7 @@ const model: ProjectModel = { name: "ticket", directory: "/project/app/domain/ticket", state: null, + retired: [], events: [ { key: "created", @@ -239,6 +242,45 @@ describe("emitRegistry", () => { ); }); + it("imports a retired event like an event and lists it under retired, giving it no types", () => { + const shipment = model.aggregates[1] as ProjectModel["aggregates"][number]; + const withRetired: ProjectModel = { + ...model, + aggregates: [ + model.aggregates[0] as ProjectModel["aggregates"][number], + { + ...shipment, + retired: [ + { + key: "delayed", + typeName: "Delayed", + path: "/project/app/domain/shipment/delayed.ts", + relativePath: "app/domain/shipment/delayed.ts", + }, + ], + }, + model.aggregates[2] as ProjectModel["aggregates"][number], + ], + }; + const files = emitProject({ model: withRetired }); + const registry = files.find((file) => file.path === "/project/.bounda/registry.ts")?.content; + expect(registry).toContain('import * as delayed from "../app/domain/shipment/delayed.ts";'); + expect(registry).toContain( + [ + " shipment: {", + " events: { created: shipmentCreated },", + " retired: { delayed },", + " commands: {},", + ].join("\n"), + ); + expect(files.map((file) => file.path)).toEqual(emitProject({ model }).map((file) => file.path)); + const types = files.find((file) => file.path === "/project/.bounda/types.ts")?.content; + expect(types).not.toContain("Delayed"); + expect(emitRegistry({ model, path: "/project/.bounda/registry.ts" }).content).not.toContain( + "retired", + ); + }); + it("checks every implementation of every port against its interface, quoting file names that are not identifiers", () => { const { content } = emitRegistry({ model: withPorts, @@ -645,6 +687,7 @@ describe("emitTypes for an aggregate without modules", () => { name: "ledger", directory: "/project/app/domain/ledger", state: null, + retired: [], events: [], ports: [], commands: [], diff --git a/packages/cli/src/generate/emit/registry.ts b/packages/cli/src/generate/emit/registry.ts index eb4bd6c6a..0b989e71b 100644 --- a/packages/cli/src/generate/emit/registry.ts +++ b/packages/cli/src/generate/emit/registry.ts @@ -49,6 +49,7 @@ const collectImports = (model: ProjectModel): readonly ImportEntry[] => { add(joinKeys(event.key, "upcasts"), aggregate.name, event.upcasts.path); } } + for (const event of aggregate.retired) add(event.key, aggregate.name, event.path); addPorts(aggregate); for (const command of aggregate.commands) add(command.key, aggregate.name, command.path); for (const policy of aggregate.policies) add(policy.key, aggregate.name, policy.path); @@ -218,6 +219,13 @@ const emitUpcasts = (aggregate: AggregateModel, aliases: Aliases, indent: string ]; }; +const emitRetired = (aggregate: AggregateModel, aliases: Aliases, indent: string): string[] => + aggregate.retired.length === 0 + ? [] + : [ + `${indent}retired: ${record(aggregate.retired.map((event) => [event.key, aliases.of(event.path)]))},`, + ]; + const emitAggregate = ( aggregate: AggregateModel, aliases: Aliases, @@ -232,6 +240,7 @@ const emitAggregate = ( : [`${indent}stateFingerprint: ${JSON.stringify(fingerprint)},`]), `${indent}events: ${record(aggregate.events.map((event) => [event.key, aliases.of(event.path)]))},`, ...emitUpcasts(aggregate, aliases, indent), + ...emitRetired(aggregate, aliases, indent), ...emitPorts(aggregate, aliases, indent), ...emitRecipients(aggregate, aliases, indent), ...emitReturns(aggregate, aliases, indent), diff --git a/packages/cli/src/generate/fingerprint.test.ts b/packages/cli/src/generate/fingerprint.test.ts index 9541f1a76..f45c76b42 100644 --- a/packages/cli/src/generate/fingerprint.test.ts +++ b/packages/cli/src/generate/fingerprint.test.ts @@ -2,6 +2,7 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { afterAll, describe, expect, it } from "vitest"; +import { discoverProject } from "./discover.ts"; import { fingerprintStates, readStateSources } from "./fingerprint.ts"; import type { AggregateModel, ProjectModel } from "./model.ts"; @@ -32,6 +33,7 @@ const project = async (files: Readonly>): Promise { ).toBe(first); }); + it("changes when an event of the aggregate is retired, and not with a retired event alone", async () => { + const discovered = async (files: Readonly>): Promise => { + const root = await mkdtemp(join(tmpdir(), "bounda-fingerprint-")); + temporary.push(root); + for (const [path, content] of Object.entries(files)) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content); + } + const model = await discoverProject({ root }); + return fingerprintStates({ sources: await readStateSources(model) }).order ?? ""; + }; + const placed = { + "app/domain/order/state.ts": "export const initialState = { total: 0, note: '' };\n", + "app/domain/order/order-placed.ts": "export const evolve = () => ({ total: 1 });\n", + }; + const noted = { + ...placed, + "app/domain/order/order-noted.ts": "export const evolve = () => ({ note: 'ring' });\n", + }; + const retired = { + ...placed, + "app/domain/order/order-noted.ts": "export const retired = true;\n", + }; + expect(await discovered(retired)).not.toBe(await discovered(noted)); + expect(await discovered(retired)).toBe(await discovered(placed)); + }); + it("takes the inferred state type in, for the aggregates that have one", async () => { const sources = await readStateSources(await project(base)); const plain = fingerprintStates({ sources }); diff --git a/packages/cli/src/generate/model.ts b/packages/cli/src/generate/model.ts index c846a11b1..195be1472 100644 --- a/packages/cli/src/generate/model.ts +++ b/packages/cli/src/generate/model.ts @@ -10,6 +10,13 @@ export interface EventModel extends ModuleRef { readonly upcasts: ModuleRef | null; } +// A module at the aggregate's root that exports only `retired`: its events stay in the store, read +// as stored, but nothing folds, projects or reacts to them. +export interface RetiredEventModel extends ModuleRef { + readonly key: string; + readonly typeName: string; +} + export interface ImplementationModel extends ModuleRef { // The file name as the configuration names it: `in-memory`. readonly name: string; @@ -68,6 +75,7 @@ export interface AggregateModel { readonly directory: string; readonly state: ModuleRef | null; readonly events: readonly EventModel[]; + readonly retired: readonly RetiredEventModel[]; readonly ports: readonly PortModel[]; readonly commands: readonly CommandModel[]; readonly policies: readonly PolicyModel[]; diff --git a/packages/cloudflare/test/bounda-object.test.ts b/packages/cloudflare/test/bounda-object.test.ts index 972119148..ee5a26ce1 100644 --- a/packages/cloudflare/test/bounda-object.test.ts +++ b/packages/cloudflare/test/bounda-object.test.ts @@ -985,7 +985,7 @@ describe("a Bounda Durable Object", () => { outage.projection = false; const status = await store.status(); expect(status.schema).toEqual([ - { database: "storage", scope: "storage", version: 15, latest: 15 }, + { database: "storage", scope: "storage", version: 16, latest: 16 }, { database: "storage", scope: "checkpoints", version: 5, latest: 5 }, ]); expect(status.subscriberFailures).toContainEqual( diff --git a/packages/core/src/adapter/index.ts b/packages/core/src/adapter/index.ts index 9e7f8ea1e..d11dd5af2 100644 --- a/packages/core/src/adapter/index.ts +++ b/packages/core/src/adapter/index.ts @@ -67,16 +67,21 @@ export type { AppendArgs, AppendResult, EventStore, + EventTypeMarks, LoadArgs, LoadManyArgs, LoadResult, + MarksOfArgs, PendingEvent, ReadAllArgs, ReadByPersonArgs, ReadOneArgs, + RecordedPersonalMarks, + RecordMarksArgs, ResealedEvent, ResealedFrom, StoredEventType, + StoredEventTypeMarks, } from "./storage/event-store.ts"; export type { AppendForgetLedgerOptions, diff --git a/packages/core/src/adapter/sql/dead-letters.ts b/packages/core/src/adapter/sql/dead-letters.ts index 57bad4025..9fb8d9cad 100644 --- a/packages/core/src/adapter/sql/dead-letters.ts +++ b/packages/core/src/adapter/sql/dead-letters.ts @@ -54,3 +54,30 @@ export interface ResolvedAtOfEarlierLettersFunction { */ export const resolvedAtOfEarlierLetters: ResolvedAtOfEarlierLettersFunction = (table) => `UPDATE ${table} SET "resolved_at" = "last_failed_at" WHERE "status" <> 'failed'`; + +export interface InstancesOfEarlierLettersArgs { + /** + * Both already quoted. + */ + readonly deadLetters: string; + readonly events: string; + /** + * The engine's expression for the `letterId` in an event row's `"payload"`. + */ + readonly letterId: string; +} + +export interface InstancesOfEarlierLettersFunction { + (args: InstancesOfEarlierLettersArgs): string; +} + +/** + * For a table that has just gained `instance_id`: each process letter takes the instance its + * process recorded failing in, the stream of the `ProcessFailed` that names the letter. + */ +export const instancesOfEarlierLetters: InstancesOfEarlierLettersFunction = ({ + deadLetters, + events, + letterId, +}) => + `UPDATE ${deadLetters} SET "instance_id" = "failed"."aggregate_id" FROM (SELECT ${letterId} AS "letter_id", "aggregate_type", "aggregate_id" FROM ${events} WHERE "type" = 'ProcessFailed' AND substr("aggregate_type", 1, 8) = 'process:') AS "failed" WHERE ${deadLetters}."id" = "failed"."letter_id" AND "failed"."aggregate_type" = 'process:' || ${deadLetters}."handler" AND ${deadLetters}."kind" = 'process' AND ${deadLetters}."instance_id" IS NULL`; diff --git a/packages/core/src/adapter/sql/event-marks.test.ts b/packages/core/src/adapter/sql/event-marks.test.ts new file mode 100644 index 000000000..57204d6a4 --- /dev/null +++ b/packages/core/src/adapter/sql/event-marks.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from "vitest"; +import type { EventTypeMarks } from "../storage/event-store.ts"; +import { postgresqlDialect, sqliteDialect } from "./dialect.ts"; +import { + eventMarksTableStatement, + marksOfRow, + recordMarksStatements, + selectMarksStatement, +} from "./event-marks.ts"; +import { MAX_PARAMETERS_PER_STATEMENT } from "./event-rows.ts"; + +const MARKS = { person: "customerId", fields: ["email"], categories: { email: "contact" } }; + +const set = (type: string, fingerprint: string, aggregateType = "order"): EventTypeMarks => ({ + aggregateType, + type, + fingerprint, + marks: MARKS, +}); + +const AT = "2026-01-01T00:00:00.000Z"; + +describe("eventMarksTableStatement", () => { + it("keys the sets by aggregate type, type and fingerprint, numbered by a rowid on SQLite and a serial on PostgreSQL", () => { + const sqlite = eventMarksTableStatement({ dialect: sqliteDialect, table: '"m"' }); + expect(sqlite).toContain('"seq" INTEGER PRIMARY KEY AUTOINCREMENT'); + expect(sqlite).toContain('UNIQUE ("aggregate_type", "type", "fingerprint")'); + expect(sqlite).toContain('"marks" TEXT,'); + const postgresql = eventMarksTableStatement({ dialect: postgresqlDialect, table: '"m"' }); + expect(postgresql).toContain('"seq" BIGSERIAL NOT NULL'); + expect(postgresql).toContain('PRIMARY KEY ("aggregate_type", "type", "fingerprint")'); + expect(postgresql).toContain('"marks" jsonb,'); + }); +}); + +describe("recordMarksStatements", () => { + it("records nothing for no sets", () => { + expect( + recordMarksStatements({ dialect: sqliteDialect, table: '"m"', marks: [], at: AT }), + ).toEqual([]); + }); + + it("records each set with when it was seen, leaving one already there as it is, its marks as JSON and none as null", () => { + expect( + recordMarksStatements({ + dialect: sqliteDialect, + table: '"m"', + marks: [set("OrderPlaced", "a"), { ...set("OrderPaid", "b"), marks: null }], + at: AT, + }), + ).toEqual([ + { + sql: 'INSERT INTO "m" ("aggregate_type", "type", "fingerprint", "marks", "first_seen_at") VALUES (?, ?, ?, ?, ?), (?, ?, ?, ?, ?) ON CONFLICT ("aggregate_type", "type", "fingerprint") DO NOTHING', + params: [ + "order", + "OrderPaid", + "b", + null, + AT, + "order", + "OrderPlaced", + "a", + JSON.stringify(MARKS), + AT, + ], + }, + ]); + }); + + it("records the sets in one order every writer shares, by aggregate type, type and fingerprint in code points, the first given of two that share them", () => { + const [statement] = recordMarksStatements({ + dialect: postgresqlDialect, + table: '"m"', + marks: [ + set("a", "2"), + set("a", "10"), + set("B", "1"), + set("z", "1", "Zeta"), + { ...set("B", "1"), marks: null }, + ], + at: AT, + }); + const keys = []; + const params = statement?.params ?? []; + for (let index = 0; index < params.length; index += 5) { + keys.push([params[index], params[index + 1], params[index + 2], params[index + 3]]); + } + expect(keys.map((key) => key.slice(0, 3))).toEqual([ + ["Zeta", "z", "1"], + ["order", "B", "1"], + ["order", "a", "10"], + ["order", "a", "2"], + ]); + expect(keys[1]?.[3]).not.toBeNull(); + }); + + it("splits the sets across statements within the parameters one carries, numbering each from the first", () => { + const perStatement = Math.floor(MAX_PARAMETERS_PER_STATEMENT / 5); + const statements = recordMarksStatements({ + dialect: postgresqlDialect, + table: '"m"', + marks: Array.from({ length: perStatement + 1 }, (_, index) => + set(`T${String(index).padStart(3, "0")}`, "f"), + ), + at: AT, + }); + expect(statements.map(({ params }) => params.length)).toEqual([perStatement * 5, 5]); + expect(statements[1]?.sql).toBe( + 'INSERT INTO "m" ("aggregate_type", "type", "fingerprint", "marks", "first_seen_at") VALUES ($1, $2, $3, $4, $5) ON CONFLICT ("aggregate_type", "type", "fingerprint") DO NOTHING', + ); + }); +}); + +describe("selectMarksStatement", () => { + it("reads the sets of one type in the order they were first recorded", () => { + expect( + selectMarksStatement({ + dialect: postgresqlDialect, + table: '"m"', + of: { aggregateType: "order", type: "OrderPlaced" }, + }), + ).toEqual({ + sql: 'SELECT "aggregate_type", "type", "fingerprint", "marks", "first_seen_at" FROM "m" WHERE "aggregate_type" = $1 AND "type" = $2 ORDER BY "seq"', + params: ["order", "OrderPlaced"], + }); + }); + + it("reads the sets of every type in the order they were first recorded when no type is given", () => { + expect(selectMarksStatement({ dialect: postgresqlDialect, table: '"m"' })).toEqual({ + sql: 'SELECT "aggregate_type", "type", "fingerprint", "marks", "first_seen_at" FROM "m" ORDER BY "seq"', + params: [], + }); + }); +}); + +describe("marksOfRow", () => { + const row = { aggregate_type: "order", type: "OrderPlaced", fingerprint: "a", first_seen_at: AT }; + + it("reads the marks as SQLite's JSON text and as PostgreSQL's parsed jsonb alike", () => { + const expected = { + aggregateType: "order", + type: "OrderPlaced", + fingerprint: "a", + marks: MARKS, + firstSeenAt: AT, + }; + expect(marksOfRow({ ...row, marks: JSON.stringify(MARKS) })).toEqual(expected); + expect(marksOfRow({ ...row, marks: MARKS })).toEqual(expected); + }); + + it("reads no marks as null", () => { + expect(marksOfRow({ ...row, marks: null }).marks).toBeNull(); + }); +}); diff --git a/packages/core/src/adapter/sql/event-marks.ts b/packages/core/src/adapter/sql/event-marks.ts new file mode 100644 index 000000000..9c408ad9f --- /dev/null +++ b/packages/core/src/adapter/sql/event-marks.ts @@ -0,0 +1,171 @@ +import type { + EventTypeMarks, + MarksOfArgs, + RecordedPersonalMarks, + StoredEventTypeMarks, +} from "../storage/event-store.ts"; +import type { SqlDialect } from "./dialect.ts"; +import { type InsertStatement, MAX_PARAMETERS_PER_STATEMENT } from "./event-rows.ts"; +import { codePointOrder } from "./order.ts"; +import type { SqlFragment } from "./query-builder.ts"; + +export interface EventMarksTableStatementArgs { + readonly dialect: Pick; + /** + * Already quoted. + */ + readonly table: string; +} + +export interface EventMarksTableStatementFunction { + (args: EventMarksTableStatementArgs): string; +} + +/** + * The statement that creates the table of the marks event types had, `EventStore.marksOf` reads: + * one row per aggregate type, event type and fingerprint, numbered in the order they were first + * recorded. + */ +export const eventMarksTableStatement: EventMarksTableStatementFunction = ({ dialect, table }) => + dialect.name === "sqlite" + ? `CREATE TABLE IF NOT EXISTS ${table} ( + "aggregate_type" TEXT NOT NULL, + "type" TEXT NOT NULL, + "fingerprint" TEXT NOT NULL, + "marks" TEXT, + "seq" INTEGER PRIMARY KEY AUTOINCREMENT, + "first_seen_at" TEXT NOT NULL, + UNIQUE ("aggregate_type", "type", "fingerprint") + )` + : `CREATE TABLE IF NOT EXISTS ${table} ( + "aggregate_type" text NOT NULL, + "type" text NOT NULL, + "fingerprint" text NOT NULL, + "marks" jsonb, + "seq" BIGSERIAL NOT NULL, + "first_seen_at" text NOT NULL, + PRIMARY KEY ("aggregate_type", "type", "fingerprint") + )`; + +export interface RecordMarksStatementsArgs { + readonly dialect: Pick; + /** + * Already quoted. + */ + readonly table: string; + readonly marks: readonly EventTypeMarks[]; + readonly at: string; +} + +export interface RecordMarksStatementsFunction { + (args: RecordMarksStatementsArgs): readonly InsertStatement[]; +} + +const PARAMETERS_PER_SET = 5; + +const SETS_PER_INSERT = Math.floor(MAX_PARAMETERS_PER_STATEMENT / PARAMETERS_PER_SET); + +export interface MarkSetsInOrderFunction { + (marks: readonly EventTypeMarks[]): readonly EventTypeMarks[]; +} + +/** + * Each set once, the first given of those that share an aggregate type, type and fingerprint, in + * the order `recordMarks` records them: one every writer shares, so two that record the same new + * sets wait on each other instead of deadlocking. + */ +export const markSetsInOrder: MarkSetsInOrderFunction = (marks) => { + const sets = new Map(); + for (const set of marks) { + const key = JSON.stringify([set.aggregateType, set.type, set.fingerprint]); + if (!sets.has(key)) sets.set(key, set); + } + return [...sets.values()].sort( + (a, b) => + codePointOrder(a.aggregateType, b.aggregateType) || + codePointOrder(a.type, b.type) || + codePointOrder(a.fingerprint, b.fingerprint), + ); +}; + +/** + * The statements that record each set of `marks` its aggregate type, type and fingerprint have + * none for yet, leaving one already there as it is, run in one transaction. + */ +export const recordMarksStatements: RecordMarksStatementsFunction = ({ + dialect, + table, + marks, + at, +}) => { + const sets = markSetsInOrder(marks); + const statements: InsertStatement[] = []; + for (let start = 0; start < sets.length; start += SETS_PER_INSERT) { + const slice = sets.slice(start, start + SETS_PER_INSERT); + const rows = slice.map((_, row) => { + const first = row * PARAMETERS_PER_SET + 1; + return `(${Array.from({ length: PARAMETERS_PER_SET }, (_, index) => dialect.placeholder(first + index)).join(", ")})`; + }); + statements.push({ + sql: `INSERT INTO ${table} ("aggregate_type", "type", "fingerprint", "marks", "first_seen_at") VALUES ${rows.join(", ")} ON CONFLICT ("aggregate_type", "type", "fingerprint") DO NOTHING`, + params: slice.flatMap(({ aggregateType, type, fingerprint, marks: set }) => [ + aggregateType, + type, + fingerprint, + dialect.encode("json", set), + at, + ]), + }); + } + return statements; +}; + +export interface SelectMarksStatementArgs { + readonly dialect: Pick; + /** + * Already quoted. + */ + readonly table: string; + /** + * The type whose sets to read; every type's when left out. + */ + readonly of?: MarksOfArgs | undefined; +} + +export interface SelectMarksStatementFunction { + (args: SelectMarksStatementArgs): SqlFragment; +} + +/** + * The statement that reads every set of marks of one type, or of every type, in the order they + * were first recorded, each row one `marksOfRow` decodes. + */ +export const selectMarksStatement: SelectMarksStatementFunction = ({ dialect, table, of }) => { + const columns = `SELECT "aggregate_type", "type", "fingerprint", "marks", "first_seen_at" FROM ${table}`; + return of === undefined + ? { sql: `${columns} ORDER BY "seq"`, params: [] } + : { + sql: `${columns} WHERE "aggregate_type" = ${dialect.placeholder(1)} AND "type" = ${dialect.placeholder(2)} ORDER BY "seq"`, + params: [of.aggregateType, of.type], + }; +}; + +export interface MarksOfRowFunction { + (row: Readonly>): StoredEventTypeMarks; +} + +/** + * A set of marks as `selectMarksStatement` reads it. + */ +export const marksOfRow: MarksOfRowFunction = (row) => ({ + aggregateType: String(row.aggregate_type), + type: String(row.type), + fingerprint: String(row.fingerprint), + marks: + row.marks === null || row.marks === undefined + ? null + : ((typeof row.marks === "string" + ? JSON.parse(row.marks) + : row.marks) as RecordedPersonalMarks), + firstSeenAt: String(row.first_seen_at), +}); diff --git a/packages/core/src/adapter/sql/event-types.test.ts b/packages/core/src/adapter/sql/event-types.test.ts index 1e55b93ed..64ae7fa4d 100644 --- a/packages/core/src/adapter/sql/event-types.test.ts +++ b/packages/core/src/adapter/sql/event-types.test.ts @@ -5,43 +5,52 @@ import { MAX_PARAMETERS_PER_STATEMENT } from "./event-rows.ts"; import { eventTypeOfRow, eventTypesTableStatement, + fillOpenedEventTypesStatement, kindsOfEvents, pendingEventTypes, recordEventTypesStatements, } from "./event-types.ts"; -const ofKind = (aggregateType: string, type: string, schemaVersion: number) => ({ +const ofKind = (aggregateType: string, type: string, schemaVersion: number, opened = false) => ({ aggregateType, type, schemaVersion, + opened, }); describe("eventTypesTableStatement", () => { - it("keys the catalogue by aggregate type, type and schema version, without a rowid on SQLite", () => { + it("keys the catalogue by aggregate type, type and schema version, without a rowid on SQLite, each kind not opened until marked", () => { expect(eventTypesTableStatement({ dialect: sqliteDialect, table: '"t"' })).toBe( `CREATE TABLE IF NOT EXISTS "t" ( "aggregate_type" TEXT NOT NULL, "type" TEXT NOT NULL, "schema_version" INTEGER NOT NULL, + "opened" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("aggregate_type", "type", "schema_version") ) WITHOUT ROWID`, ); - expect(eventTypesTableStatement({ dialect: postgresqlDialect, table: '"t"' })).toMatch( + const postgresql = eventTypesTableStatement({ dialect: postgresqlDialect, table: '"t"' }); + expect(postgresql).toContain('"opened" boolean NOT NULL DEFAULT false,'); + expect(postgresql).toMatch( /PRIMARY KEY \("aggregate_type", "type", "schema_version"\)\n {2}\)$/, ); }); }); describe("kindsOfEvents", () => { - it("takes each event's aggregate type, type and the schema version its metadata names", () => { + it("takes each event's aggregate type, type and the schema version its metadata names, opened when the event is at version 1 of its stream", () => { expect( kindsOfEvents([ { ...pendingEvent({ aggregateType: "order", aggregateId: "1", version: 1, type: "A" }), metadata: { ...testMetadata, schemaVersion: 3 }, }, + { + ...pendingEvent({ aggregateType: "order", aggregateId: "1", version: 2, type: "B" }), + metadata: { ...testMetadata, schemaVersion: 3 }, + }, ]), - ).toEqual([{ aggregateType: "order", type: "A", schemaVersion: 3 }]); + ).toEqual([ofKind("order", "A", 3, true), ofKind("order", "B", 3)]); }); }); @@ -57,6 +66,13 @@ describe("pendingEventTypes", () => { ofKind("order", "b", 1), ]); }); + + it("holds a kind opened when any event that added it opened a stream", () => { + const pending = pendingEventTypes(); + pending.add([ofKind("order", "a", 1, true), ofKind("order", "b", 1)]); + pending.add([ofKind("order", "a", 1), ofKind("order", "b", 1, true)]); + expect(pending.held()).toEqual([ofKind("order", "a", 1, true), ofKind("order", "b", 1, true)]); + }); }); describe("recordEventTypesStatements", () => { @@ -66,22 +82,40 @@ describe("recordEventTypesStatements", () => { ).toEqual([]); }); - it("records each kind once, leaving one already there as it is", () => { + it("records each kind once, leaving one already there as it is, and then marks opened the kind of the event at version 1", () => { expect( recordEventTypesStatements({ dialect: postgresqlDialect, table: '"t"', kinds: [ ofKind("order", "OrderPlaced", 1), - ofKind("order", "OrderPlaced", 1), + ofKind("order", "OrderPlaced", 1, true), ofKind("order", "OrderPlaced", 2), ], }), ).toEqual([ { - sql: 'INSERT INTO "t" ("aggregate_type", "type", "schema_version") VALUES ($1, $2, $3), ($4, $5, $6) ON CONFLICT DO NOTHING', + sql: 'INSERT INTO "t" ("aggregate_type", "type", "schema_version", "opened") VALUES ($1, $2, $3, TRUE), ($4, $5, $6, FALSE) ON CONFLICT DO NOTHING', params: ["order", "OrderPlaced", 1, "order", "OrderPlaced", 2], }, + { + sql: 'UPDATE "t" SET "opened" = TRUE WHERE "aggregate_type" = $1 AND "type" = $2 AND "schema_version" = $3 AND NOT "opened"', + params: ["order", "OrderPlaced", 1], + }, + ]); + }); + + it("marks no kind opened that no event opened a stream in", () => { + const statements = recordEventTypesStatements({ + dialect: sqliteDialect, + table: '"t"', + kinds: [ofKind("order", "OrderPlaced", 1), ofKind("order", "OrderPaid", 1)], + }); + expect(statements).toEqual([ + { + sql: 'INSERT INTO "t" ("aggregate_type", "type", "schema_version", "opened") VALUES (?, ?, ?, FALSE), (?, ?, ?, FALSE) ON CONFLICT DO NOTHING', + params: ["order", "OrderPaid", 1, "order", "OrderPlaced", 1], + }, ]); }); @@ -124,16 +158,40 @@ describe("recordEventTypesStatements", () => { }); expect(statements.map(({ params }) => params.length)).toEqual([perStatement * 3, 3]); expect(statements[1]).toEqual({ - sql: 'INSERT INTO "t" ("aggregate_type", "type", "schema_version") VALUES ($1, $2, $3) ON CONFLICT DO NOTHING', + sql: 'INSERT INTO "t" ("aggregate_type", "type", "schema_version", "opened") VALUES ($1, $2, $3, FALSE) ON CONFLICT DO NOTHING', params: ["order", `T${String(perStatement).padStart(3, "0")}`, 1], }); }); }); +describe("fillOpenedEventTypesStatement", () => { + it("marks opened every kind an event at version 1 of its stream is stored in, read in the engine's expression for its schema version", () => { + expect( + fillOpenedEventTypesStatement({ table: '"t"', events: '"e"', schemaVersion: "sv" }), + ).toBe( + 'UPDATE "t" SET "opened" = TRUE WHERE NOT "opened" AND ("aggregate_type", "type", "schema_version") IN (SELECT "aggregate_type", "type", sv FROM "e" WHERE "version" = 1)', + ); + }); +}); + describe("eventTypeOfRow", () => { it("reads a row's schema version as a number, as an engine that returns it as text gives it", () => { expect( - eventTypeOfRow({ aggregate_type: "order", type: "OrderPlaced", schema_version: "2" }), - ).toEqual({ aggregateType: "order", type: "OrderPlaced", schemaVersion: 2 }); + eventTypeOfRow({ + aggregate_type: "order", + type: "OrderPlaced", + schema_version: "2", + opened: false, + }), + ).toEqual({ aggregateType: "order", type: "OrderPlaced", schemaVersion: 2, opened: false }); + }); + + it("reads opened from PostgreSQL's boolean and from SQLite's integer, as a number or a bigint", () => { + const row = { aggregate_type: "order", type: "OrderPlaced", schema_version: 1 }; + expect(eventTypeOfRow({ ...row, opened: true }).opened).toBe(true); + expect(eventTypeOfRow({ ...row, opened: 1 }).opened).toBe(true); + expect(eventTypeOfRow({ ...row, opened: 1n }).opened).toBe(true); + expect(eventTypeOfRow({ ...row, opened: 0 }).opened).toBe(false); + expect(eventTypeOfRow({ ...row, opened: 0n }).opened).toBe(false); }); }); diff --git a/packages/core/src/adapter/sql/event-types.ts b/packages/core/src/adapter/sql/event-types.ts index 3d684d271..d839ae982 100644 --- a/packages/core/src/adapter/sql/event-types.ts +++ b/packages/core/src/adapter/sql/event-types.ts @@ -15,15 +15,26 @@ export interface EventTypesTableStatementFunction { (args: EventTypesTableStatementArgs): string; } +export interface OpenedColumnFunction { + (dialect: Pick): string; +} + +/** + * The definition of the catalogue's `"opened"` column, as `CREATE TABLE` and `ADD COLUMN` take it. + */ +export const openedColumn: OpenedColumnFunction = (dialect) => + `"opened" ${dialect.name === "sqlite" ? "INTEGER NOT NULL DEFAULT 0" : "boolean NOT NULL DEFAULT false"}`; + /** * The statement that creates the catalogue of event types `EventStore.types` reads: one row per - * aggregate type, event type and schema version. + * aggregate type, event type and schema version, with whether an event of it opened a stream. */ export const eventTypesTableStatement: EventTypesTableStatementFunction = ({ dialect, table }) => `CREATE TABLE IF NOT EXISTS ${table} ( "aggregate_type" TEXT NOT NULL, "type" TEXT NOT NULL, "schema_version" INTEGER NOT NULL, + ${openedColumn(dialect)}, PRIMARY KEY ("aggregate_type", "type", "schema_version") )${dialect.name === "sqlite" ? " WITHOUT ROWID" : ""}`; @@ -56,18 +67,20 @@ export const fillEventTypesStatement: FillEventTypesStatementFunction = ({ export interface KindsOfEventsFunction { ( - events: readonly Pick[], + events: readonly Pick[], ): readonly StoredEventType[]; } /** - * The kind of each event, as the catalogue keeps it. + * The kind of each event, as the catalogue keeps it, opened when the event is at version 1 of its + * stream. */ export const kindsOfEvents: KindsOfEventsFunction = (events) => - events.map(({ aggregateType, type, metadata }) => ({ + events.map(({ aggregateType, type, metadata, version }) => ({ aggregateType, type, schemaVersion: metadata.schemaVersion, + opened: version === 1, })); // Each kind once, in one order every writer shares, so two that record the same new kinds wait on @@ -75,7 +88,8 @@ export const kindsOfEvents: KindsOfEventsFunction = (events) => const ordered = (kinds: readonly StoredEventType[]): readonly StoredEventType[] => { const unique = new Map(); for (const kind of kinds) { - unique.set(JSON.stringify([kind.aggregateType, kind.type, kind.schemaVersion]), kind); + const key = JSON.stringify([kind.aggregateType, kind.type, kind.schemaVersion]); + unique.set(key, { ...kind, opened: kind.opened || unique.get(key)?.opened === true }); } return [...unique.values()].sort( (a, b) => @@ -112,6 +126,21 @@ export const pendingEventTypes: PendingEventTypesFunction = () => { }; }; +export interface FillOpenedEventTypesFunction { + (args: FillEventTypesStatementArgs): string; +} + +/** + * The statement that marks opened every kind of the catalogue an event at version 1 of its stream + * is stored in, for the migration that adds `"opened"` over events written before it. + */ +export const fillOpenedEventTypesStatement: FillOpenedEventTypesFunction = ({ + table, + events, + schemaVersion, +}) => + `UPDATE ${table} SET "opened" = TRUE WHERE NOT "opened" AND ("aggregate_type", "type", "schema_version") IN (SELECT "aggregate_type", "type", ${schemaVersion} FROM ${events} WHERE "version" = 1)`; + export interface RecordEventTypesArgs { readonly dialect: Pick; /** @@ -132,8 +161,9 @@ const TYPES_PER_INSERT = Math.floor(MAX_PARAMETERS_PER_STATEMENT / PARAMETERS_PE /** * The statements that record `kinds` in the catalogue, each once, in the order every writer * shares, leaving a kind already there as it is, so two writers recording the same one never - * conflict: what an append or a reseal runs in its transaction, or a transaction just before it - * commits. + * conflict, and then mark opened a kind already there that an event at version 1 of its stream + * opens for the first time, an update that finds it opened writing nothing: what an append or a + * reseal runs in its transaction, or a transaction just before it commits. */ export const recordEventTypesStatements: RecordEventTypesFunction = ({ dialect, @@ -144,12 +174,15 @@ export const recordEventTypesStatements: RecordEventTypesFunction = ({ const statements: InsertStatement[] = []; for (let start = 0; start < kinds.length; start += TYPES_PER_INSERT) { const slice = kinds.slice(start, start + TYPES_PER_INSERT); - const rows = slice.map((_, row) => { + const rows = slice.map(({ opened }, row) => { const first = row * PARAMETERS_PER_TYPE + 1; - return `(${Array.from({ length: PARAMETERS_PER_TYPE }, (_, index) => dialect.placeholder(first + index)).join(", ")})`; + const keys = Array.from({ length: PARAMETERS_PER_TYPE }, (_, index) => + dialect.placeholder(first + index), + ); + return `(${keys.join(", ")}, ${opened ? "TRUE" : "FALSE"})`; }); statements.push({ - sql: `INSERT INTO ${table} ("aggregate_type", "type", "schema_version") VALUES ${rows.join(", ")} ON CONFLICT DO NOTHING`, + sql: `INSERT INTO ${table} ("aggregate_type", "type", "schema_version", "opened") VALUES ${rows.join(", ")} ON CONFLICT DO NOTHING`, params: slice.flatMap(({ aggregateType, type, schemaVersion }) => [ aggregateType, type, @@ -157,6 +190,12 @@ export const recordEventTypesStatements: RecordEventTypesFunction = ({ ]), }); } + for (const { aggregateType, type, schemaVersion } of kinds.filter(({ opened }) => opened)) { + statements.push({ + sql: `UPDATE ${table} SET "opened" = TRUE WHERE "aggregate_type" = ${dialect.placeholder(1)} AND "type" = ${dialect.placeholder(2)} AND "schema_version" = ${dialect.placeholder(3)} AND NOT "opened"`, + params: [aggregateType, type, schemaVersion], + }); + } return statements; }; @@ -168,7 +207,7 @@ export interface SelectEventTypesFunction { * The statement that reads the whole catalogue, each row one `eventTypeOfRow` decodes. */ export const selectEventTypesStatement: SelectEventTypesFunction = (table) => - `SELECT "aggregate_type", "type", "schema_version" FROM ${table}`; + `SELECT "aggregate_type", "type", "schema_version", "opened" FROM ${table}`; export interface EventTypeOfRowFunction { (row: Readonly>): StoredEventType; @@ -181,4 +220,5 @@ export const eventTypeOfRow: EventTypeOfRowFunction = (row) => ({ aggregateType: String(row.aggregate_type), type: String(row.type), schemaVersion: Number(row.schema_version), + opened: typeof row.opened === "boolean" ? row.opened : Number(row.opened) !== 0, }); diff --git a/packages/core/src/adapter/sql/index.ts b/packages/core/src/adapter/sql/index.ts index 352cbca4a..fc53dd092 100644 --- a/packages/core/src/adapter/sql/index.ts +++ b/packages/core/src/adapter/sql/index.ts @@ -17,9 +17,25 @@ export { decodeErrorText, decodeReadPersons, encodeErrorText, + instancesOfEarlierLetters, resolvedAtOfEarlierLetters, } from "./dead-letters.ts"; export { postgresqlDialect } from "./dialect.ts"; +export type { + EventMarksTableStatementArgs, + EventMarksTableStatementFunction, + MarksOfRowFunction, + RecordMarksStatementsArgs, + RecordMarksStatementsFunction, + SelectMarksStatementArgs, + SelectMarksStatementFunction, +} from "./event-marks.ts"; +export { + eventMarksTableStatement, + marksOfRow, + recordMarksStatements, + selectMarksStatement, +} from "./event-marks.ts"; export type { InsertEventsArgs, InsertEventsFunction, InsertStatement } from "./event-rows.ts"; export { EVENTS_PER_INSERT, insertEventsStatements, positionsByVersion } from "./event-rows.ts"; export type { @@ -28,7 +44,9 @@ export type { EventTypesTableStatementFunction, FillEventTypesStatementArgs, FillEventTypesStatementFunction, + FillOpenedEventTypesFunction, KindsOfEventsFunction, + OpenedColumnFunction, PendingEventTypes, PendingEventTypesFunction, RecordEventTypesArgs, @@ -39,7 +57,9 @@ export { eventTypeOfRow, eventTypesTableStatement, fillEventTypesStatement, + fillOpenedEventTypesStatement, kindsOfEvents, + openedColumn, pendingEventTypes, recordEventTypesStatements, selectEventTypesStatement, diff --git a/packages/core/src/adapter/sqlite/adapter.ts b/packages/core/src/adapter/sqlite/adapter.ts index ffbd396be..2c68cc6d9 100644 --- a/packages/core/src/adapter/sqlite/adapter.ts +++ b/packages/core/src/adapter/sqlite/adapter.ts @@ -218,6 +218,7 @@ export const createSqliteAdapter: CreateSqliteAdapterFunction = < db: database, table: tables.events, eventTypes: tables.eventTypes, + eventMarks: tables.eventMarks, personalKeys: tables.personalKeys, restrictions: tables.restrictions, }), diff --git a/packages/core/src/adapter/sqlite/dead-letter-store.ts b/packages/core/src/adapter/sqlite/dead-letter-store.ts index 4b3d98841..423230fc4 100644 --- a/packages/core/src/adapter/sqlite/dead-letter-store.ts +++ b/packages/core/src/adapter/sqlite/dead-letter-store.ts @@ -32,7 +32,7 @@ export interface CreateSqliteDeadLetterStoreFunction { } const COLUMNS = - '"id", "kind", "handler", "event_id", "event_type", "aggregate_type", "aggregate_id", "person", "error_type", "error_name", "error_code", "error_message", "error_stack", "attempts", "first_failed_at", "last_failed_at", "status", "resolved_at", "payload", "persons", "state_person", "read_persons"'; + '"id", "kind", "handler", "event_id", "event_type", "aggregate_type", "aggregate_id", "person", "error_type", "error_name", "error_code", "error_message", "error_stack", "attempts", "first_failed_at", "last_failed_at", "status", "resolved_at", "payload", "persons", "state_person", "read_persons", "instance_id"'; const personsOf = (row: Record): { persons?: KeyedPerson[] } => { const persons = JSON.parse(String(row.persons)) as KeyedPerson[]; @@ -51,6 +51,9 @@ const toLetter = (row: Record): StoredDeadLetter => ({ ...(row.state_person === null || row.state_person === undefined ? {} : { statePerson: String(row.state_person) }), + ...(row.instance_id === null || row.instance_id === undefined + ? {} + : { instanceId: String(row.instance_id) }), ...decodeReadPersons(row.read_persons), errorType: String(row.error_type) as DeadLetterErrorType, errorName: String(row.error_name), @@ -117,7 +120,7 @@ export const createSqliteDeadLetterStore: CreateSqliteDeadLetterStoreFunction = return { add: async (letter) => { await db.run( - `INSERT INTO ${table} (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'failed', NULL, ?, ?, ?, ?) ON CONFLICT ("id") DO NOTHING`, + `INSERT INTO ${table} (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'failed', NULL, ?, ?, ?, ?, ?) ON CONFLICT ("id") DO NOTHING`, [ letter.id, letter.kind, @@ -139,6 +142,7 @@ export const createSqliteDeadLetterStore: CreateSqliteDeadLetterStoreFunction = JSON.stringify(letter.persons ?? []), letter.statePerson ?? null, JSON.stringify(letter.readPersons ?? []), + letter.instanceId ?? null, ], ); return (await get(letter.id)) as StoredDeadLetter; diff --git a/packages/core/src/adapter/sqlite/event-store.ts b/packages/core/src/adapter/sqlite/event-store.ts index 5e33c41f6..e7c1db331 100644 --- a/packages/core/src/adapter/sqlite/event-store.ts +++ b/packages/core/src/adapter/sqlite/event-store.ts @@ -5,6 +5,7 @@ import type { EventStore, StoredEventType } from "../index.ts"; import { checkSqlAppend } from "../sql/append-checks.ts"; import { runInOrder, type SqlDatabase, type SqlTransaction } from "../sql/database.ts"; import { sqliteDialect } from "../sql/dialect.ts"; +import { marksOfRow, recordMarksStatements, selectMarksStatement } from "../sql/event-marks.ts"; import { insertEventsStatements, positionsByVersion } from "../sql/event-rows.ts"; import { eventTypeOfRow, @@ -22,6 +23,10 @@ export interface CreateSqliteEventStoreArgs { * write transaction at a time, so the order they record in can hold no lock against another. */ readonly eventTypes: string; + /** + * The marks event types had, which `recordMarks` writes and `marksOf` reads. + */ + readonly eventMarks: string; /** * The key and restriction tables an append checks the persons it names against. */ @@ -66,6 +71,7 @@ export const createSqliteEventStore: CreateSqliteEventStoreFunction = ({ db, table, eventTypes, + eventMarks, personalKeys, restrictions, }) => { @@ -202,6 +208,25 @@ export const createSqliteEventStore: CreateSqliteEventStoreFunction = ({ }, types: async () => (await db.all(selectEventTypesStatement(eventTypes), [])).map(eventTypeOfRow), + recordMarks: ({ marks, at }) => + db.write(async (tx) => { + for (const { sql, params } of recordMarksStatements({ + dialect: sqliteDialect, + table: eventMarks, + marks, + at, + })) { + await tx.run(sql, params); + } + }), + marksOf: async (of) => { + const { sql, params } = selectMarksStatement({ + dialect: sqliteDialect, + table: eventMarks, + of, + }); + return (await db.all(sql, params)).map(marksOfRow); + }, reseal: (events) => db.write(async (tx) => { const kinds: StoredEventType[] = []; @@ -218,7 +243,7 @@ export const createSqliteEventStore: CreateSqliteEventStoreFunction = ({ } } const rows = await tx.all( - `UPDATE ${table} SET "payload" = ?, "person" = ?, "metadata" = CASE WHEN ? IS NULL THEN "metadata" ELSE json_set("metadata", '$.schemaVersion', ?) END WHERE "position" = ? RETURNING "aggregate_type", "type"`, + `UPDATE ${table} SET "payload" = ?, "person" = ?, "metadata" = CASE WHEN ? IS NULL THEN "metadata" ELSE json_set("metadata", '$.schemaVersion', ?) END WHERE "position" = ? RETURNING "aggregate_type", "type", "version"`, [ JSON.stringify(payload), person, @@ -230,7 +255,13 @@ export const createSqliteEventStore: CreateSqliteEventStoreFunction = ({ if (rows.length === 0) left.push(position); if (schemaVersion === undefined) continue; kinds.push( - ...rows.map((row) => eventTypeOfRow({ ...row, schema_version: schemaVersion })), + ...rows.map((row) => + eventTypeOfRow({ + ...row, + schema_version: schemaVersion, + opened: Number(row.version) === 1, + }), + ), ); } await record(tx, kinds); diff --git a/packages/core/src/adapter/sqlite/migrations.ts b/packages/core/src/adapter/sqlite/migrations.ts index 194932585..20e4daae2 100644 --- a/packages/core/src/adapter/sqlite/migrations.ts +++ b/packages/core/src/adapter/sqlite/migrations.ts @@ -1,9 +1,15 @@ import { ConfigurationError } from "../../contracts/errors.ts"; import type { SchemaScopeName } from "../adapter.ts"; import type { SqlDatabase, SqlTransaction } from "../sql/database.ts"; -import { resolvedAtOfEarlierLetters } from "../sql/dead-letters.ts"; +import { instancesOfEarlierLetters, resolvedAtOfEarlierLetters } from "../sql/dead-letters.ts"; import { sqliteDialect } from "../sql/dialect.ts"; -import { eventTypesTableStatement, fillEventTypesStatement } from "../sql/event-types.ts"; +import { eventMarksTableStatement } from "../sql/event-marks.ts"; +import { + eventTypesTableStatement, + fillEventTypesStatement, + fillOpenedEventTypesStatement, + openedColumn, +} from "../sql/event-types.ts"; import { forgetLedgerAppliedAgainStatement, forgetLedgerCategoriesStatement, @@ -306,6 +312,44 @@ const catalogue = async (tx: SqlTransaction, tables: StorageTables): Promise => { + // Both read before any write, so a libSQL server sends the writes in one request. + const opened = (await columnsOf(tx, tables.eventTypes)).has("opened"); + const instances = (await columnsOf(tx, tables.deadLetters)).has("instance_id"); + if (!opened) { + await tx.run(`ALTER TABLE ${tables.eventTypes} ADD COLUMN ${openedColumn(sqliteDialect)}`, []); + } + await tx.run( + fillOpenedEventTypesStatement({ + table: tables.eventTypes, + events: tables.events, + schemaVersion: `json_extract("metadata", '$.schemaVersion')`, + }), + [], + ); + await tx.run(eventMarksTableStatement({ dialect: sqliteDialect, table: tables.eventMarks }), []); + if (!instances) { + await tx.run(`ALTER TABLE ${tables.deadLetters} ADD COLUMN "instance_id" TEXT`, []); + } + await tx.run( + instancesOfEarlierLetters({ + deadLetters: tables.deadLetters, + events: tables.events, + letterId: `json_extract("payload", '$.letterId')`, + }), + [], + ); +}; + export interface SqliteStorageScopeFunction { (tables: StorageTables): SchemaScope; } @@ -333,6 +377,7 @@ export const sqliteStorageScope: SqliteStorageScopeFunction = (tables) => ({ tables.supersededKeys, tables.eventTypes, tables.personalCategories, + tables.eventMarks, ], statements: [ ...latestStorageTablesStatements(tables), @@ -346,6 +391,7 @@ export const sqliteStorageScope: SqliteStorageScopeFunction = (tables) => ({ dialect: sqliteDialect, table: tables.personalCategories, }), + eventMarksTableStatement({ dialect: sqliteDialect, table: tables.eventMarks }), ], }, migrations: [ @@ -430,6 +476,7 @@ export const sqliteStorageScope: SqliteStorageScopeFunction = (tables) => ({ { version: 13, migrate: (tx) => keepTransfers(tx, tables) }, { version: 14, migrate: (tx) => keyDisclosuresByTransfer(tx, tables) }, { version: 15, migrate: (tx) => catalogue(tx, tables) }, + { version: 16, migrate: (tx) => keepOpeningsMarksAndInstances(tx, tables) }, ], }); diff --git a/packages/core/src/adapter/sqlite/restore-copy.test.ts b/packages/core/src/adapter/sqlite/restore-copy.test.ts index 3ceef2471..2773df7d4 100644 --- a/packages/core/src/adapter/sqlite/restore-copy.test.ts +++ b/packages/core/src/adapter/sqlite/restore-copy.test.ts @@ -9,7 +9,7 @@ import { ON_DISK_TIMEOUT_MS } from "../../kernel/test-support.ts"; import type { SqlDatabase } from "../sql/database.ts"; import { DEFAULT_TABLE_PREFIX, storageTableNameFor } from "../sql/identifiers.ts"; import { schemaMigrationsTableFor } from "../sql/migrations.ts"; -import { pendingEvent, testMetadata } from "../testing/fixtures.ts"; +import { pendingEvent, testDeadLetter, testMetadata } from "../testing/fixtures.ts"; import { createSqliteAdapter } from "./adapter.ts"; import { type NodeSqliteAdapter, @@ -288,6 +288,78 @@ describe("restoring a copy of a SQLite database in place", { timeout: ON_DISK_TI await restored.close(); }); + it("marks the kinds that opened a stream, adds the table of marks and names each process letter's instance in a copy taken before them", async () => { + const copy = fresh("copy"); + const source = open(copy); + const stores = await source.adapter.createStorage(); + await stores.eventStore.append({ + aggregateType: "order", + aggregateId: "o-1", + expectedVersion: 0, + events: [ + pendingEvent({ aggregateId: "o-1", version: 1 }), + pendingEvent({ aggregateId: "o-1", version: 2, type: "OrderShipped" }), + ], + }); + await stores.eventStore.append({ + aggregateType: "process:order.payment", + aggregateId: "i-1", + expectedVersion: 0, + events: [ + { + ...pendingEvent({ + aggregateType: "process:order.payment", + aggregateId: "i-1", + version: 1, + type: "ProcessFailed", + payload: { eventId: "e-1", errorName: "Error", letterId: "dl-1" }, + }), + metadata: { ...testMetadata, system: true }, + }, + ], + }); + const letter = { + ...testDeadLetter("dl-1"), + kind: "process" as const, + handler: "order.payment", + }; + await stores.deadLetterStore.add(letter); + await stores.close(); + // As a Bounda from before the marks left it. + const table = (name: string): string => + `"${storageTableNameFor({ prefix: DEFAULT_TABLE_PREFIX, table: name })}"`; + source.db.exec(`DROP TABLE ${table("eventMarks")}`); + source.db.exec(`ALTER TABLE ${table("eventTypes")} DROP COLUMN "opened"`); + source.db.exec(`ALTER TABLE ${table("deadLetters")} DROP COLUMN "instance_id"`); + source.db.exec( + `DELETE FROM ${schemaMigrationsTableFor(DEFAULT_TABLE_PREFIX)} WHERE "scope" = 'storage' AND "version" >= 16`, + ); + const live = open(fresh("live")); + await (await live.adapter.createStorage()).close(); + await live.adapter.restore?.({ copy }); + const restored = await live.adapter.createStorage(); + expect( + (await restored.eventStore.types()) + .map( + ({ aggregateType, type, opened }) => `${aggregateType}.${type}${opened ? " opened" : ""}`, + ) + .sort(), + ).toEqual([ + "order.OrderPlaced opened", + "order.OrderShipped", + "process:order.payment.ProcessFailed opened", + ]); + expect(await restored.deadLetterStore.get("dl-1")).toMatchObject({ instanceId: "i-1" }); + const placed = { aggregateType: "order", type: "OrderPlaced" }; + expect(await restored.eventStore.marksOf(placed)).toEqual([]); + await restored.eventStore.recordMarks({ + marks: [{ ...placed, fingerprint: "f", marks: null }], + at: "2026-01-01T00:00:00.000Z", + }); + expect(await restored.eventStore.marksOf(placed)).toHaveLength(1); + await restored.close(); + }); + it("refuses a copy a newer version migrated, a copy of another tenant's, and none at all, changing nothing", async () => { const live = await seeded(fresh("live"), 5); const before = rowsOf(live.db, "SELECT * FROM notes ORDER BY id"); diff --git a/packages/core/src/adapter/sqlite/schema.ts b/packages/core/src/adapter/sqlite/schema.ts index 7c8d5aede..64ec82a60 100644 --- a/packages/core/src/adapter/sqlite/schema.ts +++ b/packages/core/src/adapter/sqlite/schema.ts @@ -4,6 +4,7 @@ import { quoteIdentifier, storageTableNameFor } from "../sql/index.ts"; export interface StorageTables { readonly events: string; readonly eventTypes: string; + readonly eventMarks: string; readonly checkpoints: string; readonly inbox: string; readonly deadLetters: string; @@ -34,6 +35,7 @@ export interface StorageTablesForFunction { export const storageTablesFor: StorageTablesForFunction = (prefix) => ({ events: quoteIdentifier(storageTableNameFor({ prefix, table: "events" })), eventTypes: quoteIdentifier(storageTableNameFor({ prefix, table: "eventTypes" })), + eventMarks: quoteIdentifier(storageTableNameFor({ prefix, table: "eventMarks" })), checkpoints: quoteIdentifier(storageTableNameFor({ prefix, table: "checkpoints" })), inbox: quoteIdentifier(storageTableNameFor({ prefix, table: "inbox" })), deadLetters: quoteIdentifier(storageTableNameFor({ prefix, table: "deadLetters" })), @@ -206,7 +208,8 @@ const leadingTablesStatements = (tables: StorageTables): readonly string[] => [ "payload" TEXT, "persons" TEXT NOT NULL DEFAULT '[]', "state_person" TEXT, - "read_persons" TEXT NOT NULL DEFAULT '[]' + "read_persons" TEXT NOT NULL DEFAULT '[]', + "instance_id" TEXT )`, `CREATE INDEX IF NOT EXISTS ${indexName(tables.deadLetters, "listing")} ON ${tables.deadLetters} ("status", "first_failed_at", "id")`, `CREATE INDEX IF NOT EXISTS ${indexName(tables.deadLetters, "person")} ON ${tables.deadLetters} ("person")`, diff --git a/packages/core/src/adapter/sqlite/sqlite.test.ts b/packages/core/src/adapter/sqlite/sqlite.test.ts index 6d028e0cf..4791e7aa1 100644 --- a/packages/core/src/adapter/sqlite/sqlite.test.ts +++ b/packages/core/src/adapter/sqlite/sqlite.test.ts @@ -61,8 +61,14 @@ import { createSqliteAdapter } from "./index.ts"; import { createNodeSqliteAdapter } from "./node-sqlite.ts"; import { storageTablesFor } from "./schema.ts"; -const { events: table, eventTypes, personalKeys, restrictions } = storageTablesFor("bounda_"); -const eventTables = { table, eventTypes, personalKeys, restrictions }; +const { + events: table, + eventTypes, + eventMarks, + personalKeys, + restrictions, +} = storageTablesFor("bounda_"); +const eventTables = { table, eventTypes, eventMarks, personalKeys, restrictions }; const bind = (params: readonly unknown[]): SQLInputValue[] => params.map((value) => (typeof value === "boolean" ? Number(value) : value)) as SQLInputValue[]; @@ -653,6 +659,7 @@ describe("createSqliteAdapter", () => { "app_checkpoints", "app_dead_letters", "app_disclosures", + "app_event_marks", "app_event_types", "app_events", "app_forgotten_recipients", diff --git a/packages/core/src/adapter/staged-event-store.ts b/packages/core/src/adapter/staged-event-store.ts index 88a89a73d..d7bb1351e 100644 --- a/packages/core/src/adapter/staged-event-store.ts +++ b/packages/core/src/adapter/staged-event-store.ts @@ -1,9 +1,17 @@ import { ConcurrencyError } from "../contracts/errors.ts"; import { type StoredEvent, streamId } from "../contracts/event.ts"; import type { RestrictionBasis } from "../modules/personal-data.ts"; +import { markSetsInOrder } from "./sql/event-marks.ts"; import { kindsOfEvents, pendingEventTypes } from "./sql/event-types.ts"; import { holdsResealedFrom } from "./sql/resealed-from.ts"; -import type { AppendArgs, EventStore, ResealedEvent } from "./storage/event-store.ts"; +import type { + AppendArgs, + EventStore, + EventTypeMarks, + RecordMarksArgs, + ResealedEvent, + StoredEventTypeMarks, +} from "./storage/event-store.ts"; import { type KeyedPerson, keyedPersonId } from "./storage/personal-key-store.ts"; /** @@ -12,12 +20,15 @@ import { type KeyedPerson, keyedPersonId } from "./storage/personal-key-store.ts * in that view, and `readOne`, `readAll`, `readByPerson`, `firstPositions`, `loadMany` and * `lastPosition` read the base store alone, since staged events are not written yet, nor are the * events `reseal` stages. `types` adds to the base store's the kinds staged, as a transaction's - * catalogue holds the kinds it wrote. `batches` hands out what to append at commit, one batch per stream, each expecting the version the stream - * had in the base store when the view first met it, and `reseals` what to write again after. + * catalogue holds the kinds it wrote, and `marksOf` adds to the base store's sets those + * `recordMarks` staged that it holds none of, after them. `batches` hands out what to append at + * commit, one batch per stream, each expecting the version the stream had in the base store when + * the view first met it, `reseals` what to write again after, and `markings` the marks to record. */ export interface StagedEventStore extends EventStore { batches(): readonly StagedBatch[]; reseals(): readonly ResealedEvent[]; + markings(): readonly RecordMarksArgs[]; } /** @@ -43,6 +54,9 @@ export interface CreateStagedEventStoreFunction { (base: EventStore, args?: CreateStagedEventStoreArgs): StagedEventStore; } +const markSetKey = ({ aggregateType, type, fingerprint }: EventTypeMarks): string => + JSON.stringify([aggregateType, type, fingerprint]); + interface StagedStream { readonly aggregateType: string; readonly aggregateId: string; @@ -62,6 +76,7 @@ export const createStagedEventStore: CreateStagedEventStoreFunction = ( ) => { const streams = new Map(); const resealed: ResealedEvent[] = []; + const marked: RecordMarksArgs[] = []; const stagedFor = async (aggregateType: string, aggregateId: string): Promise => { const key = streamId({ aggregateType, aggregateId }); @@ -173,6 +188,26 @@ export const createStagedEventStore: CreateStagedEventStoreFunction = ( } return kinds.held(); }, + recordMarks: async (args) => { + marked.push(args); + }, + marksOf: async (of) => { + const recorded = await base.marksOf(of); + const held = new Set(recorded.map(markSetKey)); + const staged: StoredEventTypeMarks[] = []; + for (const { marks, at } of marked) { + for (const set of markSetsInOrder(marks)) { + const key = markSetKey(set); + const other = + of !== undefined && (set.aggregateType !== of.aggregateType || set.type !== of.type); + if (other || held.has(key)) continue; + held.add(key); + staged.push({ ...set, firstSeenAt: at }); + } + } + return [...recorded, ...staged]; + }, + markings: () => marked, // An event given `from` is checked against the base store as it holds it now, and checked // again as it is written at commit. reseal: async (events) => { diff --git a/packages/core/src/adapter/storage/dead-letter-store.ts b/packages/core/src/adapter/storage/dead-letter-store.ts index 53e9a4dd4..578f2a588 100644 --- a/packages/core/src/adapter/storage/dead-letter-store.ts +++ b/packages/core/src/adapter/storage/dead-letter-store.ts @@ -41,6 +41,11 @@ export interface StoredDeadLetter { * redaction reach it, and a forget leaves it, its text unreadable. */ readonly statePerson?: string; + /** + * Only on process letters: the instance the failed step ran for, so a retry or a discard reaches + * it without routing the event again, which a type the app retired since no longer is. + */ + readonly instanceId?: string; /** * Whom else the failed work read data of, besides `person` and `statePerson`, as the aggregates * the commands it dispatched loaded: the error text is sealed under their keys too, around the diff --git a/packages/core/src/adapter/storage/event-store.ts b/packages/core/src/adapter/storage/event-store.ts index f3c9a37bd..edac6f54b 100644 --- a/packages/core/src/adapter/storage/event-store.ts +++ b/packages/core/src/adapter/storage/event-store.ts @@ -117,6 +117,59 @@ export interface StoredEventType { readonly aggregateType: string; readonly type: string; readonly schemaVersion: number; + /** + * Whether an event of this kind opened a stream: an event at version 1 of its stream was + * appended in it, or a `reseal` wrote one in it. Once true, never false again. + */ + readonly opened: boolean; +} + +/** + * What an event type's payload schema marked as personal data: the fields it seals, the category + * each is sealed under, and the field that names the person, `null` when the stream's id names + * them. + */ +export interface RecordedPersonalMarks { + readonly person: string | null; + readonly fields: readonly string[]; + readonly categories: Readonly>; +} + +/** + * One set of marks an event type had, as `recordMarks` takes it. + */ +export interface EventTypeMarks { + readonly aggregateType: string; + readonly type: string; + /** + * What tells the set from the type's other sets: the runtime derives it from the marks, so + * equal marks give equal fingerprints. + */ + readonly fingerprint: string; + /** + * `null` for a type whose payload marks nothing. + */ + readonly marks: RecordedPersonalMarks | null; +} + +/** + * A set of marks as the store keeps it, with when it was first recorded. + */ +export interface StoredEventTypeMarks extends EventTypeMarks { + readonly firstSeenAt: string; +} + +export interface RecordMarksArgs { + readonly marks: readonly EventTypeMarks[]; + /** + * When the sets were seen: what each one recorded for the first time keeps as `firstSeenAt`. + */ + readonly at: string; +} + +export interface MarksOfArgs { + readonly aggregateType: string; + readonly type: string; } export interface LoadManyArgs { @@ -162,10 +215,25 @@ export interface EventStore { * The store's catalogue of event types: every kind of event it holds, each once, in no order, * and a kind no event has any more after a `reseal` took its events to another schema version. * `append` records the kinds of its events in its own transaction, so a kind is there once an - * event of it commits and never before, and `reseal` records the kind it gives an event. Read - * from the store every time, never from a copy in memory. + * event of it commits and never before, and `reseal` records the kind it gives an event; each + * sets `opened` the same way. Read from the store every time, never from a copy in memory. */ types(): Promise; + /** + * Records, in one transaction, each set of marks its aggregate type, type and fingerprint have + * no set for yet, and leaves a set already recorded as it is, whatever the new one holds: a set + * is written once, never changed or removed. Each set recorded takes the next place in the + * order `marksOf` reads, never by a clock; those of one call in the code-point order of their + * aggregate type, type and fingerprint, so two callers recording the same sets at once never + * wait on each other in a loop. A write, refused behind the tenant's fence as `append` is. + */ + recordMarks(args: RecordMarksArgs): Promise; + /** + * Every set of marks recorded for the type given, or for every type when none is given, in the + * order they were first recorded; none for a type never recorded. Read from the store every + * time. + */ + marksOf(args?: MarksOfArgs): Promise; /** * Replaces the payload and `person` of the event at each position given, and its * `metadata.schemaVersion` when given, and nothing else of it. An event given `from` is written diff --git a/packages/core/src/adapter/storage/inspection.ts b/packages/core/src/adapter/storage/inspection.ts index 56bbfe563..631f534a9 100644 --- a/packages/core/src/adapter/storage/inspection.ts +++ b/packages/core/src/adapter/storage/inspection.ts @@ -7,6 +7,7 @@ import { isHiddenField } from "./sealed-fields.ts"; export type InspectedStore = | "events" | "eventTypes" + | "eventMarks" | "checkpoints" | "inbox" | "deadLetters" @@ -41,6 +42,7 @@ export type InspectedStore = export const STORAGE_STORES: readonly Exclude[] = [ "events", "eventTypes", + "eventMarks", "checkpoints", "inbox", "deadLetters", diff --git a/packages/core/src/adapter/testing/dead-letter-store.contract.ts b/packages/core/src/adapter/testing/dead-letter-store.contract.ts index 9170a28e0..fcc929183 100644 --- a/packages/core/src/adapter/testing/dead-letter-store.contract.ts +++ b/packages/core/src/adapter/testing/dead-letter-store.contract.ts @@ -581,6 +581,34 @@ export const deadLetterStoreContract: DeadLetterStoreContractFunction = ({ creat expect(await store.listByPerson({ person: "c-2" })).toEqual([]); }); + it("keeps the instance a process letter names through every read, a status change and a reseal, and names none on a letter without one", async () => { + await store.add( + letter("process", { + kind: "process", + handler: "order.orderPayment", + person: "c-1", + instanceId: "order-1", + errorMessage: sealed("c-1", "1"), + }), + ); + await store.add(letter("policy", { person: "c-1", errorMessage: sealed("c-1", "1") })); + expect(await store.get("process")).toMatchObject({ instanceId: "order-1" }); + expect(await store.get("policy")).not.toHaveProperty("instanceId"); + expect((await store.list()).map(({ id, instanceId }) => [id, instanceId])).toEqual([ + ["policy", undefined], + ["process", "order-1"], + ]); + expect( + (await store.listByPerson({ person: "c-1" })).find(({ id }) => id === "process"), + ).toMatchObject({ instanceId: "order-1" }); + await store.reseal("process", { person: "c-1", errorMessage: sealed("c-1", "2") }); + await store.updateStatus("process", "retried", new Date("2026-01-02T00:00:00.000Z")); + expect(await store.get("process")).toMatchObject({ + status: "retried", + instanceId: "order-1", + }); + }); + it("names whom else a letter's work read: lists it for each of them, pages them, and forgets it for none", async () => { await store.add( letter("read", { diff --git a/packages/core/src/adapter/testing/documented-tables.ts b/packages/core/src/adapter/testing/documented-tables.ts index 70d9cb2bb..b0669d8fc 100644 --- a/packages/core/src/adapter/testing/documented-tables.ts +++ b/packages/core/src/adapter/testing/documented-tables.ts @@ -4,6 +4,7 @@ export const DOCUMENTED_TABLES: readonly string[] = [ "events", "event_types", + "event_marks", "checkpoints", "inbox", "scheduled_commands", diff --git a/packages/core/src/adapter/testing/earlier-rows.ts b/packages/core/src/adapter/testing/earlier-rows.ts index d03a6f922..b04d111bc 100644 --- a/packages/core/src/adapter/testing/earlier-rows.ts +++ b/packages/core/src/adapter/testing/earlier-rows.ts @@ -162,25 +162,36 @@ export const expectEarlierRowsTakenIn: ExpectEarlierRowsTakenInFunction = async }, ]); expect(events[0]?.metadata).toEqual(testMetadata); - // Recorded by the migration that creates the catalogue, from the events it finds. + // Recorded by the migrations that create the catalogue and mark the kinds that opened a stream, + // from the events they find. expect( (await storage.eventStore.types()) - .map(({ aggregateType, type, schemaVersion }) => `${aggregateType}.${type}@${schemaVersion}`) + .map( + ({ aggregateType, type, schemaVersion, opened }) => + `${aggregateType}.${type}@${schemaVersion}${opened ? " opened" : ""}`, + ) .sort(), ).toEqual([ - "bounda.PersonalDataForgotten@1", - "order.OrderPlaced@1", + "bounda.PersonalDataForgotten@1 opened", + "order.OrderPlaced@1 opened", "order.ScheduledCommandFailed@1", - "process:order.payment.ProcessFailed@1", + "process:order.payment.ProcessFailed@1 opened", ]); + // No migration knows the marks the event types had. + expect(await storage.eventStore.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual( + [], + ); + // The instance comes from the `ProcessFailed` that names the letter. expect(await storage.deadLetterStore.get("dl-process")).toMatchObject({ status: "failed", person: null, + instanceId: "i-1", errorName: "TypeError", errorMessage: "card of Ada declined", errorStack: PROCESS_STACK, }); expect(await storage.deadLetterStore.get("dl-process")).not.toHaveProperty("resolvedAt"); + expect(await storage.deadLetterStore.get("dl-bare")).not.toHaveProperty("instanceId"); expect(await storage.deadLetterStore.get("dl-bare")).toMatchObject({ errorName: "RangeError", errorMessage: "", diff --git a/packages/core/src/adapter/testing/event-store.contract.ts b/packages/core/src/adapter/testing/event-store.contract.ts index 7d19bea0f..8e20cf7e5 100644 --- a/packages/core/src/adapter/testing/event-store.contract.ts +++ b/packages/core/src/adapter/testing/event-store.contract.ts @@ -5,6 +5,7 @@ import { ForgottenSinceLoadError } from "../storage/append-checks.ts"; import type { AppendArgs, EventStore, + EventTypeMarks, PendingEvent, StoredEventType, } from "../storage/event-store.ts"; @@ -1003,10 +1004,41 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr events: [pendingEvent({ aggregateType: "customer", aggregateId: "1", version: 1 })], }); expect(await kindsIn()).toEqual([ - { aggregateType: "customer", type: "OrderPlaced", schemaVersion: 1 }, - { aggregateType: "order", type: "OrderPaid", schemaVersion: 1 }, - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1 }, - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 2 }, + { aggregateType: "customer", type: "OrderPlaced", schemaVersion: 1, opened: true }, + { aggregateType: "order", type: "OrderPaid", schemaVersion: 1, opened: false }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1, opened: true }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 2, opened: false }, + ]); + }); + + it("marks opened a kind recorded past version 1 once an event of it opens a stream, and never takes the mark back", async () => { + await store.append({ + aggregateType: "order", + aggregateId: "1", + expectedVersion: 0, + events: [ + pendingEvent({ aggregateId: "1", version: 1 }), + pendingEvent({ aggregateId: "1", version: 2, type: "OrderPaid" }), + ], + }); + await store.append({ + aggregateType: "order", + aggregateId: "2", + expectedVersion: 0, + events: [pendingEvent({ aggregateId: "2", version: 1, type: "OrderPaid" })], + }); + await store.append({ + aggregateType: "order", + aggregateId: "2", + expectedVersion: 1, + events: [ + pendingEvent({ aggregateId: "2", version: 2 }), + pendingEvent({ aggregateId: "2", version: 3, type: "OrderPaid" }), + ], + }); + expect(await kindsIn()).toEqual([ + { aggregateType: "order", type: "OrderPaid", schemaVersion: 1, opened: true }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1, opened: true }, ]); }); @@ -1039,7 +1071,37 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr }), ).rejects.toBeInstanceOf(ConcurrencyError); expect(await kindsIn()).toEqual([ - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1 }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1, opened: true }, + ]); + }); + + it("marks no kind opened for an append that fails or rolls back", async () => { + await store.append({ + aggregateType: "order", + aggregateId: "1", + expectedVersion: 0, + events: [ + pendingEvent({ aggregateId: "1", version: 1 }), + pendingEvent({ aggregateId: "1", version: 2, type: "OrderPaid" }), + ], + }); + const opening = { + aggregateType: "order", + aggregateId: "2", + events: [pendingEvent({ aggregateId: "2", version: 1, type: "OrderPaid" })], + }; + await expect(store.append({ ...opening, expectedVersion: 1 })).rejects.toBeInstanceOf( + ConcurrencyError, + ); + await expect( + storage.transact(async (transaction) => { + await transaction.eventStore.append({ ...opening, expectedVersion: 0 }); + throw new Error("undone"); + }), + ).rejects.toThrow("undone"); + expect(await kindsIn()).toEqual([ + { aggregateType: "order", type: "OrderPaid", schemaVersion: 1, opened: false }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1, opened: true }, ]); }); @@ -1065,7 +1127,7 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr }), ); expect(await kindsIn()).toEqual([ - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1 }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1, opened: true }, ]); }); @@ -1076,10 +1138,11 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr expectedVersion: 0, events: [pendingEvent({ aggregateId: "1", version: 1 })], }); + // The event resealed is at version 1 of its stream: the kind it is written in opened it too. const written = [ - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1 }, - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 3 }, - { aggregateType: "payment", type: "PaymentRequested", schemaVersion: 1 }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1, opened: true }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 3, opened: true }, + { aggregateType: "payment", type: "PaymentRequested", schemaVersion: 1, opened: true }, ]; const writing = (fail: boolean) => storage.transact(async (transaction) => { @@ -1126,8 +1189,8 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr ]); expect(await store.lastPosition()).toBe(4); expect(await kindsIn()).toEqual([ - { aggregateType: "order", type: "OrderPaid", schemaVersion: 1 }, - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1 }, + { aggregateType: "order", type: "OrderPaid", schemaVersion: 1, opened: true }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1, opened: true }, ]); }); @@ -1147,8 +1210,8 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr ); expect(appended.map(({ version }) => version)).toEqual([2, 2]); expect(await kindsIn()).toEqual([ - { aggregateType: "order", type: "OrderPaid", schemaVersion: 1 }, - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 2 }, + { aggregateType: "order", type: "OrderPaid", schemaVersion: 1, opened: false }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 2, opened: true }, ]); }); @@ -1167,10 +1230,200 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr { position: 2, payload: {}, person: null }, ]); expect(await kindsIn()).toEqual([ - { aggregateType: "order", type: "OrderPaid", schemaVersion: 1 }, - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1 }, - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 3 }, + { aggregateType: "order", type: "OrderPaid", schemaVersion: 1, opened: false }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1, opened: true }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 3, opened: true }, ]); }); + + it("marks opened the kind a reseal writes an event at version 1 of its stream in, one already recorded included, and not the kind of a later event", async () => { + await store.append({ + aggregateType: "order", + aggregateId: "1", + expectedVersion: 0, + events: [ + pendingEvent({ aggregateId: "1", version: 1 }), + inVersion(pendingEvent({ aggregateId: "1", version: 2 }), 2), + pendingEvent({ aggregateId: "1", version: 3, type: "OrderPaid" }), + ], + }); + await store.reseal([ + { position: 3, payload: {}, person: null, schemaVersion: 2 }, + { position: 1, payload: {}, person: null, schemaVersion: 2 }, + ]); + expect(await kindsIn()).toEqual([ + { aggregateType: "order", type: "OrderPaid", schemaVersion: 1, opened: false }, + { aggregateType: "order", type: "OrderPaid", schemaVersion: 2, opened: false }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1, opened: true }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 2, opened: true }, + ]); + }); + + const MARKS = { + person: "customerId", + fields: ["email", "name"], + categories: { email: "contact", name: "default" }, + }; + const OTHER_MARKS = { person: null, fields: ["note"], categories: { note: "default" } }; + const T1 = "2026-01-01T00:00:00.000Z"; + const T2 = "2026-01-02T00:00:00.000Z"; + const T3 = "2026-01-03T00:00:00.000Z"; + const marksOf = ( + type: string, + fingerprint: string, + marks: EventTypeMarks["marks"] = MARKS, + ) => ({ + aggregateType: "order", + type, + fingerprint, + marks, + }); + const fingerprintsOf = async (type: string) => + (await store.marksOf({ aggregateType: "order", type })).map(({ fingerprint }) => fingerprint); + + it("holds no marks in a new store", async () => { + expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([]); + }); + + it("records each set of marks with when it was first seen, and reads those of one type alone, in the order recorded", async () => { + await store.recordMarks({ marks: [marksOf("OrderPlaced", "b")], at: T1 }); + await store.recordMarks({ + marks: [marksOf("OrderPlaced", "a", OTHER_MARKS), marksOf("OrderPaid", "x", null)], + at: T2, + }); + await store.recordMarks({ + marks: [{ ...marksOf("OrderPlaced", "c"), aggregateType: "customer" }], + at: T3, + }); + expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1 }, + { ...marksOf("OrderPlaced", "a", OTHER_MARKS), firstSeenAt: T2 }, + ]); + expect(await store.marksOf({ aggregateType: "order", type: "OrderPaid" })).toEqual([ + { ...marksOf("OrderPaid", "x", null), firstSeenAt: T2 }, + ]); + expect(await fingerprintsOf("OrderShipped")).toEqual([]); + }); + + it("keeps a set as first recorded: its fingerprint recorded again changes nothing it holds and leaves it in its place", async () => { + await store.recordMarks({ marks: [marksOf("OrderPlaced", "a")], at: T1 }); + await store.recordMarks({ marks: [marksOf("OrderPlaced", "b", OTHER_MARKS)], at: T2 }); + await store.recordMarks({ marks: [marksOf("OrderPlaced", "a", null)], at: T3 }); + expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ + { ...marksOf("OrderPlaced", "a"), firstSeenAt: T1 }, + { ...marksOf("OrderPlaced", "b", OTHER_MARKS), firstSeenAt: T2 }, + ]); + }); + + it("orders the sets one call records by fingerprint in code points, the first given of two that share one", async () => { + await store.recordMarks({ + marks: [ + marksOf("OrderPlaced", "b"), + marksOf("OrderPlaced", "B"), + marksOf("OrderPlaced", "a"), + marksOf("OrderPlaced", "b", null), + ], + at: T1, + }); + expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ + { ...marksOf("OrderPlaced", "B"), firstSeenAt: T1 }, + { ...marksOf("OrderPlaced", "a"), firstSeenAt: T1 }, + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1 }, + ]); + }); + + it("records more sets in one call than one statement carries", async () => { + const fingerprints = Array.from( + { length: 45 }, + (_, index) => `f${String(index).padStart(2, "0")}`, + ); + await store.recordMarks({ + marks: fingerprints.map((fingerprint) => marksOf("OrderPlaced", fingerprint)), + at: T1, + }); + expect(await fingerprintsOf("OrderPlaced")).toEqual(fingerprints); + }); + + it("lets two callers record the same sets at once, given in any order, keeping each once", async () => { + const sets = ["a", "b", "c"].flatMap((fingerprint) => [ + marksOf("OrderPlaced", fingerprint), + marksOf("OrderPaid", fingerprint), + ]); + await Promise.all([ + store.recordMarks({ marks: sets, at: T1 }), + store.recordMarks({ marks: [...sets].reverse(), at: T2 }), + ]); + expect(await fingerprintsOf("OrderPlaced")).toEqual(["a", "b", "c"]); + expect(await fingerprintsOf("OrderPaid")).toEqual(["a", "b", "c"]); + }); + + it("records the marks a transaction records when it commits, and none when it rolls back", async () => { + await expect( + storage.transact(async (transaction) => { + await transaction.eventStore.recordMarks({ + marks: [marksOf("OrderPlaced", "a")], + at: T1, + }); + throw new Error("undone"); + }), + ).rejects.toThrow("undone"); + expect(await fingerprintsOf("OrderPlaced")).toEqual([]); + await storage.transact((transaction) => + transaction.eventStore.recordMarks({ marks: [marksOf("OrderPlaced", "b")], at: T2 }), + ); + expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T2 }, + ]); + }); + + it("records nothing for no sets", async () => { + await store.recordMarks({ marks: [], at: T1 }); + expect(await fingerprintsOf("OrderPlaced")).toEqual([]); + }); + + it("reads every type's sets in the order recorded when no type is given", async () => { + expect(await store.marksOf()).toEqual([]); + await store.recordMarks({ marks: [marksOf("OrderPlaced", "b")], at: T1 }); + await store.recordMarks({ + marks: [ + { ...marksOf("OrderPlaced", "c"), aggregateType: "customer" }, + marksOf("OrderPaid", "x", null), + marksOf("OrderPlaced", "b", OTHER_MARKS), + ], + at: T2, + }); + await store.recordMarks({ marks: [marksOf("OrderPlaced", "a", OTHER_MARKS)], at: T3 }); + expect(await store.marksOf()).toEqual([ + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1 }, + { ...marksOf("OrderPlaced", "c"), aggregateType: "customer", firstSeenAt: T2 }, + { ...marksOf("OrderPaid", "x", null), firstSeenAt: T2 }, + { ...marksOf("OrderPlaced", "a", OTHER_MARKS), firstSeenAt: T3 }, + ]); + }); + + it("reads in a transaction the sets it recorded, after the stored ones, before it commits", async () => { + await store.recordMarks({ marks: [marksOf("OrderPlaced", "b")], at: T1 }); + await storage.transact(async (transaction) => { + await transaction.eventStore.recordMarks({ + marks: [marksOf("OrderPlaced", "c"), marksOf("OrderPlaced", "b", null)], + at: T2, + }); + await transaction.eventStore.recordMarks({ + marks: [marksOf("OrderPlaced", "a", OTHER_MARKS), marksOf("OrderPaid", "x", null)], + at: T3, + }); + expect( + await transaction.eventStore.marksOf({ aggregateType: "order", type: "OrderPlaced" }), + ).toEqual([ + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1 }, + { ...marksOf("OrderPlaced", "c"), firstSeenAt: T2 }, + { ...marksOf("OrderPlaced", "a", OTHER_MARKS), firstSeenAt: T3 }, + ]); + expect( + (await transaction.eventStore.marksOf()).map(({ fingerprint }) => fingerprint), + ).toEqual(["b", "c", "x", "a"]); + }); + expect(await fingerprintsOf("OrderPlaced")).toEqual(["b", "c", "a"]); + }); }); }; diff --git a/packages/core/src/adapter/testing/inspection.contract.ts b/packages/core/src/adapter/testing/inspection.contract.ts index d2265b935..404f347e5 100644 --- a/packages/core/src/adapter/testing/inspection.contract.ts +++ b/packages/core/src/adapter/testing/inspection.contract.ts @@ -46,6 +46,10 @@ export const inspectionContract: InspectionContractFunction = ({ create }) => { expectedVersion: 0, events: [pendingEvent({ aggregateId: "o-1", version: 1, payload: { note: "ring twice" } })], }); + await storage.eventStore.recordMarks({ + marks: [{ aggregateType: "order", type: "OrderPlaced", fingerprint: "f-1", marks: null }], + at: now.toISOString(), + }); await storage.personalKeys.add("c-2", DEFAULT_PERSONAL_CATEGORY, { key: "a2V5Mg==", fingerprint: "ZnAy", @@ -102,6 +106,7 @@ export const inspectionContract: InspectionContractFunction = ({ create }) => { for (const [name, store] of [ ["bounda_events", "events"], ["bounda_event_types", "eventTypes"], + ["bounda_event_marks", "eventMarks"], ["bounda_checkpoints", "checkpoints"], ["bounda_inbox", "inbox"], ["bounda_scheduled_commands", "scheduledCommands"], diff --git a/packages/core/src/adapter/testing/restore.contract.ts b/packages/core/src/adapter/testing/restore.contract.ts index d68f09fce..d186b72f2 100644 --- a/packages/core/src/adapter/testing/restore.contract.ts +++ b/packages/core/src/adapter/testing/restore.contract.ts @@ -1933,6 +1933,73 @@ export const restoreContract: RestoreContractFunction = ({ create, hot }) => { RESTORE_CASE_TIMEOUT_MS, ); + it( + "restores with the copy the marks event types were seen with and the kinds that opened a stream, and records again a set seen after it", + async () => { + const target = await create(); + const clock = createFixedClock(START); + const first = await start(target.storage, target.forgetLedger, BEFORE_ROTATION, clock); + await write(first, "ana"); + const registered = { aggregateType: "customer", type: "CustomerRegistered" }; + const record = async (storage: Adapter, fingerprint: string): Promise => { + const stores = await storage.createStorage(); + try { + await stores.eventStore.recordMarks({ + marks: [{ ...registered, fingerprint, marks: null }], + at: "2026-01-01T00:00:00.000Z", + }); + } finally { + await stores.close(); + } + }; + const seen = async (storage: Adapter): Promise => { + const stores = await storage.createStorage(); + try { + return { + marks: (await stores.eventStore.marksOf(registered)).map( + ({ fingerprint }) => fingerprint, + ), + openings: (await stores.eventStore.types()) + .filter(({ opened }) => opened) + .map( + ({ aggregateType, type, schemaVersion }) => + `${aggregateType}.${type}@${schemaVersion}`, + ) + .sort(), + }; + } finally { + await stores.close(); + } + }; + const opened = openedAs(first.app.config.storage); + // The set the start recorded for the type comes first. + const { marks: started } = (await seen(opened)) as { readonly marks: readonly string[] }; + expect(started).toHaveLength(1); + await record(opened, "before"); + await target.backUp(); + const copied = await seen(opened); + expect(copied).toMatchObject({ + marks: [...started, "before"], + openings: expect.arrayContaining(["customer.CustomerRegistered@1"]), + }); + await record(opened, "after"); + expect(await seen(opened)).toMatchObject({ marks: [...started, "before", "after"] }); + await first.app.stop(); + + const restored = await start( + await target.restore(), + target.forgetLedger, + BEFORE_ROTATION, + clock, + ); + const reopened = openedAs(restored.app.config.storage); + expect(await seen(reopened)).toEqual(copied); + await record(reopened, "after"); + expect(await seen(reopened)).toMatchObject({ marks: [...started, "before", "after"] }); + }, + RESTORE_CASE_TIMEOUT_MS, + ); + it.skipIf(!hot)( "files answers under the database's key a copy from before a reseal holds, once a restore of it is found", async () => { diff --git a/packages/core/src/adapter/testing/storage-schema.contract.ts b/packages/core/src/adapter/testing/storage-schema.contract.ts index 796bbd001..e43c689e3 100644 --- a/packages/core/src/adapter/testing/storage-schema.contract.ts +++ b/packages/core/src/adapter/testing/storage-schema.contract.ts @@ -80,8 +80,8 @@ const LATEST = [ // PostgreSQL's storage takes one more: the indexes that compare text by bytes, as SQLite's does. const STORAGE_LATEST: Readonly> = { - sqlite: 15, - postgresql: 16, + sqlite: 16, + postgresql: 17, }; // The storage migration that adds the counts of forgotten persons by recipient, and the one after, @@ -103,6 +103,12 @@ const CATALOGUED: Readonly> sqlite: 15, postgresql: 16, }; +// The one that marks the kinds that opened a stream, adds the marks of event types and names the +// instance of each process letter. +const OPENINGS: Readonly> = { + sqlite: 16, + postgresql: 17, +}; const latestOf = (dialect: StorageSchemaContractArgs["dialect"]) => [ ...LATEST, @@ -572,6 +578,120 @@ export const storageSchemaContract: StorageSchemaContractFunction = ({ expect(await shapeOf(target, dialect)).toEqual(shape); }); + it("marks, at its own version, each kind of event that opened a stream, adds the table of marks, and names the instance of each process letter its process recorded failing in", async () => { + const target = await create(); + const failure = { eventId: "e-1", errorName: "Error", letterId: "dl-1" }; + const failed = { + ...pendingEvent({ + aggregateType: "process:order.payment", + aggregateId: "i-1", + version: 1, + type: "ProcessFailed", + payload: failure, + }), + metadata: { ...testMetadata, system: true }, + }; + await opened(target.adapter, async (storage) => { + await storage.checkpointStore.set("projection:x", 3); + await storage.eventStore.append({ + aggregateType: "order", + aggregateId: "o-1", + expectedVersion: 0, + events: [ + pendingEvent({ aggregateId: "o-1", version: 1 }), + { + ...pendingEvent({ aggregateId: "o-1", version: 2 }), + metadata: { ...testMetadata, schemaVersion: 2 }, + }, + pendingEvent({ aggregateId: "o-1", version: 3, type: "OrderShipped" }), + pendingEvent({ aggregateId: "o-1", version: 4, type: "OrderPaid" }), + ], + }); + await storage.eventStore.append({ + aggregateType: "order", + aggregateId: "o-2", + expectedVersion: 0, + events: [pendingEvent({ aggregateId: "o-2", version: 1, type: "OrderShipped" })], + }); + await storage.eventStore.append({ + aggregateType: "process:order.payment", + aggregateId: "i-1", + expectedVersion: 0, + events: [failed], + }); + // Names a letter of another process. + await storage.eventStore.append({ + aggregateType: "process:order.payment", + aggregateId: "i-2", + expectedVersion: 0, + events: [ + { + ...failed, + id: "failed-2", + aggregateId: "i-2", + payload: { ...failure, letterId: "dl-2" }, + }, + ], + }); + const processLetter = { + ...testDeadLetter("dl-1"), + kind: "process" as const, + handler: "order.payment", + }; + await storage.deadLetterStore.add(processLetter); + // A letter of another process, one no `ProcessFailed` names, and a policy's. + await storage.deadLetterStore.add({ + ...processLetter, + id: "dl-2", + handler: "order.refund", + }); + await storage.deadLetterStore.add({ ...processLetter, id: "dl-3" }); + await storage.deadLetterStore.add(testDeadLetter("dl-4")); + }); + const shape = await shapeOf(target, dialect); + // As the version before left the tables. + const table = (name: string) => + `"${storageTableNameFor({ prefix: target.prefix, table: name })}"`; + await target.execute(`DROP TABLE ${table("eventMarks")}`); + await target.execute(`ALTER TABLE ${table("eventTypes")} DROP COLUMN "opened"`); + await target.execute(`ALTER TABLE ${table("deadLetters")} DROP COLUMN "instance_id"`); + await target.execute( + `DELETE FROM ${schemaMigrationsTableFor(target.prefix)} WHERE "scope" = 'storage' AND "version" >= ${OPENINGS[dialect]}`, + ); + await opened(target.adapter, async (storage) => { + expect(await storage.checkpointStore.get("projection:x")).toBe(3); + expect( + (await storage.eventStore.types()) + .map( + ({ aggregateType, type, schemaVersion, opened: opening }) => + `${aggregateType}.${type}@${schemaVersion}${opening ? " opened" : ""}`, + ) + .sort(), + ).toEqual([ + "order.OrderPaid@1", + "order.OrderPlaced@1 opened", + "order.OrderPlaced@2", + "order.OrderShipped@1 opened", + "process:order.payment.ProcessFailed@1 opened", + ]); + expect(await storage.deadLetterStore.get("dl-1")).toMatchObject({ instanceId: "i-1" }); + for (const id of ["dl-2", "dl-3", "dl-4"]) { + expect(await storage.deadLetterStore.get(id), id).not.toHaveProperty("instanceId"); + } + expect( + await storage.eventStore.marksOf({ aggregateType: "order", type: "OrderPlaced" }), + ).toEqual([]); + await storage.eventStore.recordMarks({ + marks: [{ aggregateType: "order", type: "OrderPlaced", fingerprint: "f", marks: null }], + at: "2026-01-01T00:00:00.000Z", + }); + expect( + await storage.eventStore.marksOf({ aggregateType: "order", type: "OrderPlaced" }), + ).toHaveLength(1); + }); + expect(await shapeOf(target, dialect)).toEqual(shape); + }); + it("adds, at its own version, the table of the forgotten persons each recipient was listed with, keeping everything else", async () => { const target = await create(); await opened(target.adapter, (storage) => storage.checkpointStore.set("projection:x", 3)); diff --git a/packages/core/src/kernel/aggregate/build-aggregates.ts b/packages/core/src/kernel/aggregate/build-aggregates.ts index fd20548eb..5050228a8 100644 --- a/packages/core/src/kernel/aggregate/build-aggregates.ts +++ b/packages/core/src/kernel/aggregate/build-aggregates.ts @@ -7,6 +7,7 @@ import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload import { notPersonal, person, personal } from "../../modules/personal.ts"; import type { AggregateEntry, Registry } from "../../modules/registry.ts"; import { personalMarksOf } from "../personal-data/marks.ts"; +import { NO_STORED_MARKS } from "../personal-data/stored-marks.ts"; import type { ModulePorts } from "../ports/ports.ts"; import type { AggregateRuntime, @@ -108,6 +109,7 @@ const buildAggregate = ( snapshot: buildSnapshot(name, entry, config), events, eventsByType: Object.fromEntries(Object.values(events).map((event) => [event.type, event])), + retired: new Set(Object.keys(entry.retired ?? {}).map(capitalize)), eventBuilders: createEventBuilders(entry.events) as AggregateRuntime["eventBuilders"], ports, commands: buildCommands(name, entry), @@ -152,5 +154,5 @@ export const buildAggregates: BuildAggregatesFunction = ({ registry, ports, conf commandsByType[command.type] = { aggregate, command }; } } - return { byName, commandsByType }; + return { byName, commandsByType, storedMarks: NO_STORED_MARKS }; }; diff --git a/packages/core/src/kernel/aggregate/fold-state.test.ts b/packages/core/src/kernel/aggregate/fold-state.test.ts index e0db32a01..1ff94dd9c 100644 --- a/packages/core/src/kernel/aggregate/fold-state.test.ts +++ b/packages/core/src/kernel/aggregate/fold-state.test.ts @@ -2,9 +2,11 @@ import { describe, expect, it } from "vitest"; import { pendingEvent } from "../../adapter/testing/fixtures.ts"; import { resolveConfig } from "../../config/schema.ts"; import { memory } from "../../memory/index.ts"; +import type { Registry } from "../../modules/registry.ts"; import { choosePorts, orderRegistry } from "../test-support.ts"; import { buildAggregates } from "./build-aggregates.ts"; import { foldState } from "./fold-state.ts"; +import type { AggregateRuntime } from "./runtime.ts"; const ports = choosePorts( orderRegistry, @@ -18,6 +20,44 @@ const stored = (version: number, type: string, payload: unknown) => ({ position: version, }); +describe("foldState over a retired event type", () => { + const retiring = buildAggregates({ + registry: { + ...orderRegistry, + aggregates: { + order: { + ...orderRegistry.aggregates.order, + retired: { orderNoteAdded: { retired: true } }, + } as Registry["aggregates"][string], + }, + }, + ports, + }).byName.order as AggregateRuntime; + + it("skips its events wherever they stand, so they never open the aggregate", () => { + expect( + foldState({ + aggregate: retiring, + events: [ + stored(1, "OrderNoteAdded", { note: "ring" }), + stored(2, "OrderPlaced", { total: 5 }), + stored(3, "OrderNoteAdded", { status: "lost" }), + stored(4, "OrderPaid", { method: "card" }), + ], + }), + ).toEqual({ state: { status: "paid", total: 5 }, created: true, openedWithout: null }); + expect( + foldState({ aggregate: retiring, events: [stored(1, "OrderNoteAdded", { note: "ring" })] }), + ).toEqual({ state: { status: "new", total: 0 }, created: false, openedWithout: null }); + }); + + it("refuses an event no module names that its aggregate did not retire", () => { + expect(() => + foldState({ aggregate, events: [stored(1, "OrderNoteAdded", { note: "ring" })] }), + ).toThrow('Aggregate "order" has no event module for stored event "OrderNoteAdded"'); + }); +}); + describe("foldState from a snapshot", () => { it("folds the events after it over its state, keeping how the aggregate opened", () => { const from = { diff --git a/packages/core/src/kernel/aggregate/fold-state.ts b/packages/core/src/kernel/aggregate/fold-state.ts index 0b8bdbc00..1fe22875b 100644 --- a/packages/core/src/kernel/aggregate/fold-state.ts +++ b/packages/core/src/kernel/aggregate/fold-state.ts @@ -51,17 +51,17 @@ const merged = ( /** * System events, such as a failed scheduled command, carry no state and are skipped, so they never - * open the aggregate. Any other event the aggregate does not define is a configuration error: its - * module no longer exists. An event without the function its place calls for (`begin` to open, - * `evolve` after) gets the one it has, since the pipeline only stores such a stream if it predates - * the event's `begin`. + * open the aggregate; so are the events of a type the aggregate retired. Any other event the + * aggregate does not define is a configuration error: its module no longer exists. An event + * without the function its place calls for (`begin` to open, `evolve` after) gets the one it has, + * since the pipeline only stores such a stream if it predates the event's `begin`. */ export const foldState: FoldStateFunction = ({ aggregate, events, from }) => { let state = from?.state ?? aggregate.initialState; let created = from?.created ?? false; let openedWithout: string | null = from?.openedWithout ?? null; for (const event of events) { - if (event.metadata.system) continue; + if (event.metadata.system || aggregate.retired.has(event.type)) continue; const runtime = runtimeOf(aggregate, event); const fold = (!created && runtime.begin !== null) || runtime.evolve === null diff --git a/packages/core/src/kernel/aggregate/runtime.ts b/packages/core/src/kernel/aggregate/runtime.ts index 61b52b0f0..f30130617 100644 --- a/packages/core/src/kernel/aggregate/runtime.ts +++ b/packages/core/src/kernel/aggregate/runtime.ts @@ -2,6 +2,7 @@ import type { z } from "zod"; import type { NewEvent, StoredEvent } from "../../contracts/event.ts"; import type { Upcast } from "../../modules/upcast.ts"; import type { PersonalMarks } from "../personal-data/marks.ts"; +import type { StoredMarks } from "../personal-data/stored-marks.ts"; export interface EventRuntime { readonly key: string; @@ -65,6 +66,10 @@ export interface AggregateRuntime { */ readonly events: Readonly>; readonly eventsByType: Readonly>; + /** + * The event types the aggregate retired, `OrderNoteAdded`: read as stored, never folded. + */ + readonly retired: ReadonlySet; readonly eventBuilders: Readonly NewEvent>>; readonly commands: Readonly>; } @@ -77,4 +82,9 @@ export interface AggregatesRuntime { readonly commandsByType: Readonly< Record >; + /** + * The marks the store recorded for event types, read at the start: none until the store is open. + * What a retired type marks, which no schema says any more. + */ + readonly storedMarks: StoredMarks; } diff --git a/packages/core/src/kernel/aggregate/stored-types.test.ts b/packages/core/src/kernel/aggregate/stored-types.test.ts index ff66094c8..a28b5a0bb 100644 --- a/packages/core/src/kernel/aggregate/stored-types.test.ts +++ b/packages/core/src/kernel/aggregate/stored-types.test.ts @@ -10,14 +10,22 @@ import { TENANT_FORGOTTEN_EVENT, } from "../../modules/bounda-events.ts"; import type { Registry } from "../../modules/registry.ts"; +import { NO_STORED_MARKS, storedMarksOf } from "../personal-data/stored-marks.ts"; import { PROCESS_EVENTS, processAggregateType } from "../process/lifecycle.ts"; import { RUNTIME_EVENT_TYPES } from "../system-events.ts"; import { choosePorts, defaultPorts, orderAggregateEntry } from "../test-support.ts"; import { buildAggregates } from "./build-aggregates.ts"; -import { checkStoredTypes, knownVersionOf, storedTypesOf } from "./stored-types.ts"; +import { + checkRetiredMarks, + checkStoredTypes, + knownVersionOf, + storedTypesOf, +} from "./stored-types.ts"; const registry = { - aggregates: { order: orderAggregateEntry() }, + aggregates: { + order: { ...orderAggregateEntry(), retired: { orderNoteAdded: { retired: true } } }, + }, readModels: {}, } satisfies Registry; @@ -28,10 +36,30 @@ const aggregates = buildAggregates({ const PROCESS = processAggregateType("order.payment"); -const kind = (aggregateType: string, type: string, schemaVersion = 1) => ({ +const kind = (aggregateType: string, type: string, schemaVersion = 1, opened = false) => ({ aggregateType, type, schemaVersion, + opened, +}); + +// The order aggregate once a stream may also open with `OrderImported`, whose `begin` sets its +// state up, and `OrderOpened` is retired. +const beginning = buildAggregates({ + registry: { + aggregates: { + order: { + ...orderAggregateEntry(), + events: { + ...orderAggregateEntry().events, + orderImported: { begin: () => ({ status: "placed", total: 0 }) }, + }, + retired: { orderOpened: { retired: true }, orderNoteAdded: { retired: true } }, + }, + }, + readModels: {}, + } as unknown as Registry, + ports: choosePorts(registry, resolveConfig({ storage: memory(), ports: defaultPorts(registry) })), }); describe("knownVersionOf", () => { @@ -82,22 +110,45 @@ describe("knownVersionOf", () => { }); describe("checkStoredTypes", () => { - it("accepts every kind this code reads at or below its version, and a kind it has no module for", () => { + it("accepts every kind this code reads at or below its version, a retired type in any version, and any type of an aggregate it does not know", () => { const stored = checkStoredTypes({ aggregates, types: [ kind("order", "OrderPlaced"), - kind("order", "OrderLost", 7), + kind("order", "OrderNoteAdded", 1), + kind("order", "OrderNoteAdded", 9), kind("invoice", "InvoiceSent", 3), kind(BOUNDA_AGGREGATE, TENANT_FORGOTTEN_EVENT), kind("order", SCHEDULED_COMMAND_FAILED_EVENT), kind(PROCESS, PROCESS_EVENTS.abandoned), + kind(processAggregateType("order.gone"), PROCESS_EVENTS.started), ], }); - expect(stored.has(kind("order", "OrderLost", 7))).toBe(true); - expect(stored.has(kind("order", "OrderLost", 6))).toBe(false); - expect(stored.has(kind("order", "OrderLos", 7))).toBe(false); - expect(stored.has(kind("orde", "OrderLost", 7))).toBe(false); + expect(stored.has(kind("invoice", "InvoiceSent", 3))).toBe(true); + expect(stored.has(kind("invoice", "InvoiceSent", 2))).toBe(false); + expect(stored.has(kind("invoice", "InvoiceSen", 3))).toBe(false); + expect(stored.has(kind("invoic", "InvoiceSent", 3))).toBe(false); + }); + + it("refuses the start for a type of an aggregate of the app that no module names, naming each and how to retire it", () => { + const check = () => + checkStoredTypes({ + aggregates, + types: [ + kind("order", "OrderLost", 7), + kind("order", "OrderPlaced"), + kind("order", "OrderCancelledByCustomer"), + kind("order", "OrderLost", 1), + ], + }); + expect(check).toThrow(ConfigurationError); + expect(check).toThrow( + [ + "The store holds events this code cannot read:", + '- order.OrderCancelledByCustomer: no module of the aggregate "order" names it. Retire it: add order-cancelled-by-customer.ts to the aggregate, exporting only `export const retired = true`', + '- order.OrderLost: no module of the aggregate "order" names it. Retire it: add order-lost.ts to the aggregate, exporting only `export const retired = true`', + ].join("\n"), + ); }); it("refuses the start, naming in code-point order every kind newer code wrote, each version past the one this code reads in order", () => { @@ -130,6 +181,37 @@ describe("checkStoredTypes", () => { ); }); + it("refuses retiring a type that opened streams of an aggregate whose state begin sets up, naming it and keeping its module as the way out", () => { + const check = () => + checkStoredTypes({ + aggregates: beginning, + types: [ + kind("order", "OrderOpened", 1, false), + kind("order", "OrderOpened", 2, true), + kind("order", "OrderNoteAdded", 1, false), + ], + }); + expect(check).toThrow(ConfigurationError); + expect(check).toThrow( + [ + "The store holds events this code cannot read:", + '- order.OrderOpened is retired, but it opened streams of "order", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep its module instead of retiring it', + ].join("\n"), + ); + }); + + it("accepts retiring a type that opened streams of an aggregate without begin, or that opened none of one with it", () => { + expect(() => + checkStoredTypes({ aggregates, types: [kind("order", "OrderNoteAdded", 1, true)] }), + ).not.toThrow(); + expect(() => + checkStoredTypes({ + aggregates: beginning, + types: [kind("order", "OrderOpened", 1, false), kind("order", "OrderImported", 1, true)], + }), + ).not.toThrow(); + }); + it("accepts an empty catalogue", () => { expect(checkStoredTypes({ aggregates, types: [] }).has(kind("order", "OrderPlaced"))).toBe( false, @@ -137,6 +219,73 @@ describe("checkStoredTypes", () => { }); }); +describe("checkRetiredMarks", () => { + const marks = (aggregateType: string, type: string, fields: readonly string[] | null) => ({ + aggregateType, + type, + fingerprint: JSON.stringify(fields), + firstSeenAt: "2026-01-01T00:00:00.000Z", + marks: + fields === null + ? null + : { + person: null, + fields, + categories: Object.fromEntries(fields.map((field) => [field, "default"])), + }, + }); + + it("refuses a retired type the store holds events of with no marks recorded, naming each and the way out", () => { + const check = () => + checkRetiredMarks({ + aggregates: { + ...beginning, + storedMarks: storedMarksOf([marks("order", "OrderPlaced", [])]), + }, + types: [ + kind("order", "OrderOpened", 1), + kind("order", "OrderOpened", 2), + kind("order", "OrderNoteAdded", 1), + kind("order", "OrderPlaced", 1), + ], + }); + expect(check).toThrow(ConfigurationError); + expect(check).toThrow( + [ + "The store holds events of retired types this code cannot seal:", + "- order.OrderNoteAdded is retired, but no start recorded what it marks personal: deploy once with its module, on a tenant that is not frozen, then retire it", + "- order.OrderOpened is retired, but no start recorded what it marks personal: deploy once with its module, on a tenant that is not frozen, then retire it", + ].join("\n"), + ); + }); + + it("accepts a retired type with a set recorded, one that marks nothing too, a current type with none, and a retired type the store holds no event of", () => { + expect(() => + checkRetiredMarks({ + aggregates: { + ...beginning, + storedMarks: storedMarksOf([ + marks("order", "OrderOpened", null), + marks("order", "OrderNoteAdded", ["note"]), + ]), + }, + types: [ + kind("order", "OrderOpened", 1), + kind("order", "OrderNoteAdded", 1), + kind("order", "OrderPlaced", 1), + kind("invoice", "InvoiceSent", 1), + ], + }), + ).not.toThrow(); + expect(() => + checkRetiredMarks({ + aggregates: { ...beginning, storedMarks: NO_STORED_MARKS }, + types: [kind("order", "OrderPlaced", 1)], + }), + ).not.toThrow(); + }); +}); + describe("storedTypesOf", () => { it("tells a kind apart by aggregate type, type and schema version together", () => { const stored = storedTypesOf([kind("a", "b", 1), kind("ab", "", 2)]); diff --git a/packages/core/src/kernel/aggregate/stored-types.ts b/packages/core/src/kernel/aggregate/stored-types.ts index ef2874cfa..9daba06fb 100644 --- a/packages/core/src/kernel/aggregate/stored-types.ts +++ b/packages/core/src/kernel/aggregate/stored-types.ts @@ -6,6 +6,7 @@ import { RUNTIME_SCHEMA_VERSION, SCHEDULED_COMMAND_FAILED_EVENT, } from "../../modules/bounda-events.ts"; +import { toKebabCase } from "../../modules/naming.ts"; import { PROCESS_EVENTS, processOfStream } from "../process/lifecycle.ts"; import { RUNTIME_EVENT_TYPES } from "../system-events.ts"; import type { AggregatesRuntime } from "./runtime.ts"; @@ -47,10 +48,14 @@ export const knownVersionOf: KnownVersionFunction = ({ aggregates, aggregateType * The kinds of event the store's catalogue held when the app started. */ export interface StoredTypes { - has(kind: StoredEventType): boolean; + has(kind: Pick): boolean; } -const keyOf = ({ aggregateType, type, schemaVersion }: StoredEventType): string => +const keyOf = ({ + aggregateType, + type, + schemaVersion, +}: Pick): string => JSON.stringify([aggregateType, type, schemaVersion]); export interface StoredTypesOfFunction { @@ -62,6 +67,31 @@ export const storedTypesOf: StoredTypesOfFunction = (types) => { return { has: (kind) => keys.has(keyOf(kind)) }; }; +interface StoredKind { + readonly aggregateType: string; + readonly type: string; + readonly versions: number[]; + opened: boolean; +} + +// Each aggregate type and type once, in code-point order, with the schema versions held of it in +// order and whether any of them opened a stream. +const kindsOf = (types: readonly StoredEventType[]): readonly StoredKind[] => { + const kinds = new Map(); + for (const { aggregateType, type, schemaVersion, opened } of types) { + const key = JSON.stringify([aggregateType, type]); + const kind = kinds.get(key) ?? { aggregateType, type, versions: [], opened: false }; + kind.versions.push(schemaVersion); + kind.opened ||= opened; + kinds.set(key, kind); + } + return [...kinds.values()] + .map((kind) => ({ ...kind, versions: [...kind.versions].sort((a, b) => a - b) })) + .sort( + (a, b) => codePointOrder(a.aggregateType, b.aggregateType) || codePointOrder(a.type, b.type), + ); +}; + export interface CheckStoredTypesArgs { readonly types: readonly StoredEventType[]; readonly aggregates: AggregatesRuntime; @@ -73,17 +103,27 @@ export interface CheckStoredTypesFunction { const problemOf = ( aggregates: AggregatesRuntime, - aggregateType: string, - type: string, - versions: readonly number[], + { aggregateType, type, versions, opened }: StoredKind, ): string | null => { - const known = knownVersionOf({ aggregates, aggregateType, type }); + const aggregate = aggregates.byName[aggregateType]; const qualified = `${aggregateType}.${type}`; + // A retired type is read as stored in whatever version wrote it, but a fold skips it: one that + // opened a stream leaves the state without what `begin` put there. + if (aggregate?.retired.has(type) === true) { + return opened && aggregate.opensWithBegin + ? `${qualified} is retired, but it opened streams of "${aggregateType}", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep its module instead of retiring it` + : null; + } + const known = knownVersionOf({ aggregates, aggregateType, type }); const runtime = aggregateType === BOUNDA_AGGREGATE || processOfStream(aggregateType) !== null; if (known === null) { - return runtime - ? `${qualified} is no event of this Bounda's runtime: a newer Bounda wrote it. Upgrade @bounda-dev/core to it` - : null; + if (runtime) { + return `${qualified} is no event of this Bounda's runtime: a newer Bounda wrote it. Upgrade @bounda-dev/core to it`; + } + const file = toKebabCase(type.charAt(0).toLowerCase() + type.slice(1)); + return aggregate === undefined + ? null + : `${qualified}: no module of the aggregate "${aggregateType}" names it. Retire it: add ${file}.ts to the aggregate, exporting only \`export const retired = true\``; } const ahead = versions.filter((version) => version > known); if (ahead.length === 0) return null; @@ -94,30 +134,16 @@ const problemOf = ( * Checks every kind of event the store's catalogue holds against this code, so one that newer * code wrote refuses the start, with a `ConfigurationError` naming each, rather than the first * command or subscriber that reads it: a schema version past the one this code reads, and a type - * of the runtime's own aggregate, or of a process's lifecycle, this core does not know. A kind - * whose module this code lacks is left alone. Resolves to the kinds it checked, which tell an - * event read later that no start met from one this one did. + * of the runtime's own aggregate, or of a process's lifecycle, this core does not know. A type of + * an aggregate of the app that no module names, neither an event nor a retired one, refuses it + * too, since everything that reads would skip its events, and so does a retired type that opened + * a stream of an aggregate whose state `begin` sets up; one of an aggregate this code does not + * know is left alone. Resolves to the kinds it checked, which tell an event read later that no + * start met from one this one did. */ export const checkStoredTypes: CheckStoredTypesFunction = ({ types, aggregates }) => { - const versions = new Map(); - for (const { aggregateType, type, schemaVersion } of types) { - const key = JSON.stringify([aggregateType, type]); - const kind = versions.get(key) ?? { aggregateType, type, versions: [] }; - kind.versions.push(schemaVersion); - versions.set(key, kind); - } - const problems = [...versions.values()] - .sort( - (a, b) => codePointOrder(a.aggregateType, b.aggregateType) || codePointOrder(a.type, b.type), - ) - .map(({ aggregateType, type, versions: held }) => - problemOf( - aggregates, - aggregateType, - type, - [...held].sort((a, b) => a - b), - ), - ) + const problems = kindsOf(types) + .map((kind) => problemOf(aggregates, kind)) .filter((problem) => problem !== null); if (problems.length > 0) { throw new ConfigurationError( @@ -126,3 +152,39 @@ export const checkStoredTypes: CheckStoredTypesFunction = ({ types, aggregates } } return storedTypesOf(types); }; + +export interface CheckRetiredMarksArgs { + readonly types: readonly StoredEventType[]; + /** + * With the marks the store recorded. + */ + readonly aggregates: AggregatesRuntime; +} + +export interface CheckRetiredMarksFunction { + (args: CheckRetiredMarksArgs): void; +} + +/** + * Refuses, with a `ConfigurationError` naming each, a retired type the store holds events of but + * no marks for: no start recorded what it marked, so its values written in the clear could never + * be sealed. A start records the marks of every type it has a module for, unless the tenant is + * frozen, until it thaws. + */ +export const checkRetiredMarks: CheckRetiredMarksFunction = ({ types, aggregates }) => { + const problems = kindsOf(types) + .filter( + ({ aggregateType, type }) => + aggregates.byName[aggregateType]?.retired.has(type) === true && + aggregates.storedMarks.of(aggregateType, type).length === 0, + ) + .map( + ({ aggregateType, type }) => + `${aggregateType}.${type} is retired, but no start recorded what it marks personal: deploy once with its module, on a tenant that is not frozen, then retire it`, + ); + if (problems.length > 0) { + throw new ConfigurationError( + `The store holds events of retired types this code cannot seal:\n${problems.map((problem) => `- ${problem}`).join("\n")}`, + ); + } +}; diff --git a/packages/core/src/kernel/aggregate/upcasting.test.ts b/packages/core/src/kernel/aggregate/upcasting.test.ts index 87c816c48..55b296d63 100644 --- a/packages/core/src/kernel/aggregate/upcasting.test.ts +++ b/packages/core/src/kernel/aggregate/upcasting.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import type { EventStore, PendingEvent } from "../../adapter/storage/event-store.ts"; import { resolveConfig } from "../../config/schema.ts"; import { ConfigurationError, SchemaAheadError } from "../../contracts/errors.ts"; +import type { StoredEvent } from "../../contracts/event.ts"; import { silentLogger } from "../../contracts/logger.ts"; import { memory } from "../../memory/index.ts"; import { @@ -63,6 +64,7 @@ const registry = { }, }, upcasts: { orderPlaced: { upcasts: placedUpcasts } }, + retired: { orderNoteAdded: { retired: true } }, commands: { ...order.commands, placeOrder: { @@ -294,13 +296,61 @@ describe("withUpcasting", () => { ]); }); + it("reads a retired type as stored in whatever schema version wrote it, though the start never saw it, as withReadGuard does", async () => { + const { raw, start } = await opened(); + await raw.append({ + aggregateType: "order", + aggregateId: "o-9", + expectedVersion: 0, + events: [ + stored({ id: "ahead", aggregateId: "o-9", type: "OrderNoteAdded", person: "c-1" }), + stored({ + id: "later", + aggregateId: "o-9", + version: 2, + type: "OrderNoteAdded", + schemaVersion: 7, + person: "c-1", + payload: { note: "ring" }, + }), + ], + }); + const shape = (event: StoredEvent | null) => [ + event?.id, + event?.metadata.schemaVersion, + event?.payload, + ]; + const both = [ + ["ahead", 1, { total: 10 }], + ["later", 7, { note: "ring" }], + ]; + for (const guard of [withUpcasting, withReadGuard]) { + const store = guard({ eventStore: raw, aggregates, stored: start }); + const stream = { aggregateType: "order", aggregateId: "o-9" }; + expect((await store.load(stream)).events.map(shape)).toEqual(both); + expect(shape(await store.readOne({ ...stream, eventId: "later" }))).toEqual(both[1]); + expect((await store.readAll({ afterPosition: 0, limit: 10 })).map(shape)).toEqual(both); + expect( + (await store.readByPerson({ person: "c-1", afterPosition: 0, limit: 10 })).map(shape), + ).toEqual(both); + expect( + [...(await store.loadMany({ aggregateType: "order", aggregateIds: ["o-9"] })).values()] + .flat() + .map(shape), + ).toEqual(both); + expect((await store.readReadable({ afterPosition: 0, limit: 10 })).events.map(shape)).toEqual( + both, + ); + } + }); + it("rejects with a configuration error an event this code cannot read whose kind no Bounda writer recorded, though one near it did", async () => { const { raw, start } = await opened(); // Kinds that each differ from the event's in one part alone. const near = [ - { aggregateType: "customer", type: "OrderPlaced", schemaVersion: 4 }, - { aggregateType: "order", type: "OrderShipped", schemaVersion: 4 }, - { aggregateType: "order", type: "OrderPlaced", schemaVersion: 3 }, + { aggregateType: "customer", type: "OrderPlaced", schemaVersion: 4, opened: false }, + { aggregateType: "order", type: "OrderShipped", schemaVersion: 4, opened: false }, + { aggregateType: "order", type: "OrderPlaced", schemaVersion: 3, opened: false }, ]; const foreign: EventStore = { ...raw, types: async () => near }; const store = withUpcasting({ eventStore: foreign, aggregates, stored: start }); diff --git a/packages/core/src/kernel/aggregate/upcasting.ts b/packages/core/src/kernel/aggregate/upcasting.ts index 4228ad797..d9951353d 100644 --- a/packages/core/src/kernel/aggregate/upcasting.ts +++ b/packages/core/src/kernel/aggregate/upcasting.ts @@ -81,6 +81,8 @@ interface GuardArgs extends WithUpcastingArgs { const guarded = ({ eventStore, aggregates, stored, current }: GuardArgs): GuardedEventStore => { const reading = (event: StoredEvent): Reading => { const { aggregateType, type, metadata } = event; + // No module reads a retired type, so it is read as stored, whatever version wrote it. + if (aggregates.byName[aggregateType]?.retired.has(type) === true) return { event }; const known = knownVersionOf({ aggregates, aggregateType, type }); const from = metadata.schemaVersion; // A kind the catalogue held at the start that no module reads any more is read as stored. @@ -158,6 +160,8 @@ const guarded = ({ eventStore, aggregates, stored, current }: GuardArgs): Guarde }, lastPosition: () => eventStore.lastPosition(), types: () => eventStore.types(), + recordMarks: (args) => eventStore.recordMarks(args), + marksOf: (args) => eventStore.marksOf(args), reseal: (events) => eventStore.reseal(events), readReadable: async (args) => { const events: StoredEvent[] = []; @@ -178,7 +182,7 @@ const guarded = ({ eventStore, aggregates, stored, current }: GuardArgs): Guarde * current payloads. An event newer code wrote after the app started, a schema version past the one * this code reads or a kind it has no module for, rejects every read that meets it with * `SchemaAheadError`, or `ConfigurationError` when no Bounda writer recorded its kind; a kind the - * catalogue held at the start is read as stored. Writes pass through untouched, since the pipeline + * catalogue held at the start, and a retired type in any version, is read as stored. Writes pass through untouched, since the pipeline * stamps them with the current version. */ export const withUpcasting: WithUpcastingFunction = (args) => guarded({ ...args, current: true }); diff --git a/packages/core/src/kernel/app.ts b/packages/core/src/kernel/app.ts index 908d8a9be..8f743f5cb 100644 --- a/packages/core/src/kernel/app.ts +++ b/packages/core/src/kernel/app.ts @@ -57,7 +57,7 @@ import { validateRegistry } from "../modules/validate.ts"; import type { AppEnv, AppRegistry, EnvSection } from "../register/index.ts"; import { buildAggregates } from "./aggregate/build-aggregates.ts"; import { createAggregateLoader } from "./aggregate/load-aggregate.ts"; -import { checkStoredTypes } from "./aggregate/stored-types.ts"; +import { checkRetiredMarks, checkStoredTypes } from "./aggregate/stored-types.ts"; import { withReadGuard } from "./aggregate/upcasting.ts"; import { createCommandsFacade } from "./command/facade.ts"; import { createCommandPipeline } from "./command/pipeline.ts"; @@ -139,7 +139,11 @@ import { keySourcesOf, openKeyHierarchy } from "./personal-data/key-hierarchy.ts import { buildKeyWrapper } from "./personal-data/key-wrapper.ts"; import { type Landing, landingLedger } from "./personal-data/landing.ts"; import { expiringLedger } from "./personal-data/ledger-expiry.ts"; -import { declaresPersonalData, withForgetLedgerInForce } from "./personal-data/ledger-in-force.ts"; +import { + declaresPersonalData, + RECORDED_PERSONAL_DATA, + withForgetLedgerInForce, +} from "./personal-data/ledger-in-force.ts"; import { createLedgerOutbox } from "./personal-data/ledger-outbox.ts"; import { pruneAsApplied } from "./personal-data/ledger-prune.ts"; import { clearLedgersLeft, reachLedgersLeft } from "./personal-data/ledgers-left.ts"; @@ -165,6 +169,7 @@ import { retains, } from "./personal-data/retention.ts"; import { createKeyRotation } from "./personal-data/rotation.ts"; +import { currentMarkSets, withStoredMarks } from "./personal-data/stored-marks.ts"; import { NO_TENANT_EXPORT_RECORDS, type TenantExportCounts, @@ -1050,25 +1055,47 @@ export const assembleApp: AssembleAppFunction = async ({ }); const keyedConfig = files.config; const resolved = files.store === null ? unkeyed : resolveConfig(keyedConfig); - const aggregates = buildAggregates({ registry, ports: ports.byAggregate, config: resolved }); - checkReadModelPersons({ registry, aggregates }); + const registered = buildAggregates({ registry, ports: ports.byAggregate, config: resolved }); + checkReadModelPersons({ registry, aggregates: registered }); checkClassification(registry); - const processDefinitions = buildProcesses({ registry, aggregates, config: resolved }); + const processDefinitions = buildProcesses({ + registry, + aggregates: registered, + config: resolved, + }); + if (!isAdapter(resolved.storage)) { + throw new ConfigurationError( + `storage "${resolved.storage.name}" is a definition without factories. Import the adapter package's factory.`, + ); + } + const fallback = testForgetLedger ?? resolved.storage.ephemeralForgetLedger; + const declared = declaresPersonalData({ + marks: + marksPersonalData({ aggregates: registered, processes: processDefinitions }) || + readModelsMarkPersonalData(registry), + forgets: readModelsProjectForgetting(registry), + module: registry.personalData, + }); + // Refused before the storage opens when the registry declares personal data. + withForgetLedgerInForce({ config: resolved, declared, fallback }); + const adapted = await resolved.storage.createStorage(); + opened.unshift(() => adapted.close()); + // Before anything reads an event: a start refuses what newer code wrote, and every read after + // tells what it wrote since from what no module reads any more. + const storedTypes = await adapted.eventStore.types(); + const stored = checkStoredTypes({ types: storedTypes, aggregates: registered }); + // What every start recorded the event types to mark, which a retired type, or a field no longer + // marked, still holds sealed: read before what needs keys and a ledger is decided. + const aggregates = withStoredMarks(registered, await adapted.eventStore.marksOf()); + // And before anything forgets: a category recorded since is one only newer code declares. + const recordedCategories = await adapted.personalKeys.recordedCategories(); const marksPersonal = marksPersonalFields({ aggregates, processes: processDefinitions }) || readModelsMarkPersonal(registry); const config = withForgetLedgerInForce({ config: resolved, - declared: declaresPersonalData({ - marks: - marksPersonalData({ aggregates, processes: processDefinitions }) || - readModelsMarkPersonalData(registry), - forgets: readModelsProjectForgetting(registry), - module: registry.personalData, - }), - fallback: - testForgetLedger ?? - (isAdapter(resolved.storage) ? resolved.storage.ephemeralForgetLedger : undefined), + declared: declared ?? (aggregates.storedMarks.personalData ? RECORDED_PERSONAL_DATA : null), + fallback, }); if (!isAdapter(config.storage)) { throw new ConfigurationError( @@ -1084,13 +1111,6 @@ export const assembleApp: AssembleAppFunction = async ({ watching, [config.storage, ...Object.values(config.readModels)].filter(isAdapter), ); - const adapted = await config.storage.createStorage(); - opened.unshift(() => adapted.close()); - // Before anything reads an event: a start refuses what newer code wrote, and every read after - // tells what it wrote since from what no module reads any more. - const stored = checkStoredTypes({ types: await adapted.eventStore.types(), aggregates }); - // And before anything forgets: a category recorded since is one only newer code declares. - const recordedCategories = await adapted.personalKeys.recordedCategories(); const ledgerConfig = config.runtime.personalData.forgetLedger; const keepForMs = ledgerConfig?.keepForMs ?? null; let forgetLedger: { @@ -1301,7 +1321,8 @@ export const assembleApp: AssembleAppFunction = async ({ await freezeKeeper.keep(); // A tenant frozen when the app starts: what the start writes waits for the freeze to lift, and // the background work with it. - const frozenAtStart = (await adapted.fence.read()).state === "frozen"; + const fenceAtStart = (await adapted.fence.read()).state; + const frozenAtStart = fenceAtStart === "frozen"; const fences = createFenceWatch({ storage: adapted, clock, logger, frozen: frozenAtStart }); fenceRefused = fences.refused; const deferred: (() => Promise)[] = []; @@ -1324,6 +1345,17 @@ export const assembleApp: AssembleAppFunction = async ({ deferred.shift(); } }; + // What every type of this code marks, so a type retired later is sealed as it was marked; a + // forgotten tenant's start writes nothing, nor does it seal its events again. + if (fenceAtStart !== "forgotten" && !tenantForgotten()) { + checkRetiredMarks({ types: storedTypes, aggregates }); + await unlessFrozen(() => + adapted.eventStore.recordMarks({ + marks: currentMarkSets(aggregates), + at: clock.now().toISOString(), + }), + ); + } const keyed = hierarchy?.wrapping ?? keylessWrapping(); const wrapping = watching === undefined ? keyed : witnessedWrapping(keyed, watching); // Opened at once, never inside a transaction: none of a forgotten tenant, whose key is gone. @@ -2301,6 +2333,7 @@ export const assembleApp: AssembleAppFunction = async ({ executor: policyExecutor, eventStore: storage.eventStore, config, + logger, }), restrictedRetries: createRestrictedRetries({ storage, retries, clock, logger }), retention, diff --git a/packages/core/src/kernel/dead-letters/retry.ts b/packages/core/src/kernel/dead-letters/retry.ts index a1e775433..106f2c9d4 100644 --- a/packages/core/src/kernel/dead-letters/retry.ts +++ b/packages/core/src/kernel/dead-letters/retry.ts @@ -260,6 +260,7 @@ export const createDeadLetterRetry: CreateDeadLetterRetryFunction = ({ return !(await processes.retry({ process: letter.handler, event: await eventOf(letter), + instanceId: letter.instanceId, retryId, letter: letter.id, actor, diff --git a/packages/core/src/kernel/dispatch/subscriber-failures-app.test.ts b/packages/core/src/kernel/dispatch/subscriber-failures-app.test.ts index 25a3fbd55..3adf9fade 100644 --- a/packages/core/src/kernel/dispatch/subscriber-failures-app.test.ts +++ b/packages/core/src/kernel/dispatch/subscriber-failures-app.test.ts @@ -446,7 +446,7 @@ describe("the status of the app", () => { const { adapter } = createNodeSqliteAdapter(); const { app } = await start(adapter); expect((await app.status()).schema).toEqual([ - { database: "storage", scope: "storage", version: 15, latest: 15 }, + { database: "storage", scope: "storage", version: 16, latest: 16 }, { database: "storage", scope: "checkpoints", version: 5, latest: 5 }, ]); const inMemory = await start(memory()); @@ -502,7 +502,7 @@ describe("the status of the app", () => { await app.runUntilIdle(); const status = await app.status(); expect(status.schema).toEqual([ - { database: "storage", scope: "storage", version: 15, latest: 15 }, + { database: "storage", scope: "storage", version: 16, latest: 16 }, { database: "storage", scope: "checkpoints", version: 5, latest: 5 }, { database: "readModels.customers", scope: "checkpoints", version: 5, latest: 5 }, { database: "forgetLedger", scope: "forget-ledger", version: 15, latest: 15 }, diff --git a/packages/core/src/kernel/migrate.test.ts b/packages/core/src/kernel/migrate.test.ts index 0b5bc9342..bf2f0258c 100644 --- a/packages/core/src/kernel/migrate.test.ts +++ b/packages/core/src/kernel/migrate.test.ts @@ -29,7 +29,7 @@ describe("migrateTables", { timeout: ON_DISK_TIMEOUT_MS }, () => { }, }; expect(await migrateTables({ config })).toEqual([ - { database: "storage", scope: "storage", version: 15, latest: 15 }, + { database: "storage", scope: "storage", version: 16, latest: 16 }, { database: "storage", scope: "checkpoints", version: 5, latest: 5 }, { database: "readModels.customers", scope: "checkpoints", version: 5, latest: 5 }, { database: "forgetLedger", scope: "forget-ledger", version: 15, latest: 15 }, diff --git a/packages/core/src/kernel/personal-data/backfill-walk.test.ts b/packages/core/src/kernel/personal-data/backfill-walk.test.ts index 894c64f6d..12ebb7f52 100644 --- a/packages/core/src/kernel/personal-data/backfill-walk.test.ts +++ b/packages/core/src/kernel/personal-data/backfill-walk.test.ts @@ -21,6 +21,7 @@ import { } from "./backfill.ts"; import { seal } from "./crypto.ts"; import { HOLD_MS } from "./hold.ts"; +import { NO_STORED_MARKS } from "./stored-marks.ts"; const START = new Date("2026-06-01T00:00:00.000Z"); @@ -29,6 +30,7 @@ const aggregates = { customer: { name: "customer", snapshot: null, + retired: new Set(), eventsByType: { CustomerRegistered: { personal: { person: null, fields: ["email"], categories: {} } }, }, @@ -36,6 +38,7 @@ const aggregates = { order: { name: "order", snapshot: null, + retired: new Set(), eventsByType: { OrderPlaced: { personal: { person: "customerId", fields: ["address"], categories: {} } }, }, @@ -44,6 +47,7 @@ const aggregates = { contact: { name: "contact", snapshot: null, + retired: new Set(), eventsByType: { ContactAdded: { personal: { person: null, fields: ["email"], categories: {} }, @@ -58,6 +62,7 @@ const aggregates = { command: { personal: { person: "customerId", fields: ["address"], categories: {} } }, }, }, + storedMarks: NO_STORED_MARKS, } as unknown as AggregatesRuntime; const processes = { byName: {} } as unknown as Pick; diff --git a/packages/core/src/kernel/personal-data/event-store.test.ts b/packages/core/src/kernel/personal-data/event-store.test.ts index 8dbaeb853..09ccc0536 100644 --- a/packages/core/src/kernel/personal-data/event-store.test.ts +++ b/packages/core/src/kernel/personal-data/event-store.test.ts @@ -24,6 +24,7 @@ import type { ProcessesRuntime } from "../process/build-processes.ts"; import { keysOver, newStoredKey, removeKeys } from "../test-support.ts"; import { createDisposableKey, isSealed, seal } from "./crypto.ts"; import { + envelopesIn, hidingRetained, openedUnder, redactedIn, @@ -31,6 +32,7 @@ import { withoutRetained, withPersonalData, } from "./event-store.ts"; +import { personOfEvent } from "./persons.ts"; const registry: Registry = { aggregates: { @@ -615,6 +617,133 @@ describe("withPersonalData", () => { expect(redactedIn(withoutRetained(direct as StoredEvent))).toEqual(["name"]); }); + it("tells whom and under which category each field of an event it hands out was sealed, through an upcast and with what a forgetting kept hidden", async () => { + const storage = await memory().createStorage(); + const upcast = { + aggregates: { + customer: { + ...registry.aggregates.customer, + upcasts: { + customerBilled: { + upcasts: [(payload: object) => ({ ...payload, email: "none" })], + }, + }, + }, + }, + readModels: {}, + } as Registry; + const aggregates = buildAggregates({ registry: upcast, ports: {} }); + const sealing = withPersonalData({ + eventStore: storage.eventStore, + aggregates, + processes: { byName: {} }, + keys: keysOver(storage.personalKeys), + }); + const store = withUpcasting({ eventStore: sealing, aggregates, stored: storedTypesOf([]) }); + await sealing.append({ + aggregateType: "customer", + aggregateId: "c-1", + expectedVersion: 0, + events: [ + pendingEvent({ + aggregateType: "customer", + aggregateId: "c-1", + version: 1, + type: "CustomerBilled", + payload: { name: "Ana", iban: "ES00" }, + }), + pendingEvent({ + aggregateType: "customer", + aggregateId: "c-1", + version: 2, + type: "CustomerRenamed", + payload: { name: "Ana" }, + }), + ], + }); + const sealed = { + name: { person: "c-1", category: "profile" }, + iban: { person: "c-1", category: "invoices" }, + }; + + const [billed, renamed] = await store.readAll({ afterPosition: 0, limit: 10 }); + expect(billed?.payload).toEqual({ name: "Ana", iban: "ES00", email: "none" }); + expect(envelopesIn(billed as StoredEvent)).toEqual(sealed); + expect(envelopesIn(renamed as StoredEvent)).toEqual({}); + expect(envelopesIn({ ...(billed as StoredEvent) })).toEqual({}); + const [opened] = await sealing.readByPerson({ person: "c-1", afterPosition: 0, limit: 1 }); + expect(envelopesIn(opened as StoredEvent)).toEqual(sealed); + + const invoices = await storage.personalKeys.get("c-1", "invoices"); + await storage.personalKeys.retain("c-1", invoices?.fingerprint ?? "", { + since: "2026-02-01T00:00:00.000Z", + lastActiveAt: "2026-01-01T00:00:00.000Z", + }); + const [kept] = await store.readAll({ afterPosition: 0, limit: 1 }); + expect(envelopesIn(withoutRetained(kept as StoredEvent))).toEqual(sealed); + const [direct] = await sealing.readAll({ afterPosition: 0, limit: 1 }); + expect(envelopesIn(withoutRetained(direct as StoredEvent))).toEqual(sealed); + // Forgotten, the fields read null, and their envelopes still say whose they were. + await removeKeys(storage.personalKeys, "c-1"); + const [forgotten] = await sealing.readAll({ afterPosition: 0, limit: 1 }); + expect(forgotten?.payload).toEqual({ name: null, iban: null }); + expect(envelopesIn(forgotten as StoredEvent)).toEqual(sealed); + }); + + it("names the person a retired type's fields were sealed for, as it hands the event out, and nobody once they are forgotten", async () => { + const storage = await memory().createStorage(); + const writing = withPersonalData({ + eventStore: storage.eventStore, + aggregates: buildAggregates({ registry, ports: {} }), + processes: { byName: {} }, + keys: keysOver(storage.personalKeys), + }); + const { customerBilled: _, ...events } = registry.aggregates.customer?.events ?? {}; + const retired = buildAggregates({ + registry: { + ...registry, + aggregates: { + ...registry.aggregates, + customer: { + ...registry.aggregates.customer, + events, + retired: { customerBilled: { retired: true } }, + }, + }, + } as Registry, + ports: {}, + }); + const reading = withPersonalData({ + eventStore: storage.eventStore, + aggregates: retired, + processes: { byName: {} }, + keys: keysOver(storage.personalKeys), + }); + await writing.append({ + aggregateType: "customer", + aggregateId: "c-1", + expectedVersion: 0, + events: [ + pendingEvent({ + aggregateType: "customer", + aggregateId: "c-1", + version: 1, + type: "CustomerBilled", + payload: { name: "Ana", iban: "ES00" }, + }), + ], + }); + + const [billed] = await reading.readAll({ afterPosition: 0, limit: 1 }); + expect(billed?.payload).toEqual({ name: "Ana", iban: "ES00" }); + expect(personOfEvent({ aggregates: retired, event: billed as StoredEvent })).toBe("c-1"); + await removeKeys(storage.personalKeys, "c-1"); + const [forgotten] = await reading.readAll({ afterPosition: 0, limit: 1 }); + expect(personOfEvent({ aggregates: retired, event: forgotten as StoredEvent })).toBeNull(); + const [stored] = await storage.eventStore.readAll({ afterPosition: 0, limit: 1 }); + expect(personOfEvent({ aggregates: retired, event: stored as StoredEvent })).toBe("c-1"); + }); + it("hides what a forgetting kept in a process's state as in an event's payload", async () => { const storage = await memory().createStorage(); const sealing = withPersonalData({ diff --git a/packages/core/src/kernel/personal-data/event-store.ts b/packages/core/src/kernel/personal-data/event-store.ts index c71187efa..4ed5d1d0f 100644 --- a/packages/core/src/kernel/personal-data/event-store.ts +++ b/packages/core/src/kernel/personal-data/event-store.ts @@ -8,6 +8,7 @@ import type { ProcessesRuntime } from "../process/build-processes.ts"; import { processOfStream } from "../process/lifecycle.ts"; import { isRecord } from "../shared/merge-fields.ts"; import { + categoryOf, heldFingerprint, holdsSealed, isSealed, @@ -81,6 +82,31 @@ export interface RedactedInFunction { */ export const redactedIn: RedactedInFunction = (event) => sealedForGood.get(event) ?? []; +/** + * A field an event held sealed, as its envelope names it: whose key opens it, and the category of + * that key. + */ +export interface EnvelopedField { + readonly person: string; + readonly category: string; +} + +export type Envelopes = Readonly>; + +// The fields each event handed out held sealed, by the event. +const envelopes = new WeakMap(); + +export interface EnvelopesInFunction { + (event: StoredEvent): Envelopes; +} + +/** + * The fields `event` held sealed in the store, by name, as their envelopes say: what a type no + * schema marks any more, as a retired one, holds personal. None for an event this store did not + * hand out. + */ +export const envelopesIn: EnvelopesInFunction = (event) => envelopes.get(event) ?? {}; + // Each event handed out with a field opened under a key a forgetting kept, by the event: the same // event with those fields `null`, as work that names no basis for them reads it. const hiddenRetained = new WeakMap(); @@ -116,8 +142,10 @@ export interface CarryOpeningFunction { export const carryOpening: CarryOpeningFunction = (from, to, hidden) => { openings.set(to, openedUnder(from)); sealedForGood.set(to, redactedIn(from)); + envelopes.set(to, envelopesIn(from)); if (hidden !== undefined) { sealedForGood.set(hidden, redactedIn(from)); + envelopes.set(hidden, envelopesIn(from)); openings.set( hidden, openedUnder(from).filter(({ retained }) => retained !== true), @@ -241,19 +269,22 @@ export const withPersonalData: WithPersonalDataFunction = ({ }; // `read` gets each person whose fields opened, with the key that opened them; `kept`, the - // fields opened under a key a forgetting kept; `redacted`, those a redaction sealed for good. + // fields opened under a key a forgetting kept; `redacted`, those a redaction sealed for good; + // `sealed`, every field that held an envelope. const openFields = async ( fields: Readonly>, key: OpeningKey, read: Map, kept: string[], redacted: string[], + sealed: Record, ): Promise> => { const unsealed: Record = { ...fields }; for (const field in fields) { const value = fields[field]; if (!isSealed(value)) continue; const { person, key: sealedUnder, redacted: gone } = (value as SealedValue).$personal; + sealed[field] = { person, category: categoryOf(value as SealedValue) }; if (gone === true) redacted.push(field); const personal = await key(person, sealedUnder); unsealed[field] = await unseal({ key: personal, sealed: value as SealedValue }); @@ -286,12 +317,14 @@ export const withPersonalData: WithPersonalDataFunction = ({ const read = new Map(); const kept: string[] = []; const redacted: string[] = []; + const sealed: Record = {}; const fields = await openFields( where === "state" ? (lifecycleStateOf(payload) ?? {}) : payload, key, read, kept, redacted, + sealed, ); const placed = (open: Record): Record => where === "state" ? { ...payload, state: open } : open; @@ -299,12 +332,14 @@ export const withPersonalData: WithPersonalDataFunction = ({ const result = { ...event, payload: placed(fields) }; openings.set(result, [...read.values()]); sealedForGood.set(result, redacted); + envelopes.set(result, sealed); if (kept.length > 0) { const hidden = { ...event, payload: placed({ ...fields, ...Object.fromEntries(kept.map((field) => [field, null])) }), }; sealedForGood.set(hidden, redacted); + envelopes.set(hidden, sealed); openings.set( hidden, [...read.values()].filter(({ retained }) => retained !== true), @@ -440,6 +475,8 @@ export const withPersonalData: WithPersonalDataFunction = ({ }, lastPosition: () => eventStore.lastPosition(), types: () => eventStore.types(), + recordMarks: (args) => eventStore.recordMarks(args), + marksOf: (args) => eventStore.marksOf(args), // Written as given: whoever reseals an event has sealed its payload already. reseal: (events) => eventStore.reseal(events), }; diff --git a/packages/core/src/kernel/personal-data/export-stream.ts b/packages/core/src/kernel/personal-data/export-stream.ts index eaf912fe0..a4b065717 100644 --- a/packages/core/src/kernel/personal-data/export-stream.ts +++ b/packages/core/src/kernel/personal-data/export-stream.ts @@ -30,7 +30,7 @@ import { openAnswer } from "./answers.ts"; import type { PersonalCategories } from "./categories.ts"; import { openCommandPayload, sealedKeys } from "./commands.ts"; import { type OpenTextFunction, openTextWith, textPersons } from "./errors.ts"; -import { openedUnder, redactedIn } from "./event-store.ts"; +import { type Envelopes, envelopesIn, openedUnder, redactedIn } from "./event-store.ts"; import { collectPersonalDataExport, countPart, @@ -54,6 +54,7 @@ import { fieldCategory, type PersonalMarks } from "./marks.ts"; import { lifecycleStateOf } from "./process-state.ts"; import { restrictedAmong } from "./restricted-reads.ts"; import { processingRestrictionsOf } from "./restriction.ts"; +import { eventMarksOf } from "./stored-marks.ts"; import { checkPersonId } from "./transact.ts"; export interface StreamPersonalDataArgs { @@ -132,6 +133,32 @@ const markedFields = (marks: PersonalMarks | null, payload: unknown): Marked => }; }; +// What the marks name, and every other field the store held sealed under the person, under the +// category its envelope names: a type retired, or a field no longer marked, still holds their data. +const heldFields = ( + marks: PersonalMarks | null, + payload: unknown, + sealed: Envelopes, + personId: string, +): Marked => { + const marked = markedFields(marks, payload); + if (!isRecord(payload)) return marked; + const enveloped = Object.entries(sealed).filter( + ([field, { person }]) => + person === personId && !(field in marked.data) && payload[field] !== undefined, + ); + return { + data: { + ...marked.data, + ...Object.fromEntries(enveloped.map(([field]) => [field, payload[field]])), + }, + categories: { + ...marked.categories, + ...Object.fromEntries(enveloped.map(([field, { category }]) => [field, category])), + }, + }; +}; + // Pages by a key no write changes, so a record written or removed meanwhile cannot make another // one skip a page or repeat; the last page is the first that comes back empty. async function* paged( @@ -332,12 +359,14 @@ export const streamPersonalData: StreamPersonalDataFunction = async ({ const eventData = (event: StoredEvent): Marked => { const process = processOfStream(event.aggregateType); if (process === null) { - const marks = aggregates.byName[event.aggregateType]?.eventsByType[event.type]?.personal; - return markedFields(marks ?? null, event.payload); + const marks = eventMarksOf({ aggregates, event }); + return heldFields(marks, event.payload, envelopesIn(event), personId); } - return markedFields( + return heldFields( processes.byName[process]?.personal ?? null, lifecycleStateOf(event.payload), + envelopesIn(event), + personId, ); }; const commandMarks = (type: string): PersonalMarks | null => diff --git a/packages/core/src/kernel/personal-data/export.test.ts b/packages/core/src/kernel/personal-data/export.test.ts index a0896a913..67a0654c7 100644 --- a/packages/core/src/kernel/personal-data/export.test.ts +++ b/packages/core/src/kernel/personal-data/export.test.ts @@ -189,7 +189,9 @@ const setup = async () => { const written = await memory().createStorage(); const storage: AppStorage = appStorage({ // The kinds of event the store held when the app started, one whose module it no longer has. - stored: storedTypesOf([{ aggregateType: "customer", type: "CustomerMoved", schemaVersion: 1 }]), + stored: storedTypesOf([ + { aggregateType: "customer", type: "CustomerMoved", schemaVersion: 1, opened: false }, + ]), storage: written, aggregates, processes: { byName: {} }, diff --git a/packages/core/src/kernel/personal-data/key-hierarchy.test.ts b/packages/core/src/kernel/personal-data/key-hierarchy.test.ts index fbc12fd8b..a71119e57 100644 --- a/packages/core/src/kernel/personal-data/key-hierarchy.test.ts +++ b/packages/core/src/kernel/personal-data/key-hierarchy.test.ts @@ -104,7 +104,7 @@ describe("openKeyHierarchy", () => { const without = await opening({ master: null }); await expect(openKeyHierarchy(without.args)).rejects.toThrow( new ConfigurationError( - 'The registry marks personal fields, so runtime.personalData.keyWrapper must wrap their keys: set masterKey({ from: "BOUNDA_MASTER_KEY" }) or a wrapper from defineKeyWrapper', + 'The registry marks personal fields, or an earlier deploy did for events the store holds, so runtime.personalData.keyWrapper must wrap their keys: set masterKey({ from: "BOUNDA_MASTER_KEY" }) or a wrapper from defineKeyWrapper', ), ); const storeAlone = await opening({ master: null, personal: false }); diff --git a/packages/core/src/kernel/personal-data/key-hierarchy.ts b/packages/core/src/kernel/personal-data/key-hierarchy.ts index db8ea8945..047e26b24 100644 --- a/packages/core/src/kernel/personal-data/key-hierarchy.ts +++ b/packages/core/src/kernel/personal-data/key-hierarchy.ts @@ -77,7 +77,8 @@ export interface OpenKeyHierarchyArgs { readonly claims?: boolean; readonly tenant: string; /** - * Whether the registry marks a field personal, anywhere: the keys are then required. + * Whether the registry marks a field personal, anywhere, or a set of marks the store recorded + * does: the keys are then required. */ readonly personal: boolean; readonly env: AppEnv; @@ -116,7 +117,7 @@ export const openKeyHierarchy: OpenKeyHierarchyFunction = async ({ throw runtimeText( new ConfigurationError( personal - ? 'The registry marks personal fields, so runtime.personalData.keyWrapper must wrap their keys: set masterKey({ from: "BOUNDA_MASTER_KEY" }) or a wrapper from defineKeyWrapper' + ? 'The registry marks personal fields, or an earlier deploy did for events the store holds, so runtime.personalData.keyWrapper must wrap their keys: set masterKey({ from: "BOUNDA_MASTER_KEY" }) or a wrapper from defineKeyWrapper' : 'runtime.personalData.tenantKeys needs runtime.personalData.keyWrapper, which wraps the tenant\'s key: set masterKey({ from: "BOUNDA_MASTER_KEY" }) or a wrapper from defineKeyWrapper', ), ); diff --git a/packages/core/src/kernel/personal-data/ledger-in-force.ts b/packages/core/src/kernel/personal-data/ledger-in-force.ts index 1448963d4..612a73a48 100644 --- a/packages/core/src/kernel/personal-data/ledger-in-force.ts +++ b/packages/core/src/kernel/personal-data/ledger-in-force.ts @@ -31,6 +31,11 @@ export const declaresPersonalData: DeclaresPersonalDataFunction = ({ marks, forg : null; }; +// What declares personal data in an app whose registry declares none, when a set of marks the store +// recorded marked a field `personal()` or `person()`: its events still hold that data. +export const RECORDED_PERSONAL_DATA = + "The store holds events of types an earlier deploy marked personal() or person()"; + export interface WithForgetLedgerInForceArgs { readonly config: ResolvedConfig; // What `declaresPersonalData` said. diff --git a/packages/core/src/kernel/personal-data/ledger-prune.test.ts b/packages/core/src/kernel/personal-data/ledger-prune.test.ts index c31a1e93c..854e9f91c 100644 --- a/packages/core/src/kernel/personal-data/ledger-prune.test.ts +++ b/packages/core/src/kernel/personal-data/ledger-prune.test.ts @@ -30,6 +30,7 @@ import { } from "./ledger-prune.ts"; import type { ReconciledReads } from "./reconciled-reads.ts"; import { FORGET_LEDGER_CURSOR } from "./reconciliation.ts"; +import { NO_STORED_MARKS } from "./stored-marks.ts"; const DAY = 24 * 60 * 60_000; const NOW = new Date("2026-11-25T12:00:00.000Z"); @@ -93,6 +94,7 @@ const RULES: ReconciliationRules = { }, }, commandsByType: {}, + storedMarks: NO_STORED_MARKS, } as unknown as AggregatesRuntime, processes: { byName: {} }, batchSize: 100, diff --git a/packages/core/src/kernel/personal-data/ledger-prune.ts b/packages/core/src/kernel/personal-data/ledger-prune.ts index b55f932c1..d2f7d8b14 100644 --- a/packages/core/src/kernel/personal-data/ledger-prune.ts +++ b/packages/core/src/kernel/personal-data/ledger-prune.ts @@ -1,4 +1,5 @@ import { type Adapter, isAdapter, type Storage } from "../../adapter/adapter.ts"; +import type { StoredEventTypeMarks } from "../../adapter/storage/event-store.ts"; import type { ForgetLedger, ForgetLedgerEntry, @@ -17,7 +18,7 @@ import { validateRegistry } from "../../modules/validate.ts"; import type { AppEnv } from "../../register/index.ts"; import { buildAggregates } from "../aggregate/build-aggregates.ts"; import type { AggregatesRuntime } from "../aggregate/runtime.ts"; -import { checkStoredTypes } from "../aggregate/stored-types.ts"; +import { checkRetiredMarks, checkStoredTypes } from "../aggregate/stored-types.ts"; import { withEventGuard } from "../events/guarded-storage.ts"; import { buildProcesses, type ProcessesRuntime } from "../process/build-processes.ts"; import { disclosureHeld, forgottenSince } from "../recipients/again.ts"; @@ -57,6 +58,7 @@ import { import { redactionSeals } from "./redaction.ts"; import { restrictionDue } from "./restriction.ts"; import { appRetentionDue } from "./retention.ts"; +import { withStoredMarks } from "./stored-marks.ts"; import { openTenantKeyStore } from "./tenant-key-source.ts"; export type AppliedStorage = Pick< @@ -99,6 +101,16 @@ export const reconciliationRulesOf: ReconciliationRulesOfFunction = ({ registry, }; }; +export interface WithRecordedMarksFunction { + (rules: ReconciliationRules, marks: readonly StoredEventTypeMarks[]): ReconciliationRules; +} + +// The rules with the marks the database recorded, which a redaction of a retired type reads. +export const withRecordedMarks: WithRecordedMarksFunction = (rules, marks) => ({ + ...rules, + aggregates: withStoredMarks(rules.aggregates, marks), +}); + export interface PruneAsAppliedArgs { readonly ledger: Pick & Required>; @@ -815,8 +827,11 @@ const pruneOpened = async ({ config, env, tenant, - aggregates: () => { - rules ??= reconciliationRulesOf({ registry, config: resolved }); + aggregates: (marks) => { + rules = withRecordedMarks( + rules ?? reconciliationRulesOf({ registry, config: resolved }), + marks, + ); return rules.aggregates; }, work, @@ -843,8 +858,9 @@ export interface WithTenantStorageArgs { readonly config: Config; readonly env: AppEnv; readonly tenant: string; - // Asked once the database is open, to check what its catalogue holds as an app's start does. - readonly aggregates: () => AggregatesRuntime; + // Asked once the database is open, with the marks it recorded, to check what its catalogue holds + // as an app's start does. + readonly aggregates: (marks: readonly StoredEventTypeMarks[]) => AggregatesRuntime; // `null` for a database that holds no table yet. readonly work: (storage: AppliedStorage | null) => Promise; } @@ -874,11 +890,13 @@ export const withTenantStorage: WithTenantStorageFunction = ({ } const created = await adapter.createStorage(); try { - const built = aggregates(); - const stored = checkStoredTypes({ - types: await created.eventStore.types(), - aggregates: built, - }); + const built = aggregates(await created.eventStore.marksOf()); + const types = await created.eventStore.types(); + const stored = checkStoredTypes({ types, aggregates: built }); + // A forgotten tenant's start records no marks: nothing of it is sealed again. + if ((await created.fence.read()).state !== "forgotten") { + checkRetiredMarks({ types, aggregates: built }); + } return await work(withEventGuard({ storage: created, aggregates: built, stored })); } finally { await created.close(); diff --git a/packages/core/src/kernel/personal-data/marks.test.ts b/packages/core/src/kernel/personal-data/marks.test.ts index 42b381bd9..89c5abc7e 100644 --- a/packages/core/src/kernel/personal-data/marks.test.ts +++ b/packages/core/src/kernel/personal-data/marks.test.ts @@ -12,6 +12,7 @@ import { type PersonalMarks, personalMarksOf, } from "./marks.ts"; +import { NO_STORED_MARKS } from "./stored-marks.ts"; const path = "aggregates.order.events.orderPlaced"; @@ -118,6 +119,7 @@ describe("marksPersonalFields", () => { other: { eventsByType: {}, commands: {} }, }, commandsByType: {}, + storedMarks: NO_STORED_MARKS, }) as unknown as AggregatesRuntime; const processes = (states: readonly (PersonalMarks | null)[]): ProcessesRuntime => ({ all: states.map((personal) => ({ personal })) }) as unknown as ProcessesRuntime; diff --git a/packages/core/src/kernel/personal-data/marks.ts b/packages/core/src/kernel/personal-data/marks.ts index ef2f93d82..6f88c3722 100644 --- a/packages/core/src/kernel/personal-data/marks.ts +++ b/packages/core/src/kernel/personal-data/marks.ts @@ -53,6 +53,14 @@ export const personalMarksOf: PersonalMarksOfFunction = ({ schema, path }) => { return { person: persons[0] ?? null, fields, categories }; }; +export interface PersonNamedByFunction { + (value: unknown): string | null; +} + +// The person's id a person field holds, `null` for a value no id can be. +export const personNamedBy: PersonNamedByFunction = (value) => + (typeof value === "string" && value !== "") || typeof value === "number" ? String(value) : null; + export interface FieldCategoryFunction { (marks: PersonalMarks, field: string): string; } @@ -70,10 +78,12 @@ export interface MarksPersonalFieldsFunction { } /** - * Whether any event, command or process state of the registry marks a field `personal`, which - * then needs keys. + * Whether any event, command or process state of the registry marks a field `personal`, or any + * set of marks the store recorded did, which then needs keys: what an event type, retired or + * no longer marked, sealed stays sealed. */ export const marksPersonalFields: MarksPersonalFieldsFunction = ({ aggregates, processes }) => + aggregates.storedMarks.personalFields || processes.all.some((process) => (process.personal?.fields.length ?? 0) > 0) || Object.values(aggregates.byName).some( (aggregate) => @@ -85,9 +95,10 @@ export const marksPersonalFields: MarksPersonalFieldsFunction = ({ aggregates, p ), ); -// Whether any event, command or process state marks a field `personal` or `person`: the app then -// holds data of persons it can be asked to forget. +// Whether any event, command or process state marks a field `personal` or `person`, or any set of +// marks the store recorded did: the app then holds data of persons it can be asked to forget. export const marksPersonalData: MarksPersonalFieldsFunction = ({ aggregates, processes }) => + aggregates.storedMarks.personalData || processes.all.some((process) => (process.personal ?? null) !== null) || Object.values(aggregates.byName).some( (aggregate) => diff --git a/packages/core/src/kernel/personal-data/persons.test.ts b/packages/core/src/kernel/personal-data/persons.test.ts index 05a3219cf..fc2b4ed55 100644 --- a/packages/core/src/kernel/personal-data/persons.test.ts +++ b/packages/core/src/kernel/personal-data/persons.test.ts @@ -45,6 +45,7 @@ const registry: Registry = { }, }, }, + retired: { orderNoted: { retired: true } }, policies: {}, processes: {}, }, @@ -187,6 +188,25 @@ describe("personOfEvent", () => { }); }); +describe("personOfEvent of a retired type", () => { + const sealed = (person: string) => ({ $personal: { person, key: "k", iv: "i", data: "d" } }); + + it("names whom the stored fields are sealed for, and nobody for an event that holds none", () => { + const noted = (payload: unknown) => + personOfEvent({ aggregates, event: event(1, "OrderNoted", payload) }); + expect(noted({ total: 3, note: sealed("c-1") })).toBe("c-1"); + expect(noted({ note: "in the clear" })).toBeNull(); + expect(noted({ note: null })).toBeNull(); + expect(noted("note")).toBeNull(); + expect( + personOfEvent({ + aggregates, + event: { ...event(2, "OrderNoted", { note: sealed("c-1") }), aggregateType: "customer" }, + }), + ).toBeNull(); + }); +}); + describe("personTouchedByEvent", () => { const touched = (type: string, payload: unknown, aggregateType = "order"): string | null => personTouchedByEvent({ aggregates, event: { ...event(1, type, payload), aggregateType } }); diff --git a/packages/core/src/kernel/personal-data/persons.ts b/packages/core/src/kernel/personal-data/persons.ts index 5e02b682e..0c3f89bea 100644 --- a/packages/core/src/kernel/personal-data/persons.ts +++ b/packages/core/src/kernel/personal-data/persons.ts @@ -2,6 +2,10 @@ import { type KeyedPerson, keyedPersonId } from "../../adapter/storage/personal- import type { StoredEvent } from "../../contracts/event.ts"; import type { AggregateRuntime, AggregatesRuntime, CommandRuntime } from "../aggregate/runtime.ts"; import { isRecord } from "../shared/merge-fields.ts"; +import { isSealed } from "./crypto.ts"; +import { openedUnder } from "./event-store.ts"; +import { personNamedBy } from "./marks.ts"; +import { retiredMarksOf } from "./stored-marks.ts"; export interface PersonsOfArgs { readonly aggregate: AggregateRuntime; @@ -55,14 +59,37 @@ export interface PersonOfEventFunction { (args: PersonOfEventArgs): string | null; } +// A retired type, which no schema marks, names whom its fields are sealed for: as it was handed +// out, the person a key opened one for; as stored, the person an envelope names; with none sealed, +// whom the sets the store recorded for it name for a field holding a value. +const retiredPerson = (aggregates: AggregatesRuntime, event: StoredEvent): string | null => { + const opened = openedUnder(event)[0]; + if (opened !== undefined) return opened.person; + if (!isRecord(event.payload)) return null; + const payload = event.payload; + const sealed = Object.values(payload).find(isSealed)?.$personal.person; + if (sealed !== undefined) return sealed; + const { marks } = retiredMarksOf({ + sets: aggregates.storedMarks.of(event.aggregateType, event.type), + event, + }); + if (marks === null) return null; + if (!marks.fields.some((field) => payload[field] !== undefined && payload[field] !== null)) { + return null; + } + return marks.person === null ? event.aggregateId : personNamedBy(payload[marks.person]); +}; + /** - * Whom the event names, as `personsOf` tells it for one event: `null` for an event without - * personal fields, of an aggregate the runtime does not know, or whose person was forgotten, so - * nothing is sealed again under a key they no longer hold. + * Whom the event names, as `personsOf` tells it for one event, or, for a retired type, as its + * sealed fields do: `null` for an event without personal fields, of an aggregate the runtime does + * not know, or whose person was forgotten, so nothing is sealed again under a key they no longer + * hold. */ export const personOfEvent: PersonOfEventFunction = ({ aggregates, event }) => { const aggregate = aggregates.byName[event.aggregateType]; if (aggregate === undefined) return null; + if (aggregate.retired.has(event.type)) return retiredPerson(aggregates, event); return personsOf({ aggregate, events: [event] })[0]?.person ?? null; }; diff --git a/packages/core/src/kernel/personal-data/redact.ts b/packages/core/src/kernel/personal-data/redact.ts index e44c580af..bea099f24 100644 --- a/packages/core/src/kernel/personal-data/redact.ts +++ b/packages/core/src/kernel/personal-data/redact.ts @@ -35,7 +35,7 @@ import { redactWithin, scrubStores, } from "./redaction.ts"; -import { checkRedactionTargets, redactionMarks } from "./redaction-targets.ts"; +import { checkRedactionTargets, redactionReach } from "./redaction-targets.ts"; import { checkPersonId, throughFreeze, transactRetrying } from "./transact.ts"; import type { PersonalKeys, PersonalKeyWrapping } from "./wrapped-keys.ts"; @@ -220,7 +220,13 @@ export const redactPersonalData: RedactPersonalDataFunction = async ({ processes: redactions.processes, events: options?.events, }); - await checkReachable({ eventStore: redactions.storage.eventStore, personId, targets }); + await checkReachable({ + eventStore: redactions.storage.eventStore, + aggregates: redactions.aggregates, + processes: redactions.processes, + personId, + targets, + }); report.changing(); const outcome = await redactIntended({ redactions, @@ -275,8 +281,9 @@ const openValues = async ( return opened; }; -// The person's events appended after the redaction whose marked fields hold an old value: a -// command or a reaction that read it just before the redaction committed wrote it after. +// The person's events appended after the redaction whose sealed fields hold an old value: a +// command or a reaction that read it just before the redaction committed wrote it after, or an +// instance not yet upgraded wrote it in a type now retired. const writtenSince = async ( redactions: Redactions, keys: PersonalKeys, @@ -294,7 +301,7 @@ const writtenSince = async ( limit: batchSize, }); for (const event of batch) { - const marks = redactionMarks({ + const reach = redactionReach({ aggregates, processes, aggregateType: event.aggregateType, @@ -304,9 +311,9 @@ const writtenSince = async ( processOfStream(event.aggregateType) === null ? event.payload : lifecycleStateOf(event.payload); - if (marks === null || !isRecord(holder)) continue; + if (reach === null || !isRecord(holder)) continue; const fields: string[] = []; - for (const field of marks.fields) { + for (const field of Object.keys(holder)) { const stored = holder[field]; if (!isSealed(stored)) continue; const key = await keyOf(stored.$personal.person, stored.$personal.key); diff --git a/packages/core/src/kernel/personal-data/redaction-details.test.ts b/packages/core/src/kernel/personal-data/redaction-details.test.ts index 08d1eff11..faccba0fb 100644 --- a/packages/core/src/kernel/personal-data/redaction-details.test.ts +++ b/packages/core/src/kernel/personal-data/redaction-details.test.ts @@ -964,7 +964,7 @@ describe("redact, in detail", () => { expect(exported.events.map(({ type }) => type)).toContain("PersonalDataRedacted"); }); - it("says redacted only of the fields its event still marks", async () => { + it("says redacted of every field its event holds sealed, one it no longer marks included", async () => { const adapter = memory(); const before = await createTestApp({ registry, adapter }); await ( @@ -1002,8 +1002,9 @@ describe("redact, in detail", () => { const after = await createTestApp({ registry: unmarked, adapter }); stops.push(() => after.app.stop()); expect((await after.app.exportPersonalData("ana")).events[0]).toMatchObject({ - data: { email: null }, - redacted: ["email"], + data: { email: null, note: null }, + categories: { email: "default", note: "default" }, + redacted: ["email", "note"], }); }); diff --git a/packages/core/src/kernel/personal-data/redaction-targets.test.ts b/packages/core/src/kernel/personal-data/redaction-targets.test.ts index 08b8adb5f..a33e63246 100644 --- a/packages/core/src/kernel/personal-data/redaction-targets.test.ts +++ b/packages/core/src/kernel/personal-data/redaction-targets.test.ts @@ -3,7 +3,7 @@ import { ValidationError } from "../../contracts/errors.ts"; import type { EventPayloadArgs } from "../../modules/payload.ts"; import type { Registry } from "../../modules/registry.ts"; import { buildAggregates } from "../aggregate/build-aggregates.ts"; -import { checkRedactionTargets, redactionMarks } from "./redaction-targets.ts"; +import { checkRedactionTargets, redactionReach, unsealedFor } from "./redaction-targets.ts"; const registry = { aggregates: { @@ -33,6 +33,7 @@ const registry = { evolve: () => ({}), }, }, + retired: { customerNoted: { retired: true } }, commands: {}, policies: {}, processes: {}, @@ -144,6 +145,14 @@ describe("checkRedactionTargets", () => { expect(error.issues).toEqual([{ path: ["events", 0, "fields"], message }]); }); + it("takes any field of a retired type, which the stored event's envelopes decide, and refuses one another aggregate retired", () => { + const noted = { ...registered, type: "CustomerNoted", fields: ["text", "anything"] }; + expect(checkRedactionTargets({ aggregates, processes, events: [noted] })).toEqual([noted]); + expect(refusal([{ ...noted, aggregateType: "member" }]).message).toBe( + "redact cannot reach member.CustomerNoted: it marks no field personal", + ); + }); + it("takes each event once, with its fields once each, and refuses one id named as two events", () => { expect( checkRedactionTargets({ @@ -189,11 +198,11 @@ describe("checkRedactionTargets", () => { }); }); -describe("redactionMarks", () => { +describe("redactionReach", () => { it("reads an event's marks, a lifecycle event's state's, and nothing for what it does not know", () => { const of = (aggregateType: string, type: string) => - redactionMarks({ aggregates, processes, aggregateType, type }); - expect(of("customer", "CustomerRegistered")?.fields).toEqual(["email", "phone"]); + redactionReach({ aggregates, processes, aggregateType, type }); + expect(of("customer", "CustomerRegistered")?.marks?.fields).toEqual(["email", "phone"]); expect(of("customer", "CustomerPaid")).toBeNull(); expect(of("customer", "Unknown")).toBeNull(); expect(of("order", "OrderPlaced")).toBeNull(); @@ -203,9 +212,31 @@ describe("redactionMarks", () => { "ProcessDeadlineReached", "ProcessTimedOut", ]) { - expect(of("process:customer.onboarding", type)).toBe(contact); + expect(of("process:customer.onboarding", type)).toEqual({ marks: contact }); } expect(of("process:customer.onboarding", "ProcessFailed")).toBeNull(); expect(of("process:customer.other", "ProcessHandled")).toBeNull(); }); + + it("reaches a retired type by its envelopes, and only the aggregate that retired it", () => { + const of = (aggregateType: string) => + redactionReach({ aggregates, processes, aggregateType, type: "CustomerNoted" }); + expect(of("customer")).toEqual({ marks: null }); + expect(of("member")).toBeNull(); + expect(of("process:customer.onboarding")).toBeNull(); + }); +}); + +describe("unsealedFor", () => { + const sealed = (person: string) => ({ $personal: { person, key: "k", iv: "i", data: "d" } }); + + it("finds a field sealed for the person, and says why one held otherwise is not reached", () => { + const holder = { mine: sealed("c-1"), theirs: sealed("c-2"), clear: "text" }; + expect(unsealedFor(holder, "mine", "c-1")).toBeNull(); + expect(unsealedFor(holder, "theirs", "c-1")).toBe( + 'it holds "theirs" sealed for another person', + ); + expect(unsealedFor(holder, "clear", "c-1")).toBe('it holds "clear" in the clear'); + expect(unsealedFor(holder, "gone", "c-1")).toBe('it holds no "gone"'); + }); }); diff --git a/packages/core/src/kernel/personal-data/redaction-targets.ts b/packages/core/src/kernel/personal-data/redaction-targets.ts index fb951f18a..309397907 100644 --- a/packages/core/src/kernel/personal-data/redaction-targets.ts +++ b/packages/core/src/kernel/personal-data/redaction-targets.ts @@ -5,35 +5,60 @@ import type { AggregatesRuntime } from "../aggregate/runtime.ts"; import type { ProcessesRuntime } from "../process/build-processes.ts"; import { PROCESS_STATE_EVENTS, processOfStream } from "../process/lifecycle.ts"; import { isRecord } from "../shared/merge-fields.ts"; +import { isSealed } from "./crypto.ts"; import type { PersonalMarks } from "./marks.ts"; -export interface RedactionMarksArgs { +export interface RedactionReachArgs { readonly aggregates: AggregatesRuntime; readonly processes: Pick; readonly aggregateType: string; readonly type: string; } -export interface RedactionMarksFunction { - (args: RedactionMarksArgs): PersonalMarks | null; +// How a redaction finds the personal fields of an event: by what its type marks, or, with `marks` +// `null`, by the envelopes the stored event holds, for a type its aggregate retired, which no +// schema marks any more. +export interface RedactionReach { + readonly marks: PersonalMarks | null; +} + +export interface RedactionReachFunction { + (args: RedactionReachArgs): RedactionReach | null; } // What an event of that stream and type marks: its payload's marks, or, for a process's lifecycle -// event that carries the state, the state's; `null` for an event that marks nothing redact -// reaches. -export const redactionMarks: RedactionMarksFunction = ({ +// event that carries the state, the state's; its envelopes for a retired type; `null` for an +// event that marks nothing redact reaches. +export const redactionReach: RedactionReachFunction = ({ aggregates, processes, aggregateType, type, }) => { const process = processOfStream(aggregateType); - if (process !== null) { - return PROCESS_STATE_EVENTS.includes(type as ProcessStateEventType) - ? (processes.byName[process]?.personal ?? null) - : null; - } - return aggregates.byName[aggregateType]?.eventsByType[type]?.personal ?? null; + const marks = + process === null + ? aggregates.byName[aggregateType]?.eventsByType[type]?.personal + : PROCESS_STATE_EVENTS.includes(type as ProcessStateEventType) + ? processes.byName[process]?.personal + : null; + if (marks !== undefined && marks !== null) return { marks }; + return aggregates.byName[aggregateType]?.retired.has(type) === true ? { marks: null } : null; +}; + +export interface UnsealedForFunction { + (holder: Readonly>, field: string, personId: string): string | null; +} + +// Why a redaction by envelope cannot reach the field, `null` when the event holds it sealed for +// the person: one held in the clear, or for another person, has no category a schema gives it. +export const unsealedFor: UnsealedForFunction = (holder, field, personId) => { + const stored = holder[field]; + if (stored === undefined) return `it holds no "${field}"`; + if (!isSealed(stored)) return `it holds "${field}" in the clear`; + return stored.$personal.person === personId + ? null + : `it holds "${field}" sealed for another person`; }; export interface CheckRedactionTargetsArgs { @@ -53,7 +78,8 @@ const invalid = (path: readonly (string | number)[], message: string): Validatio // The targets of `redact(person, { events })`, each event once with its fields once each, in the // order asked. Throws `ValidationError` for none, for a target that is not one, for an event type -// that marks no personal field `redact` reaches, and for a field it does not mark `personal`. +// that marks no personal field `redact` reaches, and for a field it does not mark `personal`. The +// fields of a retired type are checked against the stored event, by `checkReachable`. export const checkRedactionTargets: CheckRedactionTargetsFunction = ({ aggregates, processes, @@ -78,11 +104,11 @@ export const checkRedactionTargets: CheckRedactionTargetsFunction = ({ if (!Array.isArray(fields) || fields.length === 0 || !fields.every(isName)) { throw invalid([...path, "fields"], "needs the fields of each event to redact"); } - const marks = redactionMarks({ aggregates, processes, aggregateType, type }); - if (marks === null || marks.fields.length === 0) { + const reach = redactionReach({ aggregates, processes, aggregateType, type }); + if (reach === null || reach.marks?.fields.length === 0) { throw invalid(path, `cannot reach ${aggregateType}.${type}: it marks no field personal`); } - const unmarked = fields.find((field) => !marks.fields.includes(field)); + const unmarked = fields.find((field) => reach.marks?.fields.includes(field) === false); if (unmarked !== undefined) { throw invalid( [...path, "fields"], diff --git a/packages/core/src/kernel/personal-data/redaction.ts b/packages/core/src/kernel/personal-data/redaction.ts index 65da2ae5b..f331c5761 100644 --- a/packages/core/src/kernel/personal-data/redaction.ts +++ b/packages/core/src/kernel/personal-data/redaction.ts @@ -47,7 +47,8 @@ import { import { openTextWith } from "./errors.ts"; import { fieldCategory, type PersonalMarks } from "./marks.ts"; import { lifecycleStateOf } from "./process-state.ts"; -import { redactionMarks } from "./redaction-targets.ts"; +import { redactionReach, unsealedFor } from "./redaction-targets.ts"; +import { eventMarksOf } from "./stored-marks.ts"; import type { PersonalKeys } from "./wrapped-keys.ts"; // The scheduler command type of the runtime's entry that keeps what a redaction made unreadable, @@ -143,7 +144,10 @@ const refusal = (target: RedactedEvent, why: string): ValidationError => ]); export interface CheckReachableArgs { + // The store as written, which holds the envelopes. readonly eventStore: Pick; + readonly aggregates: AggregatesRuntime; + readonly processes: Pick; readonly personId: string; readonly targets: readonly RedactedEvent[]; } @@ -154,7 +158,13 @@ export interface CheckReachableFunction { // Throws `ValidationError` for the first target `redactWithin` would refuse, before anything is // recorded: a redaction refused never reaches the ledger, whose reconciliation would apply it. -export const checkReachable: CheckReachableFunction = async ({ eventStore, personId, targets }) => { +export const checkReachable: CheckReachableFunction = async ({ + eventStore, + aggregates, + processes, + personId, + targets, +}) => { for (const target of targets) { const event = await eventStore.readOne({ aggregateType: target.aggregateType, @@ -163,12 +173,27 @@ export const checkReachable: CheckReachableFunction = async ({ eventStore, perso }); const why = unreachable(event, target, personId); if (why !== null) throw refusal(target, why); + const { aggregateType, type } = target; + const reach = redactionReach({ aggregates, processes, aggregateType, type }); + if (event === null || reach?.marks !== null) continue; + const holder = isRecord(event.payload) ? event.payload : {}; + // A value the sets recorded for the retired type mark, held in the clear, has their category. + const marks = eventMarksOf({ aggregates, event }); + for (const field of target.fields) { + const unsealed = unsealedFor(holder, field, personId); + const marked = + holder[field] !== undefined && + !isSealed(holder[field]) && + marks?.fields.includes(field) === true; + if (unsealed !== null && !marked) throw refusal(target, unsealed); + } } }; interface ReachedTarget { readonly event: StoredEvent; - readonly marks: PersonalMarks; + // `null` for a type that marks nothing. + readonly marks: PersonalMarks | null; // The payload, or, for a process's lifecycle event, the state it carries. readonly holder: Readonly>; readonly lifecycle: boolean; @@ -184,7 +209,7 @@ interface ReachTargetArgs { } // The target's event with what its marks make personal, `null` for one a redaction leaves: one the -// store does not hold, of another type or person, which `strict` refuses, or that marks nothing. +// store does not hold, of another type or person, which `strict` refuses, or that holds nothing. const reachTarget = async ({ eventStore, aggregates, @@ -201,25 +226,29 @@ const reachTarget = async ({ const why = unreachable(event, target, personId); if (why !== null && strict) throw refusal(target, why); if (why !== null || event === null) return null; - const marks = redactionMarks({ - aggregates, - processes, - aggregateType: event.aggregateType, - type: event.type, - }); + // A retired type, which no schema marks, is marked by the sets the store recorded for it. + const marks = + redactionReach({ aggregates, processes, aggregateType: event.aggregateType, type: event.type }) + ?.marks ?? eventMarksOf({ aggregates, event }); const lifecycle = processOfStream(event.aggregateType) !== null; const holder = lifecycle ? lifecycleStateOf(event.payload) : event.payload; - if (marks === null || !isRecord(holder)) return null; + if (!isRecord(holder)) return null; return { event, marks, holder, lifecycle }; }; type SealableField = - | { readonly field: string; readonly clear: unknown; readonly sealed: null } + | { + readonly field: string; + readonly clear: unknown; + readonly category: string; + readonly sealed: null; + } | { readonly field: string; readonly sealed: SealedValue; readonly key: K }; -// The fields of the target, made personal by the marks, that hold a value a redaction makes -// unreadable: in the clear, or sealed for the person under a key `keyOf` finds. A field the marks -// do not name is left as it is, whatever a ledger's entry asks. +// The fields of the target that hold a value a redaction makes unreadable: one sealed for the +// person under a key `keyOf` finds, or one the marks name held in the clear. A field the type no +// longer marks, or a retired type's no recorded set marks, is reached by its envelope alone, as a ledger's entry +// recorded while it was marked asks after a restore; one in the clear is left as it is. const sealableFields = async ( { marks, holder }: ReachedTarget, target: RedactedEvent, @@ -228,11 +257,12 @@ const sealableFields = async ( ): Promise[]> => { const found: SealableField[] = []; for (const field of target.fields) { - if (!marks.fields.includes(field)) continue; const stored = holder[field]; if (stored === undefined || stored === null) continue; if (!isSealed(stored)) { - found.push({ field, clear: stored, sealed: null }); + if (marks?.fields.includes(field) === true) { + found.push({ field, clear: stored, category: fieldCategory(marks, field), sealed: null }); + } continue; } if (stored.$personal.person !== personId) continue; @@ -293,11 +323,7 @@ const redactFields = async ( for (const found of sealable) { const redacted: RedactedValue = found.sealed === null - ? { - category: fieldCategory(reached.marks, found.field), - value: found.clear, - sealed: null, - } + ? { category: found.category, value: found.clear, sealed: null } : { category: categoryOf(found.sealed), value: await unseal({ key: found.key, sealed: found.sealed }), diff --git a/packages/core/src/kernel/personal-data/reseal-batches.test.ts b/packages/core/src/kernel/personal-data/reseal-batches.test.ts index 3260f4188..b334d5591 100644 --- a/packages/core/src/kernel/personal-data/reseal-batches.test.ts +++ b/packages/core/src/kernel/personal-data/reseal-batches.test.ts @@ -15,6 +15,7 @@ import { sealedKeys } from "./commands.ts"; import { isSealed, seal, unseal } from "./crypto.ts"; import { openTextWith } from "./errors.ts"; import { createResealBatches } from "./reseal-batches.ts"; +import { NO_STORED_MARKS } from "./stored-marks.ts"; const metadata = { correlationId: "c", @@ -25,8 +26,12 @@ const metadata = { system: false, }; -const customer = { name: "customer", snapshot: { every: 1, verify: 0, fingerprint: "f" } }; -const order = { name: "order", snapshot: null }; +const customer = { + name: "customer", + snapshot: { every: 1, verify: 0, fingerprint: "f" }, + retired: new Set(), +}; +const order = { name: "order", snapshot: null, retired: new Set() }; const aggregates = { byName: { @@ -61,6 +66,7 @@ const aggregates = { command: { personal: { person: "customerId", fields: ["address"], categories: {} } }, }, }, + storedMarks: NO_STORED_MARKS, } as unknown as AggregatesRuntime; const processes = { @@ -706,6 +712,7 @@ describe("what the backfill rewrites and names beyond the marks of a field", () contact: { name: "contact", snapshot: null, + retired: new Set(), eventsByType: { ContactAdded: { personal: { person: null, fields: ["email"], categories: {} }, diff --git a/packages/core/src/kernel/personal-data/reseal-batches.ts b/packages/core/src/kernel/personal-data/reseal-batches.ts index 0fcfc701d..d2fe5ef1b 100644 --- a/packages/core/src/kernel/personal-data/reseal-batches.ts +++ b/packages/core/src/kernel/personal-data/reseal-batches.ts @@ -292,7 +292,10 @@ export const createResealBatches: CreateResealBatchesFunction = ({ schemaVersion: plan.schemaVersion, from: fromOf(event), }); - } else if (plan !== null) owned.push({ person: plan.person, item: { event, plan } }); + } else if (plan !== null) { + owned.push({ person: plan.person, item: { event, plan } }); + if (plan.unsealable === true) nameless.push(event); + } } // Nobody is named: no forgetting can reach them, so no person's key is read first. const bareLeft = diff --git a/packages/core/src/kernel/personal-data/resealing.test.ts b/packages/core/src/kernel/personal-data/resealing.test.ts index f17df8a45..8ed54a810 100644 --- a/packages/core/src/kernel/personal-data/resealing.test.ts +++ b/packages/core/src/kernel/personal-data/resealing.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it } from "vitest"; +import { z } from "zod"; import type { StoredEvent } from "../../contracts/event.ts"; import { memory } from "../../memory/index.ts"; import { BOUNDA_AGGREGATE, PERSONAL_DATA_FORGOTTEN_EVENT } from "../../modules/bounda-events.ts"; import type { AggregatesRuntime } from "../aggregate/runtime.ts"; import type { ProcessesRuntime } from "../process/build-processes.ts"; import { keysOver, newStoredKey, openedKey } from "../test-support.ts"; -import { isSealed, seal, unseal } from "./crypto.ts"; +import { categoryOf, isSealed, seal, unseal } from "./crypto.ts"; import type { PersonalMarks } from "./marks.ts"; import { createResealKeys, @@ -17,6 +18,7 @@ import { type ResealPlanOf, walkFingerprint, } from "./resealing.ts"; +import { marksSetFingerprint, NO_STORED_MARKS, storedMarksOf } from "./stored-marks.ts"; interface Marked { readonly events?: Readonly>; @@ -32,8 +34,11 @@ const runtimes = ({ events = {}, commands = {}, process = null }: Marked) => { Object.entries(commands).map(([type, personal]) => [type, { type, personal }]), ); const aggregates = { - byName: { customer: { name: "customer", eventsByType, commands: commandRuntimes } }, + byName: { + customer: { name: "customer", eventsByType, retired: new Set(), commands: commandRuntimes }, + }, commandsByType: {}, + storedMarks: NO_STORED_MARKS, } as unknown as AggregatesRuntime; const onboarding = { name: "signup.onboarding", personal: process }; const processes = { @@ -664,6 +669,138 @@ describe("createResealKeys", () => { }); }); +describe("marksFingerprint of a retired type", () => { + const marks: PersonalMarks = { person: null, fields: ["email"], categories: {} }; + const retiredWith = (sets: readonly (PersonalMarks | null)[]) => { + const { aggregates, processes } = runtimes({}); + const customer = aggregates.byName.customer as unknown as { retired: Set }; + customer.retired = new Set(["CustomerRegistered"]); + return { + aggregates: { + ...aggregates, + storedMarks: storedMarksOf( + sets.map((set) => ({ + aggregateType: "customer", + type: "CustomerRegistered", + fingerprint: marksSetFingerprint(set), + marks: set, + firstSeenAt: "2026-01-01T00:00:00.000Z", + })), + ), + }, + processes, + }; + }; + + it("names it by the one set recorded for it as it was named while current, so retiring it walks nothing again", () => { + const current = runtimes({ events: { CustomerRegistered: marks } }); + expect(marksFingerprint(retiredWith([marks]))).toEqual(marksFingerprint(current)); + expect(marksFingerprint(retiredWith([null, marks]))).toEqual(marksFingerprint(current)); + expect(walkFingerprint(retiredWith([marks]))).toEqual(walkFingerprint(current)); + }); + + it("names it by every set recorded for it, so a set it did not have while current walks again", () => { + const current = runtimes({ events: { CustomerRegistered: marks } }); + const other: PersonalMarks = { + person: null, + fields: ["email"], + categories: { email: "profile" }, + }; + expect(marksFingerprint(retiredWith([other, marks]))).not.toEqual(marksFingerprint(current)); + expect(marksFingerprint(retiredWith([other, marks]))).toEqual( + marksFingerprint(retiredWith([marks, other])), + ); + expect(marksFingerprint(retiredWith([null]))).toBeNull(); + expect(marksFingerprint(retiredWith([]))).toBeNull(); + }); +}); + +describe("planEventReseal of a retired type", () => { + const retiredWith = (sets: readonly (PersonalMarks | null)[]) => { + const { aggregates, processes } = runtimes({}); + const customer = aggregates.byName.customer as unknown as { retired: Set }; + customer.retired = new Set(["CustomerRegistered"]); + return { + aggregates: { + ...aggregates, + storedMarks: storedMarksOf( + sets.map((set) => ({ + aggregateType: "customer", + type: "CustomerRegistered", + fingerprint: marksSetFingerprint(set), + marks: set, + firstSeenAt: "2026-01-01T00:00:00.000Z", + })), + ), + }, + processes, + }; + }; + + it("seals what it holds in the clear under every set recorded for it, each field in the newest set's category", async () => { + const { aggregates, processes } = retiredWith([ + { person: null, fields: ["email"], categories: {} }, + null, + { person: null, fields: ["email", "phone"], categories: { email: "profile" } }, + ]); + const sealed = await sealedWith( + planEventReseal({ + event: event({ payload: { email: "ana@example.com", phone: "600", name: "Ana" } }), + aggregates, + processes, + }), + ); + expect(sealed.person).toBe("c-1"); + expect([...sealed.categories].sort()).toEqual(["default", "profile"]); + const value = sealed.value as Record; + expect(value.name).toBe("Ana"); + expect(value.email).toMatchObject({ $personal: { person: "c-1", category: "profile" } }); + expect(value.phone).toMatchObject({ $personal: { person: "c-1" } }); + expect(categoryOf(value.phone as never)).toBe("default"); + }); + + it("leaves what it holds sealed as it is, under whatever category, since no schema says which is its own", async () => { + const key = await openedKey(await newStoredKey()); + const email = await seal({ key, person: "c-1", category: "default", value: "ana@example.com" }); + const { aggregates, processes } = retiredWith([ + { person: null, fields: ["email"], categories: { email: "profile" } }, + ]); + expect( + planEventReseal({ + event: event({ person: "c-1", payload: { email } }), + aggregates, + processes, + }), + ).toBeNull(); + }); + + it("marks unsealable, after sealing what it can, a value in the clear a set marks for somebody the event does not name", async () => { + const { aggregates, processes } = retiredWith([ + { person: "customerId", fields: ["address"], categories: {} }, + { person: null, fields: ["email"], categories: {} }, + ]); + const plan = planEventReseal({ + event: event({ + person: "c-1", + payload: { customerId: "c-2", address: "Bilbao", email: "a@b.c" }, + }), + aggregates, + processes, + }); + expect(plan).toMatchObject({ person: "c-1", unsealable: true }); + const value = (await sealedWith(plan)).value as Record; + expect(value.address).toBe("Bilbao"); + expect(isSealed(value.email)).toBe(true); + expect( + planEventReseal({ + event: event({ person: "c-1", payload: { customerId: "c-2", address: "Bilbao" } }), + aggregates, + processes, + }), + ).toBe("unsealable"); + }); +}); + describe("planUpcastReseal", () => { const upcasting = (marks: PersonalMarks | null) => ({ @@ -683,10 +820,12 @@ describe("planUpcastReseal", () => { ], }, }, + retired: new Set(), commands: {}, }, }, commandsByType: {}, + storedMarks: NO_STORED_MARKS, }) as unknown as AggregatesRuntime; const marked: PersonalMarks = { person: "customerId", fields: ["email"], categories: {} }; const older = (overrides: Partial) => @@ -767,4 +906,100 @@ describe("planUpcastReseal", () => { const rewritten = (await opened?.seal(() => key)) as Record | undefined; expect(isSealed(rewritten?.email)).toBe(true); }); + + const reshaping = (upcast: (payload: Record) => unknown) => + ({ + byName: { + customer: { + name: "customer", + eventsByType: { + CustomerRegistered: { + type: "CustomerRegistered", + personal: marked, + schema: z.object({ customerId: z.string(), email: z.string().nullable() }), + schemaVersion: 2, + upcasts: [upcast], + }, + }, + retired: new Set(), + commands: {}, + }, + }, + commandsByType: {}, + storedMarks: NO_STORED_MARKS, + }) as unknown as AggregatesRuntime; + + const rewrittenBy = async ( + upcast: (payload: Record) => unknown, + payload: (sealed: (value: string) => Promise) => Promise, + ) => { + const key = await openedKey(await newStoredKey()); + const stored = await payload((value) => + seal({ key, person: "c-1", category: "default", value }), + ); + const planned = plan(reshaping(upcast), { person: "c-1", payload: stored }); + if (planned === null || planned === "unsealable" || "bare" in planned) { + throw new Error("no plan"); + } + const opened = await planned.opened(async (value) => ({ + value: await unseal({ key, sealed: value }), + })); + if (opened === null) throw new Error("nothing to seal"); + const rewritten = (await opened.seal(() => key)) as Record; + return { key, stored: stored as Record, opened, rewritten }; + }; + + it("keeps, unopened, an envelope the upcasts carry to a key the current schema does not declare, under its own name or another", async () => { + const { key, stored, rewritten } = await rewrittenBy( + (payload) => ({ ...payload, email: payload.mail, legacy: payload.note }), + async (sealed) => ({ + customerId: "c-1", + mail: await sealed("ana@example.com"), + note: await sealed("call after 5"), + source: "web", + }), + ); + expect(rewritten.mail).toEqual(stored.mail); + expect(rewritten.note).toEqual(stored.note); + expect(rewritten.legacy).toEqual(stored.note); + expect(rewritten.source).toBe("web"); + expect(rewritten.email).not.toEqual(stored.mail); + expect(await unseal({ key, sealed: rewritten.email as never })).toBe("ana@example.com"); + expect(JSON.stringify(rewritten)).not.toContain("call after 5"); + }); + + it("seals in the default category what the upcasts make, under a key the current schema does not declare, of a value they opened", async () => { + const { key, opened, rewritten } = await rewrittenBy( + (payload) => ({ + customerId: payload.customerId, + email: payload.mail, + domain: String(payload.mail).split("@")[1], + source: "web", + }), + async (sealed) => ({ customerId: "c-1", mail: await sealed("ana@example.com") }), + ); + expect(opened.categories).toEqual(["default"]); + expect(rewritten.domain).toMatchObject({ $personal: { person: "c-1" } }); + expect(categoryOf(rewritten.domain as never)).toBe("default"); + expect(await unseal({ key, sealed: rewritten.domain as never })).toBe("example.com"); + expect(rewritten.source).toBe("web"); + expect(JSON.stringify(rewritten)).not.toContain("example.com"); + }); + + it("seals every value under a key the current schema does not declare that the stored payload did not hold as it is, when the upcasts cannot read an envelope", async () => { + const { key, rewritten } = await rewrittenBy( + (payload) => ({ + customerId: payload.customerId, + email: payload.mail, + domain: (payload.mail as string).split("@")[1], + source: "web", + kept: payload.kept, + }), + async (sealed) => ({ customerId: "c-1", mail: await sealed("ana@example.com"), kept: 7 }), + ); + expect(await unseal({ key, sealed: rewritten.domain as never })).toBe("example.com"); + expect(await unseal({ key, sealed: rewritten.source as never })).toBe("web"); + expect(rewritten.kept).toBe(7); + expect(JSON.stringify(rewritten)).not.toContain("example.com"); + }); }); diff --git a/packages/core/src/kernel/personal-data/resealing.ts b/packages/core/src/kernel/personal-data/resealing.ts index cd2dc4cf3..d50b708d6 100644 --- a/packages/core/src/kernel/personal-data/resealing.ts +++ b/packages/core/src/kernel/personal-data/resealing.ts @@ -1,3 +1,4 @@ +import { z } from "zod"; import type { StorageTransaction } from "../../adapter/adapter.ts"; import { DEFAULT_PERSONAL_CATEGORY, @@ -23,8 +24,9 @@ import { seal, unseal, } from "./crypto.ts"; -import { fieldCategory, type PersonalMarks } from "./marks.ts"; +import { fieldCategory, type PersonalMarks, personNamedBy } from "./marks.ts"; import { lifecycleStateOf, sealState, statePersonOf } from "./process-state.ts"; +import { canonicalMarks, retiredMarksOf } from "./stored-marks.ts"; import { type CategoryKey, inSealingOrder, type PersonalKeys } from "./wrapped-keys.ts"; export interface MarksFingerprintArgs { @@ -48,39 +50,44 @@ const entryOf = ( : [ JSON.stringify([ name, - marks.person, - // A field of the default category is named as it was before categories existed. - [...marks.fields].sort().map((field) => { - const category = fieldCategory(marks, field); - return category === DEFAULT_PERSONAL_CATEGORY ? field : [field, category]; - }), + ...canonicalMarks(marks), ...(schemaVersion === 1 ? [] : [schemaVersion]), ]), ]; +// A retired type is named by every set the store recorded for it, which the walk seals under: one +// set names it as it was named while current. const fingerprintOf = ( { aggregates, processes }: MarksFingerprintArgs, versions: boolean, ): string | null => { - const marked: string[] = []; + const marked = new Set(); + const add = (entries: readonly string[]): void => { + for (const entry of entries) marked.add(entry); + }; for (const aggregate of Object.values(aggregates.byName)) { for (const event of Object.values(aggregate.eventsByType)) { - marked.push( - ...entryOf( + add( + entryOf( `event:${aggregate.name}.${event.type}`, event.personal, versions ? event.schemaVersion : 1, ), ); } + for (const type of aggregate.retired) { + for (const set of aggregates.storedMarks.of(aggregate.name, type)) { + add(entryOf(`event:${aggregate.name}.${type}`, set)); + } + } for (const command of Object.values(aggregate.commands)) { - marked.push(...entryOf(`command:${aggregate.name}.${command.type}`, command.personal)); + add(entryOf(`command:${aggregate.name}.${command.type}`, command.personal)); } } for (const process of processes.all) { - marked.push(...entryOf(`process:${process.name}`, process.personal)); + add(entryOf(`process:${process.name}`, process.personal)); } - return marked.length === 0 ? null : digest(JSON.stringify(marked.sort())); + return marked.size === 0 ? null : digest(JSON.stringify([...marked].sort())); }; /** @@ -318,6 +325,11 @@ export const createResealKeys: CreateResealKeysFunction = ({ transaction, keys } */ export interface ResealPlan { readonly person: string; + /** + * Whether the record also holds values in the clear it cannot seal under that person, as when a + * set recorded for a retired type names another person for them. + */ + readonly unsealable?: boolean; /** * Opens the values sealed under a category their field is no longer in; `null` when nothing is * left to write, as when no key opens any of them and the record names its person already. @@ -349,9 +361,6 @@ export interface OpenSealedFunction { */ export type ResealPlanOf = ResealPlan | "unsealable" | null; -const personIn = (value: unknown): string | null => - (typeof value === "string" && value !== "") || typeof value === "number" ? String(value) : null; - // What is still sealed after the moved values were opened stays as it is: its key is gone. const sealFields = async ( payload: Readonly>, @@ -441,7 +450,7 @@ export const planPayloadReseal: PlanPayloadResealFunction = ({ marks, payload, a const clear = marks.fields.filter( (field) => payload[field] !== undefined && !isSealed(payload[field]), ); - const person = marks.person === null ? aggregateId : personIn(payload[marks.person]); + const person = marks.person === null ? aggregateId : personNamedBy(payload[marks.person]); const moved = movedFields(marks, payload, person); if (clear.length === 0 && moved.length === 0) return null; if (person === null) return "unsealable"; @@ -472,7 +481,8 @@ export interface PlanEventResealFunction { const holdsValue = (value: unknown): boolean => value !== undefined && value !== null; // Clear values with nobody to seal them under, or under another person than the event names, are -// left as they are; an event with none, and nothing moved, is left alone whatever it names. +// left as they are; an event with none, and nothing moved, is left alone whatever it names. Values +// sealed under another category than the field's move to it only when `moves`. const planned = ( event: StoredEvent, marks: PersonalMarks, @@ -485,9 +495,12 @@ const planned = ( pending: readonly string[], keyOf: (category: string) => PersonalKey, ) => Promise, + moves = true, ): ResealPlanOf => { const moved = - event.person === null || event.person === person ? movedFields(marks, fields, person) : []; + moves && (event.person === null || event.person === person) + ? movedFields(marks, fields, person) + : []; if (clear.length === 0 && moved.length === 0 && event.person !== null) return null; if (person === null || (event.person !== null && event.person !== person)) { return clear.length === 0 ? null : "unsealable"; @@ -510,7 +523,9 @@ const planned = ( * For an event as the store holds it: the marked fields of a domain event's payload, or of the * state a process lifecycle event carries, that hold a value in the clear, sealed as the event * store seals them as it appends, and the person the marks name, whom the event then names too. - * An event with no value in the clear that names nobody yet gets its person all the same. + * An event with no value in the clear that names nobody yet gets its person all the same. A + * retired type is marked by every set the store recorded for it, as `retiredMarksOf` reads them, + * and what it holds sealed stays as it is: no schema says which category is its own any more. */ export const planEventReseal: PlanEventResealFunction = ({ event, aggregates, processes }) => { const process = processOfStream(event.aggregateType); @@ -532,16 +547,30 @@ export const planEventReseal: PlanEventResealFunction = ({ event, aggregates, pr }), })); } - const marks = aggregates.byName[event.aggregateType]?.eventsByType[event.type]?.personal ?? null; + const aggregate = aggregates.byName[event.aggregateType]; + const retired = aggregate?.retired.has(event.type) === true; + const { marks, elsewhere } = retired + ? retiredMarksOf({ sets: aggregates.storedMarks.of(event.aggregateType, event.type), event }) + : { marks: aggregate?.eventsByType[event.type]?.personal ?? null, elsewhere: [] }; const { payload } = event; - if (marks === null || !isRecord(payload)) return null; + if (!isRecord(payload)) return null; + const left = elsewhere.length > 0; + if (marks === null) return left ? "unsealable" : null; const clear = marks.fields.filter( (field) => payload[field] !== undefined && !isSealed(payload[field]), ); - const person = marks.person === null ? event.aggregateId : personIn(payload[marks.person]); - return planned(event, marks, payload, clear, person, (named, opened, pending, keyOf) => - sealFields(opened, marks, pending, named, keyOf), + const person = marks.person === null ? event.aggregateId : personNamedBy(payload[marks.person]); + const plan = planned( + event, + marks, + payload, + clear, + person, + (named, opened, pending, keyOf) => sealFields(opened, marks, pending, named, keyOf), + !retired, ); + if (!left || plan === "unsealable") return plan; + return plan === null ? "unsealable" : { ...plan, unsealable: true }; }; export interface UpcastRewriteArgs { @@ -588,12 +617,74 @@ export interface PlanUpcastResealFunction { (args: UpcastRewriteArgs): UpcastPlan | BareRewrite | "unsealable" | null; } +// The keys of the current shape the schema does not declare; none unless both are objects. +const undeclaredIn = (schema: z.ZodType | null, payload: unknown): readonly string[] => { + if (!isRecord(payload) || !(schema instanceof z.ZodObject)) return []; + return Object.keys(payload).filter((field) => !(field in schema.shape)); +}; + +interface Undeclared { + readonly current: unknown; + readonly derived: readonly string[]; +} + +// A key no schema declares holds, once the upcasts ran over what was opened, an envelope they +// passed along, which keeps it unopened, or a value they made from an opened one, which is sealed +// again as `derived`. `unopened` is what they made of the payload as stored, `undefined` when they +// could not read an envelope where they expected a value: then any value the stored payload did +// not hold as it is counts as made from one. +const undeclaredOf = ( + schema: z.ZodType | null, + stored: unknown, + opened: unknown, + unopened: unknown, +): Undeclared => { + if (!isRecord(opened) || !isRecord(stored) || !Object.values(stored).some(isSealed)) { + return { current: opened, derived: [] }; + } + const current: Record = { ...opened }; + const derived: string[] = []; + for (const field of undeclaredIn(schema, opened)) { + const passed = isRecord(unopened) ? unopened[field] : stored[field]; + if (isSealed(passed)) current[field] = passed; + else if ( + holdsValue(opened[field]) && + JSON.stringify(passed) !== JSON.stringify(opened[field]) + ) { + derived.push(field); + } + } + return { current, derived }; +}; + +const withDerived = (marks: PersonalMarks, derived: readonly string[]): PersonalMarks => + derived.length === 0 + ? marks + : { + ...marks, + fields: [...marks.fields, ...derived], + categories: { + ...marks.categories, + ...Object.fromEntries(derived.map((field) => [field, DEFAULT_PERSONAL_CATEGORY])), + }, + }; + +const unopenedShape = (shape: () => unknown): unknown => { + try { + return shape(); + } catch { + return undefined; + } +}; + /** * For an event of a marked type stored in an older shape: every value it holds sealed is opened, * `null` when no key the person holds opens it any more, as the upcasts read it; the payload is * brought to its current shape, and what the marks of today name in it is sealed as the event * store seals it as it appends, under the person it was sealed for, or else the one the current - * shape names. `null` for any other event. + * shape names. Nothing it held sealed is written back in the clear under a key the current schema + * does not declare: an envelope the upcasts carried there keeps it, unopened, and a value they + * made there from an opened one is sealed in the default category. `null` for any other event. */ export const planUpcastReseal: PlanUpcastResealFunction = (args) => { const rewrite = rewriteOf(args); @@ -612,7 +703,7 @@ export const planUpcastReseal: PlanUpcastResealFunction = (args) => { marks.person === null ? event.aggregateId : isRecord(current) - ? personIn(current[marks.person]) + ? personNamedBy(current[marks.person]) : null; if (person === null) { return marked(current).length > 0 ? "unsealable" : { bare: current, schemaVersion }; @@ -630,13 +721,21 @@ export const planUpcastReseal: PlanUpcastResealFunction = (args) => { if (!isSealed(value) || stored === null) continue; stored[field] = (await open(value))?.value ?? null; } - const current = shaped(stored ?? event.payload); - const pending = marked(current); + const { current, derived } = undeclaredOf( + runtime.schema, + event.payload, + shaped(stored ?? event.payload), + unopenedShape(() => shaped(event.payload)), + ); + const sealing = withDerived(marks, derived); + const pending = isRecord(current) + ? sealing.fields.filter((field) => current[field] !== undefined) + : []; return { - categories: categoriesOf(marks, pending), + categories: categoriesOf(sealing, pending), movedFrom: [], seal: async (keyOf) => - isRecord(current) ? sealFields(current, marks, pending, named, keyOf) : current, + isRecord(current) ? sealFields(current, sealing, pending, named, keyOf) : current, }; }, }; diff --git a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts new file mode 100644 index 000000000..12895bbe7 --- /dev/null +++ b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts @@ -0,0 +1,674 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import type { Adapter } from "../../adapter/adapter.ts"; +import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; +import type { StoredEventTypeMarks } from "../../adapter/storage/event-store.ts"; +import { pendingEvent } from "../../adapter/testing/fixtures.ts"; +import type { Config } from "../../config/types.ts"; +import { createFixedClock } from "../../contracts/clock.ts"; +import { ConfigurationError } from "../../contracts/errors.ts"; +import type { StoredEvent } from "../../contracts/event.ts"; +import { createSequentialIdGenerator } from "../../contracts/ids.ts"; +import { silentLogger } from "../../contracts/logger.ts"; +import { memory } from "../../memory/index.ts"; +import { createMemoryTenantKeyStore } from "../../memory/tenant-key-store.ts"; +import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; +import type { Registry } from "../../modules/registry.ts"; +import { type BoundaApp, createApp } from "../app.ts"; +import { ledgerFor } from "../test-support.ts"; +import { categoryOf, isSealed } from "./crypto.ts"; +import type { ExportedEvent } from "./export.ts"; +import { RECORDED_PERSONAL_DATA } from "./ledger-in-force.ts"; +import { pruneTenantForgetLedger } from "./ledger-prune.ts"; +import { masterKey } from "./master-key.ts"; +import { defineTenantKeyStore } from "./tenant-key-source.ts"; +import { DEFAULT_TENANT } from "./tenant-keys.ts"; + +const START = new Date("2026-03-01T00:00:00.000Z"); + +// What a deploy marks of a note: nothing, the note in the default category or as an invoice, the +// note's field dropped from its schema by an upcast that keeps it, or the note's type retired. The +// email is always marked, so every note names its customer. +type Deploy = "clear" | "default" | "invoices" | "dropped" | "retired"; + +const personalData = { + automatedDecisions: {}, + categories: { + invoices: { + basis: "legal-obligation", + retention: "6y", + purposes: ["Bill the person"], + sources: ["data-subject"], + }, + }, +}; + +type Handler = (args: { + readonly command: { readonly payload: Record }; + readonly events: Record unknown>; +}) => unknown[]; + +const same = ({ state }: { readonly state: object }) => state; + +const command = (payload: (args: CommandPayloadArgs) => unknown, handler: Handler) => ({ + module: { payload, handler }, +}); + +const registerCustomer = command( + ({ z, notPersonal }) => + z.object({ customerId: notPersonal(z.string()), name: notPersonal(z.string()) }), + ({ command: { payload }, events }) => [events.customerRegistered?.({ name: payload.name })], +); + +const takeNote = command( + ({ z, notPersonal }) => + z.object({ + customerId: notPersonal(z.string()), + email: notPersonal(z.string()), + note: notPersonal(z.string()), + }), + ({ command: { payload }, events }) => [ + events.noteTaken?.({ email: payload.email, note: payload.note, topic: "support" }), + ], +); + +const noteOfDeploy = ({ z, personal, notPersonal }: EventPayloadArgs, deploy: Deploy) => { + if (deploy === "clear") return { note: notPersonal(z.string()) }; + if (deploy === "default") return { note: personal(z.string()) }; + if (deploy === "invoices") + return { note: personal(z.string(), { category: "invoices" as never }) }; + return {}; +}; + +const noteTaken = (deploy: Deploy) => ({ + payload: (args: EventPayloadArgs) => + args.z.object({ + email: args.personal(args.z.string()), + ...noteOfDeploy(args, deploy), + topic: args.notPersonal(args.z.string()), + }), + evolve: same, +}); + +// `ReminderSent` never had a module, and is retired in every deploy: only a store written past the +// runtime holds one. +const registryOf = (deploy: Deploy, declared = true): Registry => + ({ + ...(declared ? { personalData } : {}), + aggregates: { + customer: { + state: { initialState: {} }, + events: { + customerRegistered: { + payload: ({ z, notPersonal }: EventPayloadArgs) => + z.object({ name: notPersonal(z.string()) }), + evolve: same, + }, + ...(deploy === "retired" ? {} : { noteTaken: noteTaken(deploy) }), + }, + retired: { + reminderSent: { retired: true }, + ...(deploy === "retired" ? { noteTaken: { retired: true } } : {}), + }, + ...(deploy === "dropped" + ? { upcasts: { noteTaken: { upcasts: [(payload: object) => ({ ...payload })] } } } + : {}), + commands: { registerCustomer, ...(deploy === "retired" ? {} : { takeNote }) }, + policies: {}, + processes: {}, + }, + }, + readModels: {}, + }) as unknown as Registry; + +const stops: (() => Promise)[] = []; +const directories: string[] = []; + +afterEach(async () => { + for (const stop of stops.splice(0)) await stop(); + for (const directory of directories.splice(0)) rmSync(directory, { recursive: true }); +}); + +let starts = 0; + +const start = async (adapter: Adapter, deploy: Deploy) => { + starts += 1; + const app = await createApp({ + registry: registryOf(deploy), + config: { + storage: adapter, + runtime: { personalData: { forgetLedger: { store: ledgerFor(adapter) } } }, + }, + ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), + clock: createFixedClock(START), + logger: silentLogger, + }); + let stopped = false; + const stop = async (): Promise => { + if (stopped) return; + stopped = true; + await app.stop(); + }; + stops.unshift(stop); + return { app, stop }; +}; + +const send = (app: BoundaApp, type: string, payload: object) => + (app.commands as unknown as Record Promise>)[type]?.( + payload, + ); + +const note = (app: BoundaApp, customerId: string, text: string) => + send(app, "takeNote", { customerId, email: `${customerId}@example.com`, note: text }); + +const storageOf = (adapter: Adapter) => adapter.createStorage(); + +const setsOf = async (adapter: Adapter, type = "NoteTaken") => + (await (await storageOf(adapter)).eventStore.marksOf({ aggregateType: "customer", type })).map( + ({ marks }) => marks, + ); + +const notes = async (adapter: Adapter): Promise => + (await (await storageOf(adapter)).eventStore.readAll({ afterPosition: 0, limit: 100 })).filter( + ({ type }) => type === "NoteTaken", + ); + +const noteOf = (event: StoredEvent | undefined): unknown => + (event?.payload as { note?: unknown } | undefined)?.note; + +const shown = ({ type, data, categories, restricted, redacted }: ExportedEvent) => ({ + type, + data, + categories, + restricted, + redacted, +}); + +const exported = async (app: BoundaApp, customerId: string) => + (await app.exportPersonalData(customerId)).events + .filter(({ type }) => type === "NoteTaken") + .map(shown); + +const marks = (categories: Readonly>) => ({ + person: null, + fields: Object.keys(categories).sort(), + categories, +}); + +const emailOnly = marks({ email: "default" }); +const asInvoice = marks({ email: "default", note: "invoices" }); +const asDefault = marks({ email: "default", note: "default" }); + +const adapters: readonly [string, () => Adapter][] = [ + ["memory", () => memory()], + ["SQLite (node:sqlite)", () => createNodeSqliteAdapter().adapter], +]; + +describe.each(adapters)("the marks a start records, on %s", (_name, adapterOf) => { + it("records every event type's marks, one that marks nothing too, once per set however often it starts", async () => { + const adapter = adapterOf(); + await (await start(adapter, "clear")).stop(); + await (await start(adapter, "clear")).stop(); + const recorded = (sets: readonly StoredEventTypeMarks[]) => + sets + .filter(({ aggregateType }) => aggregateType === "customer") + .map(({ type, marks: set }) => [type, set]); + expect(recorded(await (await storageOf(adapter)).eventStore.marksOf())).toEqual([ + ["CustomerRegistered", null], + ["NoteTaken", emailOnly], + ]); + await (await start(adapter, "invoices")).stop(); + await (await start(adapter, "clear")).stop(); + await (await start(adapter, "invoices")).stop(); + expect(recorded(await (await storageOf(adapter)).eventStore.marksOf())).toEqual([ + ["CustomerRegistered", null], + ["NoteTaken", emailOnly], + ["NoteTaken", asInvoice], + ]); + }); + + it("seals a retired type's notes an older instance wrote in the clear after a newer one marked them, as the newer one marked them", async () => { + const adapter = adapterOf(); + const first = await start(adapter, "clear"); + await note(first.app, "c-1", "call after five"); + await first.stop(); + // The newer deploy starts, and stops before it walked a single event. + await (await start(adapter, "invoices")).stop(); + // An instance of the older one restarts after it, and writes another note in the clear. + const older = await start(adapter, "clear"); + await note(older.app, "c-2", "prefers email"); + await older.stop(); + expect(await setsOf(adapter)).toEqual([emailOnly, asInvoice]); + expect((await notes(adapter)).map(noteOf)).toEqual(["call after five", "prefers email"]); + + const retired = await start(adapter, "retired"); + await retired.app.runUntilIdle(); + + const sealed = await notes(adapter); + for (const [event, customer] of [ + [sealed[0], "c-1"], + [sealed[1], "c-2"], + ] as const) { + const value = noteOf(event); + expect(event?.person).toBe(customer); + expect(value).toMatchObject({ $personal: { person: customer } }); + expect(isSealed(value) && categoryOf(value)).toBe("invoices"); + expect(event?.payload).toMatchObject({ topic: "support" }); + } + expect(JSON.stringify(sealed)).not.toMatch(/call after five|prefers email/); + expect(await exported(retired.app, "c-2")).toEqual([ + { + type: "NoteTaken", + data: { email: "c-2@example.com", note: "prefers email" }, + categories: { email: "default", note: "invoices" }, + restricted: [], + redacted: [], + }, + ]); + }); + + it("seals what an older instance wrote after the newer one had walked every event, once the type is retired", async () => { + const adapter = adapterOf(); + const first = await start(adapter, "clear"); + await note(first.app, "c-1", "call after five"); + await first.stop(); + const newer = await start(adapter, "invoices"); + await newer.app.runUntilIdle(); + await newer.stop(); + expect(categoryOf(noteOf((await notes(adapter))[0]) as never)).toBe("invoices"); + const older = await start(adapter, "clear"); + await note(older.app, "c-2", "prefers email"); + await older.stop(); + + const retired = await start(adapter, "retired"); + await retired.app.runUntilIdle(); + + const [, late] = await notes(adapter); + expect(isSealed(noteOf(late))).toBe(true); + expect(categoryOf(noteOf(late) as never)).toBe("invoices"); + expect(await exported(retired.app, "c-2")).toEqual([ + expect.objectContaining({ + data: { email: "c-2@example.com", note: "prefers email" }, + categories: { email: "default", note: "invoices" }, + }), + ]); + }); + + it("seals, once marks went A, B and back to A, what B wrote in the clear as A marked it, A's set recorded once", async () => { + const adapter = adapterOf(); + const a = await start(adapter, "invoices"); + await note(a.app, "c-1", "call after five"); + await a.stop(); + const b = await start(adapter, "clear"); + await note(b.app, "c-2", "prefers email"); + await b.stop(); + await (await start(adapter, "invoices")).stop(); + expect(await setsOf(adapter)).toEqual([asInvoice, emailOnly]); + const [writtenByA] = await notes(adapter); + + const retired = await start(adapter, "retired"); + await retired.app.runUntilIdle(); + + const [first, second] = await notes(adapter); + expect(noteOf(first)).toEqual(noteOf(writtenByA)); + expect(categoryOf(noteOf(second) as never)).toBe("invoices"); + expect(await exported(retired.app, "c-2")).toEqual([ + expect.objectContaining({ + data: { email: "c-2@example.com", note: "prefers email" }, + categories: { email: "default", note: "invoices" }, + }), + ]); + }); + + it("exports and redacts a retired type's value still in the clear under the category its recorded marks give, before the walk seals it", async () => { + const adapter = adapterOf(); + const first = await start(adapter, "clear"); + await note(first.app, "c-1", "call after five"); + await note(first.app, "c-1", "prefers email"); + await first.stop(); + await (await start(adapter, "invoices")).stop(); + const { app } = await start(adapter, "retired"); + + expect(await exported(app, "c-1")).toEqual([ + { + type: "NoteTaken", + data: { email: "c-1@example.com", note: "call after five" }, + categories: { email: "default", note: "invoices" }, + restricted: [], + redacted: [], + }, + { + type: "NoteTaken", + data: { email: "c-1@example.com", note: "prefers email" }, + categories: { email: "default", note: "invoices" }, + restricted: [], + redacted: [], + }, + ]); + await app.restrict("c-1", { ground: "unlawful-processing", categories: ["invoices"] }); + const [, second] = await notes(adapter); + if (second === undefined) throw new Error("no second note"); + await app.redact("c-1", { + events: [ + { + id: second.id, + aggregateType: second.aggregateType, + aggregateId: second.aggregateId, + type: second.type, + fields: ["note"], + }, + ], + } as never); + await app.runUntilIdle(); + + expect(await exported(app, "c-1")).toEqual([ + { + type: "NoteTaken", + data: { email: "c-1@example.com", note: "call after five" }, + categories: { email: "default", note: "invoices" }, + restricted: ["note"], + redacted: [], + }, + { + type: "NoteTaken", + data: { email: "c-1@example.com", note: null }, + categories: { email: "default", note: "invoices" }, + restricted: ["note"], + redacted: ["note"], + }, + ]); + expect(JSON.stringify(await notes(adapter))).not.toMatch(/call after five|prefers email/); + }); + + it("refuses to retire a type the store holds events of that no start recorded marks for, naming it, until a start with its module", async () => { + const adapter = adapterOf(); + await (await storageOf(adapter)).eventStore.append({ + aggregateType: "customer", + aggregateId: "c-1", + expectedVersion: 0, + events: [ + pendingEvent({ + aggregateType: "customer", + aggregateId: "c-1", + version: 1, + type: "NoteTaken", + payload: { email: "c-1@example.com", note: "call after five", topic: "support" }, + }), + ], + }); + const refused = start(adapter, "retired"); + await expect(refused).rejects.toThrow(ConfigurationError); + await expect(refused).rejects.toThrow( + "The store holds events of retired types this code cannot seal:\n- customer.NoteTaken is retired, but no start recorded what it marks personal: deploy once with its module, on a tenant that is not frozen, then retire it", + ); + expect(await (await storageOf(adapter)).eventStore.marksOf()).toEqual([]); + + await (await start(adapter, "default")).stop(); + expect(await setsOf(adapter)).toEqual([asDefault]); + const { app } = await start(adapter, "retired"); + await app.runUntilIdle(); + expect(categoryOf(noteOf((await notes(adapter))[0]) as never)).toBe("default"); + }); + + it("refuses to prune the forget ledger of a store holding a retired type no start recorded marks for, as the start does", async () => { + const adapter = adapterOf(); + await (await storageOf(adapter)).eventStore.append({ + aggregateType: "customer", + aggregateId: "c-1", + expectedVersion: 0, + events: [ + pendingEvent({ + aggregateType: "customer", + aggregateId: "c-1", + version: 1, + type: "NoteTaken", + payload: { email: "c-1@example.com", note: "call after five", topic: "support" }, + }), + ], + }); + // An intention left in the ledger, which only the database tells whether it was applied. + await (await ledgerFor(adapter).createForgetLedger({ tenant: DEFAULT_TENANT })).append([ + { + personId: "c-1", + categories: null, + eventId: "e-c-1", + forgottenAt: START.toISOString(), + reason: "requested", + committed: false, + }, + ]); + const prune = () => + pruneTenantForgetLedger({ + logger: silentLogger, + registry: registryOf("retired"), + config: { + storage: adapter, + runtime: { + personalData: { forgetLedger: { store: ledgerFor(adapter), keepFor: "30d" } }, + }, + } as Config, + now: new Date(START.getTime() + 32 * 86_400_000), + }); + await expect(prune()).rejects.toThrow( + "customer.NoteTaken is retired, but no start recorded what it marks personal", + ); + await (await start(adapter, "default")).stop(); + await expect(prune()).resolves.toBeDefined(); + }); + + it("leaves a frozen tenant's store unwritten at start, recording the marks once it thaws", async () => { + const adapter = adapterOf(); + const first = await start(adapter, "clear"); + await first.app.freezeTenant(DEFAULT_TENANT); + await first.stop(); + + const frozen = await start(adapter, "invoices"); + expect(await setsOf(adapter)).toEqual([emailOnly]); + await frozen.app.runUntilIdle(); + expect(await setsOf(adapter)).toEqual([emailOnly]); + await frozen.app.unfreezeTenant(DEFAULT_TENANT); + await frozen.app.runUntilIdle(); + expect(await setsOf(adapter)).toEqual([emailOnly, asInvoice]); + }); + + it("records nothing on a forgotten tenant, nor refuses a retired type there that no start recorded marks for", async () => { + const adapter = adapterOf(); + const first = await start(adapter, "clear"); + await note(first.app, "c-1", "call after five"); + await (await storageOf(adapter)).eventStore.append({ + aggregateType: "customer", + aggregateId: "c-1", + expectedVersion: 1, + events: [ + pendingEvent({ + aggregateType: "customer", + aggregateId: "c-1", + version: 2, + type: "ReminderSent", + payload: { channel: "post" }, + }), + ], + }); + await first.app.forgetTenant(DEFAULT_TENANT, { despiteLegalObligations: true }); + await first.stop(); + const before = await (await storageOf(adapter)).eventStore.marksOf(); + + await (await start(adapter, "invoices")).stop(); + await (await start(adapter, "retired")).stop(); + expect(await (await storageOf(adapter)).eventStore.marksOf()).toEqual(before); + }); +}); + +describe.each(adapters)( + "an upcast that drops a sealed field from the schema, on %s", + (_name, adapterOf) => { + it("keeps the value it held sealed in its envelope, unopened, as it rewrites the event in its current shape", async () => { + const adapter = adapterOf(); + const first = await start(adapter, "invoices"); + await note(first.app, "c-1", "call after five"); + await first.stop(); + const [written] = await notes(adapter); + + const { app } = await start(adapter, "dropped"); + await app.runUntilIdle(); + + const [rewritten] = await notes(adapter); + expect(rewritten?.metadata.schemaVersion).toBe(2); + expect(noteOf(rewritten)).toEqual(noteOf(written)); + expect(isSealed((rewritten?.payload as { email?: unknown } | undefined)?.email)).toBe(true); + expect(JSON.stringify(rewritten)).not.toContain("call after five"); + expect(await exported(app, "c-1")).toEqual([ + expect.objectContaining({ + data: expect.objectContaining({ email: "c-1@example.com", note: "call after five" }), + categories: expect.objectContaining({ note: "invoices" }), + }), + ]); + }); + }, +); + +describe("an app whose only personal data is of a retired type", () => { + const env = { + BOUNDA_MASTER_KEY: Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64"), + }; + + const deployment = () => { + const directory = mkdtempSync(join(tmpdir(), "bounda-retired-marks-")); + directories.push(directory); + return { + file: join(directory, "store.db"), + tenantKeys: createMemoryTenantKeyStore(), + ledger: memory(), + }; + }; + + type Deployment = ReturnType; + + interface Keeps { + readonly keys: boolean; + readonly ledger: boolean; + } + + const startAt = async ( + at: Deployment, + deploy: Deploy, + keeps: Keeps = { keys: true, ledger: true }, + ) => { + starts += 1; + const sqlite = createNodeSqliteAdapter(at.file); + const close = () => { + if (sqlite.db.isOpen) sqlite.db.close(); + }; + try { + const app = await createApp({ + registry: registryOf(deploy, deploy !== "retired"), + config: { + storage: sqlite.adapter, + runtime: { + personalData: { + ...(keeps.keys + ? { + keyWrapper: masterKey({ from: "BOUNDA_MASTER_KEY" }), + tenantKeys: defineTenantKeyStore(() => at.tenantKeys), + } + : {}), + ...(keeps.ledger ? { forgetLedger: { store: at.ledger, keepFor: "30d" } } : {}), + }, + }, + } as Config, + env, + clock: createFixedClock(START), + ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), + logger: silentLogger, + }); + const stop = async () => { + await app.stop(); + close(); + }; + stops.unshift(stop); + return { app, stop, adapter: sqlite.adapter }; + } catch (error) { + close(); + throw error; + } + }; + + it("still needs keys and a forget ledger, which the registry alone no longer asks for, and forgets its person", async () => { + const at = deployment(); + const first = await startAt(at, "default"); + await note(first.app, "c-1", "call after five"); + await first.stop(); + + await expect(startAt(at, "retired", { keys: false, ledger: true })).rejects.toThrow( + "The registry marks personal fields, or an earlier deploy did for events the store holds, so runtime.personalData.keyWrapper must wrap their keys", + ); + await expect(startAt(at, "retired", { keys: true, ledger: false })).rejects.toThrow( + RECORDED_PERSONAL_DATA, + ); + + const { app, adapter } = await startAt(at, "retired"); + expect(await exported(app, "c-1")).toEqual([ + expect.objectContaining({ + data: { email: "c-1@example.com", note: "call after five" }, + categories: { email: "default", note: "default" }, + }), + ]); + await app.forget("c-1"); + await app.runUntilIdle(); + expect(await exported(app, "c-1")).toEqual([ + { + type: "NoteTaken", + data: { email: null, note: null }, + categories: { email: "default", note: "default" }, + restricted: [], + redacted: [], + }, + ]); + expect(JSON.stringify(await notes(adapter))).not.toContain("call after five"); + }); +}); + +// A begin-opened stream cannot be folded without the event that began it. +describe("retiring a type that opened streams of an aggregate whose state begin sets up", () => { + const ticketRegistry = (retired: boolean) => + ({ + aggregates: { + ticket: { + state: { initialState: { status: "none" } }, + events: { + ...(retired ? {} : { ticketOpened: { begin: () => ({ status: "open" }) } }), + ticketImported: { begin: () => ({ status: "imported" }) }, + }, + ...(retired ? { retired: { ticketOpened: { retired: true } } } : {}), + commands: { + openTicket: command( + ({ z, notPersonal }) => z.object({ ticketId: notPersonal(z.string()) }), + ({ events }) => [events.ticketOpened?.(undefined)], + ), + }, + policies: {}, + processes: {}, + }, + }, + readModels: {}, + }) as unknown as Registry; + + it("is refused at start, naming the type and keeping its module as the way out", async () => { + const adapter = memory(); + const opened = await createApp({ + registry: ticketRegistry(false), + config: { storage: adapter }, + }); + await send(opened, "openTicket", { ticketId: "t-1" }); + await opened.stop(); + const refused = createApp({ registry: ticketRegistry(true), config: { storage: adapter } }); + await expect(refused).rejects.toThrow(ConfigurationError); + await expect(refused).rejects.toThrow( + 'ticket.TicketOpened is retired, but it opened streams of "ticket", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep its module instead of retiring it', + ); + const kept = await createApp({ registry: ticketRegistry(false), config: { storage: adapter } }); + await kept.stop(); + }); +}); diff --git a/packages/core/src/kernel/personal-data/retired-personal-data-app.test.ts b/packages/core/src/kernel/personal-data/retired-personal-data-app.test.ts new file mode 100644 index 000000000..34465f607 --- /dev/null +++ b/packages/core/src/kernel/personal-data/retired-personal-data-app.test.ts @@ -0,0 +1,629 @@ +import { copyFileSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; +import type { ForgetLedgerEntry } from "../../adapter/storage/forget-ledger.ts"; +import type { Config } from "../../config/types.ts"; +import { createFixedClock } from "../../contracts/clock.ts"; +import { ConfigurationError, ValidationError } from "../../contracts/errors.ts"; +import type { StoredEvent } from "../../contracts/event.ts"; +import { createSequentialIdGenerator } from "../../contracts/ids.ts"; +import { silentLogger } from "../../contracts/logger.ts"; +import { memory } from "../../memory/index.ts"; +import { createMemoryTenantKeyStore } from "../../memory/tenant-key-store.ts"; +import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; +import type { Registry } from "../../modules/registry.ts"; +import { type BoundaApp, createApp } from "../app.ts"; +import type { ExportedEvent } from "./export.ts"; +import { pruneTenantForgetLedger } from "./ledger-prune.ts"; +import { masterKey } from "./master-key.ts"; +import type { TenantExportedEvent } from "./tenant-export.ts"; +import { defineTenantKeyStore } from "./tenant-key-source.ts"; +import { DEFAULT_TENANT } from "./tenant-keys.ts"; + +const START = new Date("2026-03-01T00:00:00.000Z"); +const DAY = 24 * 60 * 60_000; +const LATER = new Date(START.getTime() + 32 * DAY); + +const env = { + BOUNDA_MASTER_KEY: Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64"), +}; + +type Handler = (args: { + readonly command: { readonly payload: Record }; + readonly events: Record unknown>; +}) => unknown[]; + +const same = ({ state }: { readonly state: object }) => state; + +const command = (payload: (args: CommandPayloadArgs) => unknown, handler: Handler) => ({ + module: { payload, handler }, +}); + +const joinConversation = command( + ({ z, notPersonal }) => + z.object({ + conversationId: notPersonal(z.string()), + participantId: notPersonal(z.string()), + nickname: notPersonal(z.string()), + motto: notPersonal(z.string()), + }), + ({ command: { payload }, events }) => [ + events.participantJoined?.({ + participantId: payload.participantId, + nickname: payload.nickname, + motto: payload.motto, + }), + ], +); + +const postMessage = command( + ({ z, notPersonal }) => + z.object({ + conversationId: notPersonal(z.string()), + authorId: notPersonal(z.string()), + body: notPersonal(z.string()), + phone: notPersonal(z.string()).optional(), + topic: notPersonal(z.string()), + }), + ({ command: { payload }, events }) => [ + events.messagePosted?.({ + authorId: payload.authorId, + body: payload.body, + ...(payload.phone === undefined ? {} : { phone: payload.phone }), + topic: payload.topic, + }), + ], +); + +const personalData = { + automatedDecisions: {}, + categories: { + invoices: { + basis: "legal-obligation", + retention: "6y", + purposes: ["Bill the person"], + sources: ["data-subject"], + }, + }, +}; + +// A conversation whose participants post messages, each naming its author: the messages hold the +// author's body and phone, under two categories, and the topic in the clear. +const messagePosted = { + payload: ({ z, person, personal, notPersonal }: EventPayloadArgs) => + z.object({ + authorId: person(z.string()), + body: personal(z.string()), + phone: personal(z.string(), { category: "invoices" as never }).optional(), + topic: notPersonal(z.string()), + }), + evolve: same, +}; + +const participantJoined = (motto: "personal" | "notPersonal") => ({ + payload: (args: EventPayloadArgs) => + args.z.object({ + participantId: args.person(args.z.string()), + nickname: args.personal(args.z.string()), + motto: args[motto](args.z.string()), + }), + evolve: same, +}); + +const before = { + personalData, + aggregates: { + conversation: { + state: { initialState: {} }, + events: { participantJoined: participantJoined("personal"), messagePosted }, + commands: { joinConversation, postMessage }, + policies: {}, + processes: {}, + }, + }, + readModels: {}, +} as unknown as Registry; + +// Messages are no longer posted, and a participant's motto is no longer marked personal. +const retired = { + personalData, + aggregates: { + conversation: { + state: { initialState: {} }, + events: { participantJoined: participantJoined("notPersonal") }, + retired: { messagePosted: { retired: true } }, + commands: { joinConversation }, + policies: {}, + processes: {}, + }, + }, + readModels: {}, +} as unknown as Registry; + +// The app once the messages' module is deleted without retiring their type. +const dropped = { + ...retired, + aggregates: { conversation: { ...retired.aggregates.conversation, retired: undefined } }, +} as unknown as Registry; + +interface Deployment { + readonly file: string; + readonly copy: string; + readonly tenantKeys: ReturnType; + readonly ledger: ReturnType; +} + +const directories: string[] = []; +const stops: (() => Promise)[] = []; + +afterEach(async () => { + for (const stop of stops.splice(0)) await stop(); + for (const directory of directories.splice(0)) rmSync(directory, { recursive: true }); +}); + +const deployment = (): Deployment => { + const directory = mkdtempSync(join(tmpdir(), "bounda-retired-personal-")); + directories.push(directory); + return { + file: join(directory, "store.db"), + copy: join(directory, "copy.db"), + tenantKeys: createMemoryTenantKeyStore(), + ledger: memory(), + }; +}; + +// Every connection to a deployment's database is closed before a backup is copied over it. +const open = (at: Deployment) => { + const sqlite = createNodeSqliteAdapter(at.file); + let closed = false; + const close = () => { + if (closed) return; + closed = true; + if (sqlite.db.isOpen) sqlite.db.close(); + }; + stops.push(async () => close()); + return { ...sqlite, close }; +}; + +const configOf = (at: Deployment, storage: Config["storage"]): Config => + ({ + storage, + runtime: { + personalData: { + keyWrapper: masterKey({ from: "BOUNDA_MASTER_KEY" }), + tenantKeys: defineTenantKeyStore(() => at.tenantKeys), + forgetLedger: { store: at.ledger, keepFor: "30d" }, + }, + }, + }) as never; + +let starts = 0; + +// `pruneTenantForgetLedger` with the deployment's configuration, on a connection of its own. +const pruneWith = async (at: Deployment, registry: Registry) => { + const sqlite = open(at); + try { + return await pruneTenantForgetLedger({ + logger: silentLogger, + registry, + config: configOf(at, sqlite.adapter), + env, + now: LATER, + }); + } finally { + sqlite.close(); + } +}; + +// The app on the deployment's database; `stop` stops it and closes the database. +const start = async (at: Deployment, registry: Registry) => { + starts += 1; + const sqlite = open(at); + const app = await createApp({ + registry, + config: configOf(at, sqlite.adapter), + env, + clock: createFixedClock(START), + ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), + logger: silentLogger, + }); + let stopped = false; + const stop = async () => { + if (stopped) return; + stopped = true; + await app.stop(); + sqlite.close(); + }; + stops.unshift(stop); + return { app, db: sqlite.db, stop }; +}; + +const send = (app: BoundaApp, type: string, payload: object) => + (app.commands as unknown as Record Promise>)[type]?.( + payload, + ); + +// Ana joins and posts twice, the second time without a phone; Bo posts once in between. +const writeHistory = async (at: Deployment) => { + const { app, stop } = await start(at, before); + await send(app, "joinConversation", { + conversationId: "c-1", + participantId: "ana", + nickname: "Ana", + motto: "carpe diem", + }); + for (const [authorId, body, phone] of [ + ["ana", "hi from ana", "600 100 100"], + ["bo", "hi from bo", "600 200 200"], + ["ana", "see you", undefined], + ] as const) { + await send(app, "postMessage", { + conversationId: "c-1", + authorId, + body, + phone, + topic: "lunch", + }); + } + await app.runUntilIdle(); + const exported = { + ana: (await app.exportPersonalData("ana")).events.filter(inConversation), + bo: (await app.exportPersonalData("bo")).events.filter(inConversation), + }; + await stop(); + return exported; +}; + +const inConversation = ({ aggregateType }: { readonly aggregateType: string }) => + aggregateType === "conversation"; + +const messages = async (app: BoundaApp): Promise => + (await app.events.read({ limit: 100 })).filter(({ type }) => type === "MessagePosted"); + +const targetOf = (event: StoredEvent | undefined, fields: readonly string[]) => { + if (event === undefined) throw new Error("no such message"); + return { + id: event.id, + aggregateType: event.aggregateType, + aggregateId: event.aggregateId, + type: event.type, + fields: [...fields], + }; +}; + +const shown = ({ type, data, categories, restricted, redacted }: ExportedEvent) => ({ + type, + data, + categories, + restricted, + redacted, +}); + +const anaFirst = { + type: "MessagePosted", + data: { body: "hi from ana", phone: "600 100 100" }, + categories: { body: "default", phone: "invoices" }, + restricted: [], + redacted: [], +}; + +const anaJoined = { + type: "ParticipantJoined", + data: { nickname: "Ana", motto: "carpe diem" }, + categories: { nickname: "default", motto: "default" }, + restricted: [], + redacted: [], +}; + +describe("a retired event type's personal data", () => { + it("is exported to its person as their sealed fields and categories, as while the type was current, another person's left out", async () => { + const at = deployment(); + const current = await writeHistory(at); + const { app } = await start(at, retired); + + const ana = (await app.exportPersonalData("ana")).events.filter(inConversation); + const bo = (await app.exportPersonalData("bo")).events.filter(inConversation); + expect(ana).toEqual(current.ana); + expect(bo).toEqual(current.bo); + expect(ana.map(shown)).toEqual([ + anaJoined, + anaFirst, + { + type: "MessagePosted", + data: { body: "see you" }, + categories: { body: "default" }, + restricted: [], + redacted: [], + }, + ]); + expect(bo.map(shown)).toEqual([ + { + type: "MessagePosted", + data: { body: "hi from bo", phone: "600 200 200" }, + categories: { body: "default", phone: "invoices" }, + restricted: [], + redacted: [], + }, + ]); + }); + + it("is exported restricted by the category its envelope names, and redacted as the envelope says", async () => { + const at = deployment(); + await writeHistory(at); + const { app } = await start(at, retired); + const [, , seeYou] = await messages(app); + await app.restrict("ana", { ground: "unlawful-processing", categories: ["invoices"] }); + await app.redact("ana", { events: [targetOf(seeYou, ["body"])] } as never); + + const ana = (await app.exportPersonalData("ana")).events.filter(inConversation); + expect(ana.map(shown)).toEqual([ + anaJoined, + { ...anaFirst, restricted: ["phone"] }, + { + type: "MessagePosted", + data: { body: null }, + categories: { body: "default" }, + restricted: [], + redacted: ["body"], + }, + ]); + }); + + it("is listed in a tenant export with every field's category, restriction and redaction", async () => { + const at = deployment(); + await writeHistory(at); + const { app } = await start(at, retired); + const [, , seeYou] = await messages(app); + await app.restrict("ana", { ground: "unlawful-processing", categories: ["invoices"] }); + await app.redact("ana", { events: [targetOf(seeYou, ["body"])] } as never); + await app.freezeTenant(DEFAULT_TENANT); + + const events: TenantExportedEvent[] = []; + for await (const part of await app.exportTenant(DEFAULT_TENANT)) { + if (part.kind === "event" && part.event.aggregateType === "conversation") { + events.push(part.event); + } + } + expect( + events.map(({ type, person, payload, categories, restricted, redacted }) => ({ + type, + person, + payload, + categories, + restricted, + redacted, + })), + ).toEqual([ + { + type: "ParticipantJoined", + person: "ana", + payload: { participantId: "ana", nickname: "Ana", motto: "carpe diem" }, + categories: { nickname: "default", motto: "default" }, + restricted: [], + redacted: [], + }, + { + type: "MessagePosted", + person: "ana", + payload: { authorId: "ana", body: "hi from ana", phone: "600 100 100", topic: "lunch" }, + categories: { body: "default", phone: "invoices" }, + restricted: ["phone"], + redacted: [], + }, + { + type: "MessagePosted", + person: "bo", + payload: { authorId: "bo", body: "hi from bo", phone: "600 200 200", topic: "lunch" }, + categories: { body: "default", phone: "invoices" }, + restricted: [], + redacted: [], + }, + { + type: "MessagePosted", + person: "ana", + payload: { authorId: "ana", body: null, topic: "lunch" }, + categories: { body: "default" }, + restricted: [], + redacted: ["body"], + }, + ]); + }); + + it("is redacted where the stored event holds it sealed for the person, under the category its envelope names", async () => { + const at = deployment(); + await writeHistory(at); + const { app } = await start(at, retired); + const [first] = await messages(app); + + const dispatch = await app.redact("ana", { + events: [targetOf(first, ["phone", "body"])], + } as never); + const [redaction] = (await app.events.read({ limit: 100 })).filter( + ({ id }) => id === dispatch.eventIds[0], + ); + expect(redaction?.payload).toMatchObject({ + personId: "ana", + events: [targetOf(first, ["phone", "body"])], + categories: ["default", "invoices"], + }); + const [exported] = (await app.exportPersonalData("ana")).events.filter( + ({ type }) => type === "MessagePosted", + ); + expect(exported && shown(exported)).toEqual({ + ...anaFirst, + data: { body: null, phone: null }, + redacted: ["body", "phone"], + }); + }); + + it("refuses a field the stored event holds in the clear, or not at all, and an event of another person", async () => { + const at = deployment(); + await writeHistory(at); + const { app } = await start(at, retired); + const [first, bos, seeYou] = await messages(app); + + for (const [target, why] of [ + [targetOf(first, ["body", "topic"]), 'it holds "topic" in the clear'], + [targetOf(seeYou, ["phone"]), 'it holds no "phone"'], + [targetOf(bos, ["body"]), "it does not name the person ana"], + ] as const) { + const refused = app.redact("ana", { events: [target] } as never); + await expect(refused).rejects.toThrow(ValidationError); + await expect(refused).rejects.toThrow(`redact cannot reach the event ${target.id}: ${why}`); + } + expect((await app.events.read({ limit: 100 })).map(({ type }) => type)).not.toContain( + "PersonalDataRedacted", + ); + const ana = (await app.exportPersonalData("ana")).events.filter(inConversation); + expect(ana.map(shown)[1]).toEqual(anaFirst); + }); + + it("is redacted again by the reconciliation once a backup from before the redaction is restored", async () => { + const at = deployment(); + await writeHistory(at); + const first = await start(at, retired); + first.db.exec(`VACUUM INTO '${at.copy}'`); + const [message] = await messages(first.app); + const redacted = await first.app.redact("ana", { + events: [targetOf(message, ["body", "phone"])], + } as never); + await first.app.runUntilIdle(); + await first.stop(); + copyFileSync(at.copy, at.file); + + const { app } = await start(at, retired); + await app.runUntilIdle(); + const events = await app.events.read({ limit: 100 }); + expect(events.filter(({ type }) => type === "PersonalDataRedacted")).toMatchObject([ + { id: redacted.eventIds[0] }, + ]); + const ana = (await app.exportPersonalData("ana")).events.filter(inConversation); + expect(ana.map(shown)[1]).toEqual({ + ...anaFirst, + data: { body: null, phone: null }, + redacted: ["body", "phone"], + }); + }); + + it("is redacted again by the reconciliation in a field its type no longer marks, once a backup from before the redaction is restored", async () => { + const at = deployment(); + await writeHistory(at); + const marked = await start(at, before); + marked.db.exec(`VACUUM INTO '${at.copy}'`); + const [joined] = (await marked.app.events.read({ limit: 100 })).filter( + ({ type }) => type === "ParticipantJoined", + ); + await marked.app.redact("ana", { events: [targetOf(joined, ["motto"])] } as never); + await marked.app.runUntilIdle(); + await marked.stop(); + copyFileSync(at.copy, at.file); + + const { app } = await start(at, retired); + await app.runUntilIdle(); + const [exported] = (await app.exportPersonalData("ana")).events.filter(inConversation); + expect(exported && shown(exported)).toEqual({ + ...anaJoined, + data: { nickname: "Ana", motto: null }, + redacted: ["motto"], + }); + }); + + it("keeps a redaction's intention in the forget ledger while it would seal a field, and lets the prune remove it once redacted", async () => { + const at = deployment(); + await writeHistory(at); + const { app, stop } = await start(at, retired); + const [message] = await messages(app); + const target = targetOf(message, ["body"]); + const ledger = await at.ledger.createForgetLedger({ tenant: DEFAULT_TENANT }); + const intention: ForgetLedgerEntry = { + personId: "ana", + categories: null, + eventId: "redaction-ana", + forgottenAt: START.toISOString(), + reason: "requested", + committed: false, + redaction: { events: [target] }, + }; + await ledger.append([intention]); + await stop(); + const prune = () => pruneWith(at, retired); + expect(await prune()).toMatchObject({ before: START.toISOString(), unapplied: true }); + + const again = await start(at, retired); + await again.app.redact("ana", { events: [target] } as never); + await again.app.runUntilIdle(); + await again.stop(); + expect(await prune()).toMatchObject({ unapplied: false }); + expect((await ledger.read({ limit: 100 })).map(({ eventId }) => eventId)).not.toContain( + "redaction-ana", + ); + }); + + it("lets the prune of the forget ledger read the store with the type retired, which it refuses with the module deleted, naming the type", async () => { + const at = deployment(); + await writeHistory(at); + // An intention whose commit never happened, which only the store can tell applies or not. + const ledger = await at.ledger.createForgetLedger({ tenant: DEFAULT_TENANT }); + await ledger.append([ + { + personId: "ana", + categories: null, + eventId: "redaction-lost", + forgottenAt: START.toISOString(), + reason: "requested", + committed: false, + redaction: { + events: [ + { + id: "lost", + aggregateType: "conversation", + aggregateId: "c-1", + type: "MessagePosted", + fields: ["body"], + }, + ], + }, + }, + ]); + const prune = (registry: Registry) => pruneWith(at, registry); + const refused = prune(dropped); + await expect(refused).rejects.toThrow(ConfigurationError); + await expect(refused).rejects.toThrow( + 'conversation.MessagePosted: no module of the aggregate "conversation" names it', + ); + await expect(prune(retired)).resolves.toMatchObject({ unapplied: false }); + expect(await ledger.read({ limit: 100 })).toEqual([]); + }); + + it("is redacted again when an instance not yet upgraded writes an old value after the redaction", async () => { + const at = deployment(); + await writeHistory(at); + const upgraded = await start(at, retired); + const [message] = await messages(upgraded.app); + await upgraded.app.redact("ana", { events: [targetOf(message, ["body"])] } as never); + const old = await start(at, before); + await send(old.app, "postMessage", { + conversationId: "c-1", + authorId: "ana", + body: "hi from ana", + topic: "dinner", + }); + await old.stop(); + + await upgraded.app.runUntilIdle(); + const ana = (await upgraded.app.exportPersonalData("ana")).events.filter(inConversation); + expect(ana.map(shown).slice(1)).toEqual([ + { ...anaFirst, data: { body: null, phone: "600 100 100" }, redacted: ["body"] }, + expect.objectContaining({ data: { body: "see you" } }), + { + type: "MessagePosted", + data: { body: null }, + categories: { body: "default" }, + restricted: [], + redacted: ["body"], + }, + ]); + }); +}); diff --git a/packages/core/src/kernel/personal-data/schema-ahead-readers.test.ts b/packages/core/src/kernel/personal-data/schema-ahead-readers.test.ts index 5cec243b0..49cb7f65e 100644 --- a/packages/core/src/kernel/personal-data/schema-ahead-readers.test.ts +++ b/packages/core/src/kernel/personal-data/schema-ahead-readers.test.ts @@ -94,6 +94,7 @@ describe("the runtime's work on a person's data", () => { aggregateType: "customer", type: "CustomerRegistered", schemaVersion: 2, + opened: true, }); expect((await app.exportPersonalData("c-1")).events[0]?.data).toEqual({ email: "c-1@example.com", diff --git a/packages/core/src/kernel/personal-data/stored-marks.test.ts b/packages/core/src/kernel/personal-data/stored-marks.test.ts new file mode 100644 index 000000000..62b93b1a2 --- /dev/null +++ b/packages/core/src/kernel/personal-data/stored-marks.test.ts @@ -0,0 +1,244 @@ +import { describe, expect, it } from "vitest"; +import type { StoredEventTypeMarks } from "../../adapter/storage/event-store.ts"; +import { DEFAULT_PERSONAL_CATEGORY } from "../../adapter/storage/personal-key-store.ts"; +import type { StoredEvent } from "../../contracts/event.ts"; +import type { AggregatesRuntime } from "../aggregate/runtime.ts"; +import type { PersonalMarks } from "./marks.ts"; +import { + currentMarkSets, + eventMarksOf, + marksSetFingerprint, + NO_STORED_MARKS, + retiredMarksOf, + storedMarksOf, +} from "./stored-marks.ts"; + +const set = ( + person: string | null, + categories: Readonly>, +): PersonalMarks => ({ person, fields: Object.keys(categories), categories }); + +const stored = ( + type: string, + marks: PersonalMarks | null, + aggregateType = "conversation", +): StoredEventTypeMarks => ({ + aggregateType, + type, + fingerprint: marksSetFingerprint(marks), + marks, + firstSeenAt: "2026-01-01T00:00:00.000Z", +}); + +const sealed = (person: string) => ({ + $personal: { person, category: DEFAULT_PERSONAL_CATEGORY, key: "k", iv: "i", data: "d" }, +}); + +const event = (payload: object, person: string | null = null): StoredEvent => ({ + id: "e-1", + aggregateType: "conversation", + aggregateId: "c-1", + version: 1, + position: 1, + type: "MessagePosted", + payload, + timestamp: "2026-01-01T00:00:00.000Z", + metadata: { correlationId: "c", causationId: "c", depth: 0, schemaVersion: 1, system: false }, + person, +}); + +describe("storedMarksOf", () => { + it("keeps every set of a type in the order recorded, apart from another type's of the same name elsewhere", () => { + const first = set(null, { body: "default" }); + const second = set("authorId", { body: "invoices" }); + const marks = storedMarksOf([ + stored("MessagePosted", first), + stored("MessagePosted", null, "inbox"), + stored("MessagePosted", second), + ]); + expect(marks.of("conversation", "MessagePosted")).toEqual([first, second]); + expect(marks.of("inbox", "MessagePosted")).toEqual([null]); + expect(marks.of("conversation", "Other")).toEqual([]); + }); + + it("tells whether a set marks a field personal, or only whom its events name, or nothing", () => { + const of = (marks: PersonalMarks | null) => storedMarksOf([stored("MessagePosted", marks)]); + expect(of(set(null, { body: "default" }))).toMatchObject({ + personalFields: true, + personalData: true, + }); + expect(of(set("authorId", {}))).toMatchObject({ personalFields: false, personalData: true }); + expect(of(null)).toMatchObject({ personalFields: false, personalData: false }); + expect(NO_STORED_MARKS).toMatchObject({ personalFields: false, personalData: false }); + expect(NO_STORED_MARKS.of("conversation", "MessagePosted")).toEqual([]); + }); +}); + +describe("marksSetFingerprint", () => { + it("is equal for equal marks in any order of fields, and tells a category, a person and no marks apart", () => { + const fingerprint = marksSetFingerprint(set(null, { body: "default", phone: "invoices" })); + expect(marksSetFingerprint(set(null, { phone: "invoices", body: "default" }))).toBe( + fingerprint, + ); + expect( + marksSetFingerprint({ + person: null, + fields: ["body", "phone"], + categories: { phone: "invoices" }, + }), + ).toBe(fingerprint); + const others = [ + marksSetFingerprint(set(null, { body: "invoices", phone: "invoices" })), + marksSetFingerprint(set("authorId", { body: "default", phone: "invoices" })), + marksSetFingerprint(set(null, {})), + marksSetFingerprint(null), + ]; + expect(new Set([fingerprint, ...others]).size).toBe(5); + }); +}); + +describe("currentMarkSets", () => { + it("lists every event type of every aggregate, one that marks nothing too, its fields sorted with their categories", () => { + const aggregates = { + byName: { + conversation: { + name: "conversation", + eventsByType: { + MessagePosted: { + type: "MessagePosted", + personal: { + person: "authorId", + fields: ["phone", "body"], + categories: { phone: "invoices" }, + }, + }, + ConversationOpened: { type: "ConversationOpened", personal: null }, + }, + }, + inbox: { name: "inbox", eventsByType: {} }, + }, + } as unknown as AggregatesRuntime; + expect(currentMarkSets(aggregates)).toEqual([ + { + aggregateType: "conversation", + type: "MessagePosted", + fingerprint: marksSetFingerprint(set("authorId", { body: "default", phone: "invoices" })), + marks: { + person: "authorId", + fields: ["body", "phone"], + categories: { body: DEFAULT_PERSONAL_CATEGORY, phone: "invoices" }, + }, + }, + { + aggregateType: "conversation", + type: "ConversationOpened", + fingerprint: marksSetFingerprint(null), + marks: null, + }, + ]); + }); +}); + +describe("retiredMarksOf", () => { + it("marks nothing of a type no set marked anything of", () => { + expect(retiredMarksOf({ sets: [], event: event({ body: "hi" }) })).toEqual({ + marks: null, + elsewhere: [], + }); + expect(retiredMarksOf({ sets: [null, null], event: event({ body: "hi" }) })).toEqual({ + marks: null, + elsewhere: [], + }); + }); + + it("marks every field any set marked, each in the category of the newest set that marks it, whatever order instances started in", () => { + const sets = [ + set(null, { body: "default" }), + null, + set(null, { body: "invoices", phone: "invoices" }), + set(null, { topic: "default" }), + ]; + expect(retiredMarksOf({ sets, event: event({ body: "hi", topic: "lunch" }) })).toEqual({ + marks: { + person: null, + fields: ["topic", "body", "phone"], + categories: { topic: "default", body: "invoices", phone: "invoices" }, + }, + elsewhere: [], + }); + }); + + it("keeps the category of the newest set when marks went A, B and back to A, since A's set was recorded once", () => { + const a = set(null, { body: "default" }); + const b = set(null, { body: "invoices" }); + expect(retiredMarksOf({ sets: [a, b], event: event({ body: "hi" }) }).marks).toEqual(b); + }); + + it("keeps the person the event names, and tells apart the fields a set marks for somebody else that hold a value in the clear", () => { + const sets = [ + set(null, { motto: "default" }), + set("authorId", { body: "default", phone: "invoices" }), + ]; + const payload = { authorId: "ana", body: "hi", phone: sealed("ana"), motto: "carpe diem" }; + expect(retiredMarksOf({ sets, event: event(payload, "ana") })).toEqual({ + marks: { + person: "authorId", + fields: ["body", "phone"], + categories: { body: "default", phone: "invoices" }, + }, + elsewhere: ["motto"], + }); + const sealedMotto = { ...payload, motto: sealed("c-1") }; + expect(retiredMarksOf({ sets, event: event(sealedMotto, "ana") }).elsewhere).toEqual([]); + const noMotto = { authorId: "ana", body: "hi", motto: null }; + expect(retiredMarksOf({ sets, event: event(noMotto, "ana") }).elsewhere).toEqual([]); + }); + + it("names, for an event stored naming nobody, the person of the newest set that names somebody", () => { + const sets = [set(null, { motto: "default" }), set("authorId", { body: "default" })]; + expect(retiredMarksOf({ sets, event: event({ body: "hi", motto: "carpe" }) })).toEqual({ + marks: { person: null, fields: ["motto"], categories: { motto: "default" } }, + elsewhere: ["body"], + }); + expect( + retiredMarksOf({ sets, event: event({ authorId: "bo", body: "hi", motto: "carpe" }) }), + ).toEqual({ + marks: { person: "authorId", fields: ["body"], categories: { body: "default" } }, + elsewhere: ["motto"], + }); + }); + + it("marks nothing of an event whose person no set names, leaving every clear field it marks elsewhere", () => { + const sets = [set("authorId", { body: "default" })]; + expect(retiredMarksOf({ sets, event: event({ authorId: "bo", body: "hi" }, "ana") })).toEqual({ + marks: null, + elsewhere: ["body"], + }); + }); +}); + +describe("eventMarksOf", () => { + const current = set("authorId", { body: "default" }); + const aggregates = { + byName: { + conversation: { + retired: new Set(["MessagePosted"]), + eventsByType: { ParticipantJoined: { personal: current } }, + }, + }, + storedMarks: storedMarksOf([stored("MessagePosted", set(null, { body: "invoices" }))]), + } as unknown as AggregatesRuntime; + + it("is the schema's marks for a current type, the stored sets' for a retired one, and none for a type or an aggregate the runtime does not know", () => { + expect( + eventMarksOf({ aggregates, event: { ...event({}), type: "ParticipantJoined" } }), + ).toEqual(current); + expect(eventMarksOf({ aggregates, event: event({ body: "hi" }) })).toEqual( + set(null, { body: "invoices" }), + ); + expect(eventMarksOf({ aggregates, event: { ...event({}), type: "Unknown" } })).toBeNull(); + expect( + eventMarksOf({ aggregates, event: { ...event({}), aggregateType: "elsewhere" } }), + ).toBeNull(); + }); +}); diff --git a/packages/core/src/kernel/personal-data/stored-marks.ts b/packages/core/src/kernel/personal-data/stored-marks.ts new file mode 100644 index 000000000..c49174590 --- /dev/null +++ b/packages/core/src/kernel/personal-data/stored-marks.ts @@ -0,0 +1,214 @@ +import type { + EventTypeMarks, + RecordedPersonalMarks, + StoredEventTypeMarks, +} from "../../adapter/storage/event-store.ts"; +import { DEFAULT_PERSONAL_CATEGORY } from "../../adapter/storage/personal-key-store.ts"; +import type { StoredEvent } from "../../contracts/event.ts"; +import type { AggregatesRuntime } from "../aggregate/runtime.ts"; +import { digest } from "../read-model/fingerprint.ts"; +import { isRecord } from "../shared/merge-fields.ts"; +import { isSealed } from "./crypto.ts"; +import { fieldCategory, type PersonalMarks, personNamedBy } from "./marks.ts"; + +/** + * The sets of marks the store recorded for event types, as a start read them. + */ +export interface StoredMarks { + /** + * Every set recorded for the type, in the order first recorded; `null` for one that marked + * nothing. + */ + of(aggregateType: string, type: string): readonly (PersonalMarks | null)[]; + /** + * Whether a set of any type marks a field `personal`: its events may hold values sealed under + * keys, whatever the registry marks now. + */ + readonly personalFields: boolean; + /** + * Whether a set of any type marks a field `personal` or `person`. + */ + readonly personalData: boolean; +} + +export const NO_STORED_MARKS: StoredMarks = { + of: () => [], + personalFields: false, + personalData: false, +}; + +export interface StoredMarksOfFunction { + (sets: readonly StoredEventTypeMarks[]): StoredMarks; +} + +export const storedMarksOf: StoredMarksOfFunction = (sets) => { + const byType = new Map(); + for (const { aggregateType, type, marks } of sets) { + const key = JSON.stringify([aggregateType, type]); + byType.set(key, [...(byType.get(key) ?? []), marks]); + } + return { + of: (aggregateType, type) => byType.get(JSON.stringify([aggregateType, type])) ?? [], + personalFields: sets.some(({ marks }) => (marks?.fields.length ?? 0) > 0), + personalData: sets.some(({ marks }) => marks !== null), + }; +}; + +export interface CanonicalMarksFunction { + (marks: PersonalMarks): readonly [string | null, readonly (string | readonly string[])[]]; +} + +/** + * The form that tells two sets of marks apart: whom they name and each field with its category, + * one of the default category named as it was before categories existed. + */ +export const canonicalMarks: CanonicalMarksFunction = (marks) => [ + marks.person, + [...marks.fields].sort().map((field) => { + const category = fieldCategory(marks, field); + return category === DEFAULT_PERSONAL_CATEGORY ? field : [field, category]; + }), +]; + +export interface MarksSetFingerprintFunction { + (marks: PersonalMarks | null): string; +} + +/** + * What `recordMarks` keys a type's set by: equal marks give equal fingerprints, and a type that + * marks nothing has one too. + */ +export const marksSetFingerprint: MarksSetFingerprintFunction = (marks) => + digest(JSON.stringify(marks === null ? null : canonicalMarks(marks))); + +const recorded = (marks: PersonalMarks | null): RecordedPersonalMarks | null => { + if (marks === null) return null; + const fields = [...marks.fields].sort(); + return { + person: marks.person, + fields, + categories: Object.fromEntries(fields.map((field) => [field, fieldCategory(marks, field)])), + }; +}; + +export interface CurrentMarkSetsFunction { + (aggregates: AggregatesRuntime): readonly EventTypeMarks[]; +} + +/** + * The set of marks every event type of the registry has, one that marks nothing included: what a + * start records. + */ +export const currentMarkSets: CurrentMarkSetsFunction = (aggregates) => + Object.values(aggregates.byName).flatMap((aggregate) => + Object.values(aggregate.eventsByType).map((event) => ({ + aggregateType: aggregate.name, + type: event.type, + fingerprint: marksSetFingerprint(event.personal), + marks: recorded(event.personal), + })), + ); + +export interface WithStoredMarksFunction { + (aggregates: AggregatesRuntime, sets: readonly StoredEventTypeMarks[]): AggregatesRuntime; +} + +export const withStoredMarks: WithStoredMarksFunction = (aggregates, sets) => ({ + ...aggregates, + storedMarks: storedMarksOf(sets), +}); + +/** + * What the sets recorded for a retired type mark of one of its events: `marks`, under the one + * person the event names, and `elsewhere`, the fields a set marks for another person, or for none, + * that hold a value in the clear. + */ +export interface RetiredMarks { + readonly marks: PersonalMarks | null; + readonly elsewhere: readonly string[]; +} + +export interface RetiredMarksOfArgs { + readonly sets: readonly (PersonalMarks | null)[]; + /** + * As the store holds it, or as it was handed out: its person field is never sealed. + */ + readonly event: StoredEvent; +} + +export interface RetiredMarksOfFunction { + (args: RetiredMarksOfArgs): RetiredMarks; +} + +const merged = (sets: readonly PersonalMarks[]): PersonalMarks => { + const fields: string[] = []; + const categories: Record = {}; + for (const set of sets) { + for (const field of set.fields) { + if (fields.includes(field)) continue; + fields.push(field); + categories[field] = fieldCategory(set, field); + } + } + return { person: sets[0]?.person ?? null, fields, categories }; +}; + +/** + * Every set counts, so none is lost to the order instances started in. The event keeps the one + * person it names, or else the one the newest set that names somebody names; a field takes its + * category from the newest set that marks it for that person, since the order sets were recorded + * in is the order deploys rolled forward in. `marks.person` is the field of the newest of them. + */ +export const retiredMarksOf: RetiredMarksOfFunction = ({ sets, event }) => { + const newestFirst = sets.filter((set) => set !== null).reverse(); + if (newestFirst.length === 0) return { marks: null, elsewhere: [] }; + const payload = isRecord(event.payload) ? event.payload : {}; + const named = (set: PersonalMarks): string | null => + set.person === null ? event.aggregateId : personNamedBy(payload[set.person]); + const person = + event.person ?? newestFirst.map(named).find((candidate) => candidate !== null) ?? null; + if (person === null) return { marks: merged(newestFirst), elsewhere: [] }; + const own = newestFirst.filter((set) => named(set) === person); + const marks = own.length === 0 ? null : merged(own); + const elsewhere = [ + ...new Set( + newestFirst + .filter((set) => !own.includes(set)) + .flatMap((set) => set.fields) + .filter( + (field) => + marks?.fields.includes(field) !== true && + payload[field] !== undefined && + payload[field] !== null && + !isSealed(payload[field]), + ), + ), + ]; + return { marks, elsewhere }; +}; + +export interface EventMarksOfArgs { + readonly aggregates: AggregatesRuntime; + readonly event: StoredEvent; +} + +export interface EventMarksOfFunction { + (args: EventMarksOfArgs): PersonalMarks | null; +} + +/** + * What an event's type marks of it: its schema's marks, or, for a type its aggregate retired, what + * the sets the store recorded for it mark of this event; `null` for one of an aggregate the + * runtime does not know. + */ +export const eventMarksOf: EventMarksOfFunction = ({ aggregates, event }) => { + const aggregate = aggregates.byName[event.aggregateType]; + if (aggregate === undefined) return null; + if (aggregate.retired.has(event.type)) { + return retiredMarksOf({ + sets: aggregates.storedMarks.of(event.aggregateType, event.type), + event, + }).marks; + } + return aggregate.eventsByType[event.type]?.personal ?? null; +}; diff --git a/packages/core/src/kernel/personal-data/stranded.ts b/packages/core/src/kernel/personal-data/stranded.ts index 49f056032..bb6196b65 100644 --- a/packages/core/src/kernel/personal-data/stranded.ts +++ b/packages/core/src/kernel/personal-data/stranded.ts @@ -17,6 +17,7 @@ import { reconciliationRulesOf, refused, strandedEntries, + withRecordedMarks, withTenantStorage, } from "./ledger-prune.ts"; import { eitherReads, type ReconciledReads, reconciledReadsOf } from "./reconciled-reads.ts"; @@ -148,8 +149,11 @@ export const listStrandedForgetLedgerEntries: ListStrandedForgetLedgerEntriesFun config: tenantConfig, env, tenant, - aggregates: () => { - rules ??= reconciliationRulesOf({ registry, config: resolved }); + aggregates: (marks) => { + rules = withRecordedMarks( + rules ?? reconciliationRulesOf({ registry, config: resolved }), + marks, + ); return rules.aggregates; }, work: async (database) => { diff --git a/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts b/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts index 2a8648407..82eb4a23d 100644 --- a/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts +++ b/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts @@ -5,6 +5,7 @@ import { pendingEvent, testContext, testDeadLetter } from "../../adapter/testing import { resolveConfig } from "../../config/schema.ts"; import { createFixedClock } from "../../contracts/clock.ts"; import { ConcurrencyError } from "../../contracts/errors.ts"; +import type { StoredEvent } from "../../contracts/event.ts"; import { silentLogger } from "../../contracts/logger.ts"; import { memory } from "../../memory/index.ts"; import { type ExportOutcome, MAX_ACCESS_PERSONS } from "../../modules/audit.ts"; @@ -161,7 +162,9 @@ const setup = async () => { const written = await memory().createStorage(); const storage: AppStorage = appStorage({ // The kinds of event the store held when the app started, one whose module it no longer has. - stored: storedTypesOf([{ aggregateType: "order", type: "OrderShipped", schemaVersion: 1 }]), + stored: storedTypesOf([ + { aggregateType: "order", type: "OrderShipped", schemaVersion: 1, opened: false }, + ]), storage: written, aggregates, processes: { byName: {} }, @@ -423,6 +426,41 @@ describe("streamTenantExport", () => { ]); }); + it("restricts each field by the person its envelope names, as an event written past the runtime may hold values sealed for two persons", async () => { + const { exported, register, restrict, storage, written } = await setup(); + await register("c-1", "ana@example.com"); + await register("c-2", "bo@example.com"); + const [ana, bo] = await written.eventStore.readAll({ afterPosition: 0, limit: 10 }); + const envelope = (event: StoredEvent | undefined) => + (event?.payload as { email: unknown } | undefined)?.email; + await written.eventStore.append({ + aggregateType: "order", + aggregateId: "o-1", + expectedVersion: 0, + events: [ + pendingEvent({ + aggregateId: "o-1", + version: 1, + person: "c-1", + payload: { customerId: "c-1", contact: envelope(ana), gift: envelope(bo), total: 10 }, + }), + ], + }); + const order = async () => + of(await exported(), "event").find(({ event }) => event.aggregateType === "order")?.event; + expect(await order()).toMatchObject({ + person: "c-1", + payload: { contact: "ana@example.com", gift: "bo@example.com" }, + categories: { contact: "default", gift: "default" }, + restricted: [], + }); + await restrict("c-2", null); + expect((await order())?.restricted).toEqual(["gift"]); + await storage.persons.unrestrict("c-2", { categories: null }); + await restrict("c-1", null); + expect((await order())?.restricted).toEqual(["contact"]); + }); + it("names the fields of a process's lifecycle event its state marks, and none of a process it does not have", async () => { const { exported, written } = await setup(); for (const process of ["customer.watch", "customer.gone"]) { diff --git a/packages/core/src/kernel/personal-data/tenant-export-stream.ts b/packages/core/src/kernel/personal-data/tenant-export-stream.ts index cb98607e1..91b8440c6 100644 --- a/packages/core/src/kernel/personal-data/tenant-export-stream.ts +++ b/packages/core/src/kernel/personal-data/tenant-export-stream.ts @@ -27,13 +27,14 @@ import { openAnswer } from "./answers.ts"; import type { PersonalCategories } from "./categories.ts"; import { openCommandPayload, sealedKeys } from "./commands.ts"; import { openTextWith, textPersons } from "./errors.ts"; -import { openedUnder, redactedIn } from "./event-store.ts"; +import { type Envelopes, envelopesIn, openedUnder, redactedIn } from "./event-store.ts"; import type { ExportedCategories, ExportedRestricted, ExportedTransfer } from "./export.ts"; import { personalDataInformation } from "./information.ts"; import { FORGET_LEDGER_SUBSCRIBER } from "./ledger-outbox.ts"; import { fieldCategory, type PersonalMarks } from "./marks.ts"; import { lifecycleStateOf } from "./process-state.ts"; import { processingRestrictionsOf } from "./restriction.ts"; +import { eventMarksOf } from "./stored-marks.ts"; import { countTenantRecord, NO_TENANT_EXPORT_RECORDS, @@ -132,12 +133,21 @@ const NOT_RESTRICTED: PersonRestrictions = { whole: false, requested: new Set(), const TEXT_FIELDS = ["errorMessage", "errorStack"] as const; -const categoriesOf = (marks: PersonalMarks | null, payload: unknown): ExportedCategories => { - if (marks === null || !isRecord(payload)) return {}; +// What the marks name, and every other field the store held sealed, under the category its +// envelope names: a type retired, or a field no longer marked, still holds personal data. +const categoriesOf = ( + marks: PersonalMarks | null, + payload: unknown, + sealed: Envelopes = {}, +): ExportedCategories => { + if (!isRecord(payload)) return {}; + const categories: Record = {}; + if (marks !== null) { + for (const field of marks.fields) categories[field] = fieldCategory(marks, field); + } + for (const [field, { category }] of Object.entries(sealed)) categories[field] ??= category; return Object.fromEntries( - marks.fields - .filter((field) => payload[field] !== undefined) - .map((field) => [field, fieldCategory(marks, field)]), + Object.entries(categories).filter(([field]) => payload[field] !== undefined), ); }; @@ -316,18 +326,42 @@ export const streamTenantExport: StreamTenantExportFunction = async ({ person === null ? Promise.resolve(NOT_RESTRICTED) : restrictionsOf(person), ), ); + // Each field is restricted by the person its envelope names, else the event's: one event may hold + // values sealed for more than one person, as an envelope a payload carried in names another. + const eventRestricted = async ( + event: StoredEvent, + of: ExportedCategories, + restrictionsOf: (person: string) => Promise, + ): Promise => { + const envelopes = envelopesIn(event); + const ownerOf = (field: string): string | null => envelopes[field]?.person ?? event.person; + const owners = [...new Set(Object.keys(of).map(ownerOf))]; + const restrictions = await restrictionsOfAll(restrictionsOf, owners); + const opened = openedUnder(event); + return Object.entries(of) + .filter(([field, category]) => { + const owner = ownerOf(field); + const { whole, requested, kept } = restrictions[owners.indexOf(owner)] ?? NOT_RESTRICTED; + const retained = opened.some( + ({ person, retained: held }) => person === owner && held === true, + ); + return whole || requested.has(category) || (retained && kept.has(category)); + }) + .map(([field]) => field); + }; const commandMarks = (type: string): PersonalMarks | null => aggregates.commandsByType[type]?.command.personal ?? null; // A process's lifecycle event holds the fields its state marks, in that state. const eventCategories = (event: StoredEvent): ExportedCategories => { const process = processOfStream(event.aggregateType); if (process === null) { - const marks = aggregates.byName[event.aggregateType]?.eventsByType[event.type]?.personal; - return categoriesOf(marks ?? null, event.payload); + const marks = eventMarksOf({ aggregates, event }); + return categoriesOf(marks, event.payload, envelopesIn(event)); } return categoriesOf( processes.byName[process]?.personal ?? null, lifecycleStateOf(event.payload), + envelopesIn(event), ); }; @@ -401,8 +435,7 @@ export const streamTenantExport: StreamTenantExportFunction = async ({ const restrictionsOf = restrictionsOfPage(); yield await built(page, async (event) => { const of = eventCategories(event); - const restrictions = await restrictionsOfAll(restrictionsOf, [event.person]); - const kept = openedUnder(event).some(({ retained }) => retained === true); + const restricted = await eventRestricted(event, of, restrictionsOf); return { kind: "event", event: { @@ -417,7 +450,7 @@ export const streamTenantExport: StreamTenantExportFunction = async ({ person: event.person, payload: event.payload, categories: of, - restricted: restrictedOf(of, restrictions, kept), + restricted, redacted: redactedIn(event), }, }; diff --git a/packages/core/src/kernel/personal-data/tenant-keys-app.test.ts b/packages/core/src/kernel/personal-data/tenant-keys-app.test.ts index 72dae1b17..c5fba9d2a 100644 --- a/packages/core/src/kernel/personal-data/tenant-keys-app.test.ts +++ b/packages/core/src/kernel/personal-data/tenant-keys-app.test.ts @@ -416,7 +416,7 @@ describe("the keys of a tenant", () => { const store = createMemoryTenantKeyStore(); const env = { BOUNDA_MASTER_KEY: randomKey() }; await expect(start({ adapter })).rejects.toThrow( - 'The registry marks personal fields, so runtime.personalData.keyWrapper must wrap their keys: set masterKey({ from: "BOUNDA_MASTER_KEY" }) or a wrapper from defineKeyWrapper', + 'The registry marks personal fields, or an earlier deploy did for events the store holds, so runtime.personalData.keyWrapper must wrap their keys: set masterKey({ from: "BOUNDA_MASTER_KEY" }) or a wrapper from defineKeyWrapper', ); await expect( start({ diff --git a/packages/core/src/kernel/policy/build-policies.ts b/packages/core/src/kernel/policy/build-policies.ts index b6a30c3d9..66b34d4ab 100644 --- a/packages/core/src/kernel/policy/build-policies.ts +++ b/packages/core/src/kernel/policy/build-policies.ts @@ -5,7 +5,7 @@ import { policyTrigger } from "../../modules/naming.ts"; import { RESTRICTION_BASES, type RestrictionBasis } from "../../modules/personal-data.ts"; import type { PolicyModule } from "../../modules/policy.ts"; import type { Registry } from "../../modules/registry.ts"; -import { eventTypesOf } from "../../modules/validate.ts"; +import { eventTypesOf, retiredTypesOf } from "../../modules/validate.ts"; import type { AggregatesRuntime } from "../aggregate/runtime.ts"; import { qualifiedEventType } from "../shared/qualified-event.ts"; @@ -73,9 +73,17 @@ const triggersOf = ( ); } const types = eventTypesOf(registry.aggregates, source); + const retired = retiredTypesOf(registry.aggregates, source); const known = new Set(types); - const triggers = declaredTriggers(path, key, module, source, types); + // With the retired types, a name that ends with one resolves to it, to be refused, rather than + // to a shorter current type it also ends with. + const triggers = declaredTriggers(path, key, module, source, [...types, ...retired]); for (const trigger of triggers) { + if (retired.has(trigger)) { + throw new ConfigurationError( + `${path}: "${trigger}" is a retired event of the aggregate "${source}", which nothing reacts to`, + ); + } if (!known.has(trigger)) { throw new ConfigurationError( `${path}: "${trigger}" is not an event of the aggregate "${source}"`, diff --git a/packages/core/src/kernel/policy/delayed.ts b/packages/core/src/kernel/policy/delayed.ts index ec8de3d79..cebc3e83a 100644 --- a/packages/core/src/kernel/policy/delayed.ts +++ b/packages/core/src/kernel/policy/delayed.ts @@ -3,6 +3,7 @@ import type { ScheduledCommand, Scheduler } from "../../adapter/storage/schedule import type { ResolvedConfig, ResolvedRetryConfig } from "../../config/types.ts"; import { ConfigurationError, NotFoundError } from "../../contracts/errors.ts"; import type { StoredEvent } from "../../contracts/event.ts"; +import type { Logger } from "../../contracts/logger.ts"; import { causedBy } from "../shared/causation.ts"; import { runtimeText } from "../shared/runtime-text.ts"; import type { UnitOfWork } from "../unit-of-work/unit-of-work.ts"; @@ -73,7 +74,9 @@ export interface DelayedPolicies { isDelayedPolicy(entry: ScheduledCommand): boolean; /** * Runs the policy for `event`, as `eventOf` read it, on `within`, the worker's unit of work for - * the entry. A policy no longer in the registry or an event that is gone fails for good. + * the entry. A policy no longer in the registry or an event that is gone fails for good; a + * policy whose `on` no longer holds the event's type, retired or not, runs nothing, so the entry + * settles, with a warning. */ run(entry: ScheduledCommand, event: StoredEvent | undefined, within: UnitOfWork): Promise; /** @@ -95,6 +98,7 @@ export interface CreateDelayedPoliciesArgs { */ readonly eventStore: EventStore; readonly config: ResolvedConfig; + readonly logger: Logger; } export interface CreateDelayedPoliciesFunction { @@ -109,6 +113,7 @@ export const createDelayedPolicies: CreateDelayedPoliciesFunction = ({ executor, eventStore, config, + logger, }) => { const payloadOf = (entry: ScheduledCommand): DelayedPolicyPayload => entry.command.payload as DelayedPolicyPayload; @@ -144,6 +149,14 @@ export const createDelayedPolicies: CreateDelayedPoliciesFunction = ({ ), ); } + if (event.aggregateType !== policy.source || !policy.on.includes(event.type)) { + logger.warn("delayed policy run dropped: the policy no longer handles its event", { + policy: policy.name, + eventId: event.id, + eventType: `${event.aggregateType}.${event.type}`, + }); + return; + } await executor.run({ policy, event, attempt: entry.attempts + 1, within }); }, }; diff --git a/packages/core/src/kernel/policy/runner.test.ts b/packages/core/src/kernel/policy/runner.test.ts index a1065ac65..de6e3536e 100644 --- a/packages/core/src/kernel/policy/runner.test.ts +++ b/packages/core/src/kernel/policy/runner.test.ts @@ -915,6 +915,45 @@ describe("policies and the aggregate whose events they react to", () => { 'aggregates.order.policies.payOnOrderShipped: there is no aggregate "billing" whose events to react to', ); }); + + it("refuses a policy triggered by a retired event type, by its name or its on, even when its name ends with a current one too", () => { + const withPolicy = ( + key: string, + policy: Registry["aggregates"][string]["policies"][string], + ): Registry => ({ + ...twoAggregates, + aggregates: { + ...twoAggregates.aggregates, + order: { + ...orderAggregateEntry(), + retired: { orderPlacedAgain: { retired: true }, orderNoteAdded: { retired: true } }, + policies: { [key]: policy }, + }, + }, + }); + expect(() => + policiesOf(withPolicy("payOnOrderNoteAdded", { module: { handler: () => {} } })), + ).toThrow( + 'aggregates.order.policies.payOnOrderNoteAdded: "OrderNoteAdded" is a retired event of the aggregate "order", which nothing reacts to', + ); + expect(() => + policiesOf(withPolicy("payOnOrderPlacedAgain", { module: { handler: () => {} } })), + ).toThrow( + 'aggregates.order.policies.payOnOrderPlacedAgain: "OrderPlacedAgain" is a retired event of the aggregate "order", which nothing reacts to', + ); + expect(() => + policiesOf( + withPolicy("pay", { module: { on: ["OrderPlaced", "OrderNoteAdded"], handler: () => {} } }), + ), + ).toThrow( + 'aggregates.order.policies.pay: "OrderNoteAdded" is a retired event of the aggregate "order", which nothing reacts to', + ); + expect( + policiesOf(withPolicy("payOnOrderPlaced", { module: { handler: () => {} } })).byName[ + "order.payOnOrderPlaced" + ]?.on, + ).toEqual(["OrderPlaced"]); + }); }); describe("a policy run that fails", () => { diff --git a/packages/core/src/kernel/process/build-processes.ts b/packages/core/src/kernel/process/build-processes.ts index c6d435c75..f3db8f0ee 100644 --- a/packages/core/src/kernel/process/build-processes.ts +++ b/packages/core/src/kernel/process/build-processes.ts @@ -6,7 +6,7 @@ import type { StoredEvent } from "../../contracts/event.ts"; import { capitalize, toKebabCase } from "../../modules/naming.ts"; import type { RestrictionBasis } from "../../modules/personal-data.ts"; import type { ProcessCorrelation, ProcessEntry } from "../../modules/process.ts"; -import type { Registry } from "../../modules/registry.ts"; +import type { AggregateEntry, Registry } from "../../modules/registry.ts"; import type { AggregatesRuntime } from "../aggregate/runtime.ts"; import { type PersonalMarks, personalMarksOf } from "../personal-data/marks.ts"; import { holdsPersonalValue, statePersonOf } from "../personal-data/process-state.ts"; @@ -143,13 +143,23 @@ const compileDeadlines = ( ); }; +// The qualified event types of the app: those a process can name, and those the app retired. +interface KnownEvents { + readonly current: ReadonlySet; + readonly retired: ReadonlySet; +} + +const retiredEvent = (path: string, qualified: string): ConfigurationError => + new ConfigurationError(`${path}: "${qualified}" is a retired event, which nothing reacts to`); + const knownEvents = ( path: string, names: readonly string[], - known: ReadonlySet, + known: KnownEvents, ): ReadonlySet => { for (const name of names) { - if (!known.has(name)) { + if (known.retired.has(name)) throw retiredEvent(path, name); + if (!known.current.has(name)) { throw new ConfigurationError( `${path}: "${name}" is not an event of the app; name events as events..`, ); @@ -161,13 +171,16 @@ const knownEvents = ( const compileHandlers = ( path: string, entry: ProcessEntry, - known: ReadonlySet, + known: KnownEvents, ): ProcessRuntime["handlers"] => Object.fromEntries( Object.entries(entry.handlers).flatMap(([source, handlers]) => Object.entries(handlers).map(([eventKey, handler]) => { const qualified = qualifiedEventType(source, capitalize(eventKey)); - if (!known.has(qualified)) { + if (known.retired.has(qualified)) { + throw retiredEvent(`${path}.handlers.${source}.${eventKey}`, qualified); + } + if (!known.current.has(qualified)) { throw new ConfigurationError( `${path}.handlers.${source}.${eventKey}: "${qualified}" is not an event of the app`, ); @@ -187,6 +200,7 @@ const compileCorrelate = ( path: string, entry: ProcessEntry, events: AppEvents, + known: KnownEvents, ): Record => { const { correlate } = entry.module; if (correlate === undefined) return {}; @@ -225,6 +239,7 @@ const compileCorrelate = ( } const correlators: Record = {}; for (const { event, correlate: correlator } of declared) { + if (known.retired.has(event)) throw retiredEvent(`${path}.correlate`, event); if (correlators[event] !== undefined) { throw new ConfigurationError(`${path}.correlate: "${event}" is correlated twice`); } @@ -269,7 +284,7 @@ const buildProcess = ( key: string, entry: ProcessEntry, events: AppEvents, - known: ReadonlySet, + known: KnownEvents, config: ResolvedConfig, aggregates: AggregatesRuntime, ): ProcessRuntime => { @@ -284,7 +299,7 @@ const buildProcess = ( const startedBy = knownEvents(path, declared.startedBy, known); const completedBy = knownEvents(path, declared.completedBy ?? [], known); const handlers = compileHandlers(path, entry, known); - const correlate = compileCorrelate(path, entry, events); + const correlate = compileCorrelate(path, entry, events, known); const own = (qualified: string): boolean => qualified.startsWith(`${aggregate}.`); for (const qualified of new Set([...startedBy, ...completedBy, ...Object.keys(handlers)])) { if (own(qualified) || correlate[qualified] !== undefined) continue; @@ -347,18 +362,31 @@ export interface BuildProcessesFunction { * id field names, unless `correlate` says otherwise; one with neither is a configuration error. */ export const buildProcesses: BuildProcessesFunction = ({ registry, aggregates, config }) => { - const events = Object.fromEntries( - Object.entries(registry.aggregates).map(([aggregate, entry]) => [ + const qualified = (keys: (entry: AggregateEntry) => readonly string[]): AppEvents => + Object.fromEntries( + Object.entries(registry.aggregates).map(([aggregate, entry]) => [ + aggregate, + Object.fromEntries( + keys(entry).map((eventKey) => [ + capitalize(eventKey), + qualifiedEventType(aggregate, capitalize(eventKey)), + ]), + ), + ]), + ); + const typesOf = (events: AppEvents): ReadonlySet => + new Set(Object.values(events).flatMap((byType) => Object.values(byType))); + const current = qualified((entry) => Object.keys(entry.events)); + const retired = qualified((entry) => Object.keys(entry.retired ?? {})); + const known: KnownEvents = { current: typesOf(current), retired: typesOf(retired) }; + // A config that names a retired event, which typing keeps it from, is told it is retired rather + // than handed `undefined`. + const events: AppEvents = Object.fromEntries( + Object.entries(current).map(([aggregate, byType]) => [ aggregate, - Object.fromEntries( - Object.keys(entry.events).map((eventKey) => [ - capitalize(eventKey), - qualifiedEventType(aggregate, capitalize(eventKey)), - ]), - ), + { ...retired[aggregate], ...byType }, ]), ); - const known = new Set(Object.values(events).flatMap((byType) => Object.values(byType))); const all = Object.entries(registry.aggregates).flatMap(([aggregate, entry]) => Object.entries(entry.processes).map(([key, process]) => buildProcess(aggregate, key, process, events, known, config, aggregates), diff --git a/packages/core/src/kernel/process/dead-letter-retry.ts b/packages/core/src/kernel/process/dead-letter-retry.ts index e5cbf0c98..88106cb2e 100644 --- a/packages/core/src/kernel/process/dead-letter-retry.ts +++ b/packages/core/src/kernel/process/dead-letter-retry.ts @@ -45,6 +45,10 @@ export interface RetryProcessArgs extends RetryArgs { */ readonly process: string; readonly event: StoredEvent; + /** + * The instance the letter records; left out, the event is routed to one as on delivery. + */ + readonly instanceId?: string | undefined; /** * Who retries, who then acts in place of the event's actor. */ @@ -148,12 +152,13 @@ export const createProcessRetry: CreateProcessRetryFunction = ({ const retry = async ({ process: name, event, + instanceId: recorded, retryId, letter, actor, }: RetryProcessArgs): Promise => { const process = registered(processes, name); - const instanceId = process.instanceOf(event); + const instanceId = recorded ?? process.instanceOf(event); const instance = instanceId === null ? null : await load(process, instanceId); const failedHere = instance?.status === "failed" && @@ -278,7 +283,8 @@ export const createProcessRetry: CreateProcessRetryFunction = ({ const process = processes.byName[letter.handler]; if (letter.kind !== "process" || process === undefined) return null; const instanceId = - letter.eventType === PROCESS_DEADLINE_COMMAND + letter.instanceId ?? + (letter.eventType === PROCESS_DEADLINE_COMMAND ? letter.aggregateId : await units.live .parkedEvent({ @@ -288,7 +294,7 @@ export const createProcessRetry: CreateProcessRetryFunction = ({ aggregateId: letter.aggregateId, }) .then((event) => process.instanceOf(event)) - .catch(() => null); + .catch(() => null)); return instanceId === null ? null : { process, instanceId }; }; diff --git a/packages/core/src/kernel/process/failures.test.ts b/packages/core/src/kernel/process/failures.test.ts index d6b0cc2eb..d1059670d 100644 --- a/packages/core/src/kernel/process/failures.test.ts +++ b/packages/core/src/kernel/process/failures.test.ts @@ -64,6 +64,7 @@ const subject = { aggregateId: "o-1", person: null, statePerson: null, + instanceId: null, read: [], }; @@ -181,6 +182,21 @@ describe("letterOf", () => { expect(entries).toEqual([]); }); + it("records the instance the step ran for, so a retry never routes the event again", async () => { + const { failures } = await setup(); + const ran = await failures.letterOf( + orderPayment, + { ...subject, aggregateType: "payment", aggregateId: "p-1", instanceId: "o-1" }, + new Error("payment refused"), + 1, + "terminal", + ); + expect(ran).toMatchObject({ aggregateType: "payment", aggregateId: "p-1", instanceId: "o-1" }); + expect( + await failures.letterOf(orderPayment, subject, "no instance", 1, "terminal"), + ).not.toHaveProperty("instanceId"); + }); + it("gives every letter its own id and records what was thrown when it is no error, without a stack", async () => { const { failures, clock } = await setup(); await failures.letterOf(orderPayment, subject, "first", 1, "terminal"); @@ -351,6 +367,7 @@ describe("subjectOf an event on a loaded instance", () => { ...subject, person: "c-2", statePerson: null, + instanceId: "o-1", read: [held], }); expect( @@ -358,7 +375,13 @@ describe("subjectOf an event on a loaded instance", () => { instanceId: "o-1", instance: loaded, }), - ).toEqual({ ...subject, person: "c-1", statePerson: "c-2", read: [held] }); + ).toEqual({ + ...subject, + person: "c-1", + statePerson: "c-2", + instanceId: "o-1", + read: [held], + }); expect( failures.subjectOf(orderPayment, placed({ customerId: "c-1" }), { instanceId: "o-1", @@ -366,6 +389,7 @@ describe("subjectOf an event on a loaded instance", () => { }), ).toEqual({ ...subject, + instanceId: "o-1", read: [held], }); }); @@ -390,6 +414,7 @@ describe("deadlineSubject", () => { aggregateId: "o-1", person: null, statePerson: null, + instanceId: "o-1", read: [], }); }); diff --git a/packages/core/src/kernel/process/failures.ts b/packages/core/src/kernel/process/failures.ts index 4e272afc8..4880ce4b2 100644 --- a/packages/core/src/kernel/process/failures.ts +++ b/packages/core/src/kernel/process/failures.ts @@ -28,6 +28,8 @@ export interface FailureSubject extends Pick { readonly person: string | null; readonly statePerson: string | null; + // `null` for an event that belongs to no instance. + readonly instanceId: string | null; /** * What the event was handed out with opened, and the instance loaded with, so the letter is * sealed under no other key. @@ -93,6 +95,7 @@ export const createProcessFailures: CreateProcessFailuresFunction = ({ aggregateId: event.aggregateId, person, statePerson: ofState === person ? null : ofState, + instanceId: at?.instanceId ?? null, read: [...openedUnder(event), ...(at?.instance.persons ?? [])], }; }, @@ -110,6 +113,7 @@ export const createProcessFailures: CreateProcessFailuresFunction = ({ aggregateId: subject.aggregateId, person, ...(statePerson === null ? {} : { statePerson }), + ...(subject.instanceId === null ? {} : { instanceId: subject.instanceId }), errorType, ...(await sealError({ error, person, statePerson, keys, read: subject.read })), attempts, @@ -150,6 +154,7 @@ export const deadlineSubject: DeadlineSubjectFunction = (process, instanceId, fi aggregateId: instanceId, person: instancePersonOf(process, instanceId, instance), statePerson: null, + instanceId, read: instance.persons, }); diff --git a/packages/core/src/kernel/process/runner.test.ts b/packages/core/src/kernel/process/runner.test.ts index 6671f5442..2c8211686 100644 --- a/packages/core/src/kernel/process/runner.test.ts +++ b/packages/core/src/kernel/process/runner.test.ts @@ -200,6 +200,72 @@ describe("buildProcesses", () => { ); }); + it("refuses a retired event type wherever a process names it, as its config receives it too", () => { + const named = (process: Registry["aggregates"][string]["processes"][string]): Registry => ({ + aggregates: { + order: { + ...orderAggregateEntry(), + retired: { orderNoteAdded: { retired: true } }, + processes: { p: process }, + }, + }, + readModels: {}, + }); + const retired = '"order.OrderNoteAdded" is a retired event, which nothing reacts to'; + expect(() => + processesOf( + named({ + module: { + config: ({ events }: { events: Record> }) => ({ + startedBy: [events.order?.OrderNoteAdded], + }), + }, + handlers: {}, + } as never), + config, + ), + ).toThrow(`aggregates.order.processes.p: ${retired}`); + expect(() => + processesOf( + named({ + module: { + config: () => ({ + startedBy: ["order.OrderPlaced"], + completedBy: ["order.OrderNoteAdded"], + }), + }, + handlers: {}, + }), + config, + ), + ).toThrow(`aggregates.order.processes.p: ${retired}`); + expect(() => + processesOf( + named({ + module: { config: () => ({ startedBy: ["order.OrderPlaced"] }) }, + handlers: { order: { orderNoteAdded: { handler: () => ({}) } } }, + }), + config, + ), + ).toThrow(`aggregates.order.processes.p.handlers.order.orderNoteAdded: ${retired}`); + expect(() => + processesOf( + named({ + module: { + config: () => ({ startedBy: ["order.OrderPlaced"] }), + correlate: ({ + from, + }: { + from: Record unknown>>; + }) => [from.order?.OrderNoteAdded?.(() => null)], + }, + handlers: {}, + } as never), + config, + ), + ).toThrow(`aggregates.order.processes.p.correlate: ${retired}`); + }); + it("rejects unknown events and state schemas without defaults", () => { const badEvent: Registry = { aggregates: { diff --git a/packages/core/src/kernel/reactive-harness.ts b/packages/core/src/kernel/reactive-harness.ts index a1cfd7a14..89088c39e 100644 --- a/packages/core/src/kernel/reactive-harness.ts +++ b/packages/core/src/kernel/reactive-harness.ts @@ -218,6 +218,7 @@ export const createReactiveHarness: CreateReactiveHarnessFunction = async ({ executor: policyExecutor, eventStore: storage.eventStore, config, + logger, }), restrictedRetries: createRestrictedRetries({ storage, retries, clock, logger }), restores, diff --git a/packages/core/src/kernel/read-model/rebuild.ts b/packages/core/src/kernel/read-model/rebuild.ts index ed63f213d..026fa9126 100644 --- a/packages/core/src/kernel/read-model/rebuild.ts +++ b/packages/core/src/kernel/read-model/rebuild.ts @@ -17,7 +17,12 @@ import { validateRegistry } from "../../modules/validate.ts"; import { fieldBuilder } from "../../modules/view.ts"; import type { AppEnv } from "../../register/index.ts"; import { buildAggregates } from "../aggregate/build-aggregates.ts"; -import { checkStoredTypes, type StoredTypes } from "../aggregate/stored-types.ts"; +import type { AggregatesRuntime } from "../aggregate/runtime.ts"; +import { + checkRetiredMarks, + checkStoredTypes, + type StoredTypes, +} from "../aggregate/stored-types.ts"; import { PartialBatchError } from "../dispatch/delivery.ts"; import { appStorage } from "../events/app-event-store.ts"; import { epochMark, openDatabaseKey } from "../personal-data/blind-index.ts"; @@ -26,6 +31,7 @@ import { openEncryptedFiles } from "../personal-data/encrypted-files.ts"; import { keySourcesOf, openKeyHierarchy } from "../personal-data/key-hierarchy.ts"; import { buildKeyWrapper } from "../personal-data/key-wrapper.ts"; import { marksPersonalFields } from "../personal-data/marks.ts"; +import { withStoredMarks } from "../personal-data/stored-marks.ts"; import { keylessWrapping, type PersonalKeyWrapping } from "../personal-data/wrapped-keys.ts"; import { buildProcesses } from "../process/build-processes.ts"; import { projectBatch, projectionSubscriberName, withKeys } from "../projection/runner.ts"; @@ -268,7 +274,7 @@ export const rebuildReadModel: RebuildReadModelFunction = async ({ tenant, personal: marksPersonalFields({ - aggregates, + aggregates: withStoredMarks(aggregates, await storage.eventStore.marksOf()), processes: buildProcesses({ registry: args.registry, aggregates, config }), }) || readModelsMarkPersonal(args.registry), env, @@ -306,6 +312,20 @@ export interface RebuildReadModelWithArgs extends Omit => { + const types = await storage.eventStore.types(); + const stored = checkStoredTypes({ types, aggregates }); + checkRetiredMarks({ + types, + aggregates: withStoredMarks(aggregates, await storage.eventStore.marksOf()), + }); + return stored; +}; + export interface RebuildReadModelWithFunction { (args: RebuildReadModelWithArgs): Promise; } @@ -355,7 +375,7 @@ export const rebuildReadModelWith: RebuildReadModelWithFunction = async ({ aggregates, processes: { byName: {} }, wrapping, - stored: started ?? checkStoredTypes({ types: await storage.eventStore.types(), aggregates }), + stored: started ?? (await checkedTypes(storage, aggregates)), }); const layout = sealedLayoutOf({ readModel: name, diff --git a/packages/core/src/kernel/retired-events-app.test.ts b/packages/core/src/kernel/retired-events-app.test.ts new file mode 100644 index 000000000..b5ebe2cbf --- /dev/null +++ b/packages/core/src/kernel/retired-events-app.test.ts @@ -0,0 +1,436 @@ +import { afterEach, describe, expect, it } from "vitest"; +import type { Adapter } from "../adapter/adapter.ts"; +import type { Table } from "../adapter/storage/table.ts"; +import { pendingEvent } from "../adapter/testing/fixtures.ts"; +import type { RuntimeConfig } from "../config/types.ts"; +import { createFixedClock } from "../contracts/clock.ts"; +import { ConfigurationError, ValidationError } from "../contracts/errors.ts"; +import type { StoredEvent } from "../contracts/event.ts"; +import { createSequentialIdGenerator } from "../contracts/ids.ts"; +import { silentLogger } from "../contracts/logger.ts"; +import { memory } from "../memory/index.ts"; +import type { CommandPayloadArgs, EventPayloadArgs } from "../modules/payload.ts"; +import type { Registry } from "../modules/registry.ts"; +import type { FieldsArgs } from "../modules/view.ts"; +import { type BoundaApp, createApp } from "./app.ts"; +import { PROCESS_EVENTS } from "./process/lifecycle.ts"; +import { rebuildReadModel } from "./read-model/rebuild.ts"; +import { createRecordingLogger, ledgerFor } from "./test-support.ts"; + +interface OrderState { + readonly status: string; + readonly note: string | null; +} + +interface OrderRow { + readonly orderId: string; + readonly status: string; +} + +interface HandlerArgs { + readonly event: StoredEvent; + readonly state: OrderState; + readonly command: { readonly aggregateId: string; readonly payload: Record }; + readonly events: Record unknown>; +} + +const START = new Date("2026-06-01T00:00:00.000Z"); +const HOUR = 3_600_000; + +const ran: string[] = []; +let failing = false; + +const policy = (name: string, on?: string) => ({ + module: { + ...(on === undefined ? {} : { on }), + delay: "1h", + handler: ({ event }: HandlerArgs) => { + ran.push(`${name}:${event.type}`); + }, + }, +}); + +const status = + (value: string) => + async ({ event, table }: { event: StoredEvent; table: Table }) => { + await table.upsert({ orderId: event.aggregateId, status: value }); + }; + +const orderEvents = { + orderPlaced: { + begin: () => ({ status: "placed" }), + }, + orderPaid: { + evolve: ({ state }: HandlerArgs) => ({ ...state, status: "paid" }), + }, +}; + +const orderCommands = { + placeOrder: { + module: { + payload: ({ z, notPersonal }: CommandPayloadArgs) => + z.object({ orderId: notPersonal(z.string()) }), + handler: ({ events }: HandlerArgs) => [events.orderPlaced?.()], + }, + }, + payOrder: { + module: { + payload: ({ z, notPersonal }: CommandPayloadArgs) => + z.object({ orderId: notPersonal(z.string()) }), + handler: ({ events, state }: HandlerArgs) => { + if (state.status !== "placed") throw new ValidationError(`order is ${state.status}`, []); + return [events.orderPaid?.()]; + }, + }, + }, +}; + +const fulfilment = (paymentHandlers: Record) => ({ + module: { + config: ({ events }: { events: Record> }) => ({ + startedBy: [events.order?.OrderPlaced], + timeout: "30d", + }), + }, + handlers: { + order: { + orderPlaced: { handler: ({ state }: HandlerArgs) => state }, + orderPaid: { handler: ({ state }: HandlerArgs) => state }, + }, + payment: paymentHandlers, + }, +}); + +const payment = (events: Record, retired?: Record) => ({ + events, + ...(retired === undefined ? {} : { retired }), + commands: { + capturePayment: { + module: { + payload: ({ z, notPersonal }: CommandPayloadArgs) => + z.object({ paymentId: notPersonal(z.string()), orderId: notPersonal(z.string()) }), + handler: ({ events: built, command }: HandlerArgs) => [ + built.paymentCaptured?.({ orderId: command.payload.orderId }), + ], + }, + }, + }, + policies: {}, + processes: {}, +}); + +const paymentCaptured = { + payload: ({ z, notPersonal }: EventPayloadArgs) => z.object({ orderId: notPersonal(z.string()) }), + evolve: ({ state }: HandlerArgs) => state, +}; + +const orders = (projections: Record) => ({ + view: { + fields: ({ f }: FieldsArgs) => ({ + orderId: f.string().primaryKey().notPersonal(), + status: f.string().notPersonal(), + }), + }, + projections: { order: projections }, + queries: {}, +}); + +// The app before: an order is noted, its note projected and reminded of an hour later, and a +// payment captured moves its fulfilment along, which fails while `failing`. +const before = { + aggregates: { + order: { + state: { initialState: { status: "new", note: null } }, + events: { + ...orderEvents, + orderNoted: { + payload: ({ z, notPersonal }: EventPayloadArgs) => + z.object({ note: notPersonal(z.string()) }), + evolve: ({ state, event }: HandlerArgs) => ({ + ...state, + note: (event.payload as { note: string }).note, + }), + }, + }, + commands: { + ...orderCommands, + noteOrder: { + module: { + payload: ({ z, notPersonal }: CommandPayloadArgs) => + z.object({ orderId: notPersonal(z.string()), note: notPersonal(z.string()) }), + handler: ({ events, command }: HandlerArgs) => [ + events.orderNoted?.({ note: command.payload.note }), + ], + }, + }, + }, + policies: { + remindOnOrderNoted: policy("remind"), + chaseOrder: policy("chase", "OrderPlaced"), + thankOrder: policy("thank", "OrderPlaced"), + }, + processes: { + fulfilment: fulfilment({ + paymentCaptured: { + handler: ({ state }: HandlerArgs) => { + if (failing) throw new ValidationError("the warehouse refuses", []); + return state; + }, + }, + }), + }, + }, + payment: payment({ paymentCaptured }), + }, + readModels: { + orders: orders({ + orderPlaced: { project: status("placed") }, + orderNoted: { project: status("noted") }, + }), + }, +} as unknown as Registry; + +// The app once `OrderNoted` and `PaymentCaptured` are retired: what reacted to them no longer does, +// `thankOrder` now waits for a payment instead, and `chaseOrder` is unchanged. +const retired = { + aggregates: { + order: { + state: { initialState: { status: "new", note: null } }, + events: orderEvents, + retired: { orderNoted: { retired: true } }, + commands: orderCommands, + policies: { + remindOnOrderNoted: policy("remind", "OrderPaid"), + chaseOrder: policy("chase", "OrderPlaced"), + thankOrder: policy("thank", "OrderPaid"), + }, + processes: { fulfilment: fulfilment({}) }, + }, + payment: payment({}, { paymentCaptured: { retired: true } }), + }, + readModels: { orders: orders({ orderPlaced: { project: status("placed") } }) }, +} as unknown as Registry; + +// The app once their modules are deleted without retiring them. +const dropped = { + ...retired, + aggregates: { + order: { ...retired.aggregates.order, retired: undefined }, + payment: payment({}), + }, +} as unknown as Registry; + +const stops: (() => Promise)[] = []; + +afterEach(async () => { + ran.length = 0; + failing = false; + for (const stop of stops.splice(0)) await stop(); +}); + +let starts = 0; + +const configOf = (adapter: Adapter) => ({ + storage: adapter, + runtime: { + policies: { retry: { strategy: "none" } }, + processes: { retry: { strategy: "none" } }, + personalData: { forgetLedger: { store: ledgerFor(adapter) } }, + } satisfies RuntimeConfig, +}); + +const start = async (adapter: Adapter, registry: Registry, at = START) => { + starts += 1; + const { logger, entries } = createRecordingLogger("omit"); + const app = await createApp({ + registry, + config: configOf(adapter), + ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), + clock: createFixedClock(at), + logger, + }); + stops.push(() => app.stop()); + return { app, entries }; +}; + +const command = (app: BoundaApp, type: string, payload: object) => + (app.commands as Record Promise>)[type]?.(payload); + +// What the app before wrote and left: `o-1` placed and noted, its fulfilment failed on its +// payment; the reminder and the two delayed policies on it due an hour later. `paid` pays the +// order too, which its fulfilment parks behind the failure. +const written = async ({ paid = false } = {}) => { + const adapter = memory(); + const { app } = await start(adapter, before); + await command(app, "placeOrder", { orderId: "o-1" }); + await command(app, "noteOrder", { orderId: "o-1", note: "ring twice" }); + await app.runUntilIdle(); + failing = true; + await command(app, "capturePayment", { paymentId: "p-1", orderId: "o-1" }); + await app.runUntilIdle(); + failing = false; + if (paid) { + await command(app, "payOrder", { orderId: "o-1" }); + await app.runUntilIdle(); + } + await app.stop(); + return adapter; +}; + +const rowsOf = async (adapter: Adapter): Promise => + ( + await adapter.createReadModel({ name: "orders", fields: {}, logger: silentLogger }) + ).table.findMany({ orderBy: { field: "orderId", direction: "asc" } }); + +const fulfilmentOf = async (adapter: Adapter, orderId: string): Promise => + ( + await ( + await adapter.createStorage() + ).eventStore.load({ + aggregateType: "process:order.fulfilment", + aggregateId: orderId, + }) + ).events.map((event) => event.type); + +describe("an app whose store holds events of a type no module names", () => { + it("refuses to start, naming each and how to retire it, and starts once they are retired", async () => { + const adapter = await written(); + const refused = start(adapter, dropped); + await expect(refused).rejects.toThrow(ConfigurationError); + await expect(start(adapter, dropped)).rejects.toThrow( + [ + "The store holds events this code cannot read:", + '- order.OrderNoted: no module of the aggregate "order" names it. Retire it: add order-noted.ts to the aggregate, exporting only `export const retired = true`', + '- payment.PaymentCaptured: no module of the aggregate "payment" names it. Retire it: add payment-captured.ts to the aggregate, exporting only `export const retired = true`', + ].join("\n"), + ); + await expect(start(adapter, retired)).resolves.toBeDefined(); + }); + + it("refuses a rebuild of a read model just as it refuses the start", async () => { + const adapter = await written(); + const rebuild = (registry: Registry) => + rebuildReadModel({ registry, config: configOf(adapter), name: "orders" }); + await expect(rebuild(dropped)).rejects.toThrow( + 'order.OrderNoted: no module of the aggregate "order" names it', + ); + expect(await rowsOf(adapter)).toEqual([{ orderId: "o-1", status: "noted" }]); + await rebuild(retired); + expect(await rowsOf(adapter)).toEqual([{ orderId: "o-1", status: "placed" }]); + }); +}); + +describe("an app whose store holds events of a retired type no start recorded marks for", () => { + it("refuses a rebuild of a read model just as it refuses the start, until a start with its module", async () => { + const adapter = memory(); + await (await adapter.createStorage()).eventStore.append({ + aggregateType: "order", + aggregateId: "o-1", + expectedVersion: 0, + events: [ + pendingEvent({ aggregateType: "order", aggregateId: "o-1", version: 1, payload: {} }), + pendingEvent({ + aggregateType: "order", + aggregateId: "o-1", + version: 2, + type: "OrderNoted", + payload: { note: "ring twice" }, + }), + ], + }); + const rebuild = () => + rebuildReadModel({ registry: retired, config: configOf(adapter), name: "orders" }); + const refusal = + "order.OrderNoted is retired, but no start recorded what it marks personal: deploy once with its module, on a tenant that is not frozen, then retire it"; + await expect(rebuild()).rejects.toThrow(refusal); + await expect(start(adapter, retired)).rejects.toThrow(refusal); + await (await start(adapter, before)).app.stop(); + await rebuild(); + expect(await rowsOf(adapter)).toEqual([{ orderId: "o-1", status: "placed" }]); + }); +}); + +describe("an app with retired event types", () => { + it("folds a stream past its retired events", async () => { + const adapter = await written(); + const { app } = await start(adapter, retired); + expect(await command(app, "payOrder", { orderId: "o-1" })).toMatchObject({ version: 3 }); + }); + + it("drops a delayed policy run whose policy no longer handles its event's type, retired or not, settling it with a warning", async () => { + const adapter = await written(); + const { app, entries } = await start(adapter, retired, new Date(START.getTime() + 2 * HOUR)); + await app.runUntilIdle(); + expect(ran).toEqual(["chase:OrderPlaced"]); + expect( + entries + .filter(({ message }) => message.startsWith("delayed policy run dropped")) + .map(({ fields }) => [fields?.policy, fields?.eventType]), + ).toEqual( + expect.arrayContaining([ + ["order.remindOnOrderNoted", "order.OrderNoted"], + ["order.thankOrder", "order.OrderPlaced"], + ]), + ); + expect(await app.deadLetters.count({ kind: "policy" })).toBe(0); + await app.runUntilIdle(); + expect(ran).toEqual(["chase:OrderPlaced"]); + }); + + it("retries a process that failed on an event of another aggregate whose type it retired, letting the event through", async () => { + const adapter = await written(); + const { app } = await start(adapter, retired); + const [letter] = await app.deadLetters.list({ kind: "process" }); + expect(letter).toMatchObject({ + handler: "order.fulfilment", + eventType: "PaymentCaptured", + aggregateType: "payment", + instanceId: "o-1", + status: "failed", + }); + expect(await app.deadLetters.retry(letter?.id ?? "")).toMatchObject({ + status: "retried", + parked: 0, + }); + expect(await fulfilmentOf(adapter, "o-1")).toEqual([ + PROCESS_EVENTS.started, + PROCESS_EVENTS.handled, + PROCESS_EVENTS.failed, + PROCESS_EVENTS.handled, + PROCESS_EVENTS.resumed, + ]); + }); + + it("counts the events parked behind such a process's failure, and drains them on its retry", async () => { + const adapter = await written({ paid: true }); + const { app } = await start(adapter, retired); + const [letter] = await app.deadLetters.list({ kind: "process" }); + expect(letter?.parked).toBe(1); + expect(await app.deadLetters.retry(letter?.id ?? "")).toMatchObject({ + status: "retried", + parked: 0, + }); + expect(await fulfilmentOf(adapter, "o-1")).toEqual([ + PROCESS_EVENTS.started, + PROCESS_EVENTS.handled, + PROCESS_EVENTS.failed, + PROCESS_EVENTS.eventParked, + PROCESS_EVENTS.handled, + PROCESS_EVENTS.handled, + PROCESS_EVENTS.resumed, + ]); + }); + + it("abandons such a process when its letter is discarded", async () => { + const adapter = await written(); + const { app } = await start(adapter, retired); + const [letter] = await app.deadLetters.list({ kind: "process" }); + await app.deadLetters.discard(letter?.id ?? ""); + expect(await fulfilmentOf(adapter, "o-1")).toEqual([ + PROCESS_EVENTS.started, + PROCESS_EVENTS.handled, + PROCESS_EVENTS.failed, + PROCESS_EVENTS.abandoned, + ]); + }); +}); diff --git a/packages/core/src/kernel/shared/committed-events.ts b/packages/core/src/kernel/shared/committed-events.ts index 1f7b5857d..4544e5e71 100644 --- a/packages/core/src/kernel/shared/committed-events.ts +++ b/packages/core/src/kernel/shared/committed-events.ts @@ -33,6 +33,8 @@ const appendingTo = ( loadMany: (args) => eventStore.loadMany(args), lastPosition: () => eventStore.lastPosition(), types: () => eventStore.types(), + recordMarks: (args) => eventStore.recordMarks(args), + marksOf: (args) => eventStore.marksOf(args), reseal: (events) => eventStore.reseal(events), }); diff --git a/packages/core/src/kernel/unit-of-work/unit-of-work.ts b/packages/core/src/kernel/unit-of-work/unit-of-work.ts index 5d648f066..f2fd89384 100644 --- a/packages/core/src/kernel/unit-of-work/unit-of-work.ts +++ b/packages/core/src/kernel/unit-of-work/unit-of-work.ts @@ -89,11 +89,19 @@ export const createUnitOfWork: CreateUnitOfWorkFunction = ({ storage }) => { commit: async () => { const batches = staged.batches(); const reseals = staged.reseals(); - if (batches.length > 0 || reseals.length > 0 || pending() || atCommit.length > 0) { + const markings = staged.markings(); + if ( + batches.length > 0 || + reseals.length > 0 || + markings.length > 0 || + pending() || + atCommit.length > 0 + ) { for (const step of beforeCommit) await step(storage); await storage.transact(async (transaction) => { for (const batch of batches) await transaction.eventStore.append(batch); if (reseals.length > 0) await transaction.eventStore.reseal(reseals); + for (const marks of markings) await transaction.eventStore.recordMarks(marks); await flush(transaction); for (const write of atCommit) await write(transaction); }); diff --git a/packages/core/src/memory/event-store.ts b/packages/core/src/memory/event-store.ts index 73ff012a6..fe1d02480 100644 --- a/packages/core/src/memory/event-store.ts +++ b/packages/core/src/memory/event-store.ts @@ -1,3 +1,4 @@ +import { codePointOrder } from "../adapter/sql/order.ts"; import { holdsResealedFrom } from "../adapter/sql/resealed-from.ts"; import { type CheckAppendArgs, checkAppend } from "../adapter/storage/append-checks.ts"; import type { @@ -5,6 +6,7 @@ import type { AppendResult, EventStore, StoredEventType, + StoredEventTypeMarks, } from "../adapter/storage/event-store.ts"; import { ConcurrencyError } from "../contracts/errors.ts"; import type { StoredEvent } from "../contracts/event.ts"; @@ -53,6 +55,11 @@ export interface MemoryEventStore extends EventStore { * The catalogue of event types, each kind a row named as the SQL stores name its columns. */ kindRows(): readonly object[]; + /** + * The marks event types had, each set a row named as the SQL stores name its columns, in the + * order they were recorded. + */ + markRows(): readonly object[]; } export interface CreateMemoryEventStoreFunction { @@ -89,13 +96,23 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ const gaps = new Set(); // The catalogue of event types, keyed by all three fields, written with the events of each kind. const kinds = new Map(); - const record = (aggregateType: string, type: string, schemaVersion: number): void => { - kinds.set(JSON.stringify([aggregateType, type, schemaVersion]), { + const record = ( + aggregateType: string, + type: string, + schemaVersion: number, + opened: boolean, + ): void => { + const key = JSON.stringify([aggregateType, type, schemaVersion]); + kinds.set(key, { aggregateType, type, schemaVersion, + opened: opened || kinds.get(key)?.opened === true, }); }; + // The marks of event types, keyed by aggregate type, type and fingerprint, as JSON text so each + // read is a fresh copy; a `Map` keeps them in the order recorded. + const marks = new Map & { readonly marks: string }>(); let reserved = 0; // Every position up to here is written or a gap: what readers see. let watermark = 0; @@ -143,7 +160,7 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ })); streams.set(key, [...(streams.get(key) ?? []), ...written]); for (const event of events) { - record(event.aggregateType, event.type, event.metadata.schemaVersion); + record(event.aggregateType, event.type, event.metadata.schemaVersion, event.version === 1); } for (const event of written) { log.set(event.position, event); @@ -167,11 +184,23 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ appendAll, rows: () => [...log.values()].sort((a, b) => a.position - b.position), kindRows: () => - [...kinds.values()].map(({ aggregateType, type, schemaVersion }) => ({ + [...kinds.values()].map(({ aggregateType, type, schemaVersion, opened }) => ({ aggregate_type: aggregateType, type, schema_version: schemaVersion, + opened, })), + markRows: () => + [...marks.values()].map( + ({ aggregateType, type, fingerprint, marks: set, firstSeenAt }, index) => ({ + aggregate_type: aggregateType, + type, + fingerprint, + marks: set, + seq: index + 1, + first_seen_at: firstSeenAt, + }), + ), append: async (args) => (await appendAll([args]))[0] as AppendResult, reserve, release: (positions) => { @@ -234,6 +263,27 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ }, lastPosition: async () => watermark, types: async () => [...kinds.values()], + // Atomic because nothing yields between the copies and the writes. + recordMarks: async ({ marks: sets, at }) => { + const kept = sets.map((set) => ({ ...set, marks: toJson(set.marks), firstSeenAt: at })); + const sorted = [...kept].sort( + (a, b) => + codePointOrder(a.aggregateType, b.aggregateType) || + codePointOrder(a.type, b.type) || + codePointOrder(a.fingerprint, b.fingerprint), + ); + for (const set of sorted) { + const key = JSON.stringify([set.aggregateType, set.type, set.fingerprint]); + if (!marks.has(key)) marks.set(key, set); + } + }, + marksOf: async (of) => + [...marks.values()] + .filter( + (set) => + of === undefined || (set.aggregateType === of.aggregateType && set.type === of.type), + ) + .map((set) => ({ ...set, marks: JSON.parse(set.marks) })), reseal: async (events) => { const kept = events.map((resealed) => ({ resealed, payload: toJson(resealed.payload) })); const left: number[] = []; @@ -248,7 +298,9 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ schemaVersion === undefined ? event.metadata : toJson({ ...(JSON.parse(event.metadata) as object), schemaVersion }); - if (schemaVersion !== undefined) record(event.aggregateType, event.type, schemaVersion); + if (schemaVersion !== undefined) { + record(event.aggregateType, event.type, schemaVersion, event.version === 1); + } const written: Kept = { ...event, payload, person, metadata }; log.set(position, written); const key = streamId(event); diff --git a/packages/core/src/memory/index.ts b/packages/core/src/memory/index.ts index fd4e1672c..1da643776 100644 --- a/packages/core/src/memory/index.ts +++ b/packages/core/src/memory/index.ts @@ -253,6 +253,11 @@ export const memory: MemoryFunction = (options = {}) => { key: ["aggregate_type", "type", "schema_version"], rows: stores.eventStore.kindRows(), }), + storageTable({ + table: "eventMarks", + key: ["aggregate_type", "type", "fingerprint"], + rows: stores.eventStore.markRows(), + }), storageTable({ table: "snapshots", key: ["aggregateType", "aggregateId"], diff --git a/packages/core/src/memory/tenant-fence.test.ts b/packages/core/src/memory/tenant-fence.test.ts index 1439e43ec..b090673ae 100644 --- a/packages/core/src/memory/tenant-fence.test.ts +++ b/packages/core/src/memory/tenant-fence.test.ts @@ -13,6 +13,8 @@ const READS: Readonly> = { "lastPosition", "load", "loadMany", + "markRows", + "marksOf", "readAll", "readByPerson", "readOne", diff --git a/packages/core/src/memory/tenant-fence.ts b/packages/core/src/memory/tenant-fence.ts index 0a177aeaf..a38068a7f 100644 --- a/packages/core/src/memory/tenant-fence.ts +++ b/packages/core/src/memory/tenant-fence.ts @@ -7,7 +7,7 @@ import { // The methods of each store that write, which the fence puts behind it. export const FENCED_WRITES = { - eventStore: ["append", "appendAll", "reseal", "reserve", "release"], + eventStore: ["append", "appendAll", "reseal", "recordMarks", "reserve", "release"], inboxLedger: ["tryClaim", "complete", "fail", "release", "renew"], deadLetterStore: [ "add", diff --git a/packages/core/src/memory/transaction.ts b/packages/core/src/memory/transaction.ts index 5940656ae..ac7ae97d0 100644 --- a/packages/core/src/memory/transaction.ts +++ b/packages/core/src/memory/transaction.ts @@ -498,6 +498,7 @@ export const createMemoryStorageTransaction: CreateMemoryStorageTransactionFunct await flush(log.target); await eventStore.appendAll(ownChangesLeftOut(staged.batches(), removed, restricted)); await eventStore.reseal(staged.reseals()); + for (const marks of staged.markings()) await eventStore.recordMarks(marks); for (const activity of recorded) await persons.record(activity); } catch (error) { log.undo(); diff --git a/packages/core/src/modules/event.ts b/packages/core/src/modules/event.ts index b2265608e..05739207f 100644 --- a/packages/core/src/modules/event.ts +++ b/packages/core/src/modules/event.ts @@ -12,6 +12,11 @@ export interface EventModule { // Keyed by the event's camelCase name. export type EventModules = Readonly>; +// The module of a retired event type, exporting `retired = true` and nothing else. +export interface RetiredEventModule { + readonly retired: true; +} + /** * Arguments of `evolve`. When one of the aggregate's events exports `begin`, `evolve` only ever * runs on an aggregate that exists, so `state` has every field `begin` always sets. diff --git a/packages/core/src/modules/redaction.ts b/packages/core/src/modules/redaction.ts index 473e3317e..942faaf64 100644 --- a/packages/core/src/modules/redaction.ts +++ b/packages/core/src/modules/redaction.ts @@ -47,17 +47,27 @@ type ProcessTargetsOf = { : never; }[keyof Processes & string]; +// No module marks a retired event's fields any more, so any field the event sealed is one. +type RetiredTargetsOf = Entry extends { + readonly retired: infer Retired; +} + ? [keyof Retired & string] extends [never] + ? never + : RedactedFields, string> + : never; + /** * What `redact` takes of one event of the registry `R`: for each event type with personal fields, - * its aggregate, its type and the fields it marks; for each process whose state marks fields, its - * stream and the lifecycle events that carry the state. Any event and field names for the untyped - * `Registry`. + * its aggregate, its type and the fields it marks; for each retired event type, its aggregate, + * its type and any fields; for each process whose state marks fields, its stream and the + * lifecycle events that carry the state. Any event and field names for the untyped `Registry`. */ export type RedactionTarget = Registry extends R ? RedactedFields : { [Aggregate in keyof R["aggregates"] & string]: | EventTargetsOf + | RetiredTargetsOf | ProcessTargetsOf; }[keyof R["aggregates"] & string]; diff --git a/packages/core/src/modules/registry.ts b/packages/core/src/modules/registry.ts index b120931ae..c42f649fc 100644 --- a/packages/core/src/modules/registry.ts +++ b/packages/core/src/modules/registry.ts @@ -8,7 +8,7 @@ import type { DurationInput } from "../contracts/duration.ts"; import type { StateModule } from "./aggregate.ts"; import type { AuditModule } from "./audit.ts"; import type { CommandEntry, CommandModule, RejectionCodeOf } from "./command.ts"; -import type { EventModules } from "./event.ts"; +import type { EventModules, RetiredEventModule } from "./event.ts"; import type { Simplify, UnionToIntersection } from "./naming.ts"; import type { HasPayload, PayloadInputOf } from "./payload.ts"; import type { PersonalDataModule } from "./personal-data.ts"; @@ -33,6 +33,12 @@ export interface AggregateEntry { readonly events: EventModules; // Keyed like `events`; only events whose payload has changed shape have one. readonly upcasts?: Readonly>; + /** + * The event types the aggregate retired, keyed like `events`: each module exports + * `retired = true` and nothing else. Their events stay in the store and are read as stored, + * but nothing folds, projects or reacts to them. + */ + readonly retired?: Readonly>; readonly ports?: PortModules; /** * The modules of the ports that declare a recipient, by port. diff --git a/packages/core/src/modules/validate.test.ts b/packages/core/src/modules/validate.test.ts index fb3242bc0..3c781741d 100644 --- a/packages/core/src/modules/validate.test.ts +++ b/packages/core/src/modules/validate.test.ts @@ -71,6 +71,61 @@ describe("validateRegistry", () => { ).toThrow(/must be a non-empty array of functions/); }); + it("takes a retired event type only as a module exporting retired true, and no other module of that name", () => { + const upcast = (payload: unknown): unknown => payload; + expect(() => + validateRegistry(withOrder({ retired: { orderNoteAdded: { retired: true } } })), + ).not.toThrow(); + expect(() => + validateRegistry( + withOrder({ + retired: { + orderNoteAdded: { retired: false } as never, + orderLost: {} as never, + orderPlaced: { retired: true }, + }, + upcasts: { orderNoteAdded: { upcasts: [upcast] } }, + }), + ), + ).toThrow( + new ConfigurationError( + [ + "Invalid registry:", + ' aggregates.order.retired.orderNoteAdded: export "retired" must be true', + ' aggregates.order.retired.orderLost: export "retired" must be true', + " aggregates.order.retired.orderPlaced: is also aggregates.order.events.orderPlaced; an event is current or retired", + ' aggregates.order.upcasts.orderNoteAdded: "orderNoteAdded" is retired, and a retired event is read as stored', + ].join("\n"), + ), + ); + }); + + it("refuses a projection of a retired event type, by its file or its on", () => { + const registry: Registry = { + aggregates: { order: { ...order, retired: { orderNoteAdded: { retired: true } } } }, + readModels: { + orderSummary: { + ...orderSummary, + projections: { + order: { + orderNoteAdded: { project: noop }, + byOn: { on: ["OrderPlaced", "OrderNoteAdded"], project: noop }, + }, + }, + }, + }, + }; + expect(() => validateRegistry(registry)).toThrow( + new ConfigurationError( + [ + "Invalid registry:", + ' readModels.orderSummary.projections.order.orderNoteAdded: "OrderNoteAdded" is a retired event of the aggregate "order", which nothing projects', + ' readModels.orderSummary.projections.order.byOn: "OrderNoteAdded" is a retired event of the aggregate "order", which nothing projects', + ].join("\n"), + ), + ); + }); + it("takes rejections only as a function", () => { const rejections = () => ({ AlreadyPlaced: "Order already placed" }); expect(() => diff --git a/packages/core/src/modules/validate.ts b/packages/core/src/modules/validate.ts index bc404cbe4..f1e1d73e9 100644 --- a/packages/core/src/modules/validate.ts +++ b/packages/core/src/modules/validate.ts @@ -93,9 +93,26 @@ const validateAggregate = ( requireFolding(problems, event, `${base}.events.${key}`); optionalFunction(problems, event, `${base}.events.${key}`, "payload"); } + for (const [key, module] of Object.entries(aggregate.retired ?? {})) { + const path = `${base}.retired.${key}`; + if (key in aggregate.events) { + problems.push({ + path, + message: `is also ${base}.events.${key}; an event is current or retired`, + }); + } + if (Reflect.get(module, "retired") !== true) { + problems.push({ path, message: 'export "retired" must be true' }); + } + } for (const [key, module] of Object.entries(aggregate.upcasts ?? {})) { const path = `${base}.upcasts.${key}`; - if (!(key in aggregate.events)) { + if (key in (aggregate.retired ?? {})) { + problems.push({ + path, + message: `"${key}" is retired, and a retired event is read as stored`, + }); + } else if (!(key in aggregate.events)) { problems.push({ path, message: `there is no event "${key}" to upcast` }); } const upcasts: unknown = Reflect.get(module, "upcasts"); @@ -162,6 +179,16 @@ export const eventTypesOf: EventTypesOfFunction = (aggregates, aggregate) => ? Object.values(BOUNDA_EVENTS) : Object.keys(aggregates[aggregate]?.events ?? {}).map(capitalize); +export interface RetiredTypesOfFunction { + (aggregates: Registry["aggregates"], aggregate: string): ReadonlySet; +} + +/** + * The event types an aggregate of the registry retired; none for the runtime's own. + */ +export const retiredTypesOf: RetiredTypesOfFunction = (aggregates, aggregate) => + new Set(Object.keys(aggregates[aggregate]?.retired ?? {}).map(capitalize)); + const validateReadModel = ( problems: Problem[], name: string, @@ -179,6 +206,7 @@ const validateReadModel = ( }); } const events = new Set(eventTypesOf(aggregates, aggregate)); + const retired = retiredTypesOf(aggregates, aggregate); for (const [key, projection] of Object.entries(projections)) { const path = `${base}.projections.${aggregate}.${key}`; requireFunction(problems, projection, path, "project"); @@ -188,7 +216,9 @@ const validateReadModel = ( )) { problems.push({ path, - message: `"${trigger}" is not an event of the aggregate "${aggregate}"; name the file after one or export "on"`, + message: retired.has(trigger) + ? `"${trigger}" is a retired event of the aggregate "${aggregate}", which nothing projects` + : `"${trigger}" is not an event of the aggregate "${aggregate}"; name the file after one or export "on"`, }); } } diff --git a/packages/core/test-types/fixtures/order-app-inferred/.bounda/registry.ts b/packages/core/test-types/fixtures/order-app-inferred/.bounda/registry.ts index f6b3e9e5e..84504ff34 100644 --- a/packages/core/test-types/fixtures/order-app-inferred/.bounda/registry.ts +++ b/packages/core/test-types/fixtures/order-app-inferred/.bounda/registry.ts @@ -2,6 +2,7 @@ import type { Registry } from "@bounda-dev/core"; import * as payOrder from "../app/domain/order/commands/pay-order.ts"; import * as placeOrder from "../app/domain/order/commands/place-order.ts"; import * as orderCancelled from "../app/domain/order/order-cancelled.ts"; +import * as orderNoteAdded from "../app/domain/order/order-note-added.ts"; import * as orderPaid from "../app/domain/order/order-paid.ts"; import * as orderPlaced from "../app/domain/order/order-placed.ts"; import * as reminderSent from "../app/domain/order/reminder-sent.ts"; @@ -11,6 +12,7 @@ export const registry = { order: { stateFingerprint: "753014f1970d68d5", events: { orderCancelled, orderPaid, orderPlaced, reminderSent }, + retired: { orderNoteAdded }, commands: { payOrder: { module: payOrder }, placeOrder: { module: placeOrder } }, policies: {}, processes: {}, diff --git a/packages/core/test-types/fixtures/order-app-inferred/app/domain/order/order-note-added.ts b/packages/core/test-types/fixtures/order-app-inferred/app/domain/order/order-note-added.ts new file mode 100644 index 000000000..c72b81a38 --- /dev/null +++ b/packages/core/test-types/fixtures/order-app-inferred/app/domain/order/order-note-added.ts @@ -0,0 +1 @@ +export const retired = true; diff --git a/packages/core/test-types/fixtures/order-app/.bounda/registry.ts b/packages/core/test-types/fixtures/order-app/.bounda/registry.ts index 3350503cd..52ceb3da4 100644 --- a/packages/core/test-types/fixtures/order-app/.bounda/registry.ts +++ b/packages/core/test-types/fixtures/order-app/.bounda/registry.ts @@ -17,6 +17,7 @@ import * as orderRemindersFake from "../app/domain/order/infrastructure/reminder import type * as orderInventory from "../app/domain/order/inventory.ts"; import * as orderMailer from "../app/domain/order/mailer.ts"; import * as orderCancelled from "../app/domain/order/order-cancelled.ts"; +import * as orderNoteAdded from "../app/domain/order/order-note-added.ts"; import * as orderPaid from "../app/domain/order/order-paid.ts"; import * as orderPlaced from "../app/domain/order/order-placed.ts"; import * as orderPlacedUpcasts from "../app/domain/order/order-placed.upcast.ts"; @@ -64,6 +65,7 @@ export const registry = { stateFingerprint: "94cf3e015d12ce1c", events: { orderCancelled, orderPaid, orderPlaced }, upcasts: { orderPlaced: orderPlacedUpcasts }, + retired: { orderNoteAdded }, ports: { auditLog: { memory: orderAuditLogMemory satisfies ImplementationModule, diff --git a/packages/core/test-types/fixtures/order-app/app/domain/order/order-note-added.ts b/packages/core/test-types/fixtures/order-app/app/domain/order/order-note-added.ts new file mode 100644 index 000000000..c72b81a38 --- /dev/null +++ b/packages/core/test-types/fixtures/order-app/app/domain/order/order-note-added.ts @@ -0,0 +1 @@ +export const retired = true; diff --git a/packages/core/test-types/inference.test-d.ts b/packages/core/test-types/inference.test-d.ts index a5fd85af0..7a192d631 100644 --- a/packages/core/test-types/inference.test-d.ts +++ b/packages/core/test-types/inference.test-d.ts @@ -1645,6 +1645,7 @@ describe("personal data", () => { expectTypeOf>().toEqualTypeOf< | RedactedFields<"customer", "CustomerRegistered", "email"> | RedactedFields<"order", "OrderPlaced", "note"> + | RedactedFields<"order", "OrderNoteAdded", string> | RedactedFields<"process:order.orderPayment", ProcessStateEventType, "contact"> >(); expectTypeOf>().toEqualTypeOf(); diff --git a/packages/core/test-types/retired-events.test-d.ts b/packages/core/test-types/retired-events.test-d.ts new file mode 100644 index 000000000..07cd5e307 --- /dev/null +++ b/packages/core/test-types/retired-events.test-d.ts @@ -0,0 +1,49 @@ +import type { RedactedFields, RedactionTarget, Registry } from "@bounda-dev/core"; +import { describe, expectTypeOf, it } from "vitest"; +import type { registry } from "./fixtures/order-app/.bounda/registry.ts"; +import type { OrderEvents } from "./fixtures/order-app/.bounda/types.ts"; +import type { Command as PlaceOrder } from "./fixtures/order-app/app/domain/order/commands/+types/place-order.ts"; + +describe("a retired event type", () => { + it("is no event of its aggregate: no builder and no member of its events", () => { + expectTypeOf().toEqualTypeOf< + "orderCancelled" | "orderPaid" | "orderPlaced" + >(); + const build = (events: PlaceOrder.HandlerArgs["events"]) => { + // @ts-expect-error A retired event has no builder: nothing writes it any more. + events.orderNoteAdded(); + return events.orderPlaced; + }; + expectTypeOf(build).toBeFunction(); + }); + + it("is in the registry as the module that retires it", () => { + expectTypeOf< + (typeof registry)["aggregates"]["order"]["retired"]["orderNoteAdded"]["retired"] + >().toEqualTypeOf(); + }); + + it("is reached by redact with any of the fields it sealed", () => { + expectTypeOf>().toExtend< + RedactionTarget + >(); + expectTypeOf>().not.toExtend< + RedactionTarget + >(); + }); + + it("is retired only by a module that exports retired as true", () => { + const entry = { events: {}, commands: {}, policies: {}, processes: {} }; + const retiring = { + aggregates: { order: { ...entry, retired: { orderNoteAdded: { retired: true } } } }, + readModels: {}, + } as const satisfies Registry; + expectTypeOf(retiring).toExtend(); + const kept = { + aggregates: { order: { ...entry, retired: { orderNoteAdded: { retired: false } } } }, + readModels: {}, + } as const; + // @ts-expect-error A module that exports retired as false retires nothing. + expectTypeOf(kept).toExtend(); + }); +}); diff --git a/packages/core/test-types/schema-evolution.test-d.ts b/packages/core/test-types/schema-evolution.test-d.ts index 8ed319330..d95ab85a6 100644 --- a/packages/core/test-types/schema-evolution.test-d.ts +++ b/packages/core/test-types/schema-evolution.test-d.ts @@ -1,5 +1,12 @@ import type { BoundaError, SchemaAheadError, SchemaAheadErrorArgs } from "@bounda-dev/core"; -import type { EventStore, StorageTransaction, StoredEventType } from "@bounda-dev/core/adapter"; +import type { + EventStore, + EventTypeMarks, + RecordedPersonalMarks, + StorageTransaction, + StoredEventType, + StoredEventTypeMarks, +} from "@bounda-dev/core/adapter"; import { describe, expectTypeOf, it } from "vitest"; describe("an event newer code wrote", () => { @@ -24,10 +31,36 @@ describe("an adapter of your own", () => { readonly aggregateType: string; readonly type: string; readonly schemaVersion: number; + readonly opened: boolean; }>(); expectTypeOf().toEqualTypeOf<() => Promise>(); expectTypeOf().toEqualTypeOf< () => Promise >(); }); + + it("keeps every set of marks a type was seen with, first recorded first, of one type or of all, which a transaction records too", () => { + expectTypeOf().toEqualTypeOf<{ + readonly person: string | null; + readonly fields: readonly string[]; + readonly categories: Readonly>; + }>(); + expectTypeOf().toEqualTypeOf<{ + readonly aggregateType: string; + readonly type: string; + readonly fingerprint: string; + readonly marks: RecordedPersonalMarks | null; + }>(); + expectTypeOf().toExtend(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf< + (args: { readonly marks: readonly EventTypeMarks[]; readonly at: string }) => Promise + >(); + expectTypeOf().toEqualTypeOf< + (args?: { + readonly aggregateType: string; + readonly type: string; + }) => Promise + >(); + }); }); diff --git a/packages/postgresql/src/dead-letter-store.ts b/packages/postgresql/src/dead-letter-store.ts index c617452ff..90d892386 100644 --- a/packages/postgresql/src/dead-letter-store.ts +++ b/packages/postgresql/src/dead-letter-store.ts @@ -30,7 +30,7 @@ export interface CreatePostgresqlDeadLetterStoreFunction { } const COLUMNS = - '"id", "kind", "handler", "event_id", "event_type", "aggregate_type", "aggregate_id", "person", "error_type", "error_name", "error_code", "error_message", "error_stack", "attempts", "first_failed_at", "last_failed_at", "status", "resolved_at", "payload", "persons", "state_person", "read_persons"'; + '"id", "kind", "handler", "event_id", "event_type", "aggregate_type", "aggregate_id", "person", "error_type", "error_name", "error_code", "error_message", "error_stack", "attempts", "first_failed_at", "last_failed_at", "status", "resolved_at", "payload", "persons", "state_person", "read_persons", "instance_id"'; const toLetter = (row: Record): StoredDeadLetter => ({ id: String(row.id), @@ -44,6 +44,9 @@ const toLetter = (row: Record): StoredDeadLetter => ({ ...(row.state_person === null || row.state_person === undefined ? {} : { statePerson: String(row.state_person) }), + ...(row.instance_id === null || row.instance_id === undefined + ? {} + : { instanceId: String(row.instance_id) }), ...decodeReadPersons(row.read_persons), errorType: String(row.error_type) as DeadLetterErrorType, errorName: String(row.error_name), @@ -105,7 +108,7 @@ export const createPostgresqlDeadLetterStore: CreatePostgresqlDeadLetterStoreFun return { add: async (letter) => { await db.run( - `INSERT INTO ${table} (${COLUMNS}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, 'failed', NULL, $17, $18, $19, $20) ON CONFLICT ("id") DO NOTHING`, + `INSERT INTO ${table} (${COLUMNS}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, 'failed', NULL, $17, $18, $19, $20, $21) ON CONFLICT ("id") DO NOTHING`, [ letter.id, letter.kind, @@ -127,6 +130,7 @@ export const createPostgresqlDeadLetterStore: CreatePostgresqlDeadLetterStoreFun postgresqlDialect.encode("json", letter.persons ?? []), letter.statePerson ?? null, postgresqlDialect.encode("json", letter.readPersons ?? []), + letter.instanceId ?? null, ], ); return (await get(letter.id)) as StoredDeadLetter; diff --git a/packages/postgresql/src/event-store.ts b/packages/postgresql/src/event-store.ts index ca14785a7..202e3b4f2 100644 --- a/packages/postgresql/src/event-store.ts +++ b/packages/postgresql/src/event-store.ts @@ -6,14 +6,17 @@ import { holdsResealedFrom, insertEventsStatements, kindsOfEvents, + marksOfRow, type PendingEventTypes, pendingEventTypes, positionsByVersion, postgresqlDialect, recordEventTypesStatements, + recordMarksStatements, runInOrder, type SqlTransaction, selectEventTypesStatement, + selectMarksStatement, } from "@bounda-dev/core/adapter/sql"; import type { PostgresqlDatabase } from "./database.ts"; @@ -29,6 +32,10 @@ export interface CreatePostgresqlEventStoreArgs { * and reseal records its own. */ readonly pending?: PendingEventTypes; + /** + * The marks event types had, which `recordMarks` writes and `marksOf` reads. + */ + readonly eventMarks: string; /** * Text hashed into the advisory lock every append takes for the duration of its transaction. */ @@ -90,6 +97,7 @@ export const createPostgresqlEventStore: CreatePostgresqlEventStoreFunction = ({ table, eventTypes, pending, + eventMarks, lockKey, channel, personalKeys, @@ -243,6 +251,25 @@ export const createPostgresqlEventStore: CreatePostgresqlEventStoreFunction = ({ if (pending !== undefined) kinds.add(pending.held()); return kinds.held(); }, + recordMarks: ({ marks, at }) => + db.write(async (tx) => { + for (const { sql, params } of recordMarksStatements({ + dialect: postgresqlDialect, + table: eventMarks, + marks, + at, + })) { + await tx.run(sql, params); + } + }), + marksOf: async (of) => { + const { sql, params } = selectMarksStatement({ + dialect: postgresqlDialect, + table: eventMarks, + of, + }); + return (await db.all(sql, params)).map(marksOfRow); + }, reseal: (events) => db.write(async (tx) => { // Every event checked is locked, in position order, before any is written: no write comes @@ -271,13 +298,19 @@ export const createPostgresqlEventStore: CreatePostgresqlEventStoreFunction = ({ continue; } const rows = await tx.all( - `UPDATE ${table} SET "payload" = $1, "person" = $2, "metadata" = CASE WHEN $4::integer IS NULL THEN "metadata" ELSE jsonb_set("metadata", '{schemaVersion}', to_jsonb($4::integer)) END WHERE "position" = $3 RETURNING "aggregate_type", "type"`, + `UPDATE ${table} SET "payload" = $1, "person" = $2, "metadata" = CASE WHEN $4::integer IS NULL THEN "metadata" ELSE jsonb_set("metadata", '{schemaVersion}', to_jsonb($4::integer)) END WHERE "position" = $3 RETURNING "aggregate_type", "type", "version"`, [postgresqlDialect.encode("json", payload), person, position, schemaVersion ?? null], ); if (rows.length === 0) left.push(position); if (schemaVersion === undefined) continue; kinds.push( - ...rows.map((row) => eventTypeOfRow({ ...row, schema_version: schemaVersion })), + ...rows.map((row) => + eventTypeOfRow({ + ...row, + schema_version: schemaVersion, + opened: Number(row.version) === 1, + }), + ), ); } await record(tx, kinds); diff --git a/packages/postgresql/src/index.ts b/packages/postgresql/src/index.ts index e5bed4cae..ee9a8bce4 100644 --- a/packages/postgresql/src/index.ts +++ b/packages/postgresql/src/index.ts @@ -154,6 +154,7 @@ export const postgresql: PostgresqlFunction = (options) => { db: database, table: tables.events, eventTypes: tables.eventTypes, + eventMarks: tables.eventMarks, ...(pending === undefined ? {} : { pending }), lockKey: tables.appendLockKey, channel: tables.channel, diff --git a/packages/postgresql/src/migrations.ts b/packages/postgresql/src/migrations.ts index 5bf78744b..824e47861 100644 --- a/packages/postgresql/src/migrations.ts +++ b/packages/postgresql/src/migrations.ts @@ -1,8 +1,10 @@ import { ConfigurationError } from "@bounda-dev/core"; import type { SchemaScopeName, SchemaVersion } from "@bounda-dev/core/adapter"; import { + eventMarksTableStatement, eventTypesTableStatement, fillEventTypesStatement, + fillOpenedEventTypesStatement, fillPersonalCategoriesStatement, forgetLedgerAppliedAgainStatement, forgetLedgerCategoriesStatement, @@ -21,9 +23,11 @@ import { forgetLedgerStatements, forgottenRecipientsTableStatement, indexKeysTableStatement, + instancesOfEarlierLetters, type MigrateSchemasArgs, markRetiredKeys, migrateSchemas, + openedColumn, personalCategoriesTableStatement, postgresqlDialect, quoteIdentifier, @@ -333,6 +337,48 @@ const catalogue = async (tx: SqlTransaction, tables: StorageTables): Promise => { + if (!(await columnsOf(tx, schema, tables.eventTypes)).has("opened")) { + await tx.run( + `ALTER TABLE ${tables.eventTypes} ADD COLUMN ${openedColumn(postgresqlDialect)}`, + [], + ); + } + await tx.run( + fillOpenedEventTypesStatement({ + table: tables.eventTypes, + events: tables.events, + schemaVersion: `("metadata"->>'schemaVersion')::integer`, + }), + [], + ); + await tx.run( + eventMarksTableStatement({ dialect: postgresqlDialect, table: tables.eventMarks }), + [], + ); + if (!(await columnsOf(tx, schema, tables.deadLetters)).has("instance_id")) { + await tx.run(`ALTER TABLE ${tables.deadLetters} ADD COLUMN "instance_id" text`, []); + } + await tx.run( + instancesOfEarlierLetters({ + deadLetters: tables.deadLetters, + events: tables.events, + letterId: `"payload"->>'letterId'`, + }), + [], + ); +}; + export interface PostgresqlStorageScopeArgs { readonly schema: string; readonly tables: StorageTables; @@ -364,6 +410,7 @@ export const postgresqlStorageScope: PostgresqlStorageScopeFunction = ({ schema, tables.supersededKeys, tables.eventTypes, tables.personalCategories, + tables.eventMarks, ], statements: [ ...latestStorageTablesStatements(tables), @@ -377,6 +424,7 @@ export const postgresqlStorageScope: PostgresqlStorageScopeFunction = ({ schema, dialect: postgresqlDialect, table: tables.personalCategories, }), + eventMarksTableStatement({ dialect: postgresqlDialect, table: tables.eventMarks }), ], }, migrations: [ @@ -467,6 +515,7 @@ export const postgresqlStorageScope: PostgresqlStorageScopeFunction = ({ schema, { version: 14, migrate: (tx) => keepTransfers(tx, schema, tables) }, { version: 15, migrate: (tx) => keyDisclosuresByTransfer(tx, schema, tables) }, { version: 16, migrate: (tx) => catalogue(tx, tables) }, + { version: 17, migrate: (tx) => keepOpeningsMarksAndInstances(tx, schema, tables) }, ], }); diff --git a/packages/postgresql/src/postgresql.test.ts b/packages/postgresql/src/postgresql.test.ts index 85d1d5ce8..97b69d32a 100644 --- a/packages/postgresql/src/postgresql.test.ts +++ b/packages/postgresql/src/postgresql.test.ts @@ -1107,6 +1107,7 @@ describe.skipIf(testDatabase === null)("postgresql adapter", () => { }, table: `"${tablePrefix}events"`, eventTypes: "unused", + eventMarks: "unused", lockKey: "unused", channel: "unused", personalKeys: "unused", @@ -1138,6 +1139,7 @@ describe.skipIf(testDatabase === null)("postgresql adapter", () => { "checkpoints", "dead_letters", "disclosures", + "event_marks", "event_types", "events", "forgotten_recipients", @@ -1438,6 +1440,7 @@ describe.skipIf(testDatabase === null)("postgresql adapter", () => { "CREATE INDEX dead_letters_resolved_idx ON public.dead_letters USING btree (resolved_at, id) WHERE (resolved_at IS NOT NULL)", "CREATE INDEX dead_letters_state_person_idx ON public.dead_letters USING btree (state_person) WHERE (state_person IS NOT NULL)", "CREATE UNIQUE INDEX disclosures_pkey ON public.disclosures USING btree (person, port, recipient, kind, country, transfer, category)", + "CREATE UNIQUE INDEX event_marks_pkey ON public.event_marks USING btree (aggregate_type, type, fingerprint)", "CREATE UNIQUE INDEX event_types_pkey ON public.event_types USING btree (aggregate_type, type, schema_version)", "CREATE UNIQUE INDEX events_aggregate_type_aggregate_id_version_key ON public.events USING btree (aggregate_type, aggregate_id, version)", "CREATE UNIQUE INDEX events_id_key ON public.events USING btree (id)", diff --git a/packages/postgresql/src/schema.ts b/packages/postgresql/src/schema.ts index c4e25efe0..08a9ea2e5 100644 --- a/packages/postgresql/src/schema.ts +++ b/packages/postgresql/src/schema.ts @@ -9,6 +9,7 @@ import type { PostgresqlDatabase } from "./database.ts"; export interface StorageTables { readonly events: string; readonly eventTypes: string; + readonly eventMarks: string; readonly checkpoints: string; readonly inbox: string; readonly deadLetters: string; @@ -81,6 +82,7 @@ export const storageTablesFor: StorageTablesForFunction = ({ prefix, schema }) = return { events: quoteIdentifier(events), eventTypes: quoteIdentifier(storageTableNameFor({ prefix, table: "eventTypes" })), + eventMarks: quoteIdentifier(storageTableNameFor({ prefix, table: "eventMarks" })), checkpoints: quoteIdentifier(checkpoints), inbox: quoteIdentifier(storageTableNameFor({ prefix, table: "inbox" })), deadLetters: quoteIdentifier(storageTableNameFor({ prefix, table: "deadLetters" })), @@ -206,7 +208,8 @@ const leadingTablesStatements = (tables: StorageTables): readonly string[] => [ "payload" jsonb, "persons" jsonb NOT NULL DEFAULT '[]', "state_person" text, - "read_persons" jsonb NOT NULL DEFAULT '[]' + "read_persons" jsonb NOT NULL DEFAULT '[]', + "instance_id" text )`, `CREATE INDEX IF NOT EXISTS ${indexName(tables.deadLetters, "listing")} ON ${tables.deadLetters} ("status", "first_failed_at", "id")`, `CREATE INDEX IF NOT EXISTS ${indexName(tables.deadLetters, "person")} ON ${tables.deadLetters} ("person")`, diff --git a/packages/sqlite/src/libsql-server.test.ts b/packages/sqlite/src/libsql-server.test.ts index 75fb18620..791f74b28 100644 --- a/packages/sqlite/src/libsql-server.test.ts +++ b/packages/sqlite/src/libsql-server.test.ts @@ -91,7 +91,7 @@ describe.skipIf(server === null)("sqlite adapter on a libSQL server", () => { prefix: "replayed_", }), ); - expect(replayed).toBeLessThanOrEqual(58); + expect(replayed).toBeLessThanOrEqual(60); }); it("opens, commits and aborts a rebuild in a few requests each, however many statements it writes", async () => { diff --git a/packages/sqlite/src/sqlite.test.ts b/packages/sqlite/src/sqlite.test.ts index 478299b5b..0e336fc56 100644 --- a/packages/sqlite/src/sqlite.test.ts +++ b/packages/sqlite/src/sqlite.test.ts @@ -449,6 +449,7 @@ describe("sqlite adapter on a file", () => { ["storage", 13], ["storage", 14], ["storage", 15], + ["storage", 16], ]); }); @@ -511,6 +512,7 @@ describe("sqlite adapter on a file", () => { "app_checkpoints", "app_dead_letters", "app_disclosures", + "app_event_marks", "app_event_types", "app_events", "app_forgotten_recipients", From ea6858a1d5847c349e53f582e52a8ed59ff7ea99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 08:12:57 +0100 Subject: [PATCH 02/33] fix: name a retired timeout event for on-timeout.ts, and word E13 and E32's refusals for every kind they list --- packages/cli/src/generate/discover.test.ts | 11 +++++++++++ packages/cli/src/generate/discover.ts | 6 +++++- .../core/src/kernel/aggregate/stored-types.test.ts | 8 ++++---- packages/core/src/kernel/aggregate/stored-types.ts | 4 ++-- .../kernel/personal-data/retired-marks-app.test.ts | 2 +- packages/core/src/kernel/retired-events-app.test.ts | 2 +- 6 files changed, 24 insertions(+), 9 deletions(-) diff --git a/packages/cli/src/generate/discover.test.ts b/packages/cli/src/generate/discover.test.ts index 157aa2744..e69b1f569 100644 --- a/packages/cli/src/generate/discover.test.ts +++ b/packages/cli/src/generate/discover.test.ts @@ -487,6 +487,17 @@ describe("discoverProject and retired event types", () => { expect(model.warnings).toEqual([]); }); + it("names a retired Timeout event, not the renamed timeout handler, for on-timeout.ts", async () => { + const root = await project([ + ["app/domain/order/timeout.ts", RETIRED], + "app/domain/order/processes/payment/index.ts", + "app/domain/order/processes/payment/on-timeout.ts", + ]); + expect(await problemsOf(root)).toEqual([ + 'app/domain/order/processes/payment/on-timeout.ts: "timeout" is a retired event of this aggregate, which nothing reacts to; delete the handler', + ]); + }); + it("rejects a retired event that exports anything else, a misnamed one, and the upcasts of one", async () => { const root = await project([ "app/domain/order/order-placed.ts", diff --git a/packages/cli/src/generate/discover.ts b/packages/cli/src/generate/discover.ts index 20e1198b4..8690a6b12 100644 --- a/packages/cli/src/generate/discover.ts +++ b/packages/cli/src/generate/discover.ts @@ -335,7 +335,11 @@ const discoverProcess = async ( if (module === INDEX) continue; const path = join(directory, `${module}.ts`); if (rejectPortFile(context, path, module)) continue; - if (module === RENAMED_TIMEOUT_HANDLER && !eventKeys.has("timeout")) { + if ( + module === RENAMED_TIMEOUT_HANDLER && + !eventKeys.has("timeout") && + !retiredKeys.has("timeout") + ) { context.problems.add(path, "the timeout handler is at-timeout.ts now; rename the file"); continue; } diff --git a/packages/core/src/kernel/aggregate/stored-types.test.ts b/packages/core/src/kernel/aggregate/stored-types.test.ts index a28b5a0bb..729877229 100644 --- a/packages/core/src/kernel/aggregate/stored-types.test.ts +++ b/packages/core/src/kernel/aggregate/stored-types.test.ts @@ -144,7 +144,7 @@ describe("checkStoredTypes", () => { expect(check).toThrow(ConfigurationError); expect(check).toThrow( [ - "The store holds events this code cannot read:", + "The store holds events this code does not account for:", '- order.OrderCancelledByCustomer: no module of the aggregate "order" names it. Retire it: add order-cancelled-by-customer.ts to the aggregate, exporting only `export const retired = true`', '- order.OrderLost: no module of the aggregate "order" names it. Retire it: add order-lost.ts to the aggregate, exporting only `export const retired = true`', ].join("\n"), @@ -170,7 +170,7 @@ describe("checkStoredTypes", () => { expect(check).toThrow(ConfigurationError); expect(check).toThrow( [ - "The store holds events this code cannot read:", + "The store holds events this code does not account for:", "- bounda.PersonalDataForgotten was written in schema version 2, past the 1 this code reads: newer code wrote it. Deploy that code; roll forward, never back", "- bounda.Zed is no event of this Bounda's runtime: a newer Bounda wrote it. Upgrade @bounda-dev/core to it", "- bounda.apple is no event of this Bounda's runtime: a newer Bounda wrote it. Upgrade @bounda-dev/core to it", @@ -194,8 +194,8 @@ describe("checkStoredTypes", () => { expect(check).toThrow(ConfigurationError); expect(check).toThrow( [ - "The store holds events this code cannot read:", - '- order.OrderOpened is retired, but it opened streams of "order", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep its module instead of retiring it', + "The store holds events this code does not account for:", + '- order.OrderOpened is retired, but it opened streams of "order", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep a module that reads it, as its own does, instead of retiring it', ].join("\n"), ); }); diff --git a/packages/core/src/kernel/aggregate/stored-types.ts b/packages/core/src/kernel/aggregate/stored-types.ts index 9daba06fb..724beaea0 100644 --- a/packages/core/src/kernel/aggregate/stored-types.ts +++ b/packages/core/src/kernel/aggregate/stored-types.ts @@ -111,7 +111,7 @@ const problemOf = ( // opened a stream leaves the state without what `begin` put there. if (aggregate?.retired.has(type) === true) { return opened && aggregate.opensWithBegin - ? `${qualified} is retired, but it opened streams of "${aggregateType}", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep its module instead of retiring it` + ? `${qualified} is retired, but it opened streams of "${aggregateType}", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep a module that reads it, as its own does, instead of retiring it` : null; } const known = knownVersionOf({ aggregates, aggregateType, type }); @@ -147,7 +147,7 @@ export const checkStoredTypes: CheckStoredTypesFunction = ({ types, aggregates } .filter((problem) => problem !== null); if (problems.length > 0) { throw new ConfigurationError( - `The store holds events this code cannot read:\n${problems.map((problem) => `- ${problem}`).join("\n")}`, + `The store holds events this code does not account for:\n${problems.map((problem) => `- ${problem}`).join("\n")}`, ); } return storedTypesOf(types); diff --git a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts index 12895bbe7..67ee009da 100644 --- a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts +++ b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts @@ -666,7 +666,7 @@ describe("retiring a type that opened streams of an aggregate whose state begin const refused = createApp({ registry: ticketRegistry(true), config: { storage: adapter } }); await expect(refused).rejects.toThrow(ConfigurationError); await expect(refused).rejects.toThrow( - 'ticket.TicketOpened is retired, but it opened streams of "ticket", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep its module instead of retiring it', + 'ticket.TicketOpened is retired, but it opened streams of "ticket", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep a module that reads it, as its own does, instead of retiring it', ); const kept = await createApp({ registry: ticketRegistry(false), config: { storage: adapter } }); await kept.stop(); diff --git a/packages/core/src/kernel/retired-events-app.test.ts b/packages/core/src/kernel/retired-events-app.test.ts index b5ebe2cbf..0f5274c18 100644 --- a/packages/core/src/kernel/retired-events-app.test.ts +++ b/packages/core/src/kernel/retired-events-app.test.ts @@ -299,7 +299,7 @@ describe("an app whose store holds events of a type no module names", () => { await expect(refused).rejects.toThrow(ConfigurationError); await expect(start(adapter, dropped)).rejects.toThrow( [ - "The store holds events this code cannot read:", + "The store holds events this code does not account for:", '- order.OrderNoted: no module of the aggregate "order" names it. Retire it: add order-noted.ts to the aggregate, exporting only `export const retired = true`', '- payment.PaymentCaptured: no module of the aggregate "payment" names it. Retire it: add payment-captured.ts to the aggregate, exporting only `export const retired = true`', ].join("\n"), From 5d73ce5b09e0e3963ab5663526e6958d1a961e8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 08:13:27 +0100 Subject: [PATCH 03/33] test(core): refuse to restart older code once newer code wrote a type it has no module for --- .../core/src/kernel/retired-events-app.test.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/core/src/kernel/retired-events-app.test.ts b/packages/core/src/kernel/retired-events-app.test.ts index 0f5274c18..0768e8fe5 100644 --- a/packages/core/src/kernel/retired-events-app.test.ts +++ b/packages/core/src/kernel/retired-events-app.test.ts @@ -4,7 +4,7 @@ import type { Table } from "../adapter/storage/table.ts"; import { pendingEvent } from "../adapter/testing/fixtures.ts"; import type { RuntimeConfig } from "../config/types.ts"; import { createFixedClock } from "../contracts/clock.ts"; -import { ConfigurationError, ValidationError } from "../contracts/errors.ts"; +import { ConfigurationError, SchemaAheadError, ValidationError } from "../contracts/errors.ts"; import type { StoredEvent } from "../contracts/event.ts"; import { createSequentialIdGenerator } from "../contracts/ids.ts"; import { silentLogger } from "../contracts/logger.ts"; @@ -307,6 +307,19 @@ describe("an app whose store holds events of a type no module names", () => { await expect(start(adapter, retired)).resolves.toBeDefined(); }); + it("refuses to restart an instance of older code once newer code wrote a type it has no module for, which it met running as newer code's", async () => { + const adapter = memory(); + const { app: older } = await start(adapter, dropped); + await command(older, "placeOrder", { orderId: "o-1" }); + const { app: newer } = await start(adapter, before); + await command(newer, "noteOrder", { orderId: "o-1", note: "ring twice" }); + await expect(command(older, "payOrder", { orderId: "o-1" })).rejects.toThrow(SchemaAheadError); + await older.stop(); + await expect(start(adapter, dropped)).rejects.toThrow( + 'order.OrderNoted: no module of the aggregate "order" names it', + ); + }); + it("refuses a rebuild of a read model just as it refuses the start", async () => { const adapter = await written(); const rebuild = (registry: Registry) => From 960d67a161894d8ab3db9efadbf0c452f5b9f480 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 09:53:27 +0100 Subject: [PATCH 04/33] fix(core): renew the backfill's lease through a hold, so instances on other marks see it run A held walk returned before taking the lease, which then lapsed: an instance on other marks read these as stopped, rewrote events in a shape they may not read, called itself caught up and removed their rows, the hold included. The held instance now passes every follow interval to renew the lease, and nextDueAt still waits for the hold's end. --- .../personal-data/backfill-walk.test.ts | 36 ++++++++++++++++++- .../core/src/kernel/personal-data/backfill.ts | 28 +++++++++++---- 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/packages/core/src/kernel/personal-data/backfill-walk.test.ts b/packages/core/src/kernel/personal-data/backfill-walk.test.ts index 12ebb7f52..c1cf2dc73 100644 --- a/packages/core/src/kernel/personal-data/backfill-walk.test.ts +++ b/packages/core/src/kernel/personal-data/backfill-walk.test.ts @@ -523,10 +523,15 @@ describe("the backfill's walk", () => { expect(await one.backfill.nextDueAt()).toEqual(new Date(START.getTime() + HOLD_MS)); expect(await one.backfill.sweep(new Date(START.getTime() + HOLD_MS - 1))).toBe(0); + // Waiting, it takes the lease that lapsed, and walks nothing until it gives it back. const other = walker({ storage }); await base.checkpointStore.remove(`${BACKFILL_PREFIX}m1:lease`); expect(await other.backfill.sweep(new Date(START.getTime() + 1))).toBe(0); - expect(await rows(base)).toMatchObject({ "m1:attempts": 1 }); + expect(await rows(base)).toMatchObject({ + "m1:attempts": 1, + "m1:lease": START.getTime() + 1 + BACKFILL_LEASE_MS, + }); + await other.backfill.release(); const due = new Date(START.getTime() + HOLD_MS); expect(await one.backfill.sweep(due)).toBe(0); @@ -902,6 +907,35 @@ describe("the backfill's walk beside an instance on other marks", () => { expect(await rows(storage)).not.toHaveProperty("m1:rewrite"); }); + it("counts as running an instance whose walk is held, which renews its lease through the hold", async () => { + const storage = await memory().createStorage(); + await append(storage, pending("contact", "c-1", "ContactAdded", { mail: "a" })); + const failing: Storage = { + ...storage, + transact: () => Promise.reject(new Error("store is down")), + }; + const held = walker({ storage: failing, marks: "m0" }); + expect(await held.backfill.sweep(START)).toBe(0); + // Held far longer than a lease, as after failures in a row. + const holdEnd = START.getTime() + 30 * BACKFILL_FOLLOW_INTERVAL_MS; + await storage.checkpointStore.set(`${BACKFILL_PREFIX}m0:held-until`, holdEnd); + expect(await held.backfill.nextDueAt()).toEqual(new Date(START.getTime() + HOLD_MS)); + + const { backfill } = walker({ storage }); + for (let interval = 1; interval <= 20; interval += 1) { + const at = new Date(START.getTime() + interval * BACKFILL_FOLLOW_INTERVAL_MS); + await held.backfill.sweep(at); + await backfill.sweep(at); + } + expect(await held.backfill.nextDueAt()).toEqual(new Date(holdEnd)); + expect(await backfill.status()).toMatchObject({ caughtUp: false }); + expect(await rows(storage)).toMatchObject({ + "m0:held-until": holdEnd, + "m0:attempts": 1, + "m1:rewrite": 1, + }); + }); + it("is not caught up while a rewrite is left, and goes through the stores again after walking back", async () => { const storage = await memory().createStorage(); await append(storage, pending("contact", "c-1", "ContactAdded", { mail: "a" })); diff --git a/packages/core/src/kernel/personal-data/backfill.ts b/packages/core/src/kernel/personal-data/backfill.ts index 443865794..77e4068e4 100644 --- a/packages/core/src/kernel/personal-data/backfill.ts +++ b/packages/core/src/kernel/personal-data/backfill.ts @@ -28,7 +28,8 @@ import type { PersonalKeyWrapping } from "./wrapped-keys.ts"; * the global position the walk has sealed through; `stores`, when it last went through the * scheduled commands and dead letters; `rewrite`, the position of the first event it left in an * older shape while an instance on other marks ran; `lease`, until when the instance walking - * holds the walk; `held-until` and `attempts`, the hold of a walk that failed. Marks that change + * holds the walk, renewed through a hold too, since it tells instances on other marks that these + * still run; `held-until` and `attempts`, the hold of a walk that failed. Marks that change * start them all again. */ export const BACKFILL_PREFIX = "personal-data:backfill:"; @@ -198,6 +199,8 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ const rows = rowsOf(marks); const pause = createPause(); let restUntil = Number.NEGATIVE_INFINITY; + // The end of the hold this instance last met: it passes before then only to renew the lease. + let holdEnd = Number.NEGATIVE_INFINITY; const lease = createLease({ checkpoints: checkpointStore, row: rows.lease, clock, logger }); let caughtUp = false; let tally = NO_TALLY; @@ -245,18 +248,26 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ return { until: new Date(until).toISOString(), attempts }; }; + // A held walk passes every follow interval all the same, to renew the lease: one that lapsed + // that long tells instances on other marks that these no longer run. + const restUntilEndOf = (at: number, until: number): void => { + holdEnd = until; + restUntil = Math.min(until, at + BACKFILL_FOLLOW_INTERVAL_MS); + }; + // A hold still running was set by another instance failing in the same round: this failure // waits for it rather than counting once more. const hold = async (at: number): Promise => { const held = await storedHold(); if (!isReleasedBy(held, new Date(at))) { - restUntil = Date.parse(held.until); + restUntilEndOf(at, Date.parse(held.until)); return; } const next = holdAfter({ held, at, failed: true }); - restUntil = Date.parse(next.until); + const until = Date.parse(next.until); + restUntilEndOf(at, until); await checkpointStore.set(rows.attempts, next.attempts); - await checkpointStore.set(rows.heldUntil, restUntil); + await checkpointStore.set(rows.heldUntil, until); }; const releaseHold = async (): Promise => { @@ -460,9 +471,11 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ const at = now.getTime(); const heldUntil = await checkpointStore.get(rows.heldUntil); if (heldUntil > at) { - restUntil = heldUntil; + restUntilEndOf(at, heldUntil); + await lease.take(at); return 0; } + holdEnd = Number.NEGATIVE_INFINITY; if (!(await lease.take(at))) return 0; const listed = await listRows(); let started = await checkpointStore.get(rows.started); @@ -528,7 +541,9 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ caughtUp = (await status()).caughtUp; if (caughtUp) return null; return new Date( - pause.notBefore(Math.max(clock.now().getTime(), restUntil, lease.heldElsewhereUntil())), + pause.notBefore( + Math.max(clock.now().getTime(), restUntil, holdEnd, lease.heldElsewhereUntil()), + ), ); }, status, @@ -536,6 +551,7 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ restored: async (first) => { caughtUp = false; restUntil = Number.NEGATIVE_INFINITY; + holdEnd = Number.NEGATIVE_INFINITY; pause.resume(); lease.reset(); if (!first) return; From dc9b073f0e33325dd7e8a90c386d938a78010dff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 10:04:33 +0100 Subject: [PATCH 05/33] feat(core): record how far a walk sealed every value under each set of marks bounda_event_marks gains sealed_through, in the unreleased migration. EventStore.recordSealed raises it on the sets given and clears it on the type's other sets sealed no further, so the set sealed last holds the highest: monotone, fenced and staged in transactions like recordMarks, on memory, SQLite and PostgreSQL. --- docs/src/content/docs/adapters/index.mdx | 2 +- packages/core/src/adapter/index.ts | 2 + .../core/src/adapter/sql/event-marks.test.ts | 66 +++++++++- packages/core/src/adapter/sql/event-marks.ts | 117 ++++++++++++++++- packages/core/src/adapter/sql/index.ts | 3 + .../core/src/adapter/sqlite/event-store.ts | 18 ++- .../core/src/adapter/staged-event-store.ts | 22 +++- .../core/src/adapter/storage/event-store.ts | 34 ++++- .../adapter/testing/event-store.contract.ts | 120 +++++++++++++++--- .../adapter/testing/inspection.contract.ts | 4 + .../src/adapter/testing/restore.contract.ts | 28 +++- .../src/kernel/aggregate/stored-types.test.ts | 1 + .../core/src/kernel/aggregate/upcasting.ts | 1 + .../src/kernel/personal-data/event-store.ts | 1 + .../kernel/personal-data/resealing.test.ts | 2 + .../kernel/personal-data/stored-marks.test.ts | 1 + .../src/kernel/shared/committed-events.ts | 1 + .../src/kernel/unit-of-work/unit-of-work.ts | 3 + packages/core/src/memory/event-store.ts | 18 ++- packages/core/src/memory/tenant-fence.ts | 10 +- packages/core/src/memory/transaction.ts | 1 + packages/postgresql/src/event-store.ts | 12 ++ 22 files changed, 429 insertions(+), 38 deletions(-) diff --git a/docs/src/content/docs/adapters/index.mdx b/docs/src/content/docs/adapters/index.mdx index bc7fd77db..e27737a93 100644 --- a/docs/src/content/docs/adapters/index.mdx +++ b/docs/src/content/docs/adapters/index.mdx @@ -90,7 +90,7 @@ it brings them up to the version the installed Bounda expects | --- | --- | | `bounda_events` | Every event, with its stream version, a global position and the person it names, if any, which [`exportPersonalData`](/guides/personal-data/#exporting-a-persons-data) reads by | | `bounda_event_types` | Each kind of event the store holds, by aggregate type, type and schema version, and whether an event of it opened a stream, which every append records in its own transaction and a start [checks against the code](/guides/changing-events/#what-the-runtime-checks) | -| `bounda_event_marks` | Each set of [personal marks](/guides/personal-data/) an event type had, by aggregate type, type and a fingerprint of the marks, in the order first recorded and with when: written once and never changed, so a type's marks outlive its module | +| `bounda_event_marks` | Each set of [personal marks](/guides/personal-data/) an event type had, by aggregate type, type and a fingerprint of the marks, in the order first recorded and with when: written once and never removed, so a type's marks outlive its module. `sealed_through` is the position through which the backfill last sealed every value under the set while no instance on other marks ran, kept only on the set of the type that did so last | | `bounda_checkpoints` | How far each projection, the policy runner, the process runner, the retention and the [forget ledger](/guides/personal-data/#backups)'s copy have read, where a paused rebuild stands, the time of the last ledger entry the database applied, when the last reconciliation ran and the wait of one that failed, when the [key rotation](/guides/personal-data/#rotating-the-tenants-key) was last found complete, the leases of the [background jobs](/guides/deployment/#more-than-one-instance), the counters that tell a [restore](/guides/personal-data/#restores), and, for a read model in a database of its own, the event each of its checkpoints stands at, there, and how far it reached, in the storage's | | `bounda_inbox` | Which handler already completed for which event, so a retry does not run it again | | `bounda_scheduled_commands` | Scheduled commands, process deadlines and timeouts, and delayed policy runs, each with when it was scheduled | diff --git a/packages/core/src/adapter/index.ts b/packages/core/src/adapter/index.ts index d11dd5af2..3358db2e0 100644 --- a/packages/core/src/adapter/index.ts +++ b/packages/core/src/adapter/index.ts @@ -68,6 +68,7 @@ export type { AppendResult, EventStore, EventTypeMarks, + EventTypeMarksKey, LoadArgs, LoadManyArgs, LoadResult, @@ -78,6 +79,7 @@ export type { ReadOneArgs, RecordedPersonalMarks, RecordMarksArgs, + RecordSealedArgs, ResealedEvent, ResealedFrom, StoredEventType, diff --git a/packages/core/src/adapter/sql/event-marks.test.ts b/packages/core/src/adapter/sql/event-marks.test.ts index 57204d6a4..13a842b58 100644 --- a/packages/core/src/adapter/sql/event-marks.test.ts +++ b/packages/core/src/adapter/sql/event-marks.test.ts @@ -5,6 +5,7 @@ import { eventMarksTableStatement, marksOfRow, recordMarksStatements, + recordSealedStatements, selectMarksStatement, } from "./event-marks.ts"; import { MAX_PARAMETERS_PER_STATEMENT } from "./event-rows.ts"; @@ -26,10 +27,12 @@ describe("eventMarksTableStatement", () => { expect(sqlite).toContain('"seq" INTEGER PRIMARY KEY AUTOINCREMENT'); expect(sqlite).toContain('UNIQUE ("aggregate_type", "type", "fingerprint")'); expect(sqlite).toContain('"marks" TEXT,'); + expect(sqlite).toContain('"sealed_through" INTEGER,'); const postgresql = eventMarksTableStatement({ dialect: postgresqlDialect, table: '"m"' }); expect(postgresql).toContain('"seq" BIGSERIAL NOT NULL'); expect(postgresql).toContain('PRIMARY KEY ("aggregate_type", "type", "fingerprint")'); expect(postgresql).toContain('"marks" jsonb,'); + expect(postgresql).toContain('"sealed_through" bigint,'); }); }); @@ -120,14 +123,14 @@ describe("selectMarksStatement", () => { of: { aggregateType: "order", type: "OrderPlaced" }, }), ).toEqual({ - sql: 'SELECT "aggregate_type", "type", "fingerprint", "marks", "first_seen_at" FROM "m" WHERE "aggregate_type" = $1 AND "type" = $2 ORDER BY "seq"', + sql: 'SELECT "aggregate_type", "type", "fingerprint", "marks", "first_seen_at", "sealed_through" FROM "m" WHERE "aggregate_type" = $1 AND "type" = $2 ORDER BY "seq"', params: ["order", "OrderPlaced"], }); }); it("reads the sets of every type in the order they were first recorded when no type is given", () => { expect(selectMarksStatement({ dialect: postgresqlDialect, table: '"m"' })).toEqual({ - sql: 'SELECT "aggregate_type", "type", "fingerprint", "marks", "first_seen_at" FROM "m" ORDER BY "seq"', + sql: 'SELECT "aggregate_type", "type", "fingerprint", "marks", "first_seen_at", "sealed_through" FROM "m" ORDER BY "seq"', params: [], }); }); @@ -143,6 +146,7 @@ describe("marksOfRow", () => { fingerprint: "a", marks: MARKS, firstSeenAt: AT, + sealedThrough: null, }; expect(marksOfRow({ ...row, marks: JSON.stringify(MARKS) })).toEqual(expected); expect(marksOfRow({ ...row, marks: MARKS })).toEqual(expected); @@ -151,4 +155,62 @@ describe("marksOfRow", () => { it("reads no marks as null", () => { expect(marksOfRow({ ...row, marks: null }).marks).toBeNull(); }); + + it("reads the position sealed through as a number, PostgreSQL's bigint text included", () => { + expect(marksOfRow({ ...row, marks: null, sealed_through: 7 }).sealedThrough).toBe(7); + expect(marksOfRow({ ...row, marks: null, sealed_through: "9" }).sealedThrough).toBe(9); + }); +}); + +describe("recordSealedStatements", () => { + it("raises the sets given of each type, then clears the type's others sealed no further once one given is recorded, the types in the order recordMarks writes them", () => { + const statements = recordSealedStatements({ + dialect: sqliteDialect, + table: '"m"', + sets: [ + { aggregateType: "order", type: "OrderPlaced", fingerprint: "b" }, + { aggregateType: "order", type: "OrderPaid", fingerprint: "x" }, + { aggregateType: "order", type: "OrderPlaced", fingerprint: "a" }, + { aggregateType: "order", type: "OrderPlaced", fingerprint: "b" }, + ], + through: 7, + }); + expect(statements).toEqual([ + { + sql: 'UPDATE "m" SET "sealed_through" = ? WHERE "aggregate_type" = ? AND "type" = ? AND "fingerprint" IN (?) AND ("sealed_through" IS NULL OR "sealed_through" < ?)', + params: [7, "order", "OrderPaid", "x", 7], + }, + { + sql: 'UPDATE "m" SET "sealed_through" = NULL WHERE "aggregate_type" = ? AND "type" = ? AND "fingerprint" NOT IN (?) AND "sealed_through" <= ? AND EXISTS (SELECT 1 FROM "m" AS "own" WHERE "own"."aggregate_type" = ? AND "own"."type" = ? AND "own"."fingerprint" IN (?))', + params: ["order", "OrderPaid", "x", 7, "order", "OrderPaid", "x"], + }, + { + sql: 'UPDATE "m" SET "sealed_through" = ? WHERE "aggregate_type" = ? AND "type" = ? AND "fingerprint" IN (?, ?) AND ("sealed_through" IS NULL OR "sealed_through" < ?)', + params: [7, "order", "OrderPlaced", "a", "b", 7], + }, + { + sql: 'UPDATE "m" SET "sealed_through" = NULL WHERE "aggregate_type" = ? AND "type" = ? AND "fingerprint" NOT IN (?, ?) AND "sealed_through" <= ? AND EXISTS (SELECT 1 FROM "m" AS "own" WHERE "own"."aggregate_type" = ? AND "own"."type" = ? AND "own"."fingerprint" IN (?, ?))', + params: ["order", "OrderPlaced", "a", "b", 7, "order", "OrderPlaced", "a", "b"], + }, + ]); + }); + + it("numbers PostgreSQL's placeholders in the order their values are given, in each statement", () => { + const [raise, clear] = recordSealedStatements({ + dialect: postgresqlDialect, + table: '"m"', + sets: [{ aggregateType: "order", type: "OrderPlaced", fingerprint: "a" }], + through: 7, + }); + expect(raise?.sql).toContain('= $1 WHERE "aggregate_type" = $2 AND "type" = $3'); + expect(raise?.sql).toContain('IN ($4) AND ("sealed_through" IS NULL OR "sealed_through" < $5)'); + expect(clear?.sql).toContain('NOT IN ($3) AND "sealed_through" <= $4'); + expect(clear?.sql).toContain('"own"."type" = $6 AND "own"."fingerprint" IN ($7)'); + }); + + it("writes nothing for no sets", () => { + expect( + recordSealedStatements({ dialect: sqliteDialect, table: '"m"', sets: [], through: 7 }), + ).toEqual([]); + }); }); diff --git a/packages/core/src/adapter/sql/event-marks.ts b/packages/core/src/adapter/sql/event-marks.ts index 9c408ad9f..ed7b2305e 100644 --- a/packages/core/src/adapter/sql/event-marks.ts +++ b/packages/core/src/adapter/sql/event-marks.ts @@ -1,7 +1,9 @@ import type { EventTypeMarks, + EventTypeMarksKey, MarksOfArgs, RecordedPersonalMarks, + RecordSealedArgs, StoredEventTypeMarks, } from "../storage/event-store.ts"; import type { SqlDialect } from "./dialect.ts"; @@ -24,7 +26,7 @@ export interface EventMarksTableStatementFunction { /** * The statement that creates the table of the marks event types had, `EventStore.marksOf` reads: * one row per aggregate type, event type and fingerprint, numbered in the order they were first - * recorded. + * recorded, with the position `recordSealed` raised it to. */ export const eventMarksTableStatement: EventMarksTableStatementFunction = ({ dialect, table }) => dialect.name === "sqlite" @@ -35,6 +37,7 @@ export const eventMarksTableStatement: EventMarksTableStatementFunction = ({ dia "marks" TEXT, "seq" INTEGER PRIMARY KEY AUTOINCREMENT, "first_seen_at" TEXT NOT NULL, + "sealed_through" INTEGER, UNIQUE ("aggregate_type", "type", "fingerprint") )` : `CREATE TABLE IF NOT EXISTS ${table} ( @@ -44,6 +47,7 @@ export const eventMarksTableStatement: EventMarksTableStatementFunction = ({ dia "marks" jsonb, "seq" BIGSERIAL NOT NULL, "first_seen_at" text NOT NULL, + "sealed_through" bigint, PRIMARY KEY ("aggregate_type", "type", "fingerprint") )`; @@ -66,7 +70,7 @@ const PARAMETERS_PER_SET = 5; const SETS_PER_INSERT = Math.floor(MAX_PARAMETERS_PER_STATEMENT / PARAMETERS_PER_SET); export interface MarkSetsInOrderFunction { - (marks: readonly EventTypeMarks[]): readonly EventTypeMarks[]; + (marks: readonly Set[]): readonly Set[]; } /** @@ -74,8 +78,10 @@ export interface MarkSetsInOrderFunction { * the order `recordMarks` records them: one every writer shares, so two that record the same new * sets wait on each other instead of deadlocking. */ -export const markSetsInOrder: MarkSetsInOrderFunction = (marks) => { - const sets = new Map(); +export const markSetsInOrder: MarkSetsInOrderFunction = ( + marks: readonly Set[], +) => { + const sets = new Map(); for (const set of marks) { const key = JSON.stringify([set.aggregateType, set.type, set.fingerprint]); if (!sets.has(key)) sets.set(key, set); @@ -120,6 +126,103 @@ export const recordMarksStatements: RecordMarksStatementsFunction = ({ return statements; }; +export interface RecordSealedStatementsArgs { + readonly dialect: Pick; + /** + * Already quoted. + */ + readonly table: string; + readonly sets: readonly EventTypeMarksKey[]; + readonly through: number; +} + +export interface RecordSealedStatementsFunction { + (args: RecordSealedStatementsArgs): readonly InsertStatement[]; +} + +/** + * The given sets of each type, the types in the order `recordMarks` writes them. + */ +const byType = (sets: readonly EventTypeMarksKey[]) => { + const types = new Map(); + for (const { aggregateType, type, fingerprint } of markSetsInOrder(sets)) { + const key = JSON.stringify([aggregateType, type]); + const held = types.get(key) ?? { aggregateType, type, fingerprints: [] }; + types.set(key, { ...held, fingerprints: [...held.fingerprints, fingerprint] }); + } + return [...types.values()]; +}; + +/** + * The statements `EventStore.recordSealed` runs in one transaction, two for each type, in the + * order `recordMarks` writes them, so two writers lock the rows alike: the first raises the sets + * given, the second clears the type's other sets sealed no further, once one given is recorded. + */ +export const recordSealedStatements: RecordSealedStatementsFunction = ({ + dialect, + table, + sets, + through, +}) => { + const statements: InsertStatement[] = []; + for (const { aggregateType, type, fingerprints } of byType(sets)) { + let next = 0; + const take = (count: number): string[] => + Array.from({ length: count }, () => { + next += 1; + return dialect.placeholder(next); + }); + const [raised, raisedType, raisedKind] = take(3); + const raisedSets = take(fingerprints.length).join(", "); + const [raisedBelow] = take(1); + statements.push({ + sql: `UPDATE ${table} SET "sealed_through" = ${raised} WHERE "aggregate_type" = ${raisedType} AND "type" = ${raisedKind} AND "fingerprint" IN (${raisedSets}) AND ("sealed_through" IS NULL OR "sealed_through" < ${raisedBelow})`, + params: [through, aggregateType, type, ...fingerprints, through], + }); + next = 0; + const [clearedType, clearedKind] = take(2); + const others = take(fingerprints.length).join(", "); + const [cleared, ownType, ownKind] = take(3); + const own = take(fingerprints.length).join(", "); + statements.push({ + sql: `UPDATE ${table} SET "sealed_through" = NULL WHERE "aggregate_type" = ${clearedType} AND "type" = ${clearedKind} AND "fingerprint" NOT IN (${others}) AND "sealed_through" <= ${cleared} AND EXISTS (SELECT 1 FROM ${table} AS "own" WHERE "own"."aggregate_type" = ${ownType} AND "own"."type" = ${ownKind} AND "own"."fingerprint" IN (${own}))`, + params: [aggregateType, type, ...fingerprints, through, aggregateType, type, ...fingerprints], + }); + } + return statements; +}; + +export interface SealedSet extends EventTypeMarksKey { + readonly sealedThrough: number | null; +} + +export interface WithSealedFunction { + (stored: readonly Set[], args: RecordSealedArgs): readonly Set[]; +} + +/** + * The sets as `recordSealedStatements` leaves them, for a store that keeps them in memory. + */ +export const withSealed: WithSealedFunction = ( + stored: readonly Set[], + { sets, through }: RecordSealedArgs, +) => + byType(sets).reduce((held, { aggregateType, type, fingerprints }) => { + const ofType = (set: Set): boolean => set.aggregateType === aggregateType && set.type === type; + const recorded = held.some((set) => ofType(set) && fingerprints.includes(set.fingerprint)); + return held.map((set) => { + if (!ofType(set) || !recorded) return set; + if (fingerprints.includes(set.fingerprint)) { + return set.sealedThrough === null || set.sealedThrough < through + ? { ...set, sealedThrough: through } + : set; + } + return set.sealedThrough !== null && set.sealedThrough <= through + ? { ...set, sealedThrough: null } + : set; + }); + }, stored); + export interface SelectMarksStatementArgs { readonly dialect: Pick; /** @@ -141,7 +244,7 @@ export interface SelectMarksStatementFunction { * were first recorded, each row one `marksOfRow` decodes. */ export const selectMarksStatement: SelectMarksStatementFunction = ({ dialect, table, of }) => { - const columns = `SELECT "aggregate_type", "type", "fingerprint", "marks", "first_seen_at" FROM ${table}`; + const columns = `SELECT "aggregate_type", "type", "fingerprint", "marks", "first_seen_at", "sealed_through" FROM ${table}`; return of === undefined ? { sql: `${columns} ORDER BY "seq"`, params: [] } : { @@ -168,4 +271,8 @@ export const marksOfRow: MarksOfRowFunction = (row) => ({ ? JSON.parse(row.marks) : row.marks) as RecordedPersonalMarks), firstSeenAt: String(row.first_seen_at), + sealedThrough: + row.sealed_through === null || row.sealed_through === undefined + ? null + : Number(row.sealed_through), }); diff --git a/packages/core/src/adapter/sql/index.ts b/packages/core/src/adapter/sql/index.ts index fc53dd092..e5f1eaca9 100644 --- a/packages/core/src/adapter/sql/index.ts +++ b/packages/core/src/adapter/sql/index.ts @@ -27,6 +27,8 @@ export type { MarksOfRowFunction, RecordMarksStatementsArgs, RecordMarksStatementsFunction, + RecordSealedStatementsArgs, + RecordSealedStatementsFunction, SelectMarksStatementArgs, SelectMarksStatementFunction, } from "./event-marks.ts"; @@ -34,6 +36,7 @@ export { eventMarksTableStatement, marksOfRow, recordMarksStatements, + recordSealedStatements, selectMarksStatement, } from "./event-marks.ts"; export type { InsertEventsArgs, InsertEventsFunction, InsertStatement } from "./event-rows.ts"; diff --git a/packages/core/src/adapter/sqlite/event-store.ts b/packages/core/src/adapter/sqlite/event-store.ts index e7c1db331..e90d7052c 100644 --- a/packages/core/src/adapter/sqlite/event-store.ts +++ b/packages/core/src/adapter/sqlite/event-store.ts @@ -5,7 +5,12 @@ import type { EventStore, StoredEventType } from "../index.ts"; import { checkSqlAppend } from "../sql/append-checks.ts"; import { runInOrder, type SqlDatabase, type SqlTransaction } from "../sql/database.ts"; import { sqliteDialect } from "../sql/dialect.ts"; -import { marksOfRow, recordMarksStatements, selectMarksStatement } from "../sql/event-marks.ts"; +import { + marksOfRow, + recordMarksStatements, + recordSealedStatements, + selectMarksStatement, +} from "../sql/event-marks.ts"; import { insertEventsStatements, positionsByVersion } from "../sql/event-rows.ts"; import { eventTypeOfRow, @@ -227,6 +232,17 @@ export const createSqliteEventStore: CreateSqliteEventStoreFunction = ({ }); return (await db.all(sql, params)).map(marksOfRow); }, + recordSealed: ({ sets, through }) => + db.write(async (tx) => { + for (const { sql, params } of recordSealedStatements({ + dialect: sqliteDialect, + table: eventMarks, + sets, + through, + })) { + await tx.run(sql, params); + } + }), reseal: (events) => db.write(async (tx) => { const kinds: StoredEventType[] = []; diff --git a/packages/core/src/adapter/staged-event-store.ts b/packages/core/src/adapter/staged-event-store.ts index d7bb1351e..4387949bd 100644 --- a/packages/core/src/adapter/staged-event-store.ts +++ b/packages/core/src/adapter/staged-event-store.ts @@ -1,7 +1,7 @@ import { ConcurrencyError } from "../contracts/errors.ts"; import { type StoredEvent, streamId } from "../contracts/event.ts"; import type { RestrictionBasis } from "../modules/personal-data.ts"; -import { markSetsInOrder } from "./sql/event-marks.ts"; +import { markSetsInOrder, withSealed } from "./sql/event-marks.ts"; import { kindsOfEvents, pendingEventTypes } from "./sql/event-types.ts"; import { holdsResealedFrom } from "./sql/resealed-from.ts"; import type { @@ -9,6 +9,7 @@ import type { EventStore, EventTypeMarks, RecordMarksArgs, + RecordSealedArgs, ResealedEvent, StoredEventTypeMarks, } from "./storage/event-store.ts"; @@ -21,14 +22,17 @@ import { type KeyedPerson, keyedPersonId } from "./storage/personal-key-store.ts * `lastPosition` read the base store alone, since staged events are not written yet, nor are the * events `reseal` stages. `types` adds to the base store's the kinds staged, as a transaction's * catalogue holds the kinds it wrote, and `marksOf` adds to the base store's sets those - * `recordMarks` staged that it holds none of, after them. `batches` hands out what to append at - * commit, one batch per stream, each expecting the version the stream had in the base store when - * the view first met it, `reseals` what to write again after, and `markings` the marks to record. + * `recordMarks` staged that it holds none of, after them, every set as `recordSealed` staged + * leaves it. `batches` hands out what to append at commit, one batch per stream, each expecting + * the version the stream had in the base store when the view first met it, `reseals` what to + * write again after, `markings` the marks to record and `sealings` what to record sealed, after + * them. */ export interface StagedEventStore extends EventStore { batches(): readonly StagedBatch[]; reseals(): readonly ResealedEvent[]; markings(): readonly RecordMarksArgs[]; + sealings(): readonly RecordSealedArgs[]; } /** @@ -77,6 +81,7 @@ export const createStagedEventStore: CreateStagedEventStoreFunction = ( const streams = new Map(); const resealed: ResealedEvent[] = []; const marked: RecordMarksArgs[] = []; + const sealed: RecordSealedArgs[] = []; const stagedFor = async (aggregateType: string, aggregateId: string): Promise => { const key = streamId({ aggregateType, aggregateId }); @@ -202,12 +207,17 @@ export const createStagedEventStore: CreateStagedEventStoreFunction = ( of !== undefined && (set.aggregateType !== of.aggregateType || set.type !== of.type); if (other || held.has(key)) continue; held.add(key); - staged.push({ ...set, firstSeenAt: at }); + staged.push({ ...set, firstSeenAt: at, sealedThrough: null }); } } - return [...recorded, ...staged]; + const all = [...recorded, ...staged]; + return sealed.reduce(withSealed, all); }, markings: () => marked, + recordSealed: async (args) => { + sealed.push(args); + }, + sealings: () => sealed, // An event given `from` is checked against the base store as it holds it now, and checked // again as it is written at commit. reseal: async (events) => { diff --git a/packages/core/src/adapter/storage/event-store.ts b/packages/core/src/adapter/storage/event-store.ts index edac6f54b..846456b9a 100644 --- a/packages/core/src/adapter/storage/event-store.ts +++ b/packages/core/src/adapter/storage/event-store.ts @@ -136,9 +136,9 @@ export interface RecordedPersonalMarks { } /** - * One set of marks an event type had, as `recordMarks` takes it. + * What names one set of marks an event type had, as `recordSealed` takes it. */ -export interface EventTypeMarks { +export interface EventTypeMarksKey { readonly aggregateType: string; readonly type: string; /** @@ -146,6 +146,12 @@ export interface EventTypeMarks { * equal marks give equal fingerprints. */ readonly fingerprint: string; +} + +/** + * One set of marks an event type had, as `recordMarks` takes it. + */ +export interface EventTypeMarks extends EventTypeMarksKey { /** * `null` for a type whose payload marks nothing. */ @@ -157,6 +163,20 @@ export interface EventTypeMarks { */ export interface StoredEventTypeMarks extends EventTypeMarks { readonly firstSeenAt: string; + /** + * The global position through which a walk of the store under this set last sealed every + * value, as `recordSealed` raised it; `null` while none did, or once another set of the type + * sealed as far since. + */ + readonly sealedThrough: number | null; +} + +export interface RecordSealedArgs { + readonly sets: readonly EventTypeMarksKey[]; + /** + * The global position the walk sealed every value through. + */ + readonly through: number; } export interface RecordMarksArgs { @@ -222,7 +242,7 @@ export interface EventStore { /** * Records, in one transaction, each set of marks its aggregate type, type and fingerprint have * no set for yet, and leaves a set already recorded as it is, whatever the new one holds: a set - * is written once, never changed or removed. Each set recorded takes the next place in the + * is written once, never removed, and only `recordSealed` changes it. Each set recorded takes the next place in the * order `marksOf` reads, never by a clock; those of one call in the code-point order of their * aggregate type, type and fingerprint, so two callers recording the same sets at once never * wait on each other in a loop. A write, refused behind the tenant's fence as `append` is. @@ -234,6 +254,14 @@ export interface EventStore { * time. */ marksOf(args?: MarksOfArgs): Promise; + /** + * Records, in one transaction, that every value of each set given is sealed through + * `through`: raises the set's `sealedThrough` to it, never lowers it, and clears it on the + * type's other sets whose `sealedThrough` is no further, so the set sealed last holds the + * highest. A set not recorded is left as it is. A write, refused behind the tenant's fence as + * `append` is. + */ + recordSealed(args: RecordSealedArgs): Promise; /** * Replaces the payload and `person` of the event at each position given, and its * `metadata.schemaVersion` when given, and nothing else of it. An event given `from` is written diff --git a/packages/core/src/adapter/testing/event-store.contract.ts b/packages/core/src/adapter/testing/event-store.contract.ts index 8e20cf7e5..4ddb745c5 100644 --- a/packages/core/src/adapter/testing/event-store.contract.ts +++ b/packages/core/src/adapter/testing/event-store.contract.ts @@ -1296,11 +1296,11 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr at: T3, }); expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ - { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1 }, - { ...marksOf("OrderPlaced", "a", OTHER_MARKS), firstSeenAt: T2 }, + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1, sealedThrough: null }, + { ...marksOf("OrderPlaced", "a", OTHER_MARKS), firstSeenAt: T2, sealedThrough: null }, ]); expect(await store.marksOf({ aggregateType: "order", type: "OrderPaid" })).toEqual([ - { ...marksOf("OrderPaid", "x", null), firstSeenAt: T2 }, + { ...marksOf("OrderPaid", "x", null), firstSeenAt: T2, sealedThrough: null }, ]); expect(await fingerprintsOf("OrderShipped")).toEqual([]); }); @@ -1310,8 +1310,8 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr await store.recordMarks({ marks: [marksOf("OrderPlaced", "b", OTHER_MARKS)], at: T2 }); await store.recordMarks({ marks: [marksOf("OrderPlaced", "a", null)], at: T3 }); expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ - { ...marksOf("OrderPlaced", "a"), firstSeenAt: T1 }, - { ...marksOf("OrderPlaced", "b", OTHER_MARKS), firstSeenAt: T2 }, + { ...marksOf("OrderPlaced", "a"), firstSeenAt: T1, sealedThrough: null }, + { ...marksOf("OrderPlaced", "b", OTHER_MARKS), firstSeenAt: T2, sealedThrough: null }, ]); }); @@ -1326,9 +1326,9 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr at: T1, }); expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ - { ...marksOf("OrderPlaced", "B"), firstSeenAt: T1 }, - { ...marksOf("OrderPlaced", "a"), firstSeenAt: T1 }, - { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1 }, + { ...marksOf("OrderPlaced", "B"), firstSeenAt: T1, sealedThrough: null }, + { ...marksOf("OrderPlaced", "a"), firstSeenAt: T1, sealedThrough: null }, + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1, sealedThrough: null }, ]); }); @@ -1372,7 +1372,7 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr transaction.eventStore.recordMarks({ marks: [marksOf("OrderPlaced", "b")], at: T2 }), ); expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ - { ...marksOf("OrderPlaced", "b"), firstSeenAt: T2 }, + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T2, sealedThrough: null }, ]); }); @@ -1394,10 +1394,15 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr }); await store.recordMarks({ marks: [marksOf("OrderPlaced", "a", OTHER_MARKS)], at: T3 }); expect(await store.marksOf()).toEqual([ - { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1 }, - { ...marksOf("OrderPlaced", "c"), aggregateType: "customer", firstSeenAt: T2 }, - { ...marksOf("OrderPaid", "x", null), firstSeenAt: T2 }, - { ...marksOf("OrderPlaced", "a", OTHER_MARKS), firstSeenAt: T3 }, + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1, sealedThrough: null }, + { + ...marksOf("OrderPlaced", "c"), + aggregateType: "customer", + firstSeenAt: T2, + sealedThrough: null, + }, + { ...marksOf("OrderPaid", "x", null), firstSeenAt: T2, sealedThrough: null }, + { ...marksOf("OrderPlaced", "a", OTHER_MARKS), firstSeenAt: T3, sealedThrough: null }, ]); }); @@ -1415,9 +1420,9 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr expect( await transaction.eventStore.marksOf({ aggregateType: "order", type: "OrderPlaced" }), ).toEqual([ - { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1 }, - { ...marksOf("OrderPlaced", "c"), firstSeenAt: T2 }, - { ...marksOf("OrderPlaced", "a", OTHER_MARKS), firstSeenAt: T3 }, + { ...marksOf("OrderPlaced", "b"), firstSeenAt: T1, sealedThrough: null }, + { ...marksOf("OrderPlaced", "c"), firstSeenAt: T2, sealedThrough: null }, + { ...marksOf("OrderPlaced", "a", OTHER_MARKS), firstSeenAt: T3, sealedThrough: null }, ]); expect( (await transaction.eventStore.marksOf()).map(({ fingerprint }) => fingerprint), @@ -1425,5 +1430,88 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr }); expect(await fingerprintsOf("OrderPlaced")).toEqual(["b", "c", "a"]); }); + + const keyOf = (type: string, fingerprint: string) => ({ + aggregateType: "order", + type, + fingerprint, + }); + const sealedOf = async (target: EventStore = store) => + (await target.marksOf()).map( + ({ type, fingerprint, sealedThrough }) => `${type}:${fingerprint}:${sealedThrough}`, + ); + + it("raises a set's sealedThrough, never lowers it, and leaves a set not recorded as it is", async () => { + await store.recordMarks({ + marks: [marksOf("OrderPlaced", "a"), marksOf("OrderPaid", "x", null)], + at: T1, + }); + expect(await sealedOf()).toEqual(["OrderPaid:x:null", "OrderPlaced:a:null"]); + await store.recordSealed({ + sets: [keyOf("OrderPlaced", "a"), keyOf("OrderPlaced", "gone")], + through: 5, + }); + expect(await sealedOf()).toEqual(["OrderPaid:x:null", "OrderPlaced:a:5"]); + await store.recordSealed({ sets: [keyOf("OrderPlaced", "a")], through: 3 }); + expect(await sealedOf()).toEqual(["OrderPaid:x:null", "OrderPlaced:a:5"]); + await store.recordSealed({ sets: [keyOf("OrderPlaced", "a")], through: 8 }); + await store.recordSealed({ sets: [], through: 9 }); + expect(await store.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ + { ...marksOf("OrderPlaced", "a"), firstSeenAt: T1, sealedThrough: 8 }, + ]); + }); + + it("clears it on the type's other sets sealed no further, so the set sealed last holds the highest", async () => { + await store.recordMarks({ + marks: [ + marksOf("OrderPlaced", "a"), + marksOf("OrderPlaced", "b", OTHER_MARKS), + marksOf("OrderPaid", "x", null), + ], + at: T1, + }); + await store.recordSealed({ sets: [keyOf("OrderPlaced", "a")], through: 5 }); + await store.recordSealed({ sets: [keyOf("OrderPaid", "x")], through: 5 }); + await store.recordSealed({ sets: [keyOf("OrderPlaced", "b")], through: 5 }); + expect(await sealedOf()).toEqual(["OrderPaid:x:5", "OrderPlaced:a:null", "OrderPlaced:b:5"]); + // Recorded late, by a walk that read the store before the other sealed. + await store.recordSealed({ sets: [keyOf("OrderPlaced", "a")], through: 4 }); + expect(await sealedOf()).toEqual(["OrderPaid:x:5", "OrderPlaced:a:4", "OrderPlaced:b:5"]); + // Sets of one type given together each hold it, and clear none of the others given. + await store.recordSealed({ + sets: [keyOf("OrderPlaced", "a"), keyOf("OrderPlaced", "b")], + through: 6, + }); + expect(await sealedOf()).toEqual(["OrderPaid:x:5", "OrderPlaced:a:6", "OrderPlaced:b:6"]); + }); + + it("records sealed what a transaction records when it commits, shown to it before, and nothing when it rolls back", async () => { + await store.recordMarks({ + marks: [marksOf("OrderPlaced", "a"), marksOf("OrderPlaced", "b", OTHER_MARKS)], + at: T1, + }); + await store.recordSealed({ sets: [keyOf("OrderPlaced", "a")], through: 5 }); + await storage.transact(async (transaction) => { + await transaction.eventStore.recordSealed({ + sets: [keyOf("OrderPlaced", "b")], + through: 7, + }); + expect(await sealedOf(transaction.eventStore)).toEqual([ + "OrderPlaced:a:null", + "OrderPlaced:b:7", + ]); + }); + expect(await sealedOf()).toEqual(["OrderPlaced:a:null", "OrderPlaced:b:7"]); + await expect( + storage.transact(async (transaction) => { + await transaction.eventStore.recordSealed({ + sets: [keyOf("OrderPlaced", "a")], + through: 9, + }); + throw new Error("undone"); + }), + ).rejects.toThrow("undone"); + expect(await sealedOf()).toEqual(["OrderPlaced:a:null", "OrderPlaced:b:7"]); + }); }); }; diff --git a/packages/core/src/adapter/testing/inspection.contract.ts b/packages/core/src/adapter/testing/inspection.contract.ts index 404f347e5..3bfbeccd7 100644 --- a/packages/core/src/adapter/testing/inspection.contract.ts +++ b/packages/core/src/adapter/testing/inspection.contract.ts @@ -134,6 +134,10 @@ export const inspectionContract: InspectionContractFunction = ({ create }) => { const versions = tables.find(({ name }) => name === "bounda_migrations"); if (versions !== undefined) expect(versions.store).toBe("migrations"); expect(tables.filter(({ store }) => store === null)).toEqual([]); + // What a walk sealed under each set shows with it. + for (const row of tableOf(tables, "bounda_event_marks").rows) { + expect(row).toHaveProperty("sealed_through"); + } const events = tableOf(tables, "bounda_events"); expect(events.key).toEqual(["position"]); expect(events.rows).toHaveLength(1); diff --git a/packages/core/src/adapter/testing/restore.contract.ts b/packages/core/src/adapter/testing/restore.contract.ts index d186b72f2..d2f26f329 100644 --- a/packages/core/src/adapter/testing/restore.contract.ts +++ b/packages/core/src/adapter/testing/restore.contract.ts @@ -1934,7 +1934,7 @@ export const restoreContract: RestoreContractFunction = ({ create, hot }) => { ); it( - "restores with the copy the marks event types were seen with and the kinds that opened a stream, and records again a set seen after it", + "restores with the copy the marks event types were seen with, how far each was sealed, and the kinds that opened a stream, and records again a set seen after it", async () => { const target = await create(); const clock = createFixedClock(START); @@ -1971,12 +1971,37 @@ export const restoreContract: RestoreContractFunction = ({ create, hot }) => { await stores.close(); } }; + // A type no module of the app names, so no walk of it seals under its set. + const archived = { aggregateType: "archive", type: "Archived", fingerprint: "kept" }; + const seal = async (storage: Adapter, through: number): Promise => { + const stores = await storage.createStorage(); + try { + await stores.eventStore.recordMarks({ + marks: [{ ...archived, marks: null }], + at: "2026-01-01T00:00:00.000Z", + }); + await stores.eventStore.recordSealed({ sets: [archived], through }); + } finally { + await stores.close(); + } + }; + const sealedThrough = async (storage: Adapter): Promise => { + const stores = await storage.createStorage(); + try { + return (await stores.eventStore.marksOf(archived)).map((set) => set.sealedThrough); + } finally { + await stores.close(); + } + }; const opened = openedAs(first.app.config.storage); // The set the start recorded for the type comes first. const { marks: started } = (await seen(opened)) as { readonly marks: readonly string[] }; expect(started).toHaveLength(1); await record(opened, "before"); + await seal(opened, 5); await target.backUp(); + await seal(opened, 9); + expect(await sealedThrough(opened)).toEqual([9]); const copied = await seen(opened); expect(copied).toMatchObject({ marks: [...started, "before"], @@ -1994,6 +2019,7 @@ export const restoreContract: RestoreContractFunction = ({ create, hot }) => { ); const reopened = openedAs(restored.app.config.storage); expect(await seen(reopened)).toEqual(copied); + expect(await sealedThrough(reopened)).toEqual([5]); await record(reopened, "after"); expect(await seen(reopened)).toMatchObject({ marks: [...started, "before", "after"] }); }, diff --git a/packages/core/src/kernel/aggregate/stored-types.test.ts b/packages/core/src/kernel/aggregate/stored-types.test.ts index 729877229..e89176142 100644 --- a/packages/core/src/kernel/aggregate/stored-types.test.ts +++ b/packages/core/src/kernel/aggregate/stored-types.test.ts @@ -225,6 +225,7 @@ describe("checkRetiredMarks", () => { type, fingerprint: JSON.stringify(fields), firstSeenAt: "2026-01-01T00:00:00.000Z", + sealedThrough: null, marks: fields === null ? null diff --git a/packages/core/src/kernel/aggregate/upcasting.ts b/packages/core/src/kernel/aggregate/upcasting.ts index d9951353d..a6acdb11d 100644 --- a/packages/core/src/kernel/aggregate/upcasting.ts +++ b/packages/core/src/kernel/aggregate/upcasting.ts @@ -162,6 +162,7 @@ const guarded = ({ eventStore, aggregates, stored, current }: GuardArgs): Guarde types: () => eventStore.types(), recordMarks: (args) => eventStore.recordMarks(args), marksOf: (args) => eventStore.marksOf(args), + recordSealed: (args) => eventStore.recordSealed(args), reseal: (events) => eventStore.reseal(events), readReadable: async (args) => { const events: StoredEvent[] = []; diff --git a/packages/core/src/kernel/personal-data/event-store.ts b/packages/core/src/kernel/personal-data/event-store.ts index 4ed5d1d0f..fb810a6fb 100644 --- a/packages/core/src/kernel/personal-data/event-store.ts +++ b/packages/core/src/kernel/personal-data/event-store.ts @@ -477,6 +477,7 @@ export const withPersonalData: WithPersonalDataFunction = ({ types: () => eventStore.types(), recordMarks: (args) => eventStore.recordMarks(args), marksOf: (args) => eventStore.marksOf(args), + recordSealed: (args) => eventStore.recordSealed(args), // Written as given: whoever reseals an event has sealed its payload already. reseal: (events) => eventStore.reseal(events), }; diff --git a/packages/core/src/kernel/personal-data/resealing.test.ts b/packages/core/src/kernel/personal-data/resealing.test.ts index 8ed54a810..0d5435f5e 100644 --- a/packages/core/src/kernel/personal-data/resealing.test.ts +++ b/packages/core/src/kernel/personal-data/resealing.test.ts @@ -685,6 +685,7 @@ describe("marksFingerprint of a retired type", () => { fingerprint: marksSetFingerprint(set), marks: set, firstSeenAt: "2026-01-01T00:00:00.000Z", + sealedThrough: null, })), ), }, @@ -730,6 +731,7 @@ describe("planEventReseal of a retired type", () => { fingerprint: marksSetFingerprint(set), marks: set, firstSeenAt: "2026-01-01T00:00:00.000Z", + sealedThrough: null, })), ), }, diff --git a/packages/core/src/kernel/personal-data/stored-marks.test.ts b/packages/core/src/kernel/personal-data/stored-marks.test.ts index 62b93b1a2..20f9f9141 100644 --- a/packages/core/src/kernel/personal-data/stored-marks.test.ts +++ b/packages/core/src/kernel/personal-data/stored-marks.test.ts @@ -28,6 +28,7 @@ const stored = ( fingerprint: marksSetFingerprint(marks), marks, firstSeenAt: "2026-01-01T00:00:00.000Z", + sealedThrough: null, }); const sealed = (person: string) => ({ diff --git a/packages/core/src/kernel/shared/committed-events.ts b/packages/core/src/kernel/shared/committed-events.ts index 4544e5e71..e713a460f 100644 --- a/packages/core/src/kernel/shared/committed-events.ts +++ b/packages/core/src/kernel/shared/committed-events.ts @@ -35,6 +35,7 @@ const appendingTo = ( types: () => eventStore.types(), recordMarks: (args) => eventStore.recordMarks(args), marksOf: (args) => eventStore.marksOf(args), + recordSealed: (args) => eventStore.recordSealed(args), reseal: (events) => eventStore.reseal(events), }); diff --git a/packages/core/src/kernel/unit-of-work/unit-of-work.ts b/packages/core/src/kernel/unit-of-work/unit-of-work.ts index f2fd89384..9218e5e98 100644 --- a/packages/core/src/kernel/unit-of-work/unit-of-work.ts +++ b/packages/core/src/kernel/unit-of-work/unit-of-work.ts @@ -90,10 +90,12 @@ export const createUnitOfWork: CreateUnitOfWorkFunction = ({ storage }) => { const batches = staged.batches(); const reseals = staged.reseals(); const markings = staged.markings(); + const sealings = staged.sealings(); if ( batches.length > 0 || reseals.length > 0 || markings.length > 0 || + sealings.length > 0 || pending() || atCommit.length > 0 ) { @@ -102,6 +104,7 @@ export const createUnitOfWork: CreateUnitOfWorkFunction = ({ storage }) => { for (const batch of batches) await transaction.eventStore.append(batch); if (reseals.length > 0) await transaction.eventStore.reseal(reseals); for (const marks of markings) await transaction.eventStore.recordMarks(marks); + for (const sealed of sealings) await transaction.eventStore.recordSealed(sealed); await flush(transaction); for (const write of atCommit) await write(transaction); }); diff --git a/packages/core/src/memory/event-store.ts b/packages/core/src/memory/event-store.ts index fe1d02480..8f5064930 100644 --- a/packages/core/src/memory/event-store.ts +++ b/packages/core/src/memory/event-store.ts @@ -1,3 +1,4 @@ +import { withSealed } from "../adapter/sql/event-marks.ts"; import { codePointOrder } from "../adapter/sql/order.ts"; import { holdsResealedFrom } from "../adapter/sql/resealed-from.ts"; import { type CheckAppendArgs, checkAppend } from "../adapter/storage/append-checks.ts"; @@ -192,13 +193,14 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ })), markRows: () => [...marks.values()].map( - ({ aggregateType, type, fingerprint, marks: set, firstSeenAt }, index) => ({ + ({ aggregateType, type, fingerprint, marks: set, firstSeenAt, sealedThrough }, index) => ({ aggregate_type: aggregateType, type, fingerprint, marks: set, seq: index + 1, first_seen_at: firstSeenAt, + sealed_through: sealedThrough, }), ), append: async (args) => (await appendAll([args]))[0] as AppendResult, @@ -265,7 +267,12 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ types: async () => [...kinds.values()], // Atomic because nothing yields between the copies and the writes. recordMarks: async ({ marks: sets, at }) => { - const kept = sets.map((set) => ({ ...set, marks: toJson(set.marks), firstSeenAt: at })); + const kept = sets.map((set) => ({ + ...set, + marks: toJson(set.marks), + firstSeenAt: at, + sealedThrough: null, + })); const sorted = [...kept].sort( (a, b) => codePointOrder(a.aggregateType, b.aggregateType) || @@ -284,6 +291,13 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ of === undefined || (set.aggregateType === of.aggregateType && set.type === of.type), ) .map((set) => ({ ...set, marks: JSON.parse(set.marks) })), + recordSealed: async (args) => { + const sealed = withSealed( + [...marks.entries()].map(([key, set]) => ({ ...set, key })), + args, + ); + for (const { key, ...set } of sealed) marks.set(key, set); + }, reseal: async (events) => { const kept = events.map((resealed) => ({ resealed, payload: toJson(resealed.payload) })); const left: number[] = []; diff --git a/packages/core/src/memory/tenant-fence.ts b/packages/core/src/memory/tenant-fence.ts index a38068a7f..f3ab025c6 100644 --- a/packages/core/src/memory/tenant-fence.ts +++ b/packages/core/src/memory/tenant-fence.ts @@ -7,7 +7,15 @@ import { // The methods of each store that write, which the fence puts behind it. export const FENCED_WRITES = { - eventStore: ["append", "appendAll", "reseal", "recordMarks", "reserve", "release"], + eventStore: [ + "append", + "appendAll", + "reseal", + "recordMarks", + "recordSealed", + "reserve", + "release", + ], inboxLedger: ["tryClaim", "complete", "fail", "release", "renew"], deadLetterStore: [ "add", diff --git a/packages/core/src/memory/transaction.ts b/packages/core/src/memory/transaction.ts index ac7ae97d0..cf39f05c3 100644 --- a/packages/core/src/memory/transaction.ts +++ b/packages/core/src/memory/transaction.ts @@ -499,6 +499,7 @@ export const createMemoryStorageTransaction: CreateMemoryStorageTransactionFunct await eventStore.appendAll(ownChangesLeftOut(staged.batches(), removed, restricted)); await eventStore.reseal(staged.reseals()); for (const marks of staged.markings()) await eventStore.recordMarks(marks); + for (const sealed of staged.sealings()) await eventStore.recordSealed(sealed); for (const activity of recorded) await persons.record(activity); } catch (error) { log.undo(); diff --git a/packages/postgresql/src/event-store.ts b/packages/postgresql/src/event-store.ts index 202e3b4f2..475375861 100644 --- a/packages/postgresql/src/event-store.ts +++ b/packages/postgresql/src/event-store.ts @@ -13,6 +13,7 @@ import { postgresqlDialect, recordEventTypesStatements, recordMarksStatements, + recordSealedStatements, runInOrder, type SqlTransaction, selectEventTypesStatement, @@ -270,6 +271,17 @@ export const createPostgresqlEventStore: CreatePostgresqlEventStoreFunction = ({ }); return (await db.all(sql, params)).map(marksOfRow); }, + recordSealed: ({ sets, through }) => + db.write(async (tx) => { + for (const { sql, params } of recordSealedStatements({ + dialect: postgresqlDialect, + table: eventMarks, + sets, + through, + })) { + await tx.run(sql, params); + } + }), reseal: (events) => db.write(async (tx) => { // Every event checked is locked, in position order, before any is written: no write comes From 5a184945ea9fc34bb457703a404ce8af8fb1d751 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 10:12:27 +0100 Subject: [PATCH 06/33] feat(core): seal a retired type's clear values under the set a walk last sealed under alone A backfill walk that catches up with no instance on other marks running records its sets sealed through its position. StoredMarks.authority names the type's set sealed last, and retiredMarksOf takes a field's category from it when it marks the field for the event's person, or else from the one category every own set gives, leaving the field in the clear otherwise. checkRetiredMarks refuses, at start, rebuild and prune, a retired type whose recorded marks give a field different categories that no such walk settled, so the category no longer depends on the order sets were first recorded in. --- .../src/kernel/aggregate/stored-types.test.ts | 60 ++++++ .../core/src/kernel/aggregate/stored-types.ts | 31 ++- .../core/src/kernel/personal-data/backfill.ts | 35 ++- .../core/src/kernel/personal-data/persons.ts | 1 + .../kernel/personal-data/resealing.test.ts | 39 +++- .../src/kernel/personal-data/resealing.ts | 6 +- .../personal-data/retired-marks-app.test.ts | 204 +++++++++++++++++- .../kernel/personal-data/stored-marks.test.ts | 130 +++++++++-- .../src/kernel/personal-data/stored-marks.ts | 135 +++++++++--- 9 files changed, 573 insertions(+), 68 deletions(-) diff --git a/packages/core/src/kernel/aggregate/stored-types.test.ts b/packages/core/src/kernel/aggregate/stored-types.test.ts index e89176142..f8a82eec2 100644 --- a/packages/core/src/kernel/aggregate/stored-types.test.ts +++ b/packages/core/src/kernel/aggregate/stored-types.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import type { StoredEventTypeMarks } from "../../adapter/storage/event-store.ts"; import { resolveConfig } from "../../config/schema.ts"; import { ConfigurationError } from "../../contracts/errors.ts"; import { memory } from "../../memory/index.ts"; @@ -287,6 +288,65 @@ describe("checkRetiredMarks", () => { }); }); +describe("checkRetiredMarks of marks that disagree", () => { + const noted = ( + categories: Readonly>, + sealedThrough: number | null, + person: string | null = null, + ) => ({ + aggregateType: "order", + type: "OrderNoteAdded", + fingerprint: JSON.stringify([person, categories]), + firstSeenAt: "2026-01-01T00:00:00.000Z", + sealedThrough, + marks: { person, fields: Object.keys(categories), categories }, + }); + const check = + (...sets: StoredEventTypeMarks[]) => + () => + checkRetiredMarks({ + aggregates: { ...beginning, storedMarks: storedMarksOf(sets) }, + types: [kind("order", "OrderNoteAdded", 1)], + }); + const refusal = (field: string, categories: string) => + [ + "The store holds events of retired types this code cannot seal:", + `- order.OrderNoteAdded is retired, but its recorded marks give "${field}" different categories (${categories}) and no backfill walk has sealed every value of it under one of them: deploy once with its module marking ${field} in the category to keep, let the backfill catch up, then retire it`, + ].join("\n"); + + it("refuses a field the sets give different categories that no walk sealed under one of them, naming each", () => { + const refused = check( + noted({ note: "invoices", phone: "default" }, null), + noted({ note: "default", phone: "invoices" }, null), + ); + expect(refused).toThrow(ConfigurationError); + expect(refused).toThrow( + `${refusal("note", "default, invoices")}\n${refusal("phone", "default, invoices").split("\n")[1]}`, + ); + }); + + it("refuses one the set a walk sealed under last does not mark, or that a set marks for another person field", () => { + expect( + check( + noted({ note: "invoices" }, null), + noted({ note: "default" }, null), + noted({ topic: "default" }, 7), + ), + ).toThrow(refusal("note", "default, invoices")); + expect( + check(noted({ note: "invoices" }, 7), noted({ note: "default" }, null, "authorId")), + ).toThrow(refusal("note", "default, invoices")); + }); + + it("accepts them once a walk sealed under one that marks the field last, and sets that agree with none", () => { + expect(check(noted({ note: "invoices" }, null), noted({ note: "default" }, 3))).not.toThrow(); + expect(check(noted({ note: "invoices" }, 3), noted({ note: "default" }, null))).not.toThrow(); + expect( + check(noted({ note: "invoices" }, null), noted({ note: "invoices", phone: "default" }, null)), + ).not.toThrow(); + }); +}); + describe("storedTypesOf", () => { it("tells a kind apart by aggregate type, type and schema version together", () => { const stored = storedTypesOf([kind("a", "b", 1), kind("ab", "", 2)]); diff --git a/packages/core/src/kernel/aggregate/stored-types.ts b/packages/core/src/kernel/aggregate/stored-types.ts index 724beaea0..8f62d8b59 100644 --- a/packages/core/src/kernel/aggregate/stored-types.ts +++ b/packages/core/src/kernel/aggregate/stored-types.ts @@ -7,6 +7,7 @@ import { SCHEDULED_COMMAND_FAILED_EVENT, } from "../../modules/bounda-events.ts"; import { toKebabCase } from "../../modules/naming.ts"; +import { unsettledFields } from "../personal-data/stored-marks.ts"; import { PROCESS_EVENTS, processOfStream } from "../process/lifecycle.ts"; import { RUNTIME_EVENT_TYPES } from "../system-events.ts"; import type { AggregatesRuntime } from "./runtime.ts"; @@ -169,19 +170,29 @@ export interface CheckRetiredMarksFunction { * Refuses, with a `ConfigurationError` naming each, a retired type the store holds events of but * no marks for: no start recorded what it marked, so its values written in the clear could never * be sealed. A start records the marks of every type it has a module for, unless the tenant is - * frozen, until it thaws. + * frozen, until it thaws. Refuses too a retired type whose recorded marks give a field different + * categories that no walk settled, as `unsettledFields` names them: which one a value left in the + * clear is sealed under would depend on the order instances started in. */ export const checkRetiredMarks: CheckRetiredMarksFunction = ({ types, aggregates }) => { const problems = kindsOf(types) - .filter( - ({ aggregateType, type }) => - aggregates.byName[aggregateType]?.retired.has(type) === true && - aggregates.storedMarks.of(aggregateType, type).length === 0, - ) - .map( - ({ aggregateType, type }) => - `${aggregateType}.${type} is retired, but no start recorded what it marks personal: deploy once with its module, on a tenant that is not frozen, then retire it`, - ); + .filter(({ aggregateType, type }) => aggregates.byName[aggregateType]?.retired.has(type)) + .flatMap(({ aggregateType, type }) => { + const qualified = `${aggregateType}.${type}`; + const sets = aggregates.storedMarks.of(aggregateType, type); + if (sets.length === 0) { + return [ + `${qualified} is retired, but no start recorded what it marks personal: deploy once with its module, on a tenant that is not frozen, then retire it`, + ]; + } + return unsettledFields({ + sets, + authority: aggregates.storedMarks.authority(aggregateType, type), + }).map( + ({ field, categories }) => + `${qualified} is retired, but its recorded marks give "${field}" different categories (${categories.join(", ")}) and no backfill walk has sealed every value of it under one of them: deploy once with its module marking ${field} in the category to keep, let the backfill catch up, then retire it`, + ); + }); if (problems.length > 0) { throw new ConfigurationError( `The store holds events of retired types this code cannot seal:\n${problems.map((problem) => `- ${problem}`).join("\n")}`, diff --git a/packages/core/src/kernel/personal-data/backfill.ts b/packages/core/src/kernel/personal-data/backfill.ts index 77e4068e4..bc973aee7 100644 --- a/packages/core/src/kernel/personal-data/backfill.ts +++ b/packages/core/src/kernel/personal-data/backfill.ts @@ -1,4 +1,4 @@ -import type { EventStore } from "../../adapter/storage/event-store.ts"; +import type { EventStore, EventTypeMarksKey } from "../../adapter/storage/event-store.ts"; import type { Hold } from "../../adapter/storage/hold.ts"; import { isReleasedBy } from "../../adapter/storage/hold.ts"; import type { ErrorText } from "../../config/types.ts"; @@ -20,6 +20,7 @@ import { type Sealed, } from "./reseal-batches.ts"; import { needsUpcastRewrite } from "./resealing.ts"; +import { currentMarkSets } from "./stored-marks.ts"; import type { PersonalKeyWrapping } from "./wrapped-keys.ts"; /** @@ -456,6 +457,37 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ return { position, caughtUp: stores > 0 && rewrite === 0 }; }; + // Caught up with no instance on other marks running, every value of each type is sealed as its + // set says, through the walk's position: the type's set a retired type's values left in the + // clear later are sealed as, so this records it on each set some other walk recorded since. + const recordSealed = async (): Promise => { + const stored = await storage.eventStore.marksOf(); + const sealedLast = (set: EventTypeMarksKey): boolean => { + const own = stored.find( + (held) => + held.aggregateType === set.aggregateType && + held.type === set.type && + held.fingerprint === set.fingerprint, + )?.sealedThrough; + return ( + own !== undefined && + own !== null && + stored.every( + (held) => + held.aggregateType !== set.aggregateType || + held.type !== set.type || + held.fingerprint === set.fingerprint || + held.sealedThrough === null || + held.sealedThrough < own, + ) + ); + }; + const sets = currentMarkSets(aggregates).filter((set) => !sealedLast(set)); + if (sets.length === 0) return; + const through = await checkpointStore.get(rows.position); + await storage.eventStore.recordSealed({ sets, through }); + }; + // Once no instance on other marks runs, the walk goes back to the first event it left in an // older shape; rewriting it takes the stores back to not caught up, as any event resealed does. const rewind = async (position: number): Promise => { @@ -506,6 +538,7 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ if (!others) report(); } caughtUp = !others && (await checkpointStore.get(rows.rewrite)) === 0; + if (caughtUp) await recordSealed(); restUntil = at + BACKFILL_FOLLOW_INTERVAL_MS; await releaseHold(); await removeStale(at, listed); diff --git a/packages/core/src/kernel/personal-data/persons.ts b/packages/core/src/kernel/personal-data/persons.ts index 0c3f89bea..65a050446 100644 --- a/packages/core/src/kernel/personal-data/persons.ts +++ b/packages/core/src/kernel/personal-data/persons.ts @@ -71,6 +71,7 @@ const retiredPerson = (aggregates: AggregatesRuntime, event: StoredEvent): strin if (sealed !== undefined) return sealed; const { marks } = retiredMarksOf({ sets: aggregates.storedMarks.of(event.aggregateType, event.type), + authority: aggregates.storedMarks.authority(event.aggregateType, event.type), event, }); if (marks === null) return null; diff --git a/packages/core/src/kernel/personal-data/resealing.test.ts b/packages/core/src/kernel/personal-data/resealing.test.ts index 0d5435f5e..774fccd12 100644 --- a/packages/core/src/kernel/personal-data/resealing.test.ts +++ b/packages/core/src/kernel/personal-data/resealing.test.ts @@ -717,7 +717,8 @@ describe("marksFingerprint of a retired type", () => { }); describe("planEventReseal of a retired type", () => { - const retiredWith = (sets: readonly (PersonalMarks | null)[]) => { + // `sealedLast`: the index of the set a walk last sealed every value under. + const retiredWith = (sets: readonly (PersonalMarks | null)[], sealedLast?: number) => { const { aggregates, processes } = runtimes({}); const customer = aggregates.byName.customer as unknown as { retired: Set }; customer.retired = new Set(["CustomerRegistered"]); @@ -725,13 +726,13 @@ describe("planEventReseal of a retired type", () => { aggregates: { ...aggregates, storedMarks: storedMarksOf( - sets.map((set) => ({ + sets.map((set, index) => ({ aggregateType: "customer", type: "CustomerRegistered", fingerprint: marksSetFingerprint(set), marks: set, firstSeenAt: "2026-01-01T00:00:00.000Z", - sealedThrough: null, + sealedThrough: index === sealedLast ? 1 : null, })), ), }, @@ -739,12 +740,15 @@ describe("planEventReseal of a retired type", () => { }; }; - it("seals what it holds in the clear under every set recorded for it, each field in the newest set's category", async () => { - const { aggregates, processes } = retiredWith([ - { person: null, fields: ["email"], categories: {} }, - null, - { person: null, fields: ["email", "phone"], categories: { email: "profile" } }, - ]); + it("seals what it holds in the clear under every set recorded for it, each field in the category of the set a walk last sealed under", async () => { + const { aggregates, processes } = retiredWith( + [ + { person: null, fields: ["email", "phone"], categories: { email: "profile" } }, + null, + { person: null, fields: ["email"], categories: {} }, + ], + 0, + ); const sealed = await sealedWith( planEventReseal({ event: event({ payload: { email: "ana@example.com", phone: "600", name: "Ana" } }), @@ -761,6 +765,23 @@ describe("planEventReseal of a retired type", () => { expect(categoryOf(value.phone as never)).toBe("default"); }); + it("leaves in the clear, unsealable, a field its sets give different categories with no walk sealed under one of them last", async () => { + const { aggregates, processes } = retiredWith([ + { person: null, fields: ["email", "phone"], categories: { email: "profile" } }, + { person: null, fields: ["email"], categories: {} }, + ]); + const plan = planEventReseal({ + event: event({ payload: { email: "ana@example.com", phone: "600" } }), + aggregates, + processes, + }); + expect(plan).toMatchObject({ unsealable: true }); + const sealed = await sealedWith(plan); + const value = sealed.value as Record; + expect(value.email).toBe("ana@example.com"); + expect(value.phone).toMatchObject({ $personal: { person: "c-1" } }); + }); + it("leaves what it holds sealed as it is, under whatever category, since no schema says which is its own", async () => { const key = await openedKey(await newStoredKey()); const email = await seal({ key, person: "c-1", category: "default", value: "ana@example.com" }); diff --git a/packages/core/src/kernel/personal-data/resealing.ts b/packages/core/src/kernel/personal-data/resealing.ts index d50b708d6..841a9d02f 100644 --- a/packages/core/src/kernel/personal-data/resealing.ts +++ b/packages/core/src/kernel/personal-data/resealing.ts @@ -550,7 +550,11 @@ export const planEventReseal: PlanEventResealFunction = ({ event, aggregates, pr const aggregate = aggregates.byName[event.aggregateType]; const retired = aggregate?.retired.has(event.type) === true; const { marks, elsewhere } = retired - ? retiredMarksOf({ sets: aggregates.storedMarks.of(event.aggregateType, event.type), event }) + ? retiredMarksOf({ + sets: aggregates.storedMarks.of(event.aggregateType, event.type), + authority: aggregates.storedMarks.authority(event.aggregateType, event.type), + event, + }) : { marks: aggregate?.eventsByType[event.type]?.personal ?? null, elsewhere: [] }; const { payload } = event; if (!isRecord(payload)) return null; diff --git a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts index 67ee009da..7a8b16d1d 100644 --- a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts +++ b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync } from "node:fs"; +import { copyFileSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -7,7 +7,7 @@ import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; import type { StoredEventTypeMarks } from "../../adapter/storage/event-store.ts"; import { pendingEvent } from "../../adapter/testing/fixtures.ts"; import type { Config } from "../../config/types.ts"; -import { createFixedClock } from "../../contracts/clock.ts"; +import { type Clock, createFixedClock } from "../../contracts/clock.ts"; import { ConfigurationError } from "../../contracts/errors.ts"; import type { StoredEvent } from "../../contracts/event.ts"; import { createSequentialIdGenerator } from "../../contracts/ids.ts"; @@ -18,6 +18,7 @@ import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload import type { Registry } from "../../modules/registry.ts"; import { type BoundaApp, createApp } from "../app.ts"; import { ledgerFor } from "../test-support.ts"; +import { BACKFILL_FOLLOW_INTERVAL_MS } from "./backfill.ts"; import { categoryOf, isSealed } from "./crypto.ts"; import type { ExportedEvent } from "./export.ts"; import { RECORDED_PERSONAL_DATA } from "./ledger-in-force.ts"; @@ -133,7 +134,7 @@ afterEach(async () => { let starts = 0; -const start = async (adapter: Adapter, deploy: Deploy) => { +const start = async (adapter: Adapter, deploy: Deploy, clock = createFixedClock(START)) => { starts += 1; const app = await createApp({ registry: registryOf(deploy), @@ -142,7 +143,7 @@ const start = async (adapter: Adapter, deploy: Deploy) => { runtime: { personalData: { forgetLedger: { store: ledgerFor(adapter) } } }, }, ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), - clock: createFixedClock(START), + clock, logger: silentLogger, }); let stopped = false; @@ -501,6 +502,201 @@ describe.each(adapters)("the marks a start records, on %s", (_name, adapterOf) = }); }); +// One deploy after another, each started once the last stopped for longer than the backfill +// counts an instance as running: what `act` does, then stopped. +const deploys = (adapter: () => Adapter, clock = createFixedClock(START)) => ({ + clock, + deploy: async (deploy: Deploy, act: (app: BoundaApp) => unknown = () => undefined) => { + const started = await start(adapter(), deploy, clock); + await act(started.app); + await started.stop(); + clock.advance(2 * BACKFILL_FOLLOW_INTERVAL_MS); + }, +}); + +const walked = (app: BoundaApp) => app.runUntilIdle(); + +const sealedLast = async (adapter: Adapter) => + ( + await ( + await storageOf(adapter) + ).eventStore.marksOf({ + aggregateType: "customer", + type: "NoteTaken", + }) + ).map(({ sealedThrough }) => sealedThrough !== null); + +const unsettledNote = [ + "The store holds events of retired types this code cannot seal:", + `- customer.NoteTaken is retired, but its recorded marks give "note" different categories (default, invoices) and no backfill walk has sealed every value of it under one of them: deploy once with its module marking note in the category to keep, let the backfill catch up, then retire it`, +].join("\n"); + +describe.each(adapters)( + "retiring a type whose recorded marks give a field different categories, on %s", + (_name, adapterOf) => { + it("seals what was left in the clear as the set a walk last sealed under alone marks it, once marks went A, B, C and back to A", async () => { + const adapter = adapterOf(); + const { deploy, clock } = deploys(() => adapter); + await deploy("default", async (app) => { + await note(app, "c-1", "call after five"); + await walked(app); + }); + await deploy("clear", (app) => note(app, "c-2", "prefers email")); + await deploy("invoices", walked); + expect(await sealedLast(adapter)).toEqual([false, false, true]); + // Back to A, which walks every event again and catches up as far as B did. + await deploy("default", walked); + expect(await sealedLast(adapter)).toEqual([true, false, false]); + await deploy("clear", (app) => note(app, "c-3", "ring twice")); + expect(await setsOf(adapter)).toEqual([asDefault, emailOnly, asInvoice]); + + const retired = await start(adapter, "retired", clock); + await retired.app.runUntilIdle(); + + // A's walk sealed again as A marks it what B's had sealed as B marks it. + const [first, second, late] = await notes(adapter); + expect(categoryOf(noteOf(first) as never)).toBe("default"); + expect(categoryOf(noteOf(second) as never)).toBe("default"); + expect(isSealed(noteOf(late))).toBe(true); + expect(categoryOf(noteOf(late) as never)).toBe("default"); + expect(await exported(retired.app, "c-3")).toEqual([ + expect.objectContaining({ + data: { email: "c-3@example.com", note: "ring twice" }, + categories: { email: "default", note: "default" }, + }), + ]); + }); + + it("refuses to retire it while no walk sealed under one of them alone, naming the field and the way out", async () => { + const adapter = adapterOf(); + const { deploy, clock } = deploys(() => adapter); + await deploy("default", (app) => note(app, "c-1", "call after five")); + await deploy("clear", (app) => note(app, "c-2", "prefers email")); + await deploy("invoices"); + const refused = start(adapter, "retired", clock); + await expect(refused).rejects.toThrow(ConfigurationError); + await expect(refused).rejects.toThrow(unsettledNote); + + // A walk alone under a set that marks no note settles nothing. + await deploy("clear", walked); + expect(await sealedLast(adapter)).toEqual([false, true, false]); + await expect(start(adapter, "retired", clock)).rejects.toThrow(unsettledNote); + + await deploy("invoices", walked); + const { app } = await start(adapter, "retired", clock); + await app.runUntilIdle(); + const [first, second] = await notes(adapter); + expect(categoryOf(noteOf(first) as never)).toBe("invoices"); + expect(categoryOf(noteOf(second) as never)).toBe("invoices"); + }); + + it("refuses to prune the forget ledger of such a store, as the start does", async () => { + const adapter = adapterOf(); + const { deploy } = deploys(() => adapter); + await deploy("default", (app) => note(app, "c-1", "call after five")); + await deploy("invoices"); + // An intention left in the ledger, which only the database tells whether it was applied. + await (await ledgerFor(adapter).createForgetLedger({ tenant: DEFAULT_TENANT })).append([ + { + personId: "c-1", + categories: null, + eventId: "e-c-1", + forgottenAt: START.toISOString(), + reason: "requested", + committed: false, + }, + ]); + await expect( + pruneTenantForgetLedger({ + logger: silentLogger, + registry: registryOf("retired"), + config: { + storage: adapter, + runtime: { + personalData: { forgetLedger: { store: ledgerFor(adapter), keepFor: "30d" } }, + }, + } as Config, + now: new Date(START.getTime() + 32 * 86_400_000), + }), + ).rejects.toThrow(unsettledNote); + }); + }, +); + +describe("restoring a copy of a store whose recorded marks give a field different categories", () => { + const onFile = () => { + const directory = mkdtempSync(join(tmpdir(), "bounda-retired-marks-")); + directories.push(directory); + const opened = (file: string) => { + const sqlite = createNodeSqliteAdapter(file); + const close = (): void => { + if (sqlite.db.isOpen) sqlite.db.close(); + }; + stops.push(async () => close()); + return { adapter: sqlite.adapter, close }; + }; + const tenantKeys = createMemoryTenantKeyStore(); + const ledger = memory(); + const env = { + BOUNDA_MASTER_KEY: Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64"), + }; + const startOn = async (adapter: Adapter, deploy: Deploy, clock: Clock) => { + starts += 1; + const app = await createApp({ + registry: registryOf(deploy), + config: { + storage: adapter, + runtime: { + personalData: { + keyWrapper: masterKey({ from: "BOUNDA_MASTER_KEY" }), + tenantKeys: defineTenantKeyStore(() => tenantKeys), + forgetLedger: { store: ledger, keepFor: "30d" }, + }, + }, + } as Config, + env, + clock, + ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), + logger: silentLogger, + }); + stops.unshift(() => app.stop()); + return app; + }; + return { file: (name: string) => join(directory, name), opened, startOn }; + }; + + it("refuses to retire it on a copy taken before a walk sealed under one of them alone, and seals by that walk on one taken after", async () => { + const at = onFile(); + const clock = createFixedClock(START); + const deploy = async (deploy: Deploy, act: (app: BoundaApp) => unknown = () => undefined) => { + const { adapter, close } = at.opened(at.file("store.db")); + const app = await at.startOn(adapter, deploy, clock); + await act(app); + await app.stop(); + close(); + clock.advance(2 * BACKFILL_FOLLOW_INTERVAL_MS); + }; + await deploy("default", (app) => note(app, "c-1", "call after five")); + await deploy("clear", (app) => note(app, "c-2", "prefers email")); + await deploy("invoices"); + copyFileSync(at.file("store.db"), at.file("before.db")); + await deploy("invoices", walked); + await deploy("clear", (app) => note(app, "c-3", "ring twice")); + copyFileSync(at.file("store.db"), at.file("after.db")); + + await expect( + at.startOn(at.opened(at.file("before.db")).adapter, "retired", clock), + ).rejects.toThrow(unsettledNote); + + const after = at.opened(at.file("after.db")).adapter; + const app = await at.startOn(after, "retired", clock); + await app.runUntilIdle(); + const [, , late] = await notes(after); + expect(isSealed(noteOf(late))).toBe(true); + expect(categoryOf(noteOf(late) as never)).toBe("invoices"); + }); +}); + describe.each(adapters)( "an upcast that drops a sealed field from the schema, on %s", (_name, adapterOf) => { diff --git a/packages/core/src/kernel/personal-data/stored-marks.test.ts b/packages/core/src/kernel/personal-data/stored-marks.test.ts index 20f9f9141..498bc11a6 100644 --- a/packages/core/src/kernel/personal-data/stored-marks.test.ts +++ b/packages/core/src/kernel/personal-data/stored-marks.test.ts @@ -11,6 +11,7 @@ import { NO_STORED_MARKS, retiredMarksOf, storedMarksOf, + unsettledFields, } from "./stored-marks.ts"; const set = ( @@ -73,6 +74,53 @@ describe("storedMarksOf", () => { expect(NO_STORED_MARKS).toMatchObject({ personalFields: false, personalData: false }); expect(NO_STORED_MARKS.of("conversation", "MessagePosted")).toEqual([]); }); + + it("names as authority the set sealed through the furthest, the newest of two as far, and none before a walk sealed under one", () => { + const first = set(null, { body: "default" }); + const second = set(null, { body: "invoices" }); + const third = set(null, { body: "contact" }); + const sealedAt = (marks: PersonalMarks | null, sealedThrough: number | null) => ({ + ...stored("MessagePosted", marks), + sealedThrough, + }); + const authority = (...sets: StoredEventTypeMarks[]) => + storedMarksOf(sets).authority("conversation", "MessagePosted"); + expect(authority(sealedAt(first, null), sealedAt(second, null))).toBeNull(); + expect(authority(sealedAt(first, 9), sealedAt(second, 4), sealedAt(third, null))).toBe(first); + expect(authority(sealedAt(first, 4), sealedAt(second, 4))).toBe(second); + expect(authority(sealedAt(first, 2), sealedAt(null, 4))).toBeNull(); + expect(storedMarksOf([sealedAt(first, 9)]).authority("conversation", "Other")).toBeNull(); + expect(NO_STORED_MARKS.authority("conversation", "MessagePosted")).toBeNull(); + }); +}); + +describe("unsettledFields", () => { + it("names each field the sets mark in different categories, whomever they name, with the categories in code points", () => { + const sets = [ + set(null, { body: "invoices", phone: "default" }), + null, + set("authorId", { body: "default", phone: "default" }), + set(null, { body: "contact" }), + ]; + expect(unsettledFields({ sets, authority: null })).toEqual([ + { field: "body", categories: ["contact", "default", "invoices"] }, + ]); + expect(unsettledFields({ sets: [], authority: null })).toEqual([]); + }); + + it("leaves out a field the set a walk sealed under last marks, unless a set marks it for another person field", () => { + const first = set(null, { body: "default", phone: "default" }); + const second = set(null, { body: "invoices", phone: "invoices" }); + expect(unsettledFields({ sets: [first, second], authority: first })).toEqual([]); + const narrower = set(null, { body: "invoices" }); + expect(unsettledFields({ sets: [first, second, narrower], authority: narrower })).toEqual([ + { field: "phone", categories: ["default", "invoices"] }, + ]); + const elsewhere = set("authorId", { body: "contact" }); + expect(unsettledFields({ sets: [first, elsewhere], authority: first })).toEqual([ + { field: "body", categories: ["contact", "default"] }, + ]); + }); }); describe("marksSetFingerprint", () => { @@ -142,37 +190,71 @@ describe("currentMarkSets", () => { describe("retiredMarksOf", () => { it("marks nothing of a type no set marked anything of", () => { - expect(retiredMarksOf({ sets: [], event: event({ body: "hi" }) })).toEqual({ + expect(retiredMarksOf({ sets: [], authority: null, event: event({ body: "hi" }) })).toEqual({ marks: null, elsewhere: [], }); - expect(retiredMarksOf({ sets: [null, null], event: event({ body: "hi" }) })).toEqual({ + expect( + retiredMarksOf({ sets: [null, null], authority: null, event: event({ body: "hi" }) }), + ).toEqual({ marks: null, elsewhere: [], }); }); - it("marks every field any set marked, each in the category of the newest set that marks it, whatever order instances started in", () => { + it("marks every field the sets give one category in it, and leaves in the clear one they give different categories, whatever order instances started in", () => { const sets = [ set(null, { body: "default" }), null, set(null, { body: "invoices", phone: "invoices" }), set(null, { topic: "default" }), ]; - expect(retiredMarksOf({ sets, event: event({ body: "hi", topic: "lunch" }) })).toEqual({ + const posted = event({ body: "hi", topic: "lunch" }); + expect(retiredMarksOf({ sets, authority: null, event: posted })).toEqual({ marks: { person: null, - fields: ["topic", "body", "phone"], - categories: { topic: "default", body: "invoices", phone: "invoices" }, + fields: ["topic", "phone"], + categories: { topic: "default", phone: "invoices" }, }, - elsewhere: [], + elsewhere: ["body"], }); + expect( + retiredMarksOf({ sets, authority: null, event: event({ body: sealed("c-1") }) }).elsewhere, + ).toEqual([]); }); - it("keeps the category of the newest set when marks went A, B and back to A, since A's set was recorded once", () => { - const a = set(null, { body: "default" }); + it("takes a field's category from the set a walk last sealed every value under, not the newest recorded, so marks that went A, B and back to A seal as A", () => { + const a = set(null, { body: "default", phone: "invoices" }); const b = set(null, { body: "invoices" }); - expect(retiredMarksOf({ sets: [a, b], event: event({ body: "hi" }) }).marks).toEqual(b); + const posted = event({ body: "hi", phone: "555" }); + expect(retiredMarksOf({ sets: [a, b], authority: a, event: posted })).toEqual({ + marks: a, + elsewhere: [], + }); + expect(retiredMarksOf({ sets: [a, b], authority: b, event: posted })).toEqual({ + marks: { + person: null, + fields: ["body", "phone"], + categories: { body: "invoices", phone: "invoices" }, + }, + elsewhere: [], + }); + // One that marks nothing settles no field. + expect(retiredMarksOf({ sets: [a, b, null], authority: null, event: posted })).toEqual({ + marks: { person: null, fields: ["phone"], categories: { phone: "invoices" } }, + elsewhere: ["body"], + }); + }); + + it("settles no field with the set a walk sealed under last when it names another person than the event", () => { + const own = set("authorId", { body: "default" }); + const other = set(null, { body: "invoices" }); + const again = set("authorId", { body: "contact" }); + const posted = event({ authorId: "ana", body: "hi" }, "ana"); + expect(retiredMarksOf({ sets: [own, other, again], authority: other, event: posted })).toEqual({ + marks: { person: "authorId", fields: [], categories: {} }, + elsewhere: ["body"], + }); }); it("keeps the person the event names, and tells apart the fields a set marks for somebody else that hold a value in the clear", () => { @@ -181,7 +263,7 @@ describe("retiredMarksOf", () => { set("authorId", { body: "default", phone: "invoices" }), ]; const payload = { authorId: "ana", body: "hi", phone: sealed("ana"), motto: "carpe diem" }; - expect(retiredMarksOf({ sets, event: event(payload, "ana") })).toEqual({ + expect(retiredMarksOf({ sets, authority: null, event: event(payload, "ana") })).toEqual({ marks: { person: "authorId", fields: ["body", "phone"], @@ -190,19 +272,29 @@ describe("retiredMarksOf", () => { elsewhere: ["motto"], }); const sealedMotto = { ...payload, motto: sealed("c-1") }; - expect(retiredMarksOf({ sets, event: event(sealedMotto, "ana") }).elsewhere).toEqual([]); + expect( + retiredMarksOf({ sets, authority: null, event: event(sealedMotto, "ana") }).elsewhere, + ).toEqual([]); const noMotto = { authorId: "ana", body: "hi", motto: null }; - expect(retiredMarksOf({ sets, event: event(noMotto, "ana") }).elsewhere).toEqual([]); + expect( + retiredMarksOf({ sets, authority: null, event: event(noMotto, "ana") }).elsewhere, + ).toEqual([]); }); it("names, for an event stored naming nobody, the person of the newest set that names somebody", () => { const sets = [set(null, { motto: "default" }), set("authorId", { body: "default" })]; - expect(retiredMarksOf({ sets, event: event({ body: "hi", motto: "carpe" }) })).toEqual({ + expect( + retiredMarksOf({ sets, authority: null, event: event({ body: "hi", motto: "carpe" }) }), + ).toEqual({ marks: { person: null, fields: ["motto"], categories: { motto: "default" } }, elsewhere: ["body"], }); expect( - retiredMarksOf({ sets, event: event({ authorId: "bo", body: "hi", motto: "carpe" }) }), + retiredMarksOf({ + sets, + authority: null, + event: event({ authorId: "bo", body: "hi", motto: "carpe" }), + }), ).toEqual({ marks: { person: "authorId", fields: ["body"], categories: { body: "default" } }, elsewhere: ["motto"], @@ -211,7 +303,13 @@ describe("retiredMarksOf", () => { it("marks nothing of an event whose person no set names, leaving every clear field it marks elsewhere", () => { const sets = [set("authorId", { body: "default" })]; - expect(retiredMarksOf({ sets, event: event({ authorId: "bo", body: "hi" }, "ana") })).toEqual({ + expect( + retiredMarksOf({ + sets, + authority: null, + event: event({ authorId: "bo", body: "hi" }, "ana"), + }), + ).toEqual({ marks: null, elsewhere: ["body"], }); diff --git a/packages/core/src/kernel/personal-data/stored-marks.ts b/packages/core/src/kernel/personal-data/stored-marks.ts index c49174590..9266e210d 100644 --- a/packages/core/src/kernel/personal-data/stored-marks.ts +++ b/packages/core/src/kernel/personal-data/stored-marks.ts @@ -1,3 +1,4 @@ +import { codePointOrder } from "../../adapter/sql/order.ts"; import type { EventTypeMarks, RecordedPersonalMarks, @@ -20,6 +21,12 @@ export interface StoredMarks { * nothing. */ of(aggregateType: string, type: string): readonly (PersonalMarks | null)[]; + /** + * Of the sets `of` gives, the one a walk of the store last sealed every value under while no + * instance on other marks ran, the highest `sealedThrough`, the newest of two as high; `null` + * when no walk did, or when that set marks nothing. + */ + authority(aggregateType: string, type: string): PersonalMarks | null; /** * Whether a set of any type marks a field `personal`: its events may hold values sealed under * keys, whatever the registry marks now. @@ -33,6 +40,7 @@ export interface StoredMarks { export const NO_STORED_MARKS: StoredMarks = { of: () => [], + authority: () => null, personalFields: false, personalData: false, }; @@ -43,12 +51,19 @@ export interface StoredMarksOfFunction { export const storedMarksOf: StoredMarksOfFunction = (sets) => { const byType = new Map(); - for (const { aggregateType, type, marks } of sets) { + const sealedLast = new Map(); + for (const { aggregateType, type, marks, sealedThrough } of sets) { const key = JSON.stringify([aggregateType, type]); byType.set(key, [...(byType.get(key) ?? []), marks]); + const last = sealedLast.get(key); + if (sealedThrough !== null && (last === undefined || sealedThrough >= last.through)) { + sealedLast.set(key, { marks, through: sealedThrough }); + } } return { of: (aggregateType, type) => byType.get(JSON.stringify([aggregateType, type])) ?? [], + authority: (aggregateType, type) => + sealedLast.get(JSON.stringify([aggregateType, type]))?.marks ?? null, personalFields: sets.some(({ marks }) => (marks?.fields.length ?? 0) > 0), personalData: sets.some(({ marks }) => marks !== null), }; @@ -120,8 +135,9 @@ export const withStoredMarks: WithStoredMarksFunction = (aggregates, sets) => ({ /** * What the sets recorded for a retired type mark of one of its events: `marks`, under the one - * person the event names, and `elsewhere`, the fields a set marks for another person, or for none, - * that hold a value in the clear. + * person the event names, and `elsewhere`, the fields that hold a value in the clear no set gives + * one category for that person: those a set marks for another person, or for none, and those its + * own sets give different categories with no walk sealed under one of them last. */ export interface RetiredMarks { readonly marks: PersonalMarks | null; @@ -130,6 +146,10 @@ export interface RetiredMarks { export interface RetiredMarksOfArgs { readonly sets: readonly (PersonalMarks | null)[]; + /** + * As `StoredMarks.authority` gives it for the type: one of `sets`, or `null`. + */ + readonly authority: PersonalMarks | null; /** * As the store holds it, or as it was handed out: its person field is never sealed. */ @@ -140,53 +160,113 @@ export interface RetiredMarksOfFunction { (args: RetiredMarksOfArgs): RetiredMarks; } -const merged = (sets: readonly PersonalMarks[]): PersonalMarks => { +const categoryAmong = ( + sets: readonly PersonalMarks[], + authority: PersonalMarks | null, + field: string, +): string | null => { + if (authority !== null && sets.includes(authority) && authority.fields.includes(field)) { + return fieldCategory(authority, field); + } + const given = new Set( + sets.filter((set) => set.fields.includes(field)).map((set) => fieldCategory(set, field)), + ); + return given.size === 1 ? ([...given][0] ?? null) : null; +}; + +const settled = ( + sets: readonly PersonalMarks[], + authority: PersonalMarks | null, +): { readonly marks: PersonalMarks; readonly unsettled: readonly string[] } => { const fields: string[] = []; const categories: Record = {}; - for (const set of sets) { - for (const field of set.fields) { - if (fields.includes(field)) continue; - fields.push(field); - categories[field] = fieldCategory(set, field); + const unsettled: string[] = []; + for (const field of new Set(sets.flatMap((set) => set.fields))) { + const category = categoryAmong(sets, authority, field); + if (category === null) { + unsettled.push(field); + continue; } + fields.push(field); + categories[field] = category; } - return { person: sets[0]?.person ?? null, fields, categories }; + return { marks: { person: sets[0]?.person ?? null, fields, categories }, unsettled }; }; /** * Every set counts, so none is lost to the order instances started in. The event keeps the one - * person it names, or else the one the newest set that names somebody names; a field takes its - * category from the newest set that marks it for that person, since the order sets were recorded - * in is the order deploys rolled forward in. `marks.person` is the field of the newest of them. + * person it names, or else the one the newest set that names somebody names. A field takes the + * category of the set a walk last sealed every value under, when that set marks it for that + * person, since what it left in the clear was written after; or else the one every set that marks + * it for that person gives. `marks.person` is the field of the newest of them. */ -export const retiredMarksOf: RetiredMarksOfFunction = ({ sets, event }) => { +export const retiredMarksOf: RetiredMarksOfFunction = ({ sets, authority, event }) => { const newestFirst = sets.filter((set) => set !== null).reverse(); if (newestFirst.length === 0) return { marks: null, elsewhere: [] }; const payload = isRecord(event.payload) ? event.payload : {}; + const clear = (field: string): boolean => + payload[field] !== undefined && payload[field] !== null && !isSealed(payload[field]); const named = (set: PersonalMarks): string | null => set.person === null ? event.aggregateId : personNamedBy(payload[set.person]); const person = event.person ?? newestFirst.map(named).find((candidate) => candidate !== null) ?? null; - if (person === null) return { marks: merged(newestFirst), elsewhere: [] }; + if (person === null) { + const { marks, unsettled } = settled(newestFirst, authority); + return { marks, elsewhere: unsettled.filter(clear) }; + } const own = newestFirst.filter((set) => named(set) === person); - const marks = own.length === 0 ? null : merged(own); + const { marks, unsettled } = + own.length === 0 ? { marks: null, unsettled: [] } : settled(own, authority); const elsewhere = [ - ...new Set( - newestFirst + ...new Set([ + ...unsettled, + ...newestFirst .filter((set) => !own.includes(set)) .flatMap((set) => set.fields) - .filter( - (field) => - marks?.fields.includes(field) !== true && - payload[field] !== undefined && - payload[field] !== null && - !isSealed(payload[field]), - ), - ), - ]; + .filter((field) => marks?.fields.includes(field) !== true), + ]), + ].filter(clear); return { marks, elsewhere }; }; +export interface UnsettledField { + readonly field: string; + /** + * In code-point order. + */ + readonly categories: readonly string[]; +} + +export interface UnsettledFieldsArgs { + readonly sets: readonly (PersonalMarks | null)[]; + readonly authority: PersonalMarks | null; +} + +export interface UnsettledFieldsFunction { + (args: UnsettledFieldsArgs): readonly UnsettledField[]; +} + +/** + * The fields the sets of a retired type mark in different categories, whomever they name, that + * the set a walk last sealed every value under does not settle: it does not mark the field, or + * a set marks it for another person field. A value of one still in the clear has no category + * every instance would seal it under, so `retiredMarksOf` leaves it in the clear. + */ +export const unsettledFields: UnsettledFieldsFunction = ({ sets, authority }) => { + const marking = sets.filter((set) => set !== null); + return [...new Set(marking.flatMap((set) => set.fields))].flatMap((field) => { + const markedBy = marking.filter((set) => set.fields.includes(field)); + const categories = [...new Set(markedBy.map((set) => fieldCategory(set, field)))].sort( + codePointOrder, + ); + if (categories.length < 2) return []; + const settles = + authority?.fields.includes(field) === true && + markedBy.every((set) => set.person === authority.person); + return settles ? [] : [{ field, categories }]; + }); +}; + export interface EventMarksOfArgs { readonly aggregates: AggregatesRuntime; readonly event: StoredEvent; @@ -207,6 +287,7 @@ export const eventMarksOf: EventMarksOfFunction = ({ aggregates, event }) => { if (aggregate.retired.has(event.type)) { return retiredMarksOf({ sets: aggregates.storedMarks.of(event.aggregateType, event.type), + authority: aggregates.storedMarks.authority(event.aggregateType, event.type), event, }).marks; } From 15bb3631245afc2225f156c03cc352c206697c8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 10:19:03 +0100 Subject: [PATCH 07/33] test(core): pin when the backfill records its sets sealed --- .../personal-data/backfill-walk.test.ts | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/packages/core/src/kernel/personal-data/backfill-walk.test.ts b/packages/core/src/kernel/personal-data/backfill-walk.test.ts index c1cf2dc73..476abea18 100644 --- a/packages/core/src/kernel/personal-data/backfill-walk.test.ts +++ b/packages/core/src/kernel/personal-data/backfill-walk.test.ts @@ -21,7 +21,7 @@ import { } from "./backfill.ts"; import { seal } from "./crypto.ts"; import { HOLD_MS } from "./hold.ts"; -import { NO_STORED_MARKS } from "./stored-marks.ts"; +import { currentMarkSets, NO_STORED_MARKS } from "./stored-marks.ts"; const START = new Date("2026-06-01T00:00:00.000Z"); @@ -936,6 +936,56 @@ describe("the backfill's walk beside an instance on other marks", () => { }); }); + it("records its sets sealed through its position once caught up with none running, and again once another walk recorded its own since", async () => { + const storage = await memory().createStorage(); + await append(storage, pending("customer", "c-1", "CustomerRegistered", { email: "a" })); + const customer = aggregates.byName.customer as AggregatesRuntime["byName"][string]; + const code = { + ...aggregates, + byName: { + customer: { + ...customer, + eventsByType: { + CustomerRegistered: { + ...customer.eventsByType.CustomerRegistered, + type: "CustomerRegistered", + }, + }, + }, + }, + } as unknown as AggregatesRuntime; + const [own] = currentMarkSets(code); + if (own === undefined) throw new Error("no set"); + const older = { ...own, fingerprint: "older", marks: null }; + await storage.eventStore.recordMarks({ marks: [own, older], at: START.toISOString() }); + await storage.checkpointStore.set( + `${BACKFILL_PREFIX}m0:lease`, + START.getTime() + BACKFILL_LEASE_MS, + ); + const sealed = async () => + Object.fromEntries( + (await storage.eventStore.marksOf()).map(({ fingerprint, sealedThrough }) => [ + fingerprint === own.fingerprint ? "own" : fingerprint, + sealedThrough, + ]), + ); + const { backfill, clock } = walker({ storage, code }); + await backfill.sweep(clock.now()); + expect(await sealed()).toEqual({ own: null, older: null }); + + clock.advance(BACKFILL_LEASE_MS + BACKFILL_FOLLOW_INTERVAL_MS); + await backfill.sweep(clock.now()); + expect(await backfill.status()).toMatchObject({ caughtUp: true }); + expect(await sealed()).toEqual({ own: 1, older: null }); + + // A walk under the older set caught up as far since, while this instance was stalled. + await storage.eventStore.recordSealed({ sets: [older], through: 1 }); + expect(await sealed()).toEqual({ own: null, older: 1 }); + clock.advance(BACKFILL_FOLLOW_INTERVAL_MS); + await backfill.sweep(clock.now()); + expect(await sealed()).toEqual({ own: 1, older: null }); + }); + it("is not caught up while a rewrite is left, and goes through the stores again after walking back", async () => { const storage = await memory().createStorage(); await append(storage, pending("contact", "c-1", "ContactAdded", { mail: "a" })); From a2ec3c877198fe20a1d823b3ca71f593762540cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 10:30:15 +0100 Subject: [PATCH 08/33] feat(core): let the set a walk last sealed under alone settle a field whatever person other sets named A retired type's field marked for different person fields and in different categories no longer refuses the start once a walk sealed every value under a set that marks it. A value left in the clear takes that set's category and the person it names; one whose event names somebody else stays in the clear, as that walk left it, and what other sets sealed keeps its person. --- .../src/kernel/aggregate/stored-types.test.ts | 10 +-- .../personal-data/retired-marks-app.test.ts | 67 ++++++++++++++++--- .../kernel/personal-data/stored-marks.test.ts | 43 +++++++++--- .../src/kernel/personal-data/stored-marks.ts | 36 +++++----- 4 files changed, 118 insertions(+), 38 deletions(-) diff --git a/packages/core/src/kernel/aggregate/stored-types.test.ts b/packages/core/src/kernel/aggregate/stored-types.test.ts index f8a82eec2..2f3549d5e 100644 --- a/packages/core/src/kernel/aggregate/stored-types.test.ts +++ b/packages/core/src/kernel/aggregate/stored-types.test.ts @@ -325,7 +325,7 @@ describe("checkRetiredMarks of marks that disagree", () => { ); }); - it("refuses one the set a walk sealed under last does not mark, or that a set marks for another person field", () => { + it("refuses one the set a walk sealed under last does not mark", () => { expect( check( noted({ note: "invoices" }, null), @@ -333,14 +333,14 @@ describe("checkRetiredMarks of marks that disagree", () => { noted({ topic: "default" }, 7), ), ).toThrow(refusal("note", "default, invoices")); - expect( - check(noted({ note: "invoices" }, 7), noted({ note: "default" }, null, "authorId")), - ).toThrow(refusal("note", "default, invoices")); }); - it("accepts them once a walk sealed under one that marks the field last, and sets that agree with none", () => { + it("accepts them once a walk sealed under one that marks the field last, whatever person field the others name, and sets that agree with none", () => { expect(check(noted({ note: "invoices" }, null), noted({ note: "default" }, 3))).not.toThrow(); expect(check(noted({ note: "invoices" }, 3), noted({ note: "default" }, null))).not.toThrow(); + expect( + check(noted({ note: "invoices" }, 7), noted({ note: "default" }, null, "authorId")), + ).not.toThrow(); expect( check(noted({ note: "invoices" }, null), noted({ note: "invoices", phone: "default" }, null)), ).not.toThrow(); diff --git a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts index 7a8b16d1d..b05261f84 100644 --- a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts +++ b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it } from "vitest"; import type { Adapter } from "../../adapter/adapter.ts"; import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; import type { StoredEventTypeMarks } from "../../adapter/storage/event-store.ts"; +import type { SealedValue } from "../../adapter/storage/personal-key-store.ts"; import { pendingEvent } from "../../adapter/testing/fixtures.ts"; import type { Config } from "../../config/types.ts"; import { type Clock, createFixedClock } from "../../contracts/clock.ts"; @@ -29,10 +30,11 @@ import { DEFAULT_TENANT } from "./tenant-keys.ts"; const START = new Date("2026-03-01T00:00:00.000Z"); -// What a deploy marks of a note: nothing, the note in the default category or as an invoice, the -// note's field dropped from its schema by an upcast that keeps it, or the note's type retired. The -// email is always marked, so every note names its customer. -type Deploy = "clear" | "default" | "invoices" | "dropped" | "retired"; +// What a deploy marks of a note: nothing, the note in the default category or as an invoice, as an +// invoice of the agent who took it, the note's field dropped from its schema by an upcast that keeps +// it, or the note's type retired. The email is always marked, so every note names its customer, or +// its agent. +type Deploy = "clear" | "default" | "invoices" | "agent" | "dropped" | "retired"; const personalData = { automatedDecisions: {}, @@ -69,14 +71,25 @@ const takeNote = command( customerId: notPersonal(z.string()), email: notPersonal(z.string()), note: notPersonal(z.string()), + agentId: notPersonal(z.string()).optional(), }), ({ command: { payload }, events }) => [ - events.noteTaken?.({ email: payload.email, note: payload.note, topic: "support" }), + events.noteTaken?.({ + email: payload.email, + note: payload.note, + topic: "support", + ...(payload.agentId === undefined ? {} : { agentId: payload.agentId }), + }), ], ); -const noteOfDeploy = ({ z, personal, notPersonal }: EventPayloadArgs, deploy: Deploy) => { +const noteOfDeploy = ({ z, personal, person, notPersonal }: EventPayloadArgs, deploy: Deploy) => { if (deploy === "clear") return { note: notPersonal(z.string()) }; + if (deploy === "agent") + return { + agentId: person(z.string()), + note: personal(z.string(), { category: "invoices" as never }), + }; if (deploy === "default") return { note: personal(z.string()) }; if (deploy === "invoices") return { note: personal(z.string(), { category: "invoices" as never }) }; @@ -161,8 +174,13 @@ const send = (app: BoundaApp, type: string, payload: object) => payload, ); -const note = (app: BoundaApp, customerId: string, text: string) => - send(app, "takeNote", { customerId, email: `${customerId}@example.com`, note: text }); +const note = (app: BoundaApp, customerId: string, text: string, agentId?: string) => + send(app, "takeNote", { + customerId, + email: `${customerId}@example.com`, + note: text, + ...(agentId === undefined ? {} : { agentId }), + }); const storageOf = (adapter: Adapter) => adapter.createStorage(); @@ -567,6 +585,39 @@ describe.each(adapters)( ]); }); + it("seals what was left in the clear for the person the set a walk last sealed under alone names, whatever person another set named, and leaves what that set sealed with its own person", async () => { + const adapter = adapterOf(); + const { deploy, clock } = deploys(() => adapter); + await deploy("agent", (app) => note(app, "c-1", "call after five", "a-1")); + await deploy("clear", (app) => note(app, "c-2", "prefers email")); + await deploy("default", walked); + await deploy("clear", (app) => note(app, "c-3", "ring twice")); + + const { app } = await start(adapter, "retired", clock); + await app.runUntilIdle(); + + const sealedAs = (event: StoredEvent | undefined) => { + const sealedNote = noteOf(event) as SealedValue; + return [event?.person, sealedNote.$personal.person, categoryOf(sealedNote)]; + }; + const [byAgent, walkedOver, late] = await notes(adapter); + expect(sealedAs(byAgent)).toEqual(["a-1", "a-1", "invoices"]); + expect(sealedAs(walkedOver)).toEqual(["c-2", "c-2", "default"]); + expect(sealedAs(late)).toEqual(["c-3", "c-3", "default"]); + expect(await exported(app, "c-3")).toEqual([ + expect.objectContaining({ + data: { email: "c-3@example.com", note: "ring twice" }, + categories: { email: "default", note: "default" }, + }), + ]); + expect(await exported(app, "a-1")).toEqual([ + expect.objectContaining({ + data: { email: "c-1@example.com", note: "call after five" }, + categories: { email: "default", note: "invoices" }, + }), + ]); + }); + it("refuses to retire it while no walk sealed under one of them alone, naming the field and the way out", async () => { const adapter = adapterOf(); const { deploy, clock } = deploys(() => adapter); diff --git a/packages/core/src/kernel/personal-data/stored-marks.test.ts b/packages/core/src/kernel/personal-data/stored-marks.test.ts index 498bc11a6..71ae806c1 100644 --- a/packages/core/src/kernel/personal-data/stored-marks.test.ts +++ b/packages/core/src/kernel/personal-data/stored-marks.test.ts @@ -108,7 +108,7 @@ describe("unsettledFields", () => { expect(unsettledFields({ sets: [], authority: null })).toEqual([]); }); - it("leaves out a field the set a walk sealed under last marks, unless a set marks it for another person field", () => { + it("leaves out a field the set a walk sealed under last marks, whatever person field the other sets name", () => { const first = set(null, { body: "default", phone: "default" }); const second = set(null, { body: "invoices", phone: "invoices" }); expect(unsettledFields({ sets: [first, second], authority: first })).toEqual([]); @@ -117,9 +117,8 @@ describe("unsettledFields", () => { { field: "phone", categories: ["default", "invoices"] }, ]); const elsewhere = set("authorId", { body: "contact" }); - expect(unsettledFields({ sets: [first, elsewhere], authority: first })).toEqual([ - { field: "body", categories: ["contact", "default"] }, - ]); + expect(unsettledFields({ sets: [first, elsewhere], authority: first })).toEqual([]); + expect(unsettledFields({ sets: [first, elsewhere], authority: elsewhere })).toEqual([]); }); }); @@ -246,12 +245,40 @@ describe("retiredMarksOf", () => { }); }); - it("settles no field with the set a walk sealed under last when it names another person than the event", () => { - const own = set("authorId", { body: "default" }); + it("leaves in the clear a field the set a walk sealed under last marks for another person than the event names, whatever its own sets give", () => { + const own = set("authorId", { body: "default", phone: "default" }); const other = set(null, { body: "invoices" }); - const again = set("authorId", { body: "contact" }); - const posted = event({ authorId: "ana", body: "hi" }, "ana"); + const again = set("authorId", { body: "default" }); + const posted = event({ authorId: "ana", body: "hi", phone: "555" }, "ana"); expect(retiredMarksOf({ sets: [own, other, again], authority: other, event: posted })).toEqual({ + marks: { person: "authorId", fields: ["phone"], categories: { phone: "default" } }, + elsewhere: ["body"], + }); + expect(retiredMarksOf({ sets: [own, other, again], authority: own, event: posted })).toEqual({ + marks: { + person: "authorId", + fields: ["body", "phone"], + categories: { body: "default", phone: "default" }, + }, + elsewhere: [], + }); + }); + + it("names, for an event stored naming nobody, the person the set a walk sealed under last names, before the newest set's", () => { + const other = set(null, { body: "invoices" }); + const own = set("authorId", { body: "default" }); + const posted = event({ authorId: "ana", body: "hi" }); + expect(retiredMarksOf({ sets: [other, own], authority: other, event: posted })).toEqual({ + marks: { person: null, fields: ["body"], categories: { body: "invoices" } }, + elsewhere: [], + }); + expect(retiredMarksOf({ sets: [other, own], authority: null, event: posted })).toEqual({ + marks: { person: "authorId", fields: ["body"], categories: { body: "default" } }, + elsewhere: [], + }); + // It names nobody in this event: the newest set that names somebody decides. + const absent = set("reviewerId", { body: "contact" }); + expect(retiredMarksOf({ sets: [own, absent], authority: absent, event: posted })).toEqual({ marks: { person: "authorId", fields: [], categories: {} }, elsewhere: ["body"], }); diff --git a/packages/core/src/kernel/personal-data/stored-marks.ts b/packages/core/src/kernel/personal-data/stored-marks.ts index 9266e210d..ee8c67953 100644 --- a/packages/core/src/kernel/personal-data/stored-marks.ts +++ b/packages/core/src/kernel/personal-data/stored-marks.ts @@ -136,8 +136,9 @@ export const withStoredMarks: WithStoredMarksFunction = (aggregates, sets) => ({ /** * What the sets recorded for a retired type mark of one of its events: `marks`, under the one * person the event names, and `elsewhere`, the fields that hold a value in the clear no set gives - * one category for that person: those a set marks for another person, or for none, and those its - * own sets give different categories with no walk sealed under one of them last. + * one category for that person: those a set marks for another person, or for none, those the set a + * walk last sealed every value under marks for another person, and those its own sets give + * different categories with no walk sealed under one of them last. */ export interface RetiredMarks { readonly marks: PersonalMarks | null; @@ -165,8 +166,8 @@ const categoryAmong = ( authority: PersonalMarks | null, field: string, ): string | null => { - if (authority !== null && sets.includes(authority) && authority.fields.includes(field)) { - return fieldCategory(authority, field); + if (authority?.fields.includes(field) === true) { + return sets.includes(authority) ? fieldCategory(authority, field) : null; } const given = new Set( sets.filter((set) => set.fields.includes(field)).map((set) => fieldCategory(set, field)), @@ -194,11 +195,13 @@ const settled = ( }; /** - * Every set counts, so none is lost to the order instances started in. The event keeps the one - * person it names, or else the one the newest set that names somebody names. A field takes the - * category of the set a walk last sealed every value under, when that set marks it for that - * person, since what it left in the clear was written after; or else the one every set that marks - * it for that person gives. `marks.person` is the field of the newest of them. + * Every set counts, so none is lost to the order instances started in. A field the set a walk last + * sealed every value under marks is sealed as that walk sealed it, since what it left in the clear + * was written after: under its category, for the person it names; an event that names another + * keeps its person and the value its clearness, as that walk left them. Any other field takes the + * one category every set that marks it for the event's person gives. The event keeps the person it + * names, or else takes the one that set names, or else the newest set that names somebody names. + * `marks.person` is the field of the newest set that names it. */ export const retiredMarksOf: RetiredMarksOfFunction = ({ sets, authority, event }) => { const newestFirst = sets.filter((set) => set !== null).reverse(); @@ -209,7 +212,10 @@ export const retiredMarksOf: RetiredMarksOfFunction = ({ sets, authority, event const named = (set: PersonalMarks): string | null => set.person === null ? event.aggregateId : personNamedBy(payload[set.person]); const person = - event.person ?? newestFirst.map(named).find((candidate) => candidate !== null) ?? null; + event.person ?? + (authority === null ? null : named(authority)) ?? + newestFirst.map(named).find((candidate) => candidate !== null) ?? + null; if (person === null) { const { marks, unsettled } = settled(newestFirst, authority); return { marks, elsewhere: unsettled.filter(clear) }; @@ -248,9 +254,8 @@ export interface UnsettledFieldsFunction { /** * The fields the sets of a retired type mark in different categories, whomever they name, that - * the set a walk last sealed every value under does not settle: it does not mark the field, or - * a set marks it for another person field. A value of one still in the clear has no category - * every instance would seal it under, so `retiredMarksOf` leaves it in the clear. + * the set a walk last sealed every value under does not mark. A value of one still in the clear + * has no category every instance would seal it under, so `retiredMarksOf` leaves it in the clear. */ export const unsettledFields: UnsettledFieldsFunction = ({ sets, authority }) => { const marking = sets.filter((set) => set !== null); @@ -260,10 +265,7 @@ export const unsettledFields: UnsettledFieldsFunction = ({ sets, authority }) => codePointOrder, ); if (categories.length < 2) return []; - const settles = - authority?.fields.includes(field) === true && - markedBy.every((set) => set.person === authority.person); - return settles ? [] : [{ field, categories }]; + return authority?.fields.includes(field) === true ? [] : [{ field, categories }]; }); }; From d896499293237061b2e945b5c28b631bdb1a4ef9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 10:56:29 +0100 Subject: [PATCH 09/33] fix(core): fence recording a walk's sets sealed against leases taken since it read none running, and read the marks afresh where retired types are sealed A start takes its walk's lease before it reads the marks the store recorded, so a walk of other code that read none running records nothing after them. The lease is taken and renewed in a transaction, and a walk records its sets sealed in one that first checks no lease of other marks changed since its pass read them: transactions run one at a time on every adapter, so the two never interleave. StorageTransaction carries the checkpoint store for that. The walk, exports and redactions resolve a retired type's fields by the marks the store holds when they run, not those of the start, and the walk checks them again in the transaction that seals each person's events. Marks that no longer settle a retired type hold the walk with its error, refuse exports and redactions with the start's message, and the next start refuses. --- packages/core/src/adapter/adapter.ts | 6 + packages/core/src/adapter/sqlite/adapter.ts | 10 +- .../testing/storage-transaction.contract.ts | 49 +++++++ packages/core/src/kernel/app.ts | 22 +++- .../personal-data/backfill-walk.test.ts | 108 +++++++++++++--- .../core/src/kernel/personal-data/backfill.ts | 105 ++++++++++++--- .../src/kernel/personal-data/export-stream.ts | 6 +- .../src/kernel/personal-data/fresh-marks.ts | 31 +++++ .../kernel/personal-data/ledger-prune.test.ts | 1 + .../src/kernel/personal-data/redaction.ts | 27 +++- .../personal-data/reseal-batches.test.ts | 66 +++++++--- .../kernel/personal-data/reseal-batches.ts | 74 +++++++++-- .../personal-data/retired-marks-app.test.ts | 122 +++++++++++++++++- .../src/kernel/personal-data/stored-marks.ts | 24 ++++ .../personal-data/tenant-export-stream.ts | 5 +- .../src/kernel/unit-of-work/unit-of-work.ts | 5 +- packages/core/src/memory/index.ts | 1 + packages/core/src/memory/transaction.ts | 9 ++ packages/postgresql/src/index.ts | 10 +- packages/sqlite/src/forget-ledger.test.ts | 5 +- 20 files changed, 586 insertions(+), 100 deletions(-) create mode 100644 packages/core/src/kernel/personal-data/fresh-marks.ts diff --git a/packages/core/src/adapter/adapter.ts b/packages/core/src/adapter/adapter.ts index 94ebaed07..2832cdda2 100644 --- a/packages/core/src/adapter/adapter.ts +++ b/packages/core/src/adapter/adapter.ts @@ -52,6 +52,12 @@ export interface StorageTransaction { * adapter may remove them at once rather than when the transaction commits. */ readonly snapshotStore: SnapshotStore; + /** + * Checkpoints written with the rest. Transactions run one at a time, so a row the work reads is + * written by no other transaction until this one ends: what a lease taken in one and a write + * that must not follow it once it was taken agree on. + */ + readonly checkpointStore: CheckpointStore; } /** diff --git a/packages/core/src/adapter/sqlite/adapter.ts b/packages/core/src/adapter/sqlite/adapter.ts index 2c68cc6d9..d77e59e65 100644 --- a/packages/core/src/adapter/sqlite/adapter.ts +++ b/packages/core/src/adapter/sqlite/adapter.ts @@ -268,6 +268,11 @@ export const createSqliteAdapter: CreateSqliteAdapterFunction = < personalKeys: tables.personalKeys, personRows: tables.personRows, }), + checkpointStore: createSqlCheckpointStore({ + db: database, + table: tables.checkpoints, + dialect: sqliteDialect, + }), }); // The stores over an open transaction: their statements join it, and a `write` of their own // runs inside it instead of opening another, which SQLite would refuse. @@ -285,11 +290,6 @@ export const createSqliteAdapter: CreateSqliteAdapterFunction = < const fenceStore = fence.store(db); const storageBehind = (guarded: SqlDatabase): Storage => ({ ...storesOver(guarded), - checkpointStore: createSqlCheckpointStore({ - db: guarded, - table: tables.checkpoints, - dialect: sqliteDialect, - }), subscriberFailures: createSqlSubscriberFailureStore({ db: guarded, table: tables.subscriberFailures, diff --git a/packages/core/src/adapter/testing/storage-transaction.contract.ts b/packages/core/src/adapter/testing/storage-transaction.contract.ts index 6dc892447..0fb7b64f2 100644 --- a/packages/core/src/adapter/testing/storage-transaction.contract.ts +++ b/packages/core/src/adapter/testing/storage-transaction.contract.ts @@ -309,6 +309,55 @@ export const storageTransactionContract: StorageTransactionContractFunction = ({ expect(await storage.personalKeys.recordedCategories()).toEqual(["invoices"]); }); + it("writes checkpoints with the rest, or not at all", async () => { + await storage.checkpointStore.set("lease", 5); + await storage.checkpointStore.set("gone", 2); + const write = (fail: boolean) => + storage.transact(async (transaction) => { + expect(await transaction.checkpointStore.compareAndSet("lease", 5, 9)).toBe(true); + expect(await transaction.checkpointStore.compareAndSet("lease", 5, 7)).toBe(false); + await transaction.checkpointStore.set("other", 3); + await transaction.checkpointStore.remove("gone"); + if (fail) throw new Error("boom"); + }); + const rows = () => + Promise.all(["lease", "other", "gone"].map((row) => storage.checkpointStore.get(row))); + await expect(write(true)).rejects.toThrow("boom"); + expect(await rows()).toEqual([5, 0, 2]); + await write(false); + expect(await rows()).toEqual([9, 3, 0]); + }); + + it.skipIf(!concurrent)( + "runs one transaction at a time: a checkpoint the work reads is written by no other until it ends", + async () => { + await storage.checkpointStore.set("lease", 5); + let entered = (): void => {}; + const inside = new Promise((resolve) => { + entered = resolve; + }); + let go = (): void => {}; + const gate = new Promise((resolve) => { + go = resolve; + }); + const first = storage.transact(async (transaction) => { + const before = await transaction.checkpointStore.get("lease"); + entered(); + await gate; + return [before, await transaction.checkpointStore.get("lease")]; + }); + await inside; + const second = storage.transact((transaction) => + transaction.checkpointStore.compareAndSet("lease", 5, 9), + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + go(); + expect(await first).toEqual([5, 5]); + expect(await second).toBe(true); + expect(await storage.checkpointStore.get("lease")).toBe(9); + }, + ); + it.skipIf(!concurrent)( "keeps the category a write outside it recorded meanwhile when it rolls back", async () => { diff --git a/packages/core/src/kernel/app.ts b/packages/core/src/kernel/app.ts index 8f743f5cb..9d6d2fe3f 100644 --- a/packages/core/src/kernel/app.ts +++ b/packages/core/src/kernel/app.ts @@ -100,7 +100,7 @@ import { forgetEntriesAgain, } from "./personal-data/applied-again.ts"; import { appliedTally } from "./personal-data/applied-tally.ts"; -import { createPersonalDataBackfill } from "./personal-data/backfill.ts"; +import { createBackfillLease, createPersonalDataBackfill } from "./personal-data/backfill.ts"; import { openDatabaseKey } from "./personal-data/blind-index.ts"; import { buildPersonalCategories, checkMarkedCategories } from "./personal-data/categories.ts"; import { checkClassification } from "./personal-data/classification.ts"; @@ -1084,6 +1084,22 @@ export const assembleApp: AssembleAppFunction = async ({ // tells what it wrote since from what no module reads any more. const storedTypes = await adapted.eventStore.types(); const stored = checkStoredTypes({ types: storedTypes, aggregates: registered }); + // The walk's lease is taken first, on a tenant open to writes, so a walk of other code that + // read none running records no set sealed after the marks below are read: what this start + // checks a retired type against holds while the lease does. + const walked = walkFingerprint({ + aggregates: withStoredMarks(registered, await adapted.eventStore.marksOf()), + processes: processDefinitions, + }); + const backfillLease = + walked === null + ? null + : createBackfillLease({ storage: adapted, marks: walked, clock, logger }); + if (backfillLease !== null && (await adapted.fence.read()).state === "open") { + await backfillLease.take(clock.now().getTime()); + // A start refused after it gives it back, before the storage closes. + opened.unshift(() => backfillLease.release()); + } // What every start recorded the event types to mark, which a retired type, or a field no longer // marked, still holds sealed: read before what needs keys and a ledger is decided. const aggregates = withStoredMarks(registered, await adapted.eventStore.marksOf()); @@ -2099,9 +2115,8 @@ export const assembleApp: AssembleAppFunction = async ({ clock, logger, }); - const walked = walkFingerprint({ aggregates, processes: processDefinitions }); const backfill = - walked === null || marks === null + walked === null || marks === null || backfillLease === null ? undefined : createPersonalDataBackfill({ tracer: appTracer, @@ -2112,6 +2127,7 @@ export const assembleApp: AssembleAppFunction = async ({ processes: processDefinitions, wrapping, marks: walked, + lease: backfillLease, answerMarks: marks, batchSize: config.runtime.dispatcher.batchSize, recordsActivity, diff --git a/packages/core/src/kernel/personal-data/backfill-walk.test.ts b/packages/core/src/kernel/personal-data/backfill-walk.test.ts index 476abea18..25d97c721 100644 --- a/packages/core/src/kernel/personal-data/backfill-walk.test.ts +++ b/packages/core/src/kernel/personal-data/backfill-walk.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, onTestFinished } from "vitest"; -import type { Storage } from "../../adapter/adapter.ts"; +import type { Storage, StorageTransaction } from "../../adapter/adapter.ts"; import type { PendingEvent } from "../../adapter/storage/event-store.ts"; import { createFixedClock } from "../../contracts/clock.ts"; import { SchemaAheadError } from "../../contracts/errors.ts"; @@ -17,6 +17,7 @@ import { BACKFILL_FOLLOW_INTERVAL_MS, BACKFILL_LEASE_MS, BACKFILL_PREFIX, + createBackfillLease, createPersonalDataBackfill, } from "./backfill.ts"; import { seal } from "./crypto.ts"; @@ -132,6 +133,7 @@ const walker = ({ processes, wrapping: testWrapping(clock), marks, + lease: createBackfillLease({ storage, marks, clock, logger }), answerMarks: marks, batchSize, recordsActivity: false, @@ -153,6 +155,28 @@ const append = async (storage: Storage, ...events: PendingEvent[]) => { } }; +// The storage with the stores of each transaction it runs as `over` makes them. +const transacting = ( + storage: Storage, + over: (transaction: StorageTransaction) => StorageTransaction, +): Storage => ({ + ...storage, + transact: (work) => storage.transact((transaction) => work(over(transaction))), +}); + +// A store that seals nothing again: every reseal a transaction makes fails while `down` says so. +const resealsFailing = (storage: Storage, down: () => boolean): Storage => + transacting(storage, (transaction) => ({ + ...transaction, + eventStore: { + ...transaction.eventStore, + reseal: (resealed) => + down() + ? Promise.reject(new Error("store is down")) + : transaction.eventStore.reseal(resealed), + }, + })); + const rows = async (storage: Storage) => Object.fromEntries( (await storage.checkpointStore.list()) @@ -453,16 +477,16 @@ describe("the backfill's walk", () => { it("walks nothing when another instance takes the lease first", async () => { const base = await memory().createStorage(); await append(base, pending("customer", "c-1", "CustomerRegistered", { email: "a" })); - const storage: Storage = { - ...base, + const storage = transacting(base, (transaction) => ({ + ...transaction, checkpointStore: { - ...base.checkpointStore, + ...transaction.checkpointStore, compareAndSet: async (subscriber, expected, position) => subscriber.endsWith(":lease") ? false - : base.checkpointStore.compareAndSet(subscriber, expected, position), + : transaction.checkpointStore.compareAndSet(subscriber, expected, position), }, - }; + })); const { backfill } = walker({ storage }); expect(await backfill.sweep(START)).toBe(0); expect(await rows(base)).toEqual({}); @@ -504,10 +528,7 @@ describe("the backfill's walk", () => { const base = await memory().createStorage(); await append(base, pending("customer", "c-1", "CustomerRegistered", { email: "a" })); let down = true; - const storage: Storage = { - ...base, - transact: (work) => (down ? Promise.reject(new Error("store is down")) : base.transact(work)), - }; + const storage = resealsFailing(base, () => down); const { logs, logger } = recording(); const one = walker({ storage, logger }); expect(await one.backfill.sweep(START)).toBe(0); @@ -667,16 +688,16 @@ describe("the backfill's walk", () => { it("logs a lease it could not give back, and gives none back it does not hold", async () => { const base = await memory().createStorage(); let refusing = false; - const storage: Storage = { - ...base, + const storage = transacting(base, (transaction) => ({ + ...transaction, checkpointStore: { - ...base.checkpointStore, + ...transaction.checkpointStore, compareAndSet: (subscriber, expected, position) => refusing ? Promise.reject(new Error("cannot write")) - : base.checkpointStore.compareAndSet(subscriber, expected, position), + : transaction.checkpointStore.compareAndSet(subscriber, expected, position), }, - }; + })); const { logs, logger } = recording(); const idle = walker({ storage, logger }); await idle.backfill.release(); @@ -785,6 +806,7 @@ describe("the backfill's walk beside an instance on other marks", () => { eventsByType: { ContactAdded: { personal: { person: null, fields: ["mail"], categories: {} } }, }, + retired: new Set(), }, }, } as unknown as AggregatesRuntime; @@ -910,10 +932,7 @@ describe("the backfill's walk beside an instance on other marks", () => { it("counts as running an instance whose walk is held, which renews its lease through the hold", async () => { const storage = await memory().createStorage(); await append(storage, pending("contact", "c-1", "ContactAdded", { mail: "a" })); - const failing: Storage = { - ...storage, - transact: () => Promise.reject(new Error("store is down")), - }; + const failing = resealsFailing(storage, () => true); const held = walker({ storage: failing, marks: "m0" }); expect(await held.backfill.sweep(START)).toBe(0); // Held far longer than a lease, as after failures in a row. @@ -986,6 +1005,57 @@ describe("the backfill's walk beside an instance on other marks", () => { expect(await sealed()).toEqual({ own: 1, older: null }); }); + it("records no set sealed once a walk on other marks took its lease after the pass read none running, and does once that lease lapsed", async () => { + const storage = await memory().createStorage(); + await append(storage, pending("customer", "c-1", "CustomerRegistered", { email: "a" })); + const customer = aggregates.byName.customer as AggregatesRuntime["byName"][string]; + const code = { + ...aggregates, + byName: { + customer: { + ...customer, + eventsByType: { + CustomerRegistered: { + ...customer.eventsByType.CustomerRegistered, + type: "CustomerRegistered", + }, + }, + }, + }, + } as unknown as AggregatesRuntime; + const [own] = currentMarkSets(code); + if (own === undefined) throw new Error("no set"); + await storage.eventStore.recordMarks({ marks: [own], at: START.toISOString() }); + // Runs once the pass read the rows of every walk, before it records anything. + let between: (() => Promise) | null = null; + const listing: Storage = { + ...storage, + checkpointStore: { + ...storage.checkpointStore, + list: async () => { + const listed = await storage.checkpointStore.list(); + const run = between; + between = null; + await run?.(); + return listed; + }, + }, + }; + const sealedThrough = async () => + (await storage.eventStore.marksOf()).map(({ sealedThrough: through }) => through); + const { backfill, clock } = walker({ storage: listing, code }); + const retiring = createBackfillLease({ storage, marks: "m2", clock, logger: silentLogger }); + between = () => retiring.take(clock.now().getTime()); + await backfill.sweep(clock.now()); + expect(await backfill.status()).toMatchObject({ caughtUp: true }); + expect((await rows(storage))["m2:lease"]).toBe(START.getTime() + BACKFILL_LEASE_MS); + expect(await sealedThrough()).toEqual([null]); + + clock.advance(BACKFILL_LEASE_MS + BACKFILL_FOLLOW_INTERVAL_MS); + await backfill.sweep(clock.now()); + expect(await sealedThrough()).toEqual([1]); + }); + it("is not caught up while a rewrite is left, and goes through the stores again after walking back", async () => { const storage = await memory().createStorage(); await append(storage, pending("contact", "c-1", "ContactAdded", { mail: "a" })); diff --git a/packages/core/src/kernel/personal-data/backfill.ts b/packages/core/src/kernel/personal-data/backfill.ts index bc973aee7..4e5407186 100644 --- a/packages/core/src/kernel/personal-data/backfill.ts +++ b/packages/core/src/kernel/personal-data/backfill.ts @@ -8,9 +8,10 @@ import type { Logger } from "../../contracts/logger.ts"; import type { AggregatesRuntime } from "../aggregate/runtime.ts"; import type { GuardedStorage } from "../events/guarded-storage.ts"; import type { ProcessesRuntime } from "../process/build-processes.ts"; -import { createLease, LEASE_MS } from "../shared/lease.ts"; +import { createLease, LEASE_MS, type Lease } from "../shared/lease.ts"; import { ATTRIBUTES, type TracerFunction, traced } from "../telemetry.ts"; import type { AtRestSealer } from "./at-rest.ts"; +import { withFreshMarks } from "./fresh-marks.ts"; import { createPause, holdAfter } from "./hold.ts"; import { addSealed, @@ -132,6 +133,10 @@ export interface CreatePersonalDataBackfillArgs { * The fingerprint of what it walks for, as `walkFingerprint` names it. */ readonly marks: string; + /** + * The walk's lease for `marks`, as `createBackfillLease` makes it, which the start took first. + */ + readonly lease: Lease; /** * The fingerprint of the marks alone, as `marksFingerprint` names them: what a remembered * answer sealed under them names. @@ -153,6 +158,15 @@ export interface CreatePersonalDataBackfillFunction { (args: CreatePersonalDataBackfillArgs): PersonalDataBackfill; } +const backfillRowsOf = ( + listed: readonly { readonly subscriber: string; readonly position: number }[], +): readonly BackfillRow[] => + listed.flatMap(({ subscriber, position }) => { + if (!subscriber.startsWith(BACKFILL_PREFIX)) return []; + const [owner = "", name = ""] = subscriber.slice(BACKFILL_PREFIX.length).split(":"); + return [{ subscriber, owner, name, position }]; + }); + const rowsOf = (marks: string) => { const row = (name: string): string => `${BACKFILL_PREFIX}${marks}:${name}`; return { @@ -166,6 +180,47 @@ const rowsOf = (marks: string) => { }; }; +export interface CreateBackfillLeaseArgs { + readonly storage: Pick; + /** + * The fingerprint of what it walks for, as `walkFingerprint` names it. + */ + readonly marks: string; + readonly clock: Clock; + readonly logger: Logger; +} + +export interface CreateBackfillLeaseFunction { + (args: CreateBackfillLeaseArgs): Lease; +} + +// Taken and renewed in a transaction, so one at a time with the one in which a walk that read no +// lease of other marks running records its sets sealed: once this one was taken or renewed, that +// walk records nothing. A start takes it before it reads the marks the store recorded. +export const createBackfillLease: CreateBackfillLeaseFunction = ({ + storage, + marks, + clock, + logger, +}) => { + const { checkpointStore } = storage; + return createLease({ + checkpoints: { + get: (row) => checkpointStore.get(row), + list: () => checkpointStore.list(), + set: (row, position) => checkpointStore.set(row, position), + remove: (row) => checkpointStore.remove(row), + compareAndSet: (row, expected, position) => + storage.transact((transaction) => + transaction.checkpointStore.compareAndSet(row, expected, position), + ), + }, + row: rowsOf(marks).lease, + clock, + logger, + }); +}; + /** * Walks the global stream from its first event and seals in place what each event holds in the * clear of a field its schema marks now, under the key of the person the marks name, who becomes @@ -188,6 +243,7 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ processes, wrapping, marks, + lease, answerMarks, batchSize, recordsActivity, @@ -202,7 +258,6 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ let restUntil = Number.NEGATIVE_INFINITY; // The end of the hold this instance last met: it passes before then only to renew the lease. let holdEnd = Number.NEGATIVE_INFINITY; - const lease = createLease({ checkpoints: checkpointStore, row: rows.lease, clock, logger }); let caughtUp = false; let tally = NO_TALLY; @@ -279,11 +334,15 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ // The backfill's rows of every set of marks, read once a pass. const listRows = async (): Promise => - (await checkpointStore.list()).flatMap(({ subscriber, position }) => { - if (!subscriber.startsWith(BACKFILL_PREFIX)) return []; - const [owner = "", name = ""] = subscriber.slice(BACKFILL_PREFIX.length).split(":"); - return [{ subscriber, owner, name, position }]; - }); + backfillRowsOf(await checkpointStore.list()); + + const othersLeases = (listed: readonly BackfillRow[]): string => + JSON.stringify( + listed + .filter(({ owner, name }) => owner !== marks && name === "lease") + .map(({ owner, position }) => [owner, position]) + .sort(), + ); // The rows of other marks whose lease lapsed long ago: no instance runs those marks any more. const removeStale = async (at: number, listed: readonly BackfillRow[]): Promise => { @@ -352,7 +411,11 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ // first. An event left in an older shape, since `rewrite` is off, is noted to walk again from. // An event newer code wrote is never rewritten: the walk stops before it and rejects, so it never // catches up past it. - const walk = async (position: number, rewrite: boolean): Promise => { + const walk = async ( + position: number, + rewrite: boolean, + fresh: AggregatesRuntime, + ): Promise => { const { events, unreadable } = await storage.eventStore.readReadable({ afterPosition: position, limit: batchSize, @@ -379,7 +442,7 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ [ATTRIBUTES.afterPosition]: position, [ATTRIBUTES.eventCount]: events.length, }, - run: () => reseal.events(events, rewrite), + run: () => reseal.events(events, rewrite, fresh.storedMarks), }); // An event another wrote again since this pass read it is read again from here next pass. if (sealed.left > 0) return "moved"; @@ -411,6 +474,7 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ at: number, started: number, others: boolean, + fresh: AggregatesRuntime, ): Promise => { const commands = await sealPages( (page) => storage.scheduler.list(page), @@ -419,7 +483,7 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ if (commands === null) return null; const letters = await sealPages( (page) => storage.deadLetterStore.list(page), - (page) => reseal.letters(page, started), + (page) => reseal.letters(page, started, fresh.storedMarks), ); if (letters === null) return null; const answers = await sealPages( @@ -459,8 +523,10 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ // Caught up with no instance on other marks running, every value of each type is sealed as its // set says, through the walk's position: the type's set a retired type's values left in the - // clear later are sealed as, so this records it on each set some other walk recorded since. - const recordSealed = async (): Promise => { + // clear later are sealed as, so this records it on each set some other walk recorded since. Only + // while no lease of other marks was taken or renewed since `listed` read none running: the + // transaction runs one at a time with those that take one. + const recordSealed = async (listed: readonly BackfillRow[]): Promise => { const stored = await storage.eventStore.marksOf(); const sealedLast = (set: EventTypeMarksKey): boolean => { const own = stored.find( @@ -485,7 +551,11 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ const sets = currentMarkSets(aggregates).filter((set) => !sealedLast(set)); if (sets.length === 0) return; const through = await checkpointStore.get(rows.position); - await storage.eventStore.recordSealed({ sets, through }); + await storage.transact(async (transaction) => { + const now = backfillRowsOf(await transaction.checkpointStore.list()); + if (othersLeases(now) !== othersLeases(listed)) return; + await transaction.eventStore.recordSealed({ sets, through }); + }); }; // Once no instance on other marks runs, the walk goes back to the first event it left in an @@ -509,6 +579,9 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ } holdEnd = Number.NEGATIVE_INFINITY; if (!(await lease.take(at))) return 0; + // What a retired type's values are sealed as follows the set a walk last sealed every value + // under alone, which may have changed since the start: marks that no longer settle it hold. + const fresh = await withFreshMarks({ eventStore: storage.eventStore, aggregates }); const listed = await listRows(); let started = await checkpointStore.get(rows.started); if (started !== 0 && walkedSince(started, listed)) { @@ -527,18 +600,18 @@ export const createPersonalDataBackfill: CreatePersonalDataBackfillFunction = ({ ? await checkpointStore.get(rows.position) : await rewind(await checkpointStore.get(rows.position)); if (position === "moved") return 0; - const walked = await walk(position, !others); + const walked = await walk(position, !others, fresh); if (walked === "moved") return 0; if (walked >= batchSize) return walked; let stored = 0; if ((await checkpointStore.get(rows.stores)) === 0) { - const sealed = await sealStores(at, started, others); + const sealed = await sealStores(at, started, others, fresh); if (sealed === null) return walked; stored = sealed; if (!others) report(); } caughtUp = !others && (await checkpointStore.get(rows.rewrite)) === 0; - if (caughtUp) await recordSealed(); + if (caughtUp) await recordSealed(listed); restUntil = at + BACKFILL_FOLLOW_INTERVAL_MS; await releaseHold(); await removeStale(at, listed); diff --git a/packages/core/src/kernel/personal-data/export-stream.ts b/packages/core/src/kernel/personal-data/export-stream.ts index a4b065717..1a92a9aa0 100644 --- a/packages/core/src/kernel/personal-data/export-stream.ts +++ b/packages/core/src/kernel/personal-data/export-stream.ts @@ -49,6 +49,7 @@ import { type PersonalDataExportPart, type PersonalDataExportRecord, } from "./export.ts"; +import { withFreshMarks } from "./fresh-marks.ts"; import { personalDataInformation } from "./information.ts"; import { fieldCategory, type PersonalMarks } from "./marks.ts"; import { lifecycleStateOf } from "./process-state.ts"; @@ -289,7 +290,7 @@ async function* exportedRedactions( // `PersonalDataChangedError`. export const streamPersonalData: StreamPersonalDataFunction = async ({ storage, - aggregates, + aggregates: started, processes, readModels, sealing, @@ -303,6 +304,9 @@ export const streamPersonalData: StreamPersonalDataFunction = async ({ onPage, }) => { checkPersonId(personId, "exportPersonalData"); + // A retired type's values are told as the marks the store holds now say, which a walk of other + // code may have changed since the start; marks that no longer settle one refuse, as a start does. + const aggregates = await withFreshMarks({ eventStore: storage.eventStore, aggregates: started }); const exportedAt = clock.now().toISOString(); // The person's stream before the head: whatever it gains after this, the end finds. const before = await personVersion(storage, personId); diff --git a/packages/core/src/kernel/personal-data/fresh-marks.ts b/packages/core/src/kernel/personal-data/fresh-marks.ts new file mode 100644 index 000000000..f78e01e7f --- /dev/null +++ b/packages/core/src/kernel/personal-data/fresh-marks.ts @@ -0,0 +1,31 @@ +import type { EventStore } from "../../adapter/storage/event-store.ts"; +import type { AggregatesRuntime } from "../aggregate/runtime.ts"; +import { checkRetiredMarks } from "../aggregate/stored-types.ts"; +import { withStoredMarks } from "./stored-marks.ts"; + +export interface WithFreshMarksArgs { + /** + * The store to read, inside the transaction that writes by what it reads when there is one. + */ + readonly eventStore: Pick; + readonly aggregates: AggregatesRuntime; +} + +export interface WithFreshMarksFunction { + (args: WithFreshMarksArgs): Promise; +} + +/** + * The aggregates with the sets of marks the store holds now, for what resolves a retired type's + * fields: a walk of other code that caught up alone since the start may have sealed every value + * under another of its sets. Throws `ConfigurationError` with the start's message once they no + * longer settle a retired type's fields. The aggregates as given for a registry that retires none. + */ +export const withFreshMarks: WithFreshMarksFunction = async ({ eventStore, aggregates }) => { + if (Object.values(aggregates.byName).every(({ retired }) => retired.size === 0)) { + return aggregates; + } + const fresh = withStoredMarks(aggregates, await eventStore.marksOf()); + checkRetiredMarks({ types: await eventStore.types(), aggregates: fresh }); + return fresh; +}; diff --git a/packages/core/src/kernel/personal-data/ledger-prune.test.ts b/packages/core/src/kernel/personal-data/ledger-prune.test.ts index 854e9f91c..b75ada450 100644 --- a/packages/core/src/kernel/personal-data/ledger-prune.test.ts +++ b/packages/core/src/kernel/personal-data/ledger-prune.test.ts @@ -91,6 +91,7 @@ const RULES: ReconciliationRules = { personal: { person: "customerId", fields: ["email"], categories: {} }, }, }, + retired: new Set(), }, }, commandsByType: {}, diff --git a/packages/core/src/kernel/personal-data/redaction.ts b/packages/core/src/kernel/personal-data/redaction.ts index f331c5761..d107d4b69 100644 --- a/packages/core/src/kernel/personal-data/redaction.ts +++ b/packages/core/src/kernel/personal-data/redaction.ts @@ -45,6 +45,7 @@ import { unseal, } from "./crypto.ts"; import { openTextWith } from "./errors.ts"; +import { withFreshMarks } from "./fresh-marks.ts"; import { fieldCategory, type PersonalMarks } from "./marks.ts"; import { lifecycleStateOf } from "./process-state.ts"; import { redactionReach, unsealedFor } from "./redaction-targets.ts"; @@ -144,8 +145,8 @@ const refusal = (target: RedactedEvent, why: string): ValidationError => ]); export interface CheckReachableArgs { - // The store as written, which holds the envelopes. - readonly eventStore: Pick; + // The store as written, which holds the envelopes and the marks recorded. + readonly eventStore: Pick; readonly aggregates: AggregatesRuntime; readonly processes: Pick; readonly personId: string; @@ -157,14 +158,16 @@ export interface CheckReachableFunction { } // Throws `ValidationError` for the first target `redactWithin` would refuse, before anything is -// recorded: a redaction refused never reaches the ledger, whose reconciliation would apply it. +// recorded: a redaction refused never reaches the ledger, whose reconciliation would apply it. A +// store whose marks no longer settle a retired type refuses it as the start does. export const checkReachable: CheckReachableFunction = async ({ eventStore, - aggregates, + aggregates: started, processes, personId, targets, }) => { + const aggregates = await withFreshMarks({ eventStore, aggregates: started }); for (const target of targets) { const event = await eventStore.readOne({ aggregateType: target.aggregateType, @@ -273,7 +276,7 @@ const sealableFields = async ( }; export interface RedactionSealsArgs { - readonly eventStore: Pick; + readonly eventStore: Pick; // The store as written: a key it finds is one the person's keys open. readonly keys: Pick; readonly aggregates: AggregatesRuntime; @@ -294,8 +297,9 @@ export const redactionSeals: RedactionSealsFunction = async ({ targets, ...rest }) => { + const aggregates = await withFreshMarks(rest); for (const target of targets) { - const reached = await reachTarget({ ...rest, personId, target, strict: false }); + const reached = await reachTarget({ ...rest, aggregates, personId, target, strict: false }); if (reached === null) continue; const fields = await sealableFields(reached, target, personId, (fingerprint) => keys.find(personId, fingerprint), @@ -569,12 +573,21 @@ export const redactWithin: RedactWithinFunction = async (args) => { eventId: identity.id, }); if (applied !== null) return { held: applied }; + // A retired type's values are redacted as the marks the store holds say, read in the transaction + // that writes, which runs one at a time with the one a walk records its sets sealed in. + const fresh = { + ...args, + aggregates: await withFreshMarks({ + eventStore: transaction.eventStore, + aggregates: args.aggregates, + }), + }; const disposable = await createDisposableKey(); const values: RedactedValue[] = []; const resealed: Resealed[] = []; const events: RedactedEvent[] = []; for (const target of targets) { - const done = await resealEvent(args, target, disposable, values); + const done = await resealEvent(fresh, target, disposable, values); if (done === null) continue; resealed.push(done); events.push({ ...target, fields: done.fields }); diff --git a/packages/core/src/kernel/personal-data/reseal-batches.test.ts b/packages/core/src/kernel/personal-data/reseal-batches.test.ts index b334d5591..66762ee65 100644 --- a/packages/core/src/kernel/personal-data/reseal-batches.test.ts +++ b/packages/core/src/kernel/personal-data/reseal-batches.test.ts @@ -168,7 +168,7 @@ describe("resealing a batch of events", () => { state: "{}", persons: [], }); - const sealed = await reseal.events(await all(storage), true); + const sealed = await reseal.events(await all(storage), true, NO_STORED_MARKS); expect(sealed).toEqual({ resealed: 3, @@ -196,7 +196,7 @@ describe("resealing a batch of events", () => { expect(await storage.persons.get("c-1")).toMatchObject({ lastActiveAt: "2026-01-01T00:00:00.000Z", }); - expect(await reseal.events(await all(storage), true)).toEqual({ + expect(await reseal.events(await all(storage), true, NO_STORED_MARKS)).toEqual({ resealed: 0, discarded: 0, unsealable: 1, @@ -218,7 +218,7 @@ describe("resealing a batch of events", () => { persons: [], }; await storage.snapshotStore.put(snapshot); - await reseal.events(await all(storage), true); + await reseal.events(await all(storage), true, NO_STORED_MARKS); expect(await storage.snapshotStore.get(snapshot)).toEqual(snapshot); expect(await storage.persons.get("c-1")).toBeNull(); @@ -227,7 +227,7 @@ describe("resealing a batch of events", () => { ...event("customer", "c-1", 1, "CustomerRegistered", { email: "a" }), person: "c-1", }); - await retained.reseal.events(await all(retained.storage), true); + await retained.reseal.events(await all(retained.storage), true, NO_STORED_MARKS); expect(await retained.storage.persons.get("c-1")).toBeNull(); }); }); @@ -257,7 +257,7 @@ describe("resealing a batch of events, by transaction", () => { logger: silentLogger, recordsActivity: false, }); - expect((await reseal.events(await all(storage), true)).resealed).toBe(2); + expect((await reseal.events(await all(storage), true, NO_STORED_MARKS)).resealed).toBe(2); expect(transactions).toBe(2); }); }); @@ -272,7 +272,7 @@ describe("resealing a batch of events by category", () => { }), forgotten("c-1", 1, { whole: false, categories: ["profile"], retained: [], expired: [] }), ); - expect(await reseal.events(await all(storage), true)).toEqual({ + expect(await reseal.events(await all(storage), true, NO_STORED_MARKS)).toEqual({ resealed: 1, discarded: 1, unsealable: 0, @@ -301,7 +301,7 @@ describe("resealing a field moved to another category", () => { await append( event("customer", "c-1", 1, "CustomerProfiled", { email: "ada@example.com", nickname }), ); - expect((await reseal.events(await all(storage), true)).resealed).toBe(1); + expect((await reseal.events(await all(storage), true, NO_STORED_MARKS)).resealed).toBe(1); const [profiled] = await all(storage); expect(fieldOf(profiled?.payload, "nickname")).toMatchObject({ $personal: { category: "profile" }, @@ -348,7 +348,7 @@ describe("resealing a field moved to another category", () => { await append( event("customer", "c-1", 1, "CustomerProfiled", { email: "ada@example.com", nickname }), ); - await reseal.events(await all(storage), true); + await reseal.events(await all(storage), true, NO_STORED_MARKS); const [profiled] = await all(storage); expect(fieldOf(profiled?.payload, "nickname")).toEqual(nickname); expect((await storage.personalKeys.list("c-1")).map(({ category }) => category)).toEqual([ @@ -366,7 +366,9 @@ describe("resealing a process's lifecycle events", () => { state: { customerId: "c-1", email: "ada@example.com" }, }), ); - expect(await reseal.events(await all(storage), true)).toMatchObject({ resealed: 1 }); + expect(await reseal.events(await all(storage), true, NO_STORED_MARKS)).toMatchObject({ + resealed: 1, + }); const [handled] = await all(storage); expect(handled?.person).toBe("c-1"); expect(await opened(fieldOf(fieldOf(handled?.payload, "state"), "email"))).toBe( @@ -495,7 +497,9 @@ describe("resealing dead letters", () => { }), ); - expect(await reseal.letters(await storage.deadLetterStore.list(), started)).toEqual({ + expect( + await reseal.letters(await storage.deadLetterStore.list(), started, NO_STORED_MARKS), + ).toEqual({ resealed: 2, discarded: 0, unsealable: 1, @@ -544,7 +548,9 @@ describe("resealing dead letters", () => { payload: { email: "ada@example.com" }, }), ); - expect(await reseal.letters(await storage.deadLetterStore.list(), started)).toMatchObject({ + expect( + await reseal.letters(await storage.deadLetterStore.list(), started, NO_STORED_MARKS), + ).toMatchObject({ resealed: 2, discarded: 2, }); @@ -560,7 +566,7 @@ describe("resealing dead letters", () => { await storage.personalKeys.add("c-1", "default", await newStoredKey()); const profile = await storage.personalKeys.add("c-1", "profile", await newStoredKey()); await storage.deadLetterStore.add(letter("policy")); - await reseal.letters(await storage.deadLetterStore.list(), started); + await reseal.letters(await storage.deadLetterStore.list(), started, NO_STORED_MARKS); const policy = await storage.deadLetterStore.get("policy"); expect(policy?.errorMessage).toMatchObject({ $personal: { person: "c-1", category: "profile", key: profile.fingerprint }, @@ -593,7 +599,9 @@ describe("resealing dead letters", () => { payload: { email: "ada@example.com" }, }), ); - expect(await reseal.letters(await storage.deadLetterStore.list(), started)).toMatchObject({ + expect( + await reseal.letters(await storage.deadLetterStore.list(), started, NO_STORED_MARKS), + ).toMatchObject({ resealed: 1, }); const resealed = await storage.deadLetterStore.get("scheduled"); @@ -622,7 +630,9 @@ describe("resealing dead letters", () => { lastFailedAt: "2026-01-09T00:00:00.000Z", }), ); - expect(await reseal.letters(await storage.deadLetterStore.list(), started)).toMatchObject({ + expect( + await reseal.letters(await storage.deadLetterStore.list(), started, NO_STORED_MARKS), + ).toMatchObject({ resealed: 1, discarded: 1, }); @@ -785,20 +795,20 @@ describe("what the backfill rewrites and names beyond the marks of a field", () event("contact", "x-1", 1, "ContactNoted", {}), ); const batches = reseal(storage); - expect((await batches.events(await all(storage), false)).resealed).toBe(1); + expect((await batches.events(await all(storage), false, NO_STORED_MARKS)).resealed).toBe(1); const [kept, untouched] = await all(storage); expect(kept?.metadata.schemaVersion).toBe(1); expect(kept?.payload).toEqual({ mail: "ada@example.com" }); expect(untouched?.metadata.schemaVersion).toBe(1); - expect((await batches.events(await all(storage), true)).resealed).toBe(2); + expect((await batches.events(await all(storage), true, NO_STORED_MARKS)).resealed).toBe(2); const [added, noted] = await all(storage); expect(added?.metadata.schemaVersion).toBe(2); expect(added?.person).toBe("c-1"); expect(Object.keys(added?.payload as object)).toEqual(["email"]); expect(isSealed(fieldOf(added?.payload, "email"))).toBe(true); expect(noted).toMatchObject({ person: null, payload: {}, metadata: { schemaVersion: 2 } }); - expect((await batches.events(await all(storage), true)).resealed).toBe(0); + expect((await batches.events(await all(storage), true, NO_STORED_MARKS)).resealed).toBe(0); }); it("leaves as it is now an event written again since the batch was read, named or not, counting it left", async () => { @@ -816,7 +826,10 @@ describe("what the backfill rewrites and names beyond the marks of a field", () await storage.eventStore.reseal([ { position: again, payload: { by: "another" }, person: null, schemaVersion: 2 }, ]); - expect(await reseal(storage).events(read, true)).toMatchObject({ resealed: 1, left: 1 }); + expect(await reseal(storage).events(read, true, NO_STORED_MARKS)).toMatchObject({ + resealed: 1, + left: 1, + }); const events = await all(storage); expect(events[again - 1]).toMatchObject({ payload: { by: "another" }, @@ -914,7 +927,11 @@ describe("what the backfill rewrites and names beyond the marks of a field", () ); const batches = reseal(storage); - const sealed = await batches.letters(await storage.deadLetterStore.list(), started); + const sealed = await batches.letters( + await storage.deadLetterStore.list(), + started, + NO_STORED_MARKS, + ); expect(sealed.resealed).toBe(9); expect(sealed.discarded).toBe(1); const after = new Map( @@ -958,7 +975,10 @@ describe("what the backfill rewrites and names beyond the marks of a field", () const opened = openTextWith(sealedKeys(keysOver(storage.personalKeys))); expect(await opened(after.get("l-1")?.errorMessage ?? "")).toBe("agent +34 away"); expect(await opened(after.get("l-12")?.errorMessage ?? "")).toBeNull(); - expect((await batches.letters(await storage.deadLetterStore.list(), started)).resealed).toBe(0); + expect( + (await batches.letters(await storage.deadLetterStore.list(), started, NO_STORED_MARKS)) + .resealed, + ).toBe(0); }); it("names nobody more for a letter whose instance's state names its own person, or a process that marks nothing", async () => { @@ -990,7 +1010,11 @@ describe("what the backfill rewrites and names beyond the marks of a field", () }; await storage.deadLetterStore.add(base); await storage.deadLetterStore.add({ ...base, id: "unmarked", handler: "signup.onboarding" }); - const sealed = await reseal(storage).letters(await storage.deadLetterStore.list(), started); + const sealed = await reseal(storage).letters( + await storage.deadLetterStore.list(), + started, + NO_STORED_MARKS, + ); expect(sealed.resealed).toBe(0); expect(await storage.deadLetterStore.get("same")).not.toHaveProperty("statePerson"); }); diff --git a/packages/core/src/kernel/personal-data/reseal-batches.ts b/packages/core/src/kernel/personal-data/reseal-batches.ts index d2fe5ef1b..4be292225 100644 --- a/packages/core/src/kernel/personal-data/reseal-batches.ts +++ b/packages/core/src/kernel/personal-data/reseal-batches.ts @@ -26,6 +26,7 @@ import { type ResealKeys, type ResealPlan, } from "./resealing.ts"; +import { marksAgree, type StoredMarks, storedMarksOf } from "./stored-marks.ts"; import type { PersonalKeyWrapping } from "./wrapped-keys.ts"; /** @@ -68,9 +69,11 @@ export interface ResealBatches { /** * Seals in place what the events, as the store holds them, keep in the clear of fields marked * now; with `rewrite`, first writes in its current shape, sealed, each event of a marked type - * stored in an older one. An event written again since it was read is left as it is now. + * stored in an older one. A retired type's are sealed as `marks`, the sets the store recorded as + * the caller read them last. An event written again since it was read, or of a retired type whose + * sets the store holds otherwise by the time its person's transaction opens, is left as it is now. */ - events(events: readonly StoredEvent[], rewrite: boolean): Promise; + events(events: readonly StoredEvent[], rewrite: boolean, marks: StoredMarks): Promise; /** * The same for the payloads of scheduled commands. */ @@ -78,9 +81,13 @@ export interface ResealBatches { /** * The same for dead letters: a scheduled letter's payload and its error text, and the error text * of a policy or process letter that failed before `started`, in milliseconds, whose work names - * someone now. + * someone now, as `marks` name them for a retired type. */ - letters(letters: readonly StoredDeadLetter[], started: number): Promise; + letters( + letters: readonly StoredDeadLetter[], + started: number, + marks: StoredMarks, + ): Promise; /** * Erases each remembered answer sealed under other marks than these, or that no key opens any * more: whom it quotes, and what, the marks of its day said, so no forgetting under these @@ -273,7 +280,33 @@ export const createResealBatches: CreateResealBatchesFunction = ({ return sealed; }; - const events = async (batch: readonly StoredEvent[], rewrite: boolean): Promise => { + // A retired type's events are sealed as the sets the store recorded, read before; the + // transaction that seals them runs one at a time with the one a walk records its sets sealed in, + // so it reads them again: one that sealed under another of them alone since changes how they + // seal, and they are left to be read again. + const plannedUnder = async ( + transaction: StorageTransaction, + marks: StoredMarks, + events: readonly StoredEvent[], + ): Promise => { + const types = new Map(); + for (const { aggregateType, type } of events) { + if (aggregates.byName[aggregateType]?.retired.has(type) !== true) continue; + types.set(JSON.stringify([aggregateType, type]), { aggregateType, type }); + } + for (const { aggregateType, type } of types.values()) { + const now = storedMarksOf(await transaction.eventStore.marksOf({ aggregateType, type })); + if (!marksAgree({ read: marks, now, aggregateType, type })) return false; + } + return true; + }; + + const events = async ( + batch: readonly StoredEvent[], + rewrite: boolean, + marks: StoredMarks, + ): Promise => { + const marked = { ...aggregates, storedMarks: marks }; const owned: Owned<{ event: StoredEvent; plan: ResealPlan & { readonly schemaVersion?: number }; @@ -281,8 +314,8 @@ export const createResealBatches: CreateResealBatchesFunction = ({ const nameless: StoredEvent[] = []; const bare: ResealedEvent[] = []; for (const event of batch) { - const upcast = rewrite ? planUpcastReseal({ event, aggregates }) : null; - const plan = upcast ?? planEventReseal({ event, aggregates, processes }); + const upcast = rewrite ? planUpcastReseal({ event, aggregates: marked }) : null; + const plan = upcast ?? planEventReseal({ event, aggregates: marked, processes }); if (plan === "unsealable") nameless.push(event); else if (plan !== null && "bare" in plan) { bare.push({ @@ -303,6 +336,10 @@ export const createResealBatches: CreateResealBatchesFunction = ({ ? [] : await storage.transact((transaction) => transaction.eventStore.reseal(bare)); const sealed = await perPerson(owned, async (items, transaction, keys) => { + const planned = items.map(({ event }) => event); + if (!(await plannedUnder(transaction, marks, planned))) { + return { ...NOTHING_SEALED, left: items.length }; + } const discardedTypes = new Set(); const resealed = []; for (const { event, plan } of items) { @@ -409,13 +446,16 @@ export const createResealBatches: CreateResealBatchesFunction = ({ // Whom a policy or process letter's work names now: the person of the event it ran on, as the // marks of now name them. - const personOfWork = async (letter: StoredDeadLetter): Promise => { + const personOfWork = async ( + letter: StoredDeadLetter, + marked: AggregatesRuntime, + ): Promise => { const event = await storage.eventStore.readOne({ aggregateType: letter.aggregateType, aggregateId: letter.aggregateId, eventId: letter.eventId, }); - return event === null ? null : personOfEvent({ aggregates, event }); + return event === null ? null : personOfEvent({ aggregates: marked, event }); }; // Whom the state of a process letter's instance names, as the marks of now name them, as it @@ -471,6 +511,7 @@ export const createResealBatches: CreateResealBatchesFunction = ({ const planLetter = async ( letter: StoredDeadLetter, started: number, + marked: AggregatesRuntime, ): Promise => { const planned = letter.kind === "scheduled" @@ -489,7 +530,9 @@ export const createResealBatches: CreateResealBatchesFunction = ({ ofState = await instanceStatePerson(letter); } if (letter.person === null && letter.kind === "scheduled") text = payload?.person ?? null; - else if (letter.person === null && earlier) text = (await personOfWork(letter)) ?? ofState; + else if (letter.person === null && earlier) { + text = (await personOfWork(letter, marked)) ?? ofState; + } const statePerson = ofState === (letter.person ?? text) ? null : ofState; const person = payload?.person ?? text ?? (statePerson === null ? null : letter.person); if (person === null) return planned === "unsealable" ? "unsealable" : null; @@ -549,10 +592,17 @@ export const createResealBatches: CreateResealBatchesFunction = ({ return discarded; }; - const letters = async (batch: readonly StoredDeadLetter[], started: number): Promise => { + // A retired type's event a letter's work ran on is sealed before the letters are gone through, + // so the person its envelope names, not the sets, names whom the letter's text is sealed for. + const letters = async ( + batch: readonly StoredDeadLetter[], + started: number, + marks: StoredMarks, + ): Promise => { + const marked = { ...aggregates, storedMarks: marks }; const owned: Owned[] = []; const nameless: StoredDeadLetter[] = []; - const plans = await Promise.all(batch.map((letter) => planLetter(letter, started))); + const plans = await Promise.all(batch.map((letter) => planLetter(letter, started, marked))); plans.forEach((plan, index) => { if (plan === "unsealable") nameless.push(batch[index] as StoredDeadLetter); else if (plan !== null) { diff --git a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts index b05261f84..151accc03 100644 --- a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts +++ b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import type { Adapter } from "../../adapter/adapter.ts"; import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; -import type { StoredEventTypeMarks } from "../../adapter/storage/event-store.ts"; +import type { EventStore, StoredEventTypeMarks } from "../../adapter/storage/event-store.ts"; import type { SealedValue } from "../../adapter/storage/personal-key-store.ts"; import { pendingEvent } from "../../adapter/testing/fixtures.ts"; import type { Config } from "../../config/types.ts"; @@ -12,14 +12,14 @@ import { type Clock, createFixedClock } from "../../contracts/clock.ts"; import { ConfigurationError } from "../../contracts/errors.ts"; import type { StoredEvent } from "../../contracts/event.ts"; import { createSequentialIdGenerator } from "../../contracts/ids.ts"; -import { silentLogger } from "../../contracts/logger.ts"; +import { type Logger, silentLogger } from "../../contracts/logger.ts"; import { memory } from "../../memory/index.ts"; import { createMemoryTenantKeyStore } from "../../memory/tenant-key-store.ts"; import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; import type { Registry } from "../../modules/registry.ts"; import { type BoundaApp, createApp } from "../app.ts"; import { ledgerFor } from "../test-support.ts"; -import { BACKFILL_FOLLOW_INTERVAL_MS } from "./backfill.ts"; +import { BACKFILL_FOLLOW_INTERVAL_MS, BACKFILL_LEASE_MS } from "./backfill.ts"; import { categoryOf, isSealed } from "./crypto.ts"; import type { ExportedEvent } from "./export.ts"; import { RECORDED_PERSONAL_DATA } from "./ledger-in-force.ts"; @@ -147,17 +147,28 @@ afterEach(async () => { let starts = 0; -const start = async (adapter: Adapter, deploy: Deploy, clock = createFixedClock(START)) => { +interface StartOptions { + readonly logger?: Logger; + // What the app's storage comes from in place of `adapter`, whose forget ledger it keeps. + readonly storage?: Adapter; +} + +const start = async ( + adapter: Adapter, + deploy: Deploy, + clock = createFixedClock(START), + { logger = silentLogger, storage = adapter }: StartOptions = {}, +) => { starts += 1; const app = await createApp({ registry: registryOf(deploy), config: { - storage: adapter, + storage, runtime: { personalData: { forgetLedger: { store: ledgerFor(adapter) } } }, }, ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), clock, - logger: silentLogger, + logger, }); let stopped = false; const stop = async (): Promise => { @@ -544,6 +555,33 @@ const sealedLast = async (adapter: Adapter) => }) ).map(({ sealedThrough }) => sealedThrough !== null); +// The adapter, whose storage runs `hook` once, after its first read of every set of marks +// recorded: what lands between a start's first read of them and the lease it takes. +const afterFirstMarksRead = (adapter: Adapter, hook: () => Promise): Adapter => { + let pending = true; + return { + ...adapter, + createStorage: async () => { + const storage = await adapter.createStorage(); + const marksOf: EventStore["marksOf"] = async (args) => { + const read = await storage.eventStore.marksOf(args); + if (pending && args === undefined) { + pending = false; + await hook(); + } + return read; + }; + return { + ...storage, + eventStore: new Proxy(storage.eventStore, { + get: (target, property, receiver) => + property === "marksOf" ? marksOf : Reflect.get(target, property, receiver), + }), + }; + }, + }; +}; + const unsettledNote = [ "The store holds events of retired types this code cannot seal:", `- customer.NoteTaken is retired, but its recorded marks give "note" different categories (default, invoices) and no backfill walk has sealed every value of it under one of them: deploy once with its module marking note in the category to keep, let the backfill catch up, then retire it`, @@ -618,6 +656,70 @@ describe.each(adapters)( ]); }); + it("checks it against the set a walk of other code sealed under alone before the start took its walk's lease", async () => { + const adapter = adapterOf(); + const { deploy, clock } = deploys(() => adapter); + await deploy("default", (app) => note(app, "c-1", "call after five")); + await deploy("clear", (app) => note(app, "c-2", "prefers email")); + const invoices = await start(adapter, "invoices", clock); + + // That walk catches up alone once the start read the marks to name its own walk by. + const { app } = await start(adapter, "retired", clock, { + storage: afterFirstMarksRead(adapter, () => invoices.app.runUntilIdle()), + }); + expect(await sealedLast(adapter)).toEqual([false, false, true]); + await app.runUntilIdle(); + const [first, second] = await notes(adapter); + expect(categoryOf(noteOf(first) as never)).toBe("invoices"); + expect(categoryOf(noteOf(second) as never)).toBe("invoices"); + }); + + it("holds its walk, refuses redactions and exports, and the next start, once a walk of other code caught up alone while its lease had lapsed", async () => { + const adapter = adapterOf(); + const { deploy, clock } = deploys(() => adapter); + await deploy("default", async (app) => { + await note(app, "c-1", "call after five"); + await walked(app); + }); + await deploy("invoices", (app) => note(app, "c-2", "send the invoice")); + await deploy("clear", (app) => note(app, "c-3", "ring twice")); + const errors: [string, unknown][] = []; + const logger: Logger = { + ...silentLogger, + error: (message, fields) => errors.push([message, fields]), + }; + const retired = await start(adapter, "retired", clock, { logger }); + + // It walks nothing for longer than its lease and a follow interval, while code that marks no + // note catches up alone. + clock.advance(BACKFILL_LEASE_MS + BACKFILL_FOLLOW_INTERVAL_MS); + await deploy("clear", walked); + expect(await sealedLast(adapter)).toEqual([false, false, true]); + + await retired.app.runUntilIdle(); + expect(errors).toContainEqual([ + "personal data written before its marks could not be sealed", + expect.objectContaining({ errorName: "ConfigurationError" }), + ]); + const late = (await notes(adapter))[2]; + expect(noteOf(late)).toBe("ring twice"); + await expect( + retired.app.redact("c-3", { + events: [ + { + id: late?.id, + aggregateType: late?.aggregateType, + aggregateId: late?.aggregateId, + type: late?.type, + fields: ["note"], + }, + ], + } as never), + ).rejects.toThrow(unsettledNote); + await expect(exported(retired.app, "c-3")).rejects.toThrow(unsettledNote); + await expect(start(adapter, "retired", clock)).rejects.toThrow(unsettledNote); + }); + it("refuses to retire it while no walk sealed under one of them alone, naming the field and the way out", async () => { const adapter = adapterOf(); const { deploy, clock } = deploys(() => adapter); @@ -627,11 +729,15 @@ describe.each(adapters)( const refused = start(adapter, "retired", clock); await expect(refused).rejects.toThrow(ConfigurationError); await expect(refused).rejects.toThrow(unsettledNote); + // The refused start took its walk's lease and gave it back: a walk on other marks counts it + // running a follow interval longer. + clock.advance(2 * BACKFILL_FOLLOW_INTERVAL_MS); // A walk alone under a set that marks no note settles nothing. await deploy("clear", walked); expect(await sealedLast(adapter)).toEqual([false, true, false]); await expect(start(adapter, "retired", clock)).rejects.toThrow(unsettledNote); + clock.advance(2 * BACKFILL_FOLLOW_INTERVAL_MS); await deploy("invoices", walked); const { app } = await start(adapter, "retired", clock); @@ -758,7 +864,9 @@ describe.each(adapters)( await first.stop(); const [written] = await notes(adapter); - const { app } = await start(adapter, "dropped"); + // Once the first start's lease, given back, no longer counts as running. + const later = createFixedClock(new Date(START.getTime() + 2 * BACKFILL_FOLLOW_INTERVAL_MS)); + const { app } = await start(adapter, "dropped", later); await app.runUntilIdle(); const [rewritten] = await notes(adapter); diff --git a/packages/core/src/kernel/personal-data/stored-marks.ts b/packages/core/src/kernel/personal-data/stored-marks.ts index ee8c67953..f78fae5b9 100644 --- a/packages/core/src/kernel/personal-data/stored-marks.ts +++ b/packages/core/src/kernel/personal-data/stored-marks.ts @@ -69,6 +69,30 @@ export const storedMarksOf: StoredMarksOfFunction = (sets) => { }; }; +export interface MarksAgreeArgs { + readonly read: StoredMarks; + readonly now: StoredMarks; + readonly aggregateType: string; + readonly type: string; +} + +export interface MarksAgreeFunction { + (args: MarksAgreeArgs): boolean; +} + +/** + * Whether two reads of the sets the store recorded agree on a type: its sets, in the order + * recorded, and the one a walk last sealed every value under alone. + */ +export const marksAgree: MarksAgreeFunction = ({ read, now, aggregateType, type }) => { + const named = (marks: StoredMarks): string => + JSON.stringify([ + marks.of(aggregateType, type).map(marksSetFingerprint), + marksSetFingerprint(marks.authority(aggregateType, type)), + ]); + return named(read) === named(now); +}; + export interface CanonicalMarksFunction { (marks: PersonalMarks): readonly [string | null, readonly (string | readonly string[])[]]; } diff --git a/packages/core/src/kernel/personal-data/tenant-export-stream.ts b/packages/core/src/kernel/personal-data/tenant-export-stream.ts index 91b8440c6..8a7878698 100644 --- a/packages/core/src/kernel/personal-data/tenant-export-stream.ts +++ b/packages/core/src/kernel/personal-data/tenant-export-stream.ts @@ -29,6 +29,7 @@ import { openCommandPayload, sealedKeys } from "./commands.ts"; import { openTextWith, textPersons } from "./errors.ts"; import { type Envelopes, envelopesIn, openedUnder, redactedIn } from "./event-store.ts"; import type { ExportedCategories, ExportedRestricted, ExportedTransfer } from "./export.ts"; +import { withFreshMarks } from "./fresh-marks.ts"; import { personalDataInformation } from "./information.ts"; import { FORGET_LEDGER_SUBSCRIBER } from "./ledger-outbox.ts"; import { fieldCategory, type PersonalMarks } from "./marks.ts"; @@ -227,7 +228,7 @@ async function* mergedIds( // that moved past it by the time the last page is read rejects it with `TenantDataChangedError`. export const streamTenantExport: StreamTenantExportFunction = async ({ storage, - aggregates, + aggregates: started, processes, readModels, sealing, @@ -243,6 +244,8 @@ export const streamTenantExport: StreamTenantExportFunction = async ({ frozenAt, onPage, }) => { + // As the person's export does. + const aggregates = await withFreshMarks({ eventStore: storage.eventStore, aggregates: started }); const exportedAt = clock.now().toISOString(); const position = await storage.eventStore.lastPosition(); const projected: Record = {}; diff --git a/packages/core/src/kernel/unit-of-work/unit-of-work.ts b/packages/core/src/kernel/unit-of-work/unit-of-work.ts index 9218e5e98..c5c02f299 100644 --- a/packages/core/src/kernel/unit-of-work/unit-of-work.ts +++ b/packages/core/src/kernel/unit-of-work/unit-of-work.ts @@ -34,7 +34,10 @@ export type UnitStores = Pick< * store holds under that id already. */ export interface UnitOfWork - extends Omit { + extends Omit< + StorageTransaction, + "personalKeys" | "snapshotStore" | "recipients" | "checkpointStore" + > { commit(): Promise; /** * Runs `step` before the commit's transaction opens, in the order given, for what has to happen diff --git a/packages/core/src/memory/index.ts b/packages/core/src/memory/index.ts index 1da643776..929faefe3 100644 --- a/packages/core/src/memory/index.ts +++ b/packages/core/src/memory/index.ts @@ -346,6 +346,7 @@ export const memory: MemoryFunction = (options = {}) => { eventStore: events, writers, recipients, + checkpointStore: checkpoints, entries: { inboxLedger: inboxLedger.entries, deadLetterStore: deadLetterStore.entries, diff --git a/packages/core/src/memory/transaction.ts b/packages/core/src/memory/transaction.ts index cf39f05c3..246447e50 100644 --- a/packages/core/src/memory/transaction.ts +++ b/packages/core/src/memory/transaction.ts @@ -35,6 +35,7 @@ export interface CreateMemoryStorageTransactionArgs { readonly persons: PersonStore; readonly snapshotStore: SnapshotStore; readonly recipients: KeptRecipientStore; + readonly checkpointStore: CheckpointStore; readonly entries: { readonly inboxLedger: StoreEntries; readonly deadLetterStore: StoreEntries; @@ -66,6 +67,7 @@ type CreateUndoLogArgs = Omit< | "persons" | "snapshotStore" | "recipients" + | "checkpointStore" | "unrecordCategory" | "writers" >; @@ -451,6 +453,7 @@ export const createMemoryStorageTransaction: CreateMemoryStorageTransactionFunct persons, snapshotStore, recipients, + checkpointStore, unrecordCategory, writers, ...live @@ -475,10 +478,13 @@ export const createMemoryStorageTransaction: CreateMemoryStorageTransactionFunct // checked against a person's stream and the event that reads the disclosures to tell never // pass each other. const release = (await writers.acquire("writer", true)) as () => void; + // Written at once, under the writer this holds, and put back if the transaction fails. + const checkpoints = createCheckpointJournal(checkpointStore); try { const result = await work({ eventStore: staged, ...stores, + checkpointStore: checkpoints.store, ...trackedForgets(deferred, live, atOnce), personalKeys: trackedPersonalKeys( personalKeys, @@ -510,6 +516,9 @@ export const createMemoryStorageTransaction: CreateMemoryStorageTransactionFunct reserved.length = 0; atOnce.length = 0; return result; + } catch (error) { + await checkpoints.undo(); + throw error; } finally { eventStore.release(reserved); undoAll(atOnce); diff --git a/packages/postgresql/src/index.ts b/packages/postgresql/src/index.ts index ee9a8bce4..239d5f019 100644 --- a/packages/postgresql/src/index.ts +++ b/packages/postgresql/src/index.ts @@ -201,6 +201,11 @@ export const postgresql: PostgresqlFunction = (options) => { table: tables.snapshots, personalKeys: tables.personalKeys, }), + checkpointStore: createSqlCheckpointStore({ + db: database, + table: tables.checkpoints, + dialect: postgresqlDialect, + }), }); const boundTo = (tx: SqlTransaction): PostgresqlDatabase => ({ run: tx.run, @@ -222,11 +227,6 @@ export const postgresql: PostgresqlFunction = (options) => { const storageBehind = (guarded: PostgresqlDatabase): Storage => ({ ...storesOver(guarded), notifier, - checkpointStore: createSqlCheckpointStore({ - db: guarded, - table: tables.checkpoints, - dialect: postgresqlDialect, - }), subscriberFailures: createSqlSubscriberFailureStore({ db: guarded, table: tables.subscriberFailures, diff --git a/packages/sqlite/src/forget-ledger.test.ts b/packages/sqlite/src/forget-ledger.test.ts index 2e5fb6cf1..c8ecf7261 100644 --- a/packages/sqlite/src/forget-ledger.test.ts +++ b/packages/sqlite/src/forget-ledger.test.ts @@ -302,8 +302,7 @@ describe("restoring a backup with a forget ledger", () => { await backUp(paths.store, backup); await before.forget("c-1"); await before.stop(); - // The process stops between the intention and the commit of c-2's forgetting. - let crashing = true; + let crashing = false; const store = sqlite({ path: paths.store, encrypt: false }); const stopped: Adapter = { ...store, @@ -329,6 +328,8 @@ describe("restoring a backup with a forget ledger", () => { }, env, }); + // The process stops between the intention and the commit of c-2's forgetting. + crashing = true; await expect(stopping.forget("c-2")).rejects.toThrow("the process stopped"); crashing = false; await stopping.stop(); From 435daf477858a900a2bacc98397bba89e2dbeaa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 11:23:23 +0100 Subject: [PATCH 10/33] feat(core)!: retire personal-data categories, and refuse a store that recorded keys in a category the app neither declares nor retires A category of bounda.personal-data.ts takes `retired: true` with its whole declaration: no field, call or decision marks it any more, its data keeps its retention and exemptions and is never forgotten at once, and the inventory and the exports say it is retired (formats: export 3, inventory 3, tenant export 10). The start, the prune with no app and the stranded listing refuse every category the store recorded keys in that the app neither declares nor retires, and build their rules per database from what it recorded, so a category recorded since stays one only newer code declares. A retired type whose recorded marks seal in such a category is refused too (EV2-aa). The start checks the marks before it records them, so a refused start records none. --- .../testing/personal-data-export.contract.ts | 4 +- .../adapter/testing/tenant-export.contract.ts | 2 +- .../src/kernel/aggregate/build-aggregates.ts | 8 +- packages/core/src/kernel/aggregate/runtime.ts | 5 + .../src/kernel/aggregate/stored-types.test.ts | 58 +++++ .../core/src/kernel/aggregate/stored-types.ts | 35 ++- packages/core/src/kernel/app.ts | 33 +-- .../personal-data/backfill-walk.test.ts | 1 + .../kernel/personal-data/categories.test.ts | 145 +++++++++++++ .../src/kernel/personal-data/categories.ts | 74 ++++++- .../personal-data/category-ahead.test.ts | 34 ++- .../kernel/personal-data/export-json.test.ts | 3 +- .../src/kernel/personal-data/export.test.ts | 7 +- .../core/src/kernel/personal-data/export.ts | 7 +- .../kernel/personal-data/information.test.ts | 4 + .../src/kernel/personal-data/information.ts | 1 + .../kernel/personal-data/inventory.test.ts | 41 +++- .../src/kernel/personal-data/inventory.ts | 8 +- .../personal-data/ledger-prune-app.test.ts | 77 +++++++ .../kernel/personal-data/ledger-prune.test.ts | 1 + .../src/kernel/personal-data/ledger-prune.ts | 67 ++++-- .../src/kernel/personal-data/marks.test.ts | 1 + .../personal-data/reseal-batches.test.ts | 1 + .../kernel/personal-data/resealing.test.ts | 3 + .../retired-categories-app.test.ts | 202 ++++++++++++++++++ .../personal-data/retired-marks-app.test.ts | 98 ++++++++- .../core/src/kernel/personal-data/stranded.ts | 14 +- .../personal-data/tenant-export-json.test.ts | 23 +- .../tenant-export-stream.test.ts | 6 +- .../src/kernel/personal-data/tenant-export.ts | 2 +- .../core/src/kernel/ports/returns.test.ts | 11 + packages/core/src/kernel/ports/returns.ts | 8 +- .../core/src/kernel/recipients/build.test.ts | 13 ++ packages/core/src/kernel/recipients/build.ts | 9 +- .../src/kernel/shared/restore-model.test.ts | 2 +- packages/core/src/modules/personal-data.ts | 57 ++++- packages/core/test-types/inference.test-d.ts | 12 +- .../core/test-types/tenant-export.test-d.ts | 4 +- 38 files changed, 971 insertions(+), 110 deletions(-) create mode 100644 packages/core/src/kernel/personal-data/retired-categories-app.test.ts diff --git a/packages/core/src/adapter/testing/personal-data-export.contract.ts b/packages/core/src/adapter/testing/personal-data-export.contract.ts index 0c236ab06..2a9bb167f 100644 --- a/packages/core/src/adapter/testing/personal-data-export.contract.ts +++ b/packages/core/src/adapter/testing/personal-data-export.contract.ts @@ -346,7 +346,7 @@ export const personalDataExportContract: PersonalDataExportContractFunction = ({ expect(parts[0]).toEqual({ kind: "header", header: { - version: 2, + version: 3, personId: "ana", exportedAt: whole.exportedAt, position: whole.position, @@ -376,7 +376,7 @@ export const personalDataExportContract: PersonalDataExportContractFunction = ({ expect(text).toBe(JSON.stringify(whole, null, 2)); expect(JSON.parse(text)).toEqual(whole); // The version first, so a reader learns the format before anything else. - expect(text.startsWith('{\n "version": 2,\n')).toBe(true); + expect(text.startsWith('{\n "version": 3,\n')).toBe(true); }); it("holds no more than a page of records at once, whatever the history", async () => { diff --git a/packages/core/src/adapter/testing/tenant-export.contract.ts b/packages/core/src/adapter/testing/tenant-export.contract.ts index 6f31f005c..c1f355a5b 100644 --- a/packages/core/src/adapter/testing/tenant-export.contract.ts +++ b/packages/core/src/adapter/testing/tenant-export.contract.ts @@ -366,7 +366,7 @@ export const tenantExportContract: TenantExportContractFunction = ({ create }) = const header = parts[0]?.kind === "header" ? parts[0].header : undefined; expect(header).toEqual({ format: "bounda.tenant-export", - version: 9, + version: 10, tenant: DEFAULT_TENANT, exportId: expect.any(String), exportedAt: "2026-03-01T00:00:00.000Z", diff --git a/packages/core/src/kernel/aggregate/build-aggregates.ts b/packages/core/src/kernel/aggregate/build-aggregates.ts index 5050228a8..c2543618e 100644 --- a/packages/core/src/kernel/aggregate/build-aggregates.ts +++ b/packages/core/src/kernel/aggregate/build-aggregates.ts @@ -6,6 +6,7 @@ import { capitalize } from "../../modules/naming.ts"; import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; import { notPersonal, person, personal } from "../../modules/personal.ts"; import type { AggregateEntry, Registry } from "../../modules/registry.ts"; +import { categoryNamesOf } from "../personal-data/categories.ts"; import { personalMarksOf } from "../personal-data/marks.ts"; import { NO_STORED_MARKS } from "../personal-data/stored-marks.ts"; import type { ModulePorts } from "../ports/ports.ts"; @@ -154,5 +155,10 @@ export const buildAggregates: BuildAggregatesFunction = ({ registry, ports, conf commandsByType[command.type] = { aggregate, command }; } } - return { byName, commandsByType, storedMarks: NO_STORED_MARKS }; + return { + byName, + commandsByType, + storedMarks: NO_STORED_MARKS, + categories: new Set(categoryNamesOf(registry)), + }; }; diff --git a/packages/core/src/kernel/aggregate/runtime.ts b/packages/core/src/kernel/aggregate/runtime.ts index f30130617..7b1677763 100644 --- a/packages/core/src/kernel/aggregate/runtime.ts +++ b/packages/core/src/kernel/aggregate/runtime.ts @@ -87,4 +87,9 @@ export interface AggregatesRuntime { * What a retired type marks, which no schema says any more. */ readonly storedMarks: StoredMarks; + /** + * The categories of personal data `bounda.personal-data.ts` declares or retired, and the default + * one: those a set of marks recorded for a retired type may seal its values under. + */ + readonly categories: ReadonlySet; } diff --git a/packages/core/src/kernel/aggregate/stored-types.test.ts b/packages/core/src/kernel/aggregate/stored-types.test.ts index 2f3549d5e..60cf22948 100644 --- a/packages/core/src/kernel/aggregate/stored-types.test.ts +++ b/packages/core/src/kernel/aggregate/stored-types.test.ts @@ -59,6 +59,19 @@ const beginning = buildAggregates({ }, }, readModels: {}, + // Retired, its whole declaration kept: a retired type's recorded marks may still seal in it. + personalData: { + automatedDecisions: {}, + categories: { + invoices: { + basis: "legal-obligation", + retention: "6y", + purposes: ["Bill the person"], + sources: ["data-subject"], + retired: true, + }, + }, + }, } as unknown as Registry, ports: choosePorts(registry, resolveConfig({ storage: memory(), ports: defaultPorts(registry) })), }); @@ -286,6 +299,51 @@ describe("checkRetiredMarks", () => { }), ).not.toThrow(); }); + + it("refuses a retired type whose recorded marks seal in a category bounda.personal-data.ts neither declares nor retires, naming the type and each category", () => { + const sealedIn = ( + categories: Readonly>, + sealedThrough: number | null, + ) => ({ + ...marks("order", "OrderNoteAdded", Object.keys(categories)), + fingerprint: JSON.stringify(categories), + sealedThrough, + marks: { person: null, fields: Object.keys(categories), categories }, + }); + const check = () => + checkRetiredMarks({ + aggregates: { + ...aggregates, + storedMarks: storedMarksOf([ + sealedIn({ note: "invoices", phone: "default" }, 3), + sealedIn({ note: "billing" }, null), + ]), + }, + types: [kind("order", "OrderNoteAdded", 1)], + }); + expect(check).toThrow(ConfigurationError); + expect(check).toThrow( + [ + "The store holds events of retired types this code cannot seal:", + '- order.OrderNoteAdded is retired, and its recorded marks seal values in the category "billing", which bounda.personal-data.ts neither declares nor retires: declare it again, its whole declaration with retired: true', + '- order.OrderNoteAdded is retired, and its recorded marks seal values in the category "invoices", which bounda.personal-data.ts neither declares nor retires: declare it again, its whole declaration with retired: true', + ].join("\n"), + ); + // The same sets, with the category retired and the other one declared, and a walk settling. + expect(() => + checkRetiredMarks({ + aggregates: { + ...beginning, + categories: new Set([...beginning.categories, "billing"]), + storedMarks: storedMarksOf([ + sealedIn({ note: "invoices", phone: "default" }, 3), + sealedIn({ note: "billing" }, null), + ]), + }, + types: [kind("order", "OrderNoteAdded", 1)], + }), + ).not.toThrow(); + }); }); describe("checkRetiredMarks of marks that disagree", () => { diff --git a/packages/core/src/kernel/aggregate/stored-types.ts b/packages/core/src/kernel/aggregate/stored-types.ts index 8f62d8b59..dabbc0fcd 100644 --- a/packages/core/src/kernel/aggregate/stored-types.ts +++ b/packages/core/src/kernel/aggregate/stored-types.ts @@ -7,6 +7,7 @@ import { SCHEDULED_COMMAND_FAILED_EVENT, } from "../../modules/bounda-events.ts"; import { toKebabCase } from "../../modules/naming.ts"; +import { fieldCategory } from "../personal-data/marks.ts"; import { unsettledFields } from "../personal-data/stored-marks.ts"; import { PROCESS_EVENTS, processOfStream } from "../process/lifecycle.ts"; import { RUNTIME_EVENT_TYPES } from "../system-events.ts"; @@ -172,7 +173,9 @@ export interface CheckRetiredMarksFunction { * be sealed. A start records the marks of every type it has a module for, unless the tenant is * frozen, until it thaws. Refuses too a retired type whose recorded marks give a field different * categories that no walk settled, as `unsettledFields` names them: which one a value left in the - * clear is sealed under would depend on the order instances started in. + * clear is sealed under would depend on the order instances started in, and one whose recorded + * marks name a category `bounda.personal-data.ts` neither declares nor retires, which no retention + * or exemption would keep what is sealed under it by. */ export const checkRetiredMarks: CheckRetiredMarksFunction = ({ types, aggregates }) => { const problems = kindsOf(types) @@ -185,13 +188,29 @@ export const checkRetiredMarks: CheckRetiredMarksFunction = ({ types, aggregates `${qualified} is retired, but no start recorded what it marks personal: deploy once with its module, on a tenant that is not frozen, then retire it`, ]; } - return unsettledFields({ - sets, - authority: aggregates.storedMarks.authority(aggregateType, type), - }).map( - ({ field, categories }) => - `${qualified} is retired, but its recorded marks give "${field}" different categories (${categories.join(", ")}) and no backfill walk has sealed every value of it under one of them: deploy once with its module marking ${field} in the category to keep, let the backfill catch up, then retire it`, - ); + const unknown = [ + ...new Set( + sets.flatMap((set) => + set === null ? [] : set.fields.map((field) => fieldCategory(set, field)), + ), + ), + ] + .filter((category) => !aggregates.categories.has(category)) + .sort(codePointOrder) + .map( + (category) => + `${qualified} is retired, and its recorded marks seal values in the category "${category}", which bounda.personal-data.ts neither declares nor retires: declare it again, its whole declaration with retired: true`, + ); + return [ + ...unknown, + ...unsettledFields({ + sets, + authority: aggregates.storedMarks.authority(aggregateType, type), + }).map( + ({ field, categories }) => + `${qualified} is retired, but its recorded marks give "${field}" different categories (${categories.join(", ")}) and no backfill walk has sealed every value of it under one of them: deploy once with its module marking ${field} in the category to keep, let the backfill catch up, then retire it`, + ), + ]; }); if (problems.length > 0) { throw new ConfigurationError( diff --git a/packages/core/src/kernel/app.ts b/packages/core/src/kernel/app.ts index 9d6d2fe3f..05b86a747 100644 --- a/packages/core/src/kernel/app.ts +++ b/packages/core/src/kernel/app.ts @@ -102,7 +102,11 @@ import { import { appliedTally } from "./personal-data/applied-tally.ts"; import { createBackfillLease, createPersonalDataBackfill } from "./personal-data/backfill.ts"; import { openDatabaseKey } from "./personal-data/blind-index.ts"; -import { buildPersonalCategories, checkMarkedCategories } from "./personal-data/categories.ts"; +import { + buildPersonalCategories, + checkMarkedCategories, + checkRecordedCategories, +} from "./personal-data/categories.ts"; import { checkClassification } from "./personal-data/classification.ts"; import { logClearFields } from "./personal-data/clear-fields.ts"; import { createCommittedCopies } from "./personal-data/committed-copies.ts"; @@ -1361,17 +1365,6 @@ export const assembleApp: AssembleAppFunction = async ({ deferred.shift(); } }; - // What every type of this code marks, so a type retired later is sealed as it was marked; a - // forgotten tenant's start writes nothing, nor does it seal its events again. - if (fenceAtStart !== "forgotten" && !tenantForgotten()) { - checkRetiredMarks({ types: storedTypes, aggregates }); - await unlessFrozen(() => - adapted.eventStore.recordMarks({ - marks: currentMarkSets(aggregates), - at: clock.now().toISOString(), - }), - ); - } const keyed = hierarchy?.wrapping ?? keylessWrapping(); const wrapping = watching === undefined ? keyed : witnessedWrapping(keyed, watching); // Opened at once, never inside a transaction: none of a forgotten tenant, whose key is gone. @@ -1411,6 +1404,22 @@ export const assembleApp: AssembleAppFunction = async ({ processes: processDefinitions, readModels: readModels.byName, }); + // What every type of this code marks, so a type retired later is sealed as it was marked, once + // no mark names a category the app does not mark in; a forgotten tenant's start writes nothing, + // nor does it seal its events again. + if (fenceAtStart !== "forgotten" && !tenantForgotten()) { + checkRetiredMarks({ types: storedTypes, aggregates }); + } + // Before anything forgets: what a dropped category recorded would go at once. + checkRecordedCategories({ categories: personalCategories, recorded: recordedCategories }); + if (fenceAtStart !== "forgotten" && !tenantForgotten()) { + await unlessFrozen(() => + adapted.eventStore.recordMarks({ + marks: currentMarkSets(aggregates), + at: clock.now().toISOString(), + }), + ); + } // One list per `runUntilIdle` under way. const observers = new Set(); const recordRejection = createHostLog({ diff --git a/packages/core/src/kernel/personal-data/backfill-walk.test.ts b/packages/core/src/kernel/personal-data/backfill-walk.test.ts index 25d97c721..d6b0e713e 100644 --- a/packages/core/src/kernel/personal-data/backfill-walk.test.ts +++ b/packages/core/src/kernel/personal-data/backfill-walk.test.ts @@ -64,6 +64,7 @@ const aggregates = { }, }, storedMarks: NO_STORED_MARKS, + categories: new Set(["default"]), } as unknown as AggregatesRuntime; const processes = { byName: {} } as unknown as Pick; diff --git a/packages/core/src/kernel/personal-data/categories.test.ts b/packages/core/src/kernel/personal-data/categories.test.ts index 10e3d201a..cf58b0080 100644 --- a/packages/core/src/kernel/personal-data/categories.test.ts +++ b/packages/core/src/kernel/personal-data/categories.test.ts @@ -6,7 +6,9 @@ import { createTestApp } from "../../testing/index.ts"; import { buildPersonalCategories, checkCategory, + checkCategoryNames, checkMarkedCategories, + checkRecordedCategories, formatRetention, } from "./categories.ts"; @@ -67,6 +69,7 @@ describe("buildPersonalCategories", () => { criminal: null, processedFor: [], exemptions: [], + retired: false, }, { name: "profile", @@ -74,6 +77,7 @@ describe("buildPersonalCategories", () => { retention: { months: 0, ms: 2_592_000_000 }, ...said, exemptions: [], + retired: false, }, { name: "invoices", @@ -81,6 +85,7 @@ describe("buildPersonalCategories", () => { retention: { months: 72, ms: 0 }, ...said, exemptions: ["legal-obligation"], + retired: false, }, ]); expect(categories.decisions).toEqual([]); @@ -103,6 +108,7 @@ describe("buildPersonalCategories", () => { criminal: null, processedFor: [], exemptions: [], + retired: false, }, ]); expect(categories.declared).toEqual([]); @@ -755,6 +761,145 @@ describe("checkMarkedCategories", () => { }); }); +describe("a retired category", () => { + const declaration = { + basis: "legal-obligation", + retention: "6y", + purposes: ["Bill the person"], + sources: ["data-subject"], + }; + const categories = buildPersonalCategories({ + module: module({ + profile: { ...declaration, basis: "consent", retention: "30d" }, + invoices: { ...declaration, retired: true }, + }), + retention: null, + recorded: ["default", "profile", "invoices"], + }); + + it("keeps its whole declaration, its retention and exemptions, among the declared ones", () => { + expect(categories.of("invoices")).toEqual({ + name: "invoices", + basis: "legal-obligation", + retention: { months: 72, ms: 0 }, + purposes: ["Bill the person"], + sources: ["data-subject"], + special: null, + criminal: null, + processedFor: [], + exemptions: ["legal-obligation"], + retired: true, + }); + expect(categories.declared.map(({ name, retired }) => [name, retired])).toEqual([ + ["profile", false], + ["invoices", true], + ]); + expect(categories.ahead("invoices")).toBe(false); + }); + + it("is retired with true alone", () => { + expect(refusal({ invoices: { ...declaration, retired: false } })).toBe( + 'bounda.personal-data.ts: category "invoices" must give retired as true, or leave it out', + ); + expect(refusal({ invoices: { ...declaration, retired: "yes" } })).toBe( + 'bounda.personal-data.ts: category "invoices" must give retired as true, or leave it out', + ); + }); + + it("is decided on by no automated decision", () => { + expect( + refusal( + { invoices: { ...declaration, retired: true } }, + { + dunning: { + categories: ["default", "invoices"], + logic: "Overdue invoices are sent to collection", + significance: "A debt collection", + consequences: "A collector calls", + profiling: false, + ground: "contract", + }, + }, + ), + ).toBe( + 'bounda.personal-data.ts: automated decision "dunning" decides on "invoices", which bounda.personal-data.ts retired: no decision is made on a retired category', + ); + }); + + it("marks no field", () => { + expect(() => + checkCategory({ + categories, + category: "invoices", + at: 'Event order.OrderPaid, field "iban"', + }), + ).toThrow( + new ConfigurationError( + 'Event order.OrderPaid, field "iban" is marked personal in the category "invoices", which bounda.personal-data.ts retired: mark it in a category in use', + ), + ); + expect(() => + checkMarkedCategories({ + categories, + aggregates: { byName: {} }, + processes: { all: [] }, + readModels: { ledger: { fields: { iban: { category: "invoices" } } } }, + }), + ).toThrow( + 'Read model ledger, field "iban" is marked personal in the category "invoices", which bounda.personal-data.ts retired', + ); + }); + + it("is named by a call, which may forget, restrict or lift what was marked in it", () => { + expect(checkCategoryNames({ categories, asked: ["invoices"], operation: "forget" })).toEqual([ + "invoices", + ]); + }); +}); + +describe("checkRecordedCategories", () => { + const categories = buildPersonalCategories({ + module: { + automatedDecisions: {}, + categories: { + profile: { + basis: "consent", + retention: "30d", + purposes: ["Serve the person"], + sources: ["data-subject"], + }, + invoices: { + basis: "legal-obligation", + retention: "6y", + purposes: ["Bill the person"], + sources: ["data-subject"], + retired: true, + }, + }, + }, + retention: null, + }); + + it("accepts the default category, and those the app declares or retired", () => { + expect(() => + checkRecordedCategories({ categories, recorded: ["default", "profile", "invoices"] }), + ).not.toThrow(); + expect(() => checkRecordedCategories({ categories, recorded: [] })).not.toThrow(); + }); + + it("refuses those it neither declares nor retires, naming each, never saying the store holds keys of them", () => { + const check = () => + checkRecordedCategories({ + categories, + recorded: ["default", "legacy", "profile", "marketing"], + }); + expect(check).toThrow(ConfigurationError); + expect(check).toThrow( + 'bounda.personal-data.ts neither declares nor retires categories the store has recorded keys in: "legacy", "marketing". Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions', + ); + }); +}); + describe("formatRetention", () => { it("writes a retention in the largest unit that divides it", () => { const ms = (value: number) => formatRetention({ months: 0, ms: value }); diff --git a/packages/core/src/kernel/personal-data/categories.ts b/packages/core/src/kernel/personal-data/categories.ts index 0c8f76679..6d8f5d62a 100644 --- a/packages/core/src/kernel/personal-data/categories.ts +++ b/packages/core/src/kernel/personal-data/categories.ts @@ -57,6 +57,11 @@ export interface PersonalCategory { * for the default category and any on `consent`. */ readonly exemptions: readonly ErasureExemption[]; + /** + * Whether `bounda.personal-data.ts` retired it: no field is marked in it any more, and what was + * marked in it before stays under its retention and exemptions. + */ + readonly retired: boolean; } /** @@ -73,7 +78,7 @@ export interface DeclaredDecision extends AutomatedDecision { export interface PersonalCategories { readonly all: readonly PersonalCategory[]; /** - * The declared ones alone, whose retention a sweep of their keys applies. + * The declared ones alone, retired ones included, whose retention a sweep of their keys applies. */ readonly declared: readonly PersonalCategory[]; /** @@ -82,9 +87,9 @@ export interface PersonalCategories { readonly default: PersonalCategory; of(name: string): PersonalCategory | undefined; /** - * Whether keys of the category were given by newer code: the app does not declare it, and the - * store had recorded none of it when the app started. Forgetting them as a category the app - * stopped declaring would forget what that code keeps. + * Whether keys of the category were given by newer code: the app neither declares nor retires + * it, and the store had recorded none of it when the app started. Forgetting them as a category + * the app stopped declaring would forget what that code keeps. */ ahead(name: string): boolean; /** @@ -100,7 +105,8 @@ export interface BuildPersonalCategoriesArgs { */ readonly retention: Retention | null; /** - * The categories the store recorded when the app started; without them, none is ahead. + * The categories the store recorded when the app started, each of which the app must declare or + * retire; without them, none is ahead. */ readonly recorded?: readonly string[]; } @@ -311,6 +317,10 @@ const declaredIn = (module: PersonalDataModule | undefined): PersonalCategory[] at, }); const exemptions = exemptionsOf({ basis, special }, declared); + const { retired } = category; + if (retired !== undefined && retired !== true) { + throw new ConfigurationError(`${at} must give retired as true, or leave it out`); + } if (exemptions.length > 0 && special?.condition === "explicit-consent") { throw new ConfigurationError( `${at} is kept past a forgetting (${exemptions.join(", ")}), and cannot rest its special categories of data on explicit-consent, which a withdrawal ends`, @@ -331,6 +341,7 @@ const declaredIn = (module: PersonalDataModule | undefined): PersonalCategory[] criminal, processedFor, exemptions, + retired: retired === true, }; }); }; @@ -361,6 +372,12 @@ const decisionsIn = ( `${at} must name the categories it decides on, at least one, each declared or "default"`, ); } + const retired = [first, ...rest].find((category) => known.get(category)?.retired === true); + if (retired !== undefined) { + throw new ConfigurationError( + `${at} decides on "${retired}", which bounda.personal-data.ts retired: no decision is made on a retired category`, + ); + } for (const field of ["logic", "significance", "consequences"] as const) { if (!isText(decision[field])) { throw new ConfigurationError(`${at} must give its ${field} in words for the person`); @@ -426,6 +443,7 @@ export const buildPersonalCategories: BuildPersonalCategoriesFunction = ({ criminal: null, processedFor: [], exemptions: [], + retired: false, }; const all = [fallback, ...declared]; const byName = new Map(all.map((category) => [category.name, category])); @@ -480,10 +498,17 @@ export interface CheckCategoryFunction { } export const checkCategory: CheckCategoryFunction = ({ categories, category, at }) => { - if (categories.of(category) !== undefined) return; - throw new ConfigurationError( - `${at} is marked personal in the category "${category}", which bounda.personal-data.ts does not declare`, - ); + const declared = categories.of(category); + if (declared === undefined) { + throw new ConfigurationError( + `${at} is marked personal in the category "${category}", which bounda.personal-data.ts does not declare`, + ); + } + if (declared.retired) { + throw new ConfigurationError( + `${at} is marked personal in the category "${category}", which bounda.personal-data.ts retired: mark it in a category in use`, + ); + } }; /** @@ -589,7 +614,7 @@ export interface CheckMarkedCategoriesFunction { /** * Throws `ConfigurationError` for a field marked personal in a category the app does not declare, - * which the types refuse, for a project that skipped the type check. + * or retired, which the types refuse, for a project that skipped the type check. */ export const checkMarkedCategories: CheckMarkedCategoriesFunction = ({ categories, @@ -628,3 +653,32 @@ export const categoryNamesOf: CategoryNamesOfFunction = (registry) => [ DEFAULT_PERSONAL_CATEGORY, ...Object.keys(registry.personalData?.categories ?? {}), ]; + +export interface CheckRecordedCategoriesArgs { + readonly categories: CategoryNames; + /** + * What the store's catalogue of categories held when read. + */ + readonly recorded: readonly string[]; +} + +export interface CheckRecordedCategoriesFunction { + (args: CheckRecordedCategoriesArgs): void; +} + +/** + * Throws `ConfigurationError` naming every category the store recorded keys in that the app + * neither declares nor retires: this code cannot tell one it dropped, whose keys forgetting it at + * once would destroy past their retention and exemptions, from one newer code declares, which + * keeps them. + */ +export const checkRecordedCategories: CheckRecordedCategoriesFunction = ({ + categories, + recorded, +}) => { + const unknown = recorded.filter((name) => categories.of(name) === undefined); + if (unknown.length === 0) return; + throw new ConfigurationError( + `bounda.personal-data.ts neither declares nor retires categories the store has recorded keys in: ${unknown.map((name) => `"${name}"`).join(", ")}. Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions`, + ); +}; diff --git a/packages/core/src/kernel/personal-data/category-ahead.test.ts b/packages/core/src/kernel/personal-data/category-ahead.test.ts index 5ffacc565..d3bf347de 100644 --- a/packages/core/src/kernel/personal-data/category-ahead.test.ts +++ b/packages/core/src/kernel/personal-data/category-ahead.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { testPersonalKey } from "../../adapter/testing/fixtures.ts"; import { DEFAULT_BACKOFF_BASE_DELAY_MS } from "../../config/defaults.ts"; import type { Config } from "../../config/types.ts"; -import { CategoryAheadError } from "../../contracts/errors.ts"; +import { CategoryAheadError, ConfigurationError } from "../../contracts/errors.ts"; import type { StoredEvent } from "../../contracts/event.ts"; import { memory } from "../../memory/index.ts"; import type { PersonalDataForgottenPayload } from "../../modules/bounda-events.ts"; @@ -153,16 +153,31 @@ describe("keys of a category only newer code declares", () => { ]); }); - it("forgets at once the keys of a category the store held at the start that the app no longer declares", async () => { + it("refuses to start once the store recorded keys in a category the app neither declares nor retires, forgetting nothing", async () => { const adapter = memory(); const storage = await adapter.createStorage(); await storage.personalKeys.add("c-1", "legacy", testPersonalKey("legacy")); - const { app, run, forgotten } = await started(adapter, registry); + + await expect(started(adapter, registry)).rejects.toThrow( + new ConfigurationError( + 'bounda.personal-data.ts neither declares nor retires categories the store has recorded keys in: "legacy". Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions', + ), + ); + expect(await storage.personalKeys.get("c-1", "legacy")).toEqual(testPersonalKey("legacy")); + }); + + it("refuses to start again once newer code recorded keys in a category this code does not declare, which that code then starts on", async () => { + const adapter = memory(); + const storage = await adapter.createStorage(); + const { app, run } = await started(adapter, registry); await run("touchCustomer", "c-1"); + await storage.personalKeys.add("c-1", "profile", testPersonalKey("profile")); + await app.stop(); - await app.forget("c-1"); - expect(await storage.personalKeys.list("c-1")).toEqual([]); - expect(await forgotten()).toEqual([expect.objectContaining({ personId: "c-1", whole: true })]); + await expect(started(adapter, registry)).rejects.toThrow( + 'categories the store has recorded keys in: "profile"', + ); + await expect(started(adapter, newer)).resolves.toBeDefined(); }); it("waits, spending no attempt, with a reaction that forgets their person, and forgets once that code runs", async () => { @@ -229,12 +244,10 @@ describe("keys of a category only newer code declares", () => { ]); }); - it("keeps what a forgetting retained under such a category, while one the store held at the start goes at once", async () => { + it("keeps what a forgetting retained under such a category", async () => { const adapter = memory(); const storage = await adapter.createStorage(); const at = new Date("2026-01-01T00:00:00.000Z").toISOString(); - await storage.personalKeys.add("c-1", "legacy", testPersonalKey("legacy")); - await storage.personalKeys.retain("c-1", "f-legacy", { since: at, lastActiveAt: at }); const { app, clock, forgotten } = await started(adapter, registry); // Newer code forgets the person, keeping their key of the category it declares an exemption for. await storage.personalKeys.add("c-2", "profile", testPersonalKey("profile")); @@ -242,12 +255,11 @@ describe("keys of a category only newer code declares", () => { clock.set(new Date(clock.now().getTime() + DAY)); await app.runUntilIdle(); - expect(await storage.personalKeys.find("c-1", "f-legacy")).toBeNull(); expect(await storage.personalKeys.find("c-2", "f-profile")).toMatchObject({ category: "profile", retainedSince: at, }); - expect((await forgotten()).map(({ personId }) => personId)).toEqual(["c-1"]); + expect(await forgotten()).toEqual([]); }); it("refuses to forget the tenant, whatever its legal obligations, until that code runs", async () => { diff --git a/packages/core/src/kernel/personal-data/export-json.test.ts b/packages/core/src/kernel/personal-data/export-json.test.ts index dc3ef4025..1b3d69ee5 100644 --- a/packages/core/src/kernel/personal-data/export-json.test.ts +++ b/packages/core/src/kernel/personal-data/export-json.test.ts @@ -12,12 +12,13 @@ import { personalDataExportJson } from "./export-json.ts"; const header = (readModels: readonly string[]): PersonalDataExportPart => ({ kind: "header", header: { - version: 2, + version: 3, personId: "ana", exportedAt: "2026-01-01T00:00:00.000Z", position: 3, categories: { default: { + retired: false, basis: null, special: null, criminal: null, diff --git a/packages/core/src/kernel/personal-data/export.test.ts b/packages/core/src/kernel/personal-data/export.test.ts index 67a0654c7..9fc6df09d 100644 --- a/packages/core/src/kernel/personal-data/export.test.ts +++ b/packages/core/src/kernel/personal-data/export.test.ts @@ -147,6 +147,7 @@ const exportedCategories = { criminal: null, purposes: [], processedFor: [], + retired: false, erasureExemptions: [], sources: [], retention: "30d", @@ -160,6 +161,7 @@ const exportedCategories = { criminal: null, purposes: ["Serve the person"], processedFor: [], + retired: false, erasureExemptions: [{ exemption: "legal-obligation", article: "17(3)(b)" }], sources: ["data-subject"], retention: "60d", @@ -327,7 +329,7 @@ describe("exportPersonalData", () => { pendingEvent({ aggregateType: "customer", aggregateId: "c-1", - version: 2, + version: 3, type: "CustomerRenamed", payload: { name: "Ana" }, }), @@ -353,7 +355,7 @@ describe("exportPersonalData", () => { const exported = await exportOf("c-1"); expect(exported).toStrictEqual({ - version: 2, + version: 3, personId: "c-1", exportedAt: "2026-01-01T00:00:00.000Z", position: 7, @@ -968,6 +970,7 @@ describe("exportPersonalData", () => { criminal: null, purposes: [], processedFor: [], + retired: false, erasureExemptions: [], sources: [], retention: null, diff --git a/packages/core/src/kernel/personal-data/export.ts b/packages/core/src/kernel/personal-data/export.ts index 42db1cac7..2442e50cc 100644 --- a/packages/core/src/kernel/personal-data/export.ts +++ b/packages/core/src/kernel/personal-data/export.ts @@ -94,6 +94,11 @@ export const EXEMPTION_ARTICLES: Readonly> = { * activity, `null` when nothing forgets it for inactivity, and, for them, until when. */ export interface ExportedCategory { + /** + * Whether the app retired it: it collects nothing in it any more, and keeps what it collected + * before under its retention and exemptions. + */ + readonly retired: boolean; readonly basis: LegalBasis | null; readonly special: SpecialCategoryData | null; readonly criminal: CriminalOffenceData | null; @@ -332,7 +337,7 @@ export interface ExportedRow { /** * The version of the format a person's export is written in, as its `version` says. */ -export const PERSONAL_DATA_EXPORT_VERSION: 2 = 2; +export const PERSONAL_DATA_EXPORT_VERSION: 3 = 3; /** * What `exportPersonalData` answers: every record the runtime holds that names the person, with diff --git a/packages/core/src/kernel/personal-data/information.test.ts b/packages/core/src/kernel/personal-data/information.test.ts index 44600ea90..2e7830eb8 100644 --- a/packages/core/src/kernel/personal-data/information.test.ts +++ b/packages/core/src/kernel/personal-data/information.test.ts @@ -73,6 +73,7 @@ describe("personalDataInformation", () => { criminal: null, purposes: [], processedFor: [], + retired: false, erasureExemptions: [], sources: [], retention: "20d", @@ -86,6 +87,7 @@ describe("personalDataInformation", () => { criminal: null, ...said, processedFor: [], + retired: false, erasureExemptions: [], retention: "30d", held: true, @@ -311,10 +313,12 @@ describe("personalDataInformation", () => { const told = personalDataInformation({ categories: purposed, keys: [], person: null }); expect(told.categories.news).toMatchObject({ processedFor: ["direct-marketing"], + retired: false, erasureExemptions: [], }); expect(told.categories.study).toMatchObject({ processedFor: ["scientific-or-historical-research"], + retired: false, erasureExemptions: [{ exemption: "archiving-research-or-statistics", article: "17(3)(d)" }], }); expect(told.categories.census?.erasureExemptions).toEqual([ diff --git a/packages/core/src/kernel/personal-data/information.ts b/packages/core/src/kernel/personal-data/information.ts index 5e03fec55..3d1a964d4 100644 --- a/packages/core/src/kernel/personal-data/information.ts +++ b/packages/core/src/kernel/personal-data/information.ts @@ -92,6 +92,7 @@ export const personalDataInformation: PersonalDataInformationFunction = ({ ? own : earliest([own, whole]); exported[name] = { + retired: category.retired, basis, special, criminal, diff --git a/packages/core/src/kernel/personal-data/inventory.test.ts b/packages/core/src/kernel/personal-data/inventory.test.ts index a9675f736..c1be3b0c9 100644 --- a/packages/core/src/kernel/personal-data/inventory.test.ts +++ b/packages/core/src/kernel/personal-data/inventory.test.ts @@ -189,7 +189,7 @@ const ANSWER_HELD = [ describe("personalDataInventory", () => { it("names the version of its format first, so a reader learns it before anything else", () => { const inventory = personalDataInventory({ registry, config }); - expect(inventory.version).toBe(2); + expect(inventory.version).toBe(3); expect(Object.keys(inventory)[0]).toBe("version"); }); @@ -209,6 +209,7 @@ describe("personalDataInventory", () => { criminal: null, purposes: [], processedFor: [], + retired: false, erasureExemptions: [], sources: [], ports: [], @@ -220,6 +221,7 @@ describe("personalDataInventory", () => { basis: "consent", ...said, processedFor: ["direct-marketing"], + retired: false, erasureExemptions: [], ports: ["customer.archive", "customer.crm", "customers.lookup"], retention: "730d", @@ -230,6 +232,7 @@ describe("personalDataInventory", () => { basis: "legal-obligation", ...said, processedFor: [], + retired: false, erasureExemptions: [{ exemption: "legal-obligation", article: "17(3)(b)" }], ports: ["customer.crm"], retention: "6y", @@ -239,6 +242,42 @@ describe("personalDataInventory", () => { expect(inventory.automatedDecisions).toEqual([]); }); + it("lists a retired category with its whole declaration, saying it is retired, holding no field", () => { + const inventory = personalDataInventory({ + registry: { + ...registry, + personalData: { + ...registry.personalData, + categories: { + ...registry.personalData?.categories, + leads: { + basis: "consent", + retention: "90d", + purposes: ["Reach people who asked to be called"], + sources: [{ kind: "third-party", name: "A broker" }], + retired: true, + }, + }, + }, + } as Registry, + config, + }); + expect(inventory.categories.at(-1)).toEqual({ + name: "leads", + basis: "consent", + special: null, + criminal: null, + purposes: ["Reach people who asked to be called"], + processedFor: [], + retired: true, + erasureExemptions: [], + sources: [{ kind: "third-party", name: "A broker" }], + ports: [], + retention: "90d", + fields: 0, + }); + }); + it("lists the decisions the app makes about a person by automated means alone", () => { const scoring = { categories: ["contact"], diff --git a/packages/core/src/kernel/personal-data/inventory.ts b/packages/core/src/kernel/personal-data/inventory.ts index 032dd4b70..231da81ca 100644 --- a/packages/core/src/kernel/personal-data/inventory.ts +++ b/packages/core/src/kernel/personal-data/inventory.ts @@ -127,6 +127,11 @@ export interface InventoryTransfer { export interface InventoryCategory { readonly name: string; + /** + * Whether `bounda.personal-data.ts` retired it: no field is marked in it any more, and what was + * marked in it before is kept under its retention and exemptions. + */ + readonly retired: boolean; /** * `null` for the default category, which declares none. */ @@ -293,7 +298,7 @@ export interface InventoryFinding { /** * The version of the format a `PersonalDataInventory` is written in, as its `version` says. */ -export const PERSONAL_DATA_INVENTORY_VERSION: 2 = 2; +export const PERSONAL_DATA_INVENTORY_VERSION: 3 = 3; /** * The record of processing activities of article 30 of the GDPR, as far as the app's code and @@ -827,6 +832,7 @@ export const personalDataInventory: PersonalDataInventoryFunction = ({ registry, version: PERSONAL_DATA_INVENTORY_VERSION, categories: categories.all.map((category) => ({ name: category.name, + retired: category.retired, basis: category.basis, special: category.special, criminal: category.criminal, diff --git a/packages/core/src/kernel/personal-data/ledger-prune-app.test.ts b/packages/core/src/kernel/personal-data/ledger-prune-app.test.ts index ae42528c6..ebd59354c 100644 --- a/packages/core/src/kernel/personal-data/ledger-prune-app.test.ts +++ b/packages/core/src/kernel/personal-data/ledger-prune-app.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it } from "vitest"; import type { Adapter } from "../../adapter/adapter.ts"; import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; import type { ForgetLedger, ForgetLedgerEntry } from "../../adapter/storage/forget-ledger.ts"; +import { testPersonalKey } from "../../adapter/testing/fixtures.ts"; import type { Config, ProjectConfig } from "../../config/types.ts"; import { createFixedClock } from "../../contracts/clock.ts"; import type { DurationInput } from "../../contracts/duration.ts"; @@ -772,6 +773,82 @@ describe("pruning, with the app's registry, the intentions only the app decides" }); }); +describe("pruning, and listing what is stranded, by the categories the database recorded", () => { + const registered = async () => { + const storage = memory(); + const ledgerAdapter = memory(); + const config = configOf(storage, ledgerAdapter, "30d"); + const app = await start(config); + await register(app, "ana"); + await app.stop(); + const ledger = await ledgerAdapter.createForgetLedger({ tenant: DEFAULT_TENANT }); + return { storage, ledgerAdapter, config, ledger }; + }; + + it("keeps an intention that names a category only newer code declares, which only that code tells applied", async () => { + const { config, ledger } = await registered(); + await ledger.append([intention("ana", "profile-ana", START, { categories: ["profile"] })]); + expect( + await pruneTenantForgetLedger({ logger: silentLogger, registry, config, now: LATER }), + ).toMatchObject({ before: START.toISOString(), unapplied: true }); + expect(await entriesOf(ledger)).toEqual(["ana"]); + }); + + it("lists as stranded an entry that names a category only newer code declares, before where the reconciliation reads", async () => { + const { storage, config, ledger } = await registered(); + const lost = { ...entry("ana", "lost-ana", START), categories: ["profile"] }; + await ledger.append([lost]); + const landed = (await ledger.readLanded?.({ limit: 10 }))?.at(-1)?.landed ?? 0; + await (await storage.createStorage()).checkpointStore.set( + await landedRowFor(ledger), + landed + 1, + ); + expect(await listStrandedForgetLedgerEntries({ config, registry, now: LATER })).toEqual({ + tenant: DEFAULT_TENANT, + entries: [lost], + unreached: [], + }); + }); + + it("refuses a database that recorded keys in a category the registry neither declares nor retires, as the start does, pruning and listing nothing", async () => { + const { storage, config, ledger } = await registered(); + await ledger.append([intention("ana", "e-ana", START)]); + await (await storage.createStorage()).personalKeys.add( + "ana", + "legacy", + testPersonalKey("legacy"), + ); + const refusal = + 'bounda.personal-data.ts neither declares nor retires categories the store has recorded keys in: "legacy"'; + await expect( + pruneTenantForgetLedger({ logger: silentLogger, registry, config, now: LATER }), + ).rejects.toThrow(refusal); + await expect(listStrandedForgetLedgerEntries({ config, registry, now: LATER })).rejects.toThrow( + refusal, + ); + expect(await entriesOf(ledger)).toEqual(["ana"]); + // Retired, its whole declaration kept, it is pruned as the app reconciles it. + const retiring = { + ...registry, + personalData: { + automatedDecisions: {}, + categories: { + legacy: { + basis: "consent", + retention: "1y", + purposes: ["Serve the person"], + sources: ["data-subject"], + retired: true, + }, + }, + }, + } as unknown as Registry; + await expect( + pruneTenantForgetLedger({ logger: silentLogger, registry: retiring, config, now: LATER }), + ).resolves.toMatchObject({ tenant: DEFAULT_TENANT }); + }); +}); + describe("pruning a tenant's entries in a store its configuration no longer names", () => { // An app that wrote to `before`, whose configuration now names `now`. const moved = async () => { diff --git a/packages/core/src/kernel/personal-data/ledger-prune.test.ts b/packages/core/src/kernel/personal-data/ledger-prune.test.ts index b75ada450..7d42132c9 100644 --- a/packages/core/src/kernel/personal-data/ledger-prune.test.ts +++ b/packages/core/src/kernel/personal-data/ledger-prune.test.ts @@ -96,6 +96,7 @@ const RULES: ReconciliationRules = { }, commandsByType: {}, storedMarks: NO_STORED_MARKS, + categories: new Set(["default"]), } as unknown as AggregatesRuntime, processes: { byName: {} }, batchSize: 100, diff --git a/packages/core/src/kernel/personal-data/ledger-prune.ts b/packages/core/src/kernel/personal-data/ledger-prune.ts index d2f7d8b14..96dfc6410 100644 --- a/packages/core/src/kernel/personal-data/ledger-prune.ts +++ b/packages/core/src/kernel/personal-data/ledger-prune.ts @@ -28,7 +28,11 @@ import { runtimeText } from "../shared/runtime-text.ts"; import { tenantIdOf } from "../tenant.ts"; import { accessLogOf, ledgerPruneRecorder, recordedChange } from "./access.ts"; import { appliedEntryOf } from "./applied-record.ts"; -import { buildPersonalCategories, type PersonalCategories } from "./categories.ts"; +import { + buildPersonalCategories, + checkRecordedCategories, + type PersonalCategories, +} from "./categories.ts"; import { withEncryptedFiles } from "./encrypted-files.ts"; import { type ForgetLedgerSource, @@ -78,6 +82,10 @@ export interface ReconciliationRules { export interface ReconciliationRulesOfArgs { readonly registry: Registry; readonly config: ResolvedConfig; + /** + * The categories the database recorded, as `buildPersonalCategories` takes them. + */ + readonly recorded: readonly string[]; } export interface ReconciliationRulesOfFunction { @@ -87,13 +95,18 @@ export interface ReconciliationRulesOfFunction { // Built from the registry and the configuration as an app builds them at its start, refused as it // refuses them; no port is needed, since what an event marks is all a redaction reads of its // aggregate. -export const reconciliationRulesOf: ReconciliationRulesOfFunction = ({ registry, config }) => { +export const reconciliationRulesOf: ReconciliationRulesOfFunction = ({ + registry, + config, + recorded, +}) => { validateRegistry(registry); const aggregates = buildAggregates({ registry, ports: {} }); return { categories: buildPersonalCategories({ module: registry.personalData, retention: config.runtime.personalData.retention, + recorded, }), aggregates, processes: buildProcesses({ registry, aggregates, config }), @@ -105,6 +118,23 @@ export interface WithRecordedMarksFunction { (rules: ReconciliationRules, marks: readonly StoredEventTypeMarks[]): ReconciliationRules; } +export interface DatabaseRulesOfArgs extends Omit { + readonly recorded: RecordedByDatabase; +} + +export interface DatabaseRulesOfFunction { + (args: DatabaseRulesOfArgs): ReconciliationRules; +} + +// The rules of one database, built from what it recorded: the categories it holds keys in, of which +// a category recorded since is one only newer code declares, and the marks a redaction of a +// retired type reads. +export const databaseRulesOf: DatabaseRulesOfFunction = ({ registry, config, recorded }) => + withRecordedMarks( + reconciliationRulesOf({ registry, config, recorded: recorded.categories }), + recorded.marks, + ); + // The rules with the marks the database recorded, which a redaction of a retired type reads. export const withRecordedMarks: WithRecordedMarksFunction = (rules, marks) => ({ ...rules, @@ -805,8 +835,10 @@ const pruneOpened = async ({ followed, named: async (work) => work(await namedLedger()), former: namedFormer, + // Built once the database is open, as `withStorage` builds them; one without Bounda's + // tables, which has recorded nothing, asks for none. rules: () => { - rules ??= reconciliationRulesOf({ registry, config: resolved }); + rules ??= reconciliationRulesOf({ registry, config: resolved, recorded: [] }); return rules; }, forgotten: async () => { @@ -827,12 +859,9 @@ const pruneOpened = async ({ config, env, tenant, - aggregates: (marks) => { - rules = withRecordedMarks( - rules ?? reconciliationRulesOf({ registry, config: resolved }), - marks, - ); - return rules.aggregates; + rules: (recorded) => { + rules = databaseRulesOf({ registry, config: resolved, recorded }); + return rules; }, work, }), @@ -854,13 +883,18 @@ const pruneOpened = async ({ } }; +export interface RecordedByDatabase { + readonly marks: readonly StoredEventTypeMarks[]; + readonly categories: readonly string[]; +} + export interface WithTenantStorageArgs { readonly config: Config; readonly env: AppEnv; readonly tenant: string; - // Asked once the database is open, with the marks it recorded, to check what its catalogue holds - // as an app's start does. - readonly aggregates: (marks: readonly StoredEventTypeMarks[]) => AggregatesRuntime; + // Asked once the database is open, with what it recorded, to check what it holds as an app's + // start does. + readonly rules: (recorded: RecordedByDatabase) => ReconciliationRules; // `null` for a database that holds no table yet. readonly work: (storage: AppliedStorage | null) => Promise; } @@ -875,7 +909,7 @@ export const withTenantStorage: WithTenantStorageFunction = ({ config, env, tenant, - aggregates, + rules, work, }) => withEncryptedFiles({ @@ -890,13 +924,18 @@ export const withTenantStorage: WithTenantStorageFunction = ({ } const created = await adapter.createStorage(); try { - const built = aggregates(await created.eventStore.marksOf()); + const recorded = await created.personalKeys.recordedCategories(); + const { aggregates: built, categories } = rules({ + marks: await created.eventStore.marksOf(), + categories: recorded, + }); const types = await created.eventStore.types(); const stored = checkStoredTypes({ types, aggregates: built }); // A forgotten tenant's start records no marks: nothing of it is sealed again. if ((await created.fence.read()).state !== "forgotten") { checkRetiredMarks({ types, aggregates: built }); } + checkRecordedCategories({ categories, recorded }); return await work(withEventGuard({ storage: created, aggregates: built, stored })); } finally { await created.close(); diff --git a/packages/core/src/kernel/personal-data/marks.test.ts b/packages/core/src/kernel/personal-data/marks.test.ts index 89c5abc7e..00936677c 100644 --- a/packages/core/src/kernel/personal-data/marks.test.ts +++ b/packages/core/src/kernel/personal-data/marks.test.ts @@ -120,6 +120,7 @@ describe("marksPersonalFields", () => { }, commandsByType: {}, storedMarks: NO_STORED_MARKS, + categories: new Set(["default"]), }) as unknown as AggregatesRuntime; const processes = (states: readonly (PersonalMarks | null)[]): ProcessesRuntime => ({ all: states.map((personal) => ({ personal })) }) as unknown as ProcessesRuntime; diff --git a/packages/core/src/kernel/personal-data/reseal-batches.test.ts b/packages/core/src/kernel/personal-data/reseal-batches.test.ts index 66762ee65..af5cbafc5 100644 --- a/packages/core/src/kernel/personal-data/reseal-batches.test.ts +++ b/packages/core/src/kernel/personal-data/reseal-batches.test.ts @@ -67,6 +67,7 @@ const aggregates = { }, }, storedMarks: NO_STORED_MARKS, + categories: new Set(["default"]), } as unknown as AggregatesRuntime; const processes = { diff --git a/packages/core/src/kernel/personal-data/resealing.test.ts b/packages/core/src/kernel/personal-data/resealing.test.ts index 774fccd12..4a1d0d5a8 100644 --- a/packages/core/src/kernel/personal-data/resealing.test.ts +++ b/packages/core/src/kernel/personal-data/resealing.test.ts @@ -39,6 +39,7 @@ const runtimes = ({ events = {}, commands = {}, process = null }: Marked) => { }, commandsByType: {}, storedMarks: NO_STORED_MARKS, + categories: new Set(["default"]), } as unknown as AggregatesRuntime; const onboarding = { name: "signup.onboarding", personal: process }; const processes = { @@ -849,6 +850,7 @@ describe("planUpcastReseal", () => { }, commandsByType: {}, storedMarks: NO_STORED_MARKS, + categories: new Set(["default"]), }) as unknown as AggregatesRuntime; const marked: PersonalMarks = { person: "customerId", fields: ["email"], categories: {} }; const older = (overrides: Partial) => @@ -950,6 +952,7 @@ describe("planUpcastReseal", () => { }, commandsByType: {}, storedMarks: NO_STORED_MARKS, + categories: new Set(["default"]), }) as unknown as AggregatesRuntime; const rewrittenBy = async ( diff --git a/packages/core/src/kernel/personal-data/retired-categories-app.test.ts b/packages/core/src/kernel/personal-data/retired-categories-app.test.ts new file mode 100644 index 000000000..dcbbc2d5d --- /dev/null +++ b/packages/core/src/kernel/personal-data/retired-categories-app.test.ts @@ -0,0 +1,202 @@ +import { afterEach, describe, expect, it } from "vitest"; +import type { Adapter } from "../../adapter/adapter.ts"; +import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; +import { createFixedClock } from "../../contracts/clock.ts"; +import { ConfigurationError } from "../../contracts/errors.ts"; +import { createSequentialIdGenerator } from "../../contracts/ids.ts"; +import { memory } from "../../memory/index.ts"; +import type { PersonalDataForgottenPayload } from "../../modules/bounda-events.ts"; +import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; +import type { Registry } from "../../modules/registry.ts"; +import { createApp } from "../app.ts"; +import { ledgerFor } from "../test-support.ts"; + +const DAY = 86_400_000; +const START = new Date("2026-03-01T00:00:00.000Z"); + +// Whether a deploy sends invoices, or retired their event type with their category; one that still +// marks the amount in the retired category is refused. +type Deploy = "invoices" | "retired" | "marked"; + +const said = { purposes: ["Serve the person"], sources: ["data-subject"] }; + +type Handler = (args: { + readonly command: { readonly payload: Record }; + readonly events: Record unknown>; +}) => unknown[]; + +const command = (field: string, handler: Handler) => ({ + module: { + payload: ({ z, notPersonal }: CommandPayloadArgs) => + z.object({ customerId: notPersonal(z.string()), [field]: notPersonal(z.string()) }), + handler, + }, +}); + +const registryOf = (deploy: Deploy): Registry => + ({ + personalData: { + automatedDecisions: {}, + categories: { + contact: { basis: "consent", retention: "30d", ...said }, + invoices: { + basis: "legal-obligation", + retention: "60d", + ...said, + ...(deploy === "invoices" ? {} : { retired: true }), + }, + }, + }, + aggregates: { + customer: { + state: { initialState: {} }, + events: { + noteTaken: { + payload: ({ z, personal }: EventPayloadArgs) => + z.object({ note: personal(z.string(), { category: "contact" as never }) }), + evolve: () => ({}), + }, + ...(deploy === "retired" + ? {} + : { + invoiceSent: { + payload: ({ z, personal }: EventPayloadArgs) => + z.object({ amount: personal(z.string(), { category: "invoices" as never }) }), + evolve: () => ({}), + }, + }), + }, + retired: deploy === "retired" ? { invoiceSent: { retired: true } } : {}, + commands: { + takeNote: command("note", ({ command: { payload }, events }) => [ + events.noteTaken?.({ note: payload.note }), + ]), + ...(deploy === "retired" + ? {} + : { + sendInvoice: command("amount", ({ command: { payload }, events }) => [ + events.invoiceSent?.({ amount: payload.amount }), + ]), + }), + }, + policies: {}, + processes: {}, + }, + }, + readModels: {}, + }) as unknown as Registry; + +const stops: (() => Promise)[] = []; + +afterEach(async () => { + for (const stop of stops.splice(0).reverse()) await stop(); +}); + +let starts = 0; + +const started = async (adapter: Adapter, deploy: Deploy, clock = createFixedClock(START)) => { + starts += 1; + const app = await createApp({ + registry: registryOf(deploy), + config: { + storage: adapter, + runtime: { personalData: { retention: "1y", forgetLedger: { store: ledgerFor(adapter) } } }, + }, + ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), + clock, + }); + stops.push(() => app.stop()); + const send = async (type: string, payload: object): Promise => { + await (app.commands as unknown as Record Promise>)[ + type + ]?.(payload); + await app.runUntilIdle(); + }; + const forgotten = async (): Promise => + (await app.events.read({ limit: 1000 })) + .filter((event) => event.type === "PersonalDataForgotten") + .map((event) => event.payload as PersonalDataForgottenPayload); + return { app, clock, send, forgotten }; +}; + +// An invoice sent while the category was in use. +const invoiced = async (adapter: Adapter) => { + const older = await started(adapter, "invoices"); + await older.send("sendInvoice", { customerId: "c-1", amount: "120 EUR" }); + await older.app.stop(); +}; + +const adapters: readonly [string, () => Adapter][] = [ + ["memory", () => memory()], + ["SQLite (node:sqlite)", () => createNodeSqliteAdapter().adapter], +]; + +describe.each(adapters)("a retired category, on %s", (_name, adapterOf) => { + it("keeps what was marked in it under its retention and exemptions, never forgotten at once, and tells the person it is retired", async () => { + const adapter = adapterOf(); + const storage = await adapter.createStorage(); + await invoiced(adapter); + + const { app, clock, send, forgotten } = await started(adapter, "retired"); + await app.runUntilIdle(); + expect(await storage.personalKeys.get("c-1", "invoices")).not.toBeNull(); + const told = await app.exportPersonalData("c-1"); + expect(told.categories.invoices).toMatchObject({ retired: true, held: true }); + expect(told.categories.contact).toMatchObject({ retired: false, held: false }); + + await send("takeNote", { customerId: "c-1", note: "call after five" }); + await app.forget("c-1"); + expect(await forgotten()).toEqual([ + expect.objectContaining({ + whole: true, + categories: ["default", "contact"], + retained: ["invoices"], + }), + ]); + expect((await storage.personalKeys.list("c-1")).map(({ category }) => category)).toEqual([ + "invoices", + ]); + + // Its retention ends what the legal obligation kept, as it ends that of a category in use. + clock.set(new Date(clock.now().getTime() + 61 * DAY)); + await app.runUntilIdle(); + expect(await storage.personalKeys.list("c-1")).toEqual([]); + expect((await forgotten()).at(-1)).toMatchObject({ + reason: "retention", + expired: ["invoices"], + }); + }); + + it("forgets, restricts and lifts what was marked in it by its name", async () => { + const adapter = adapterOf(); + const storage = await adapter.createStorage(); + await invoiced(adapter); + + const { app, forgotten } = await started(adapter, "retired"); + await app.restrict("c-1", { ground: "accuracy-contested", categories: ["invoices"] as never }); + expect((await app.exportPersonalData("c-1")).restrictions).toEqual([ + expect.objectContaining({ ground: "accuracy-contested", categories: ["invoices"] }), + ]); + await app.unrestrict("c-1", { notice: "given", categories: ["invoices"] as never }); + expect((await app.exportPersonalData("c-1")).restrictions).toEqual([]); + + // Kept, restricted, under the legal obligation its declaration still names. + await app.forget("c-1", { categories: ["invoices"] as never }); + expect(await forgotten()).toEqual([ + expect.objectContaining({ whole: false, categories: [], retained: ["invoices"] }), + ]); + expect(await storage.personalKeys.list("c-1")).toEqual([ + expect.objectContaining({ category: "invoices", retainedSince: START.toISOString() }), + ]); + }); + + it("refuses to start while a field is still marked in it, recording no marks", async () => { + const adapter = adapterOf(); + await expect(started(adapter, "marked")).rejects.toThrow( + new ConfigurationError( + 'Event customer.InvoiceSent, field "amount" is marked personal in the category "invoices", which bounda.personal-data.ts retired: mark it in a category in use', + ), + ); + expect(await (await adapter.createStorage()).eventStore.marksOf()).toEqual([]); + }); +}); diff --git a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts index 151accc03..f51eeca17 100644 --- a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts +++ b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts @@ -106,11 +106,29 @@ const noteTaken = (deploy: Deploy) => ({ evolve: same, }); +// Whether `invoices` is declared, retired with its whole declaration, or dropped. +type Invoices = "declared" | "retired" | "dropped"; + +const personalDataOf = (invoices: Invoices) => + invoices === "dropped" + ? {} + : { + personalData: { + ...personalData, + categories: { + invoices: { + ...personalData.categories.invoices, + ...(invoices === "retired" ? { retired: true } : {}), + }, + }, + }, + }; + // `ReminderSent` never had a module, and is retired in every deploy: only a store written past the // runtime holds one. -const registryOf = (deploy: Deploy, declared = true): Registry => +const registryOf = (deploy: Deploy, invoices: Invoices = "declared"): Registry => ({ - ...(declared ? { personalData } : {}), + ...personalDataOf(invoices), aggregates: { customer: { state: { initialState: {} }, @@ -149,6 +167,7 @@ let starts = 0; interface StartOptions { readonly logger?: Logger; + readonly invoices?: Invoices; // What the app's storage comes from in place of `adapter`, whose forget ledger it keeps. readonly storage?: Adapter; } @@ -157,11 +176,11 @@ const start = async ( adapter: Adapter, deploy: Deploy, clock = createFixedClock(START), - { logger = silentLogger, storage = adapter }: StartOptions = {}, + { logger = silentLogger, storage = adapter, invoices }: StartOptions = {}, ) => { starts += 1; const app = await createApp({ - registry: registryOf(deploy), + registry: registryOf(deploy, invoices), config: { storage, runtime: { personalData: { forgetLedger: { store: ledgerFor(adapter) } } }, @@ -488,6 +507,75 @@ describe.each(adapters)("the marks a start records, on %s", (_name, adapterOf) = await expect(prune()).resolves.toBeDefined(); }); + it("refuses to retire a type and drop the category its recorded marks seal in, in one deploy, naming both, and starts once the category is retired", async () => { + const adapter = adapterOf(); + const first = await start(adapter, "invoices"); + await send(first.app, "registerCustomer", { customerId: "c-1", name: "Ana" }); + await note(first.app, "c-1", "paid in full"); + await first.app.runUntilIdle(); + await first.stop(); + const refusal = + 'The store holds events of retired types this code cannot seal:\n- customer.NoteTaken is retired, and its recorded marks seal values in the category "invoices", which bounda.personal-data.ts neither declares nor retires: declare it again, its whole declaration with retired: true'; + // An intention left in the ledger, which only the database tells whether it was applied. + await (await ledgerFor(adapter).createForgetLedger({ tenant: DEFAULT_TENANT })).append([ + { + personId: "c-1", + categories: null, + eventId: "e-c-1", + forgottenAt: START.toISOString(), + reason: "requested", + committed: false, + }, + ]); + + await expect(start(adapter, "retired", undefined, { invoices: "dropped" })).rejects.toThrow( + refusal, + ); + await expect( + pruneTenantForgetLedger({ + logger: silentLogger, + registry: registryOf("retired", "dropped"), + config: { + storage: adapter, + runtime: { + personalData: { forgetLedger: { store: ledgerFor(adapter), keepFor: "30d" } }, + }, + } as Config, + now: new Date(START.getTime() + 32 * 86_400_000), + }), + ).rejects.toThrow(refusal); + + const { app } = await start(adapter, "retired", undefined, { invoices: "retired" }); + await app.runUntilIdle(); + expect(categoryOf(noteOf((await notes(adapter))[0]) as never)).toBe("invoices"); + const told = await app.exportPersonalData("c-1"); + expect(told.categories.invoices).toMatchObject({ retired: true, held: true }); + expect(await exported(app, "c-1")).toEqual([ + expect.objectContaining({ data: expect.objectContaining({ note: "paid in full" }) }), + ]); + }); + + it("refuses to retire a type whose recorded marks would seal what it left in the clear in a category dropped in the same deploy, sealing nothing", async () => { + const adapter = adapterOf(); + const older = await start(adapter, "clear"); + await send(older.app, "registerCustomer", { customerId: "c-1", name: "Ana" }); + await note(older.app, "c-1", "call after five"); + await older.app.runUntilIdle(); + await older.stop(); + // A deploy that marks the note an invoice records its marks, and stops before its walk. + await (await start(adapter, "invoices")).stop(); + expect(await setsOf(adapter)).toEqual([emailOnly, asInvoice]); + expect(noteOf((await notes(adapter))[0])).toBe("call after five"); + + await expect(start(adapter, "retired", undefined, { invoices: "dropped" })).rejects.toThrow( + 'customer.NoteTaken is retired, and its recorded marks seal values in the category "invoices", which bounda.personal-data.ts neither declares nor retires', + ); + expect(noteOf((await notes(adapter))[0])).toBe("call after five"); + expect(await (await storageOf(adapter)).personalKeys.recordedCategories()).not.toContain( + "invoices", + ); + }); + it("leaves a frozen tenant's store unwritten at start, recording the marks once it thaws", async () => { const adapter = adapterOf(); const first = await start(adapter, "clear"); @@ -918,7 +1006,7 @@ describe("an app whose only personal data is of a retired type", () => { }; try { const app = await createApp({ - registry: registryOf(deploy, deploy !== "retired"), + registry: registryOf(deploy, deploy === "retired" ? "dropped" : "declared"), config: { storage: sqlite.adapter, runtime: { diff --git a/packages/core/src/kernel/personal-data/stranded.ts b/packages/core/src/kernel/personal-data/stranded.ts index bb6196b65..e3bde2ddf 100644 --- a/packages/core/src/kernel/personal-data/stranded.ts +++ b/packages/core/src/kernel/personal-data/stranded.ts @@ -13,11 +13,11 @@ import { openForgetLedgerThrough, } from "./forget-ledger.ts"; import { + databaseRulesOf, type ReconciliationRules, reconciliationRulesOf, refused, strandedEntries, - withRecordedMarks, withTenantStorage, } from "./ledger-prune.ts"; import { eitherReads, type ReconciledReads, reconciledReadsOf } from "./reconciled-reads.ts"; @@ -149,12 +149,9 @@ export const listStrandedForgetLedgerEntries: ListStrandedForgetLedgerEntriesFun config: tenantConfig, env, tenant, - aggregates: (marks) => { - rules = withRecordedMarks( - rules ?? reconciliationRulesOf({ registry, config: resolved }), - marks, - ); - return rules.aggregates; + rules: (recorded) => { + rules = databaseRulesOf({ registry, config: resolved, recorded }); + return rules; }, work: async (database) => { const reads = @@ -167,8 +164,9 @@ export const listStrandedForgetLedgerEntries: ListStrandedForgetLedgerEntriesFun const listed = (ledger: ForgetLedger, read: ReconciledReads = reads) => strandedEntries({ storage: database, + // Built once the database is open; one without Bounda's tables asks for none. rules: () => { - rules ??= reconciliationRulesOf({ registry, config: resolved }); + rules ??= reconciliationRulesOf({ registry, config: resolved, recorded: [] }); return rules; }, now, diff --git a/packages/core/src/kernel/personal-data/tenant-export-json.test.ts b/packages/core/src/kernel/personal-data/tenant-export-json.test.ts index 0cbdaf606..8c3ceee53 100644 --- a/packages/core/src/kernel/personal-data/tenant-export-json.test.ts +++ b/packages/core/src/kernel/personal-data/tenant-export-json.test.ts @@ -298,40 +298,47 @@ describe("readTenantExport", () => { // One written before a freeze cut it, which its header does not say. const earlier = { kind: "header", header: { ...header.header, version: 1 } }; await expect(read(bytes(linesOf(earlier, end())))).rejects.toThrow( - "The tenant export is in format bounda.tenant-export version 1, not bounda.tenant-export version 9", + "The tenant export is in format bounda.tenant-export version 1, not bounda.tenant-export version 10", ); // One whose transfers do not name the legal regime they go to. const unnamed = { kind: "header", header: { ...header.header, version: 3 } }; await expect(read(bytes(linesOf(unnamed, end())))).rejects.toThrow( - "The tenant export is in format bounda.tenant-export version 3, not bounda.tenant-export version 9", + "The tenant export is in format bounda.tenant-export version 3, not bounda.tenant-export version 10", ); // One that does not count the recipients of persons forgotten before it. const uncounted = { kind: "header", header: { ...header.header, version: 4 } }; await expect(read(bytes(linesOf(uncounted, end())))).rejects.toThrow( - "The tenant export is in format bounda.tenant-export version 4, not bounda.tenant-export version 9", + "The tenant export is in format bounda.tenant-export version 4, not bounda.tenant-export version 10", ); // One whose transfers do not name the partial adequacy decision they rest on. const unscoped = { kind: "header", header: { ...header.header, version: 5 } }; await expect(read(bytes(linesOf(unscoped, end())))).rejects.toThrow( - "The tenant export is in format bounda.tenant-export version 5, not bounda.tenant-export version 9", + "The tenant export is in format bounda.tenant-export version 5, not bounda.tenant-export version 10", ); // One whose forget ledger's disclosures do not name the transfer they rested on. const untransferred = { kind: "header", header: { ...header.header, version: 6 } }; await expect(read(bytes(linesOf(untransferred, end())))).rejects.toThrow( - "The tenant export is in format bounda.tenant-export version 6, not bounda.tenant-export version 9", + "The tenant export is in format bounda.tenant-export version 6, not bounda.tenant-export version 10", ); // One whose recipients name the transfer derived when it was written, not the one recorded. const derived = { kind: "header", header: { ...header.header, version: 7 } }; await expect(read(bytes(linesOf(derived, end())))).rejects.toThrow( - "The tenant export is in format bounda.tenant-export version 7, not bounda.tenant-export version 9", + "The tenant export is in format bounda.tenant-export version 7, not bounda.tenant-export version 10", ); // One whose forget ledger's entries do not name what an application by hand applied. const unapplied = { kind: "header", header: { ...header.header, version: 8 } }; await expect(read(bytes(linesOf(unapplied, end())))).rejects.toThrow( - "The tenant export is in format bounda.tenant-export version 8, not bounda.tenant-export version 9", + "The tenant export is in format bounda.tenant-export version 8, not bounda.tenant-export version 10", + ); + // One whose categories do not say which the app retired. + const unretired = { kind: "header", header: { ...header.header, version: 9 } }; + await expect(read(bytes(linesOf(unretired, end())))).rejects.toThrow( + "The tenant export is in format bounda.tenant-export version 9, not bounda.tenant-export version 10", ); const foreign = { kind: "header", header: { ...header.header, format: "other" } }; - await expect(read(bytes(linesOf(foreign, end())))).rejects.toThrow("in format other version 9"); + await expect(read(bytes(linesOf(foreign, end())))).rejects.toThrow( + "in format other version 10", + ); }); it("hands each part out as it reads it, before it knows the rest", async () => { diff --git a/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts b/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts index 82eb4a23d..c4d450d9a 100644 --- a/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts +++ b/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts @@ -330,7 +330,7 @@ describe("streamTenantExport", () => { kind: "header", header: { format: "bounda.tenant-export", - version: 9, + version: 10, tenant: "acme", exportId: "x-1", exportedAt: "2026-01-01T00:00:00.000Z", @@ -344,6 +344,7 @@ describe("streamTenantExport", () => { criminal: null, purposes: [], processedFor: [], + retired: false, erasureExemptions: [], sources: [], retention: "30d", @@ -355,6 +356,7 @@ describe("streamTenantExport", () => { criminal: null, purposes: ["Serve the person"], processedFor: [], + retired: false, erasureExemptions: [{ exemption: "legal-obligation", article: "17(3)(b)" }], sources: ["data-subject"], retention: "60d", @@ -1359,7 +1361,7 @@ describe("recordedTenantExport", () => { ): StreamedTenantExport => ({ header: { format: "bounda.tenant-export", - version: 9, + version: 10, tenant: "acme", exportId: "x-1", exportedAt: "2026-01-01T00:00:00.000Z", diff --git a/packages/core/src/kernel/personal-data/tenant-export.ts b/packages/core/src/kernel/personal-data/tenant-export.ts index 7d22db1e5..6b2c2269b 100644 --- a/packages/core/src/kernel/personal-data/tenant-export.ts +++ b/packages/core/src/kernel/personal-data/tenant-export.ts @@ -30,7 +30,7 @@ export const TENANT_EXPORT_FORMAT: "bounda.tenant-export" = "bounda.tenant-expor * The version of the format a tenant export is written in. A version that changes what a part * holds, or adds a kind of part, is a new one. */ -export const TENANT_EXPORT_VERSION: 9 = 9; +export const TENANT_EXPORT_VERSION: 10 = 10; /** * A category of the app as `bounda.personal-data.ts` declares it, as `ExportedCategory` tells a diff --git a/packages/core/src/kernel/ports/returns.test.ts b/packages/core/src/kernel/ports/returns.test.ts index 4d7653208..62cdae58d 100644 --- a/packages/core/src/kernel/ports/returns.test.ts +++ b/packages/core/src/kernel/ports/returns.test.ts @@ -13,6 +13,13 @@ const categories = buildPersonalCategories({ purposes: ["Reach the customer"], sources: ["data-subject"], }, + leads: { + basis: "consent", + retention: "30d", + purposes: ["Reach the customer"], + sources: [{ kind: "third-party", name: "A broker" }], + retired: true, + }, }, automatedDecisions: {}, } as never, @@ -110,6 +117,10 @@ describe("buildPortReturns", () => { { persons, categories: [1] }, `${prefix}: categories names 1, which the app does not have`, ); + refused( + { persons, categories: ["leads"] }, + `${prefix}: categories names "leads", which bounda.personal-data.ts retired: no call returns data of a retired category`, + ); refused( { persons, categories: ["contact", "contact"] }, `${prefix}: categories names a category twice`, diff --git a/packages/core/src/kernel/ports/returns.ts b/packages/core/src/kernel/ports/returns.ts index 573791924..e173520e9 100644 --- a/packages/core/src/kernel/ports/returns.ts +++ b/packages/core/src/kernel/ports/returns.ts @@ -66,9 +66,15 @@ const checkedCall = ( fail("categories must list the categories of the personal data returned"); } for (const category of named as readonly unknown[]) { - if (categories.of(category as string) === undefined) { + const declared = categories.of(category as string); + if (declared === undefined) { fail(`categories names ${JSON.stringify(category)}, which the app does not have`); } + if (declared?.retired === true) { + fail( + `categories names ${JSON.stringify(category)}, which bounda.personal-data.ts retired: no call returns data of a retired category`, + ); + } } if (new Set(named as readonly string[]).size !== (named as readonly string[]).length) { fail("categories names a category twice"); diff --git a/packages/core/src/kernel/recipients/build.test.ts b/packages/core/src/kernel/recipients/build.test.ts index cdf103b69..fd10422b7 100644 --- a/packages/core/src/kernel/recipients/build.test.ts +++ b/packages/core/src/kernel/recipients/build.test.ts @@ -21,6 +21,13 @@ const categories = buildPersonalCategories({ purposes: ["Serve the person"], sources: ["data-subject"], }, + newsletter: { + basis: "consent", + retention: "1y", + purposes: ["Tell the person what is new"], + sources: ["data-subject"], + retired: true, + }, }, }, retention: null, @@ -144,6 +151,12 @@ describe("buildRecipients", () => { { mailer: { ...handlers, recipient: { ...MAILCHIMP, categories: [7] } } }, "Port customer.mailer: recipient.categories names 7, which the app does not have", ); + refused( + { + mailer: { ...handlers, recipient: { ...MAILCHIMP, categories: ["contact", "newsletter"] } }, + }, + 'Port customer.mailer: recipient.categories names "newsletter", which bounda.personal-data.ts retired: the port sends it no data of a retired category', + ); refused( { mailer: { ...handlers, recipient: { ...MAILCHIMP, categories: "contact" } } }, "Port customer.mailer: recipient.categories must list the categories of personal data the port sends it", diff --git a/packages/core/src/kernel/recipients/build.ts b/packages/core/src/kernel/recipients/build.ts index 1a57aaca2..aa1dbfdda 100644 --- a/packages/core/src/kernel/recipients/build.ts +++ b/packages/core/src/kernel/recipients/build.ts @@ -157,11 +157,16 @@ const checked = ( if (!Array.isArray(named) || named.length === 0) { fail("recipient.categories must list the categories of personal data the port sends it"); } - const known: ReadonlySet = new Set(categories.all.map((category) => category.name)); for (const category of named as readonly unknown[]) { - if (!known.has(category)) { + const known = typeof category === "string" ? categories.of(category) : undefined; + if (known === undefined) { fail(`recipient.categories names ${JSON.stringify(category)}, which the app does not have`); } + if (known?.retired === true) { + fail( + `recipient.categories names ${JSON.stringify(category)}, which bounda.personal-data.ts retired: the port sends it no data of a retired category`, + ); + } } if (new Set(named as readonly string[]).size !== (named as readonly string[]).length) { fail("recipient.categories names a category twice"); diff --git a/packages/core/src/kernel/shared/restore-model.test.ts b/packages/core/src/kernel/shared/restore-model.test.ts index 3214f78ec..f1d1a9c72 100644 --- a/packages/core/src/kernel/shared/restore-model.test.ts +++ b/packages/core/src/kernel/shared/restore-model.test.ts @@ -624,7 +624,7 @@ const createWorld = ( const store = left.store(); return store === 0 ? 0 : rowOf(db, landedRowOf(store)); }; - const rules = reconciliationRulesOf({ registry, config: resolveConfig(config) }); + const rules = reconciliationRulesOf({ registry, config: resolveConfig(config), recorded: [] }); const instances: (Live | null)[] = [null, null]; const backups = new Map(); let backed = 0; diff --git a/packages/core/src/modules/personal-data.ts b/packages/core/src/modules/personal-data.ts index 7f1e08c53..7c8a4eab8 100644 --- a/packages/core/src/modules/personal-data.ts +++ b/packages/core/src/modules/personal-data.ts @@ -240,6 +240,13 @@ export interface PersonalDataCategory { * `archiving-research-or-statistics` with a purpose of article 89(1). Never on `consent`. */ readonly erasureExemption?: DeclaredErasureExemption; + /** + * Retires the category: no field, call or decision names it any more, while what was marked in + * it before stays under its retention and exemptions, never forgotten at once, and the exports + * say it is retired. A category the store recorded keys in is never dropped from + * `bounda.personal-data.ts`, which refuses the start: it is retired instead, and stays so. + */ + readonly retired?: true; } /** @@ -347,7 +354,17 @@ type DecidedOn = Decision extends { readonly categories: readonly (inf type UndeclaredIn = { [Name in keyof DecisionsOf]: Exclude< DecidedOn[Name]>, - PersonalCategoriesOf | typeof DEFAULT_PERSONAL_CATEGORY + | PersonalCategoriesOf + | RetiredPersonalCategoriesOf + | typeof DEFAULT_PERSONAL_CATEGORY + >; +}[keyof DecisionsOf]; + +// The categories the module's decisions name that it retired, `never` when none. +type RetiredIn = { + [Name in keyof DecisionsOf]: Extract< + DecidedOn[Name]>, + RetiredPersonalCategoriesOf >; }[keyof DecisionsOf]; @@ -460,11 +477,29 @@ type Breaks = Rule extends "kept-on-consent" : true : false; +// Whether a category's declaration retires it. +type IsRetired = Category extends { readonly retired: true } ? true : false; + /** - * The names of the categories a `bounda.personal-data.ts` module declares, which the generator - * registers so `personal({ category })` and `forget` take only those. + * The names of the categories a `bounda.personal-data.ts` module declares and has not retired, + * which the generator registers so `personal({ category })` and `forget` take only those. */ -export type PersonalCategoriesOf = Extract, string>; +export type PersonalCategoriesOf = { + [Name in keyof CategoriesOf]: IsRetired[Name]> extends true + ? never + : Name; +}[keyof CategoriesOf] & + string; + +/** + * The names of the categories a `bounda.personal-data.ts` module retired. + */ +export type RetiredPersonalCategoriesOf = { + [Name in keyof CategoriesOf]: IsRetired[Name]> extends true + ? Name + : never; +}[keyof CategoriesOf] & + string; // What the module's categories break, as its message says it, `true` when nothing. type CategoryRules = [BreakingIn] extends [never] @@ -489,18 +524,20 @@ type CategoryRules = [BreakingIn] extends [never] export type DeclaresPersonalData = [CategoriesOf] extends [never] ? "bounda.personal-data.ts must export categories, each with its basis, retention, purposes and sources" : CategoriesOf extends PersonalDataCategories - ? typeof DEFAULT_PERSONAL_CATEGORY extends PersonalCategoriesOf + ? typeof DEFAULT_PERSONAL_CATEGORY extends Extract, string> ? 'bounda.personal-data.ts declares "default", the category of fields marked without one; name it otherwise' : CategoryRules extends true ? [DecisionsOf] extends [never] ? "bounda.personal-data.ts must export automatedDecisions, {} when the app decides nothing about a person by automated means alone" : DecisionsOf extends AutomatedDecisions ? [UndeclaredIn] extends [never] - ? [UnallowedIn] extends [never] - ? [UnmeasuredIn] extends [never] - ? true - : "bounda.personal-data.ts has an automated decision on special categories of data that does not say its measures (article 22(4))" - : "bounda.personal-data.ts has an automated decision on special categories of data whose condition is neither explicit-consent nor substantial-public-interest (article 22(4))" + ? [RetiredIn] extends [never] + ? [UnallowedIn] extends [never] + ? [UnmeasuredIn] extends [never] + ? true + : "bounda.personal-data.ts has an automated decision on special categories of data that does not say its measures (article 22(4))" + : "bounda.personal-data.ts has an automated decision on special categories of data whose condition is neither explicit-consent nor substantial-public-interest (article 22(4))" + : "bounda.personal-data.ts has an automated decision on a category it retired" : "bounda.personal-data.ts has an automated decision on a category it does not declare" : "bounda.personal-data.ts declares an automated decision without its categories, logic, significance, consequences, profiling or ground" : CategoryRules diff --git a/packages/core/test-types/inference.test-d.ts b/packages/core/test-types/inference.test-d.ts index 7a192d631..2fbb0e292 100644 --- a/packages/core/test-types/inference.test-d.ts +++ b/packages/core/test-types/inference.test-d.ts @@ -1249,6 +1249,7 @@ describe("personal data", () => { readonly criminal?: CriminalOffenceData; readonly processedFor?: readonly [SpecificPurpose, ...SpecificPurpose[]]; readonly erasureExemption?: DeclaredErasureExemption; + readonly retired?: true; }>(); expectTypeOf().toEqualTypeOf< | "direct-marketing" @@ -1368,9 +1369,9 @@ describe("personal data", () => { expectTypeOf().toEqualTypeOf< BoundaClient["exportPersonalData"] >(); - expectTypeOf(PERSONAL_DATA_EXPORT_VERSION).toEqualTypeOf<2>(); - expectTypeOf(PERSONAL_DATA_INVENTORY_VERSION).toEqualTypeOf<2>(); - expectTypeOf().toEqualTypeOf<2>(); + expectTypeOf(PERSONAL_DATA_EXPORT_VERSION).toEqualTypeOf<3>(); + expectTypeOf(PERSONAL_DATA_INVENTORY_VERSION).toEqualTypeOf<3>(); + expectTypeOf().toEqualTypeOf<3>(); expectTypeOf().toEqualTypeOf< readonly { readonly kind: "event" | "command" | "process-state" | "read-model"; @@ -1386,7 +1387,7 @@ describe("personal data", () => { }[] >(); expectTypeOf().toEqualTypeOf<{ - readonly version: 2; + readonly version: 3; readonly personId: string; readonly exportedAt: string; readonly position: number; @@ -1414,7 +1415,7 @@ describe("personal data", () => { BoundaClient["streamPersonalData"] >(); expectTypeOf().toEqualTypeOf<{ - readonly version: 2; + readonly version: 3; readonly personId: string; readonly exportedAt: string; readonly position: number; @@ -1443,6 +1444,7 @@ describe("personal data", () => { (parts: AsyncIterable) => ReadableStream >(); expectTypeOf().toEqualTypeOf<{ + readonly retired: boolean; readonly basis: LegalBasis | null; readonly special: SpecialCategoryData | null; readonly criminal: CriminalOffenceData | null; diff --git a/packages/core/test-types/tenant-export.test-d.ts b/packages/core/test-types/tenant-export.test-d.ts index 81c5989e0..3521147d9 100644 --- a/packages/core/test-types/tenant-export.test-d.ts +++ b/packages/core/test-types/tenant-export.test-d.ts @@ -64,10 +64,10 @@ describe("the tenant export", () => { it("names its format and version as literals a reader checks", () => { expectTypeOf(TENANT_EXPORT_FORMAT).toEqualTypeOf<"bounda.tenant-export">(); - expectTypeOf(TENANT_EXPORT_VERSION).toEqualTypeOf<9>(); + expectTypeOf(TENANT_EXPORT_VERSION).toEqualTypeOf<10>(); expectTypeOf().toEqualTypeOf<{ readonly format: "bounda.tenant-export"; - readonly version: 9; + readonly version: 10; readonly tenant: string; readonly exportId: string; readonly exportedAt: string; From 663040eff986554bfec5c20f1391d93fbd576b27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 11:30:38 +0100 Subject: [PATCH 11/33] feat(core,cli): name retired personal-data categories in types, and register them from the generator `RetiredPersonalCategoryName` joins `PersonalCategoryName` wherever a category already stored is named: what forget, restrict and unrestrict take, and every forgetting, restriction, redaction, recipient and export that reaches one. `personal(...)`, `.personal(...)`, decisions and recipient declarations still take categories in use alone. The generator registers the retired names as `retiredPersonalCategories`, and the CLI's inventory marks a retired category. --- packages/cli/src/generate/emit/emit.test.ts | 4 +- packages/cli/src/generate/emit/register.ts | 12 +++-- packages/cli/src/generate/emit/types.ts | 13 +++-- packages/cli/src/inventory-output.test.ts | 27 +++++++++- packages/cli/src/inventory-output.ts | 8 ++- packages/cli/src/run-inventory.test.ts | 2 +- packages/cloudflare/test/parts.test.ts | 2 +- .../src/kernel/personal-data/tenant-export.ts | 3 +- packages/core/src/modules/bounda-events.ts | 17 ++++--- packages/core/src/modules/index.ts | 2 + packages/core/src/modules/personal-data.ts | 27 +++++++--- packages/core/src/modules/recipient.ts | 16 +++--- packages/core/src/register/index.ts | 15 +++++- packages/core/src/testing/expect-forgotten.ts | 7 ++- .../order-app-inferred/.bounda/register.d.ts | 3 +- .../order-app-inferred/.bounda/types.ts | 1 + .../fixtures/order-app/.bounda/register.d.ts | 3 +- .../fixtures/order-app/.bounda/types.ts | 1 + .../order-app/bounda.personal-data.ts | 8 +++ packages/core/test-types/inference.test-d.ts | 51 ++++++++++++++----- packages/core/test-types/negatives.test-d.ts | 18 ++++++- packages/core/test-types/recipients.test-d.ts | 5 +- .../core/test-types/tenant-export.test-d.ts | 3 +- packages/core/test-types/tenants.test-d.ts | 3 +- packages/core/test-types/testing.test-d.ts | 8 ++- .../src/personal-data-export.test.ts | 4 +- .../react-router/src/tenant-export.test.ts | 2 +- 27 files changed, 200 insertions(+), 65 deletions(-) diff --git a/packages/cli/src/generate/emit/emit.test.ts b/packages/cli/src/generate/emit/emit.test.ts index fb455069e..377fce044 100644 --- a/packages/cli/src/generate/emit/emit.test.ts +++ b/packages/cli/src/generate/emit/emit.test.ts @@ -507,6 +507,7 @@ export type ReactionCommands = core.ReactionCommandsFacadeOf = Check; export type PersonalCategory = never; +export type RetiredPersonalCategory = never; export type ShipmentsRow = core.RowOf; export type ShipmentsFieldTypes = core.FieldTypesOf; @@ -650,6 +651,7 @@ describe("emitTypes for the files at the project root", () => { expect(typesOf({ personalData })).toContain( [ 'export type PersonalCategory = core.PersonalCategoriesOf;', + 'export type RetiredPersonalCategory = core.RetiredPersonalCategoriesOf;', 'export type PersonalDataDeclaration = Expect>;', "", personalDataContract, @@ -659,7 +661,7 @@ describe("emitTypes for the files at the project root", () => { ); expect(typesOf({ personalData })).not.toContain("namespace Audit"); expect(typesOf({ audit })).toContain( - `export type PersonalCategory = never;\n\n${auditContract}\n\nexport type`, + `export type PersonalCategory = never;\nexport type RetiredPersonalCategory = never;\n\n${auditContract}\n\nexport type`, ); expect(typesOf({ personalData, audit })).toContain( `${personalDataContract}\n\n${auditContract}\n\nexport type`, diff --git a/packages/cli/src/generate/emit/register.ts b/packages/cli/src/generate/emit/register.ts index cf33ae949..f5144d2f7 100644 --- a/packages/cli/src/generate/emit/register.ts +++ b/packages/cli/src/generate/emit/register.ts @@ -2,6 +2,7 @@ import type { GeneratedFile } from "./paths.ts"; import { PERSONAL_CATEGORY_TYPE_NAME, PORTS_CONFIG_TYPE_NAME, + RETIRED_PERSONAL_CATEGORY_TYPE_NAME, TEST_PORTS_TYPE_NAME, } from "./types.ts"; @@ -15,16 +16,16 @@ export interface EmitRegisterFunction { /** * Registers the registry type, the types of the `ports` configuration and of `createTestApp`'s - * `ports`, and the names of the categories of personal data with `@bounda-dev/core/register`, so - * `BoundaApp`, `boot()` and the integrations are typed for the project without a type argument, - * `defineConfig` and `createTestApp` check the implementation names, and `personal({ category })` - * and `forget` check the categories. + * `ports`, and the names of the categories of personal data, in use and retired, with + * `@bounda-dev/core/register`, so `BoundaApp`, `boot()` and the integrations are typed for the + * project without a type argument, `defineConfig` and `createTestApp` check the implementation + * names, and `personal({ category })` and `forget` check the categories. */ export const emitRegister: EmitRegisterFunction = ({ path }) => ({ path, content: [ 'import type { registry } from "./registry.ts";', - `import type { ${PERSONAL_CATEGORY_TYPE_NAME}, ${PORTS_CONFIG_TYPE_NAME}, ${TEST_PORTS_TYPE_NAME} } from "./types.ts";`, + `import type { ${PERSONAL_CATEGORY_TYPE_NAME}, ${PORTS_CONFIG_TYPE_NAME}, ${RETIRED_PERSONAL_CATEGORY_TYPE_NAME}, ${TEST_PORTS_TYPE_NAME} } from "./types.ts";`, "", 'declare module "@bounda-dev/core/register" {', " interface Register {", @@ -32,6 +33,7 @@ export const emitRegister: EmitRegisterFunction = ({ path }) => ({ ` readonly ports: ${PORTS_CONFIG_TYPE_NAME};`, ` readonly testPorts: ${TEST_PORTS_TYPE_NAME};`, ` readonly personalCategories: ${PERSONAL_CATEGORY_TYPE_NAME};`, + ` readonly retiredPersonalCategories: ${RETIRED_PERSONAL_CATEGORY_TYPE_NAME};`, " }", "}", "", diff --git a/packages/cli/src/generate/emit/types.ts b/packages/cli/src/generate/emit/types.ts index 9c3bf8adf..98dd535a3 100644 --- a/packages/cli/src/generate/emit/types.ts +++ b/packages/cli/src/generate/emit/types.ts @@ -114,6 +114,8 @@ export const TEST_PORTS_TYPE_NAME = "TestPorts"; export const PERSONAL_CATEGORY_TYPE_NAME = "PersonalCategory"; +export const RETIRED_PERSONAL_CATEGORY_TYPE_NAME = "RetiredPersonalCategory"; + const PERSONAL_DATA_CHECK_TYPE_NAME = "PersonalDataDeclaration"; // The files at the project root have no `+types` folder: they import these from `.bounda/types.ts`. @@ -132,6 +134,7 @@ export const APP_TYPE_NAMES: readonly string[] = [ PORTS_CONFIG_TYPE_NAME, TEST_PORTS_TYPE_NAME, PERSONAL_CATEGORY_TYPE_NAME, + RETIRED_PERSONAL_CATEGORY_TYPE_NAME, PERSONAL_DATA_CHECK_TYPE_NAME, PERSONAL_DATA_CONTRACT_NAME, AUDIT_CONTRACT_NAME, @@ -371,14 +374,18 @@ const contract = (name: string, members: readonly (readonly [string, string])[]) ].join("\n"); /** - * The categories `bounda.personal-data.ts` declares, `never` without it, and a type that fails to - * compile while it declares `default` or a category that is not one. + * The categories `bounda.personal-data.ts` declares in use and those it retired, `never` without + * it, and a type that fails to compile while it declares `default` or a category that is not one. */ const emitPersonalData = (model: ProjectModel, path: string): string => model.personalData === undefined - ? `export type ${PERSONAL_CATEGORY_TYPE_NAME} = never;` + ? [ + `export type ${PERSONAL_CATEGORY_TYPE_NAME} = never;`, + `export type ${RETIRED_PERSONAL_CATEGORY_TYPE_NAME} = never;`, + ].join("\n") : [ `export type ${PERSONAL_CATEGORY_TYPE_NAME} = core.PersonalCategoriesOf<${typeofImport(path, model.personalData.path)}>;`, + `export type ${RETIRED_PERSONAL_CATEGORY_TYPE_NAME} = core.RetiredPersonalCategoriesOf<${typeofImport(path, model.personalData.path)}>;`, `export type ${PERSONAL_DATA_CHECK_TYPE_NAME} = ${EXPECT_TYPE_NAME}>;`, ].join("\n"); diff --git a/packages/cli/src/inventory-output.test.ts b/packages/cli/src/inventory-output.test.ts index 4585ce6f8..76b64e821 100644 --- a/packages/cli/src/inventory-output.test.ts +++ b/packages/cli/src/inventory-output.test.ts @@ -12,9 +12,10 @@ const ANSWER_HELD = [ ] as const; const inventory: PersonalDataInventory = { - version: 2, + version: 3, categories: [ { + retired: false, name: "default", basis: null, special: null, @@ -28,6 +29,7 @@ const inventory: PersonalDataInventory = { fields: 1, }, { + retired: false, name: "contact", basis: "consent", special: null, @@ -46,6 +48,7 @@ const inventory: PersonalDataInventory = { fields: 1, }, { + retired: false, name: "care", basis: "contract", special: { kinds: ["health", "genetic"], condition: "explicit-consent" }, @@ -59,6 +62,7 @@ const inventory: PersonalDataInventory = { fields: 0, }, { + retired: false, name: "record", basis: "public-task", special: { kinds: ["biometric"], condition: "archiving-research-or-statistics" }, @@ -74,6 +78,20 @@ const inventory: PersonalDataInventory = { retention: "6y", fields: 0, }, + { + retired: true, + name: "points", + basis: "consent", + special: null, + criminal: null, + purposes: ["Reward earlier orders"], + processedFor: [], + erasureExemptions: [], + sources: ["data-subject"], + ports: [], + retention: "1y", + fields: 0, + }, ], automatedDecisions: [ { @@ -276,9 +294,10 @@ const inventory: PersonalDataInventory = { }; const empty: PersonalDataInventory = { - version: 2, + version: 3, categories: [ { + retired: false, name: "default", basis: null, special: null, @@ -337,6 +356,9 @@ describe("formatInventory", () => { " criminal data: under official-authority (article 10)", " processed for: statistics, archiving-in-the-public-interest", " kept past erasure: public-task (article 17(3)(b)), archiving-research-or-statistics (article 17(3)(d))", + " points (retired) consent forgotten 1y after last activity 0 fields", + " for: Reward earlier orders", + " from: the person", "", "Automated decisions", " scoring profiling, on explicit-consent, from contact, default", @@ -521,6 +543,7 @@ describe("formatInventoryMarkdown", () => { "| contact | consent | none | none | Send the newsletter; Answer \\| questions | direct-marketing | the person, derived by the app, A broker (third party), The register (public source) | `customer.crm`, `customers.lookup` | forgotten 730d after last activity | none | 1 |", "| care | contract | health, genetic, on explicit-consent (article 9(2)(a)) | none | Treat them | none | the person | none | forgotten 1y after last activity | none | 0 |", "| record | public-task | biometric, on archiving-research-or-statistics (article 9(2)(j)) | under official-authority (article 10) | Vet them | statistics, archiving-in-the-public-interest | the person | none | forgotten 6y after last activity | public-task (article 17(3)(b)), archiving-research-or-statistics (article 17(3)(d)) | 0 |", + "| points (retired) | consent | none | none | Reward earlier orders | none | the person | none | forgotten 1y after last activity | none | 0 |", "", "## Automated decisions", "", diff --git a/packages/cli/src/inventory-output.ts b/packages/cli/src/inventory-output.ts index 50348a68b..cb2d1e020 100644 --- a/packages/cli/src/inventory-output.ts +++ b/packages/cli/src/inventory-output.ts @@ -154,6 +154,10 @@ const plural = (count: number, noun: string): string => `${count} ${noun}${count const basisOf = (basis: string | null): string => basis ?? "no basis declared"; +// A retired category marks nothing any more, while what was marked in it is kept as it says. +const categoryNameOf = ({ name, retired }: InventoryCategory): string => + retired ? `${name} (retired)` : name; + const retentionOf = (retention: string | null): string => retention === null ? "kept until forgotten" : `forgotten ${retention} after last activity`; @@ -228,7 +232,7 @@ export const formatInventory: FormatInventoryFunction = (inventory) => { const lines: string[] = ["Personal data inventory (GDPR article 30)", "", "Categories"]; for (const category of inventory.categories) { lines.push( - ` ${category.name} ${basisOf(category.basis)} ${retentionOf(category.retention)} ${plural(category.fields, "field")}`, + ` ${categoryNameOf(category)} ${basisOf(category.basis)} ${retentionOf(category.retention)} ${plural(category.fields, "field")}`, ` for: ${purposesOf(category)}`, ` from: ${sourcesOf(category)}`, ); @@ -345,7 +349,7 @@ export const formatInventoryMarkdown: FormatInventoryFunction = (inventory) => { "Fields", ], inventory.categories.map((category) => [ - category.name, + categoryNameOf(category), basisOf(category.basis), category.special === null ? "none" : specialOf(category.special), category.criminal === null ? "none" : criminalOf(category.criminal), diff --git a/packages/cli/src/run-inventory.test.ts b/packages/cli/src/run-inventory.test.ts index 2e24b9cb4..298f24179 100644 --- a/packages/cli/src/run-inventory.test.ts +++ b/packages/cli/src/run-inventory.test.ts @@ -35,7 +35,7 @@ describe("bounda personal-data inventory", () => { const { code, stdout } = await cli(["personal-data", "inventory", "--json"]); expect(code).toBe(EXIT_OK); const inventory = JSON.parse(stdout) as PersonalDataInventory; - expect(inventory.version).toBe(2); + expect(inventory.version).toBe(3); expect(inventory.holders.map(({ name }) => name)).toEqual([ "customer.CustomerRegistered", "customers", diff --git a/packages/cloudflare/test/parts.test.ts b/packages/cloudflare/test/parts.test.ts index ef1e8fcb7..9900ac874 100644 --- a/packages/cloudflare/test/parts.test.ts +++ b/packages/cloudflare/test/parts.test.ts @@ -5,7 +5,7 @@ import { partLines, partsOf } from "../src/parts.ts"; const header: PersonalDataExportPart = { kind: "header", header: { - version: 2, + version: 3, personId: "ada", exportedAt: "2026-01-01T00:00:00.000Z", position: 2, diff --git a/packages/core/src/kernel/personal-data/tenant-export.ts b/packages/core/src/kernel/personal-data/tenant-export.ts index 6b2c2269b..cd6f4db35 100644 --- a/packages/core/src/kernel/personal-data/tenant-export.ts +++ b/packages/core/src/kernel/personal-data/tenant-export.ts @@ -11,6 +11,7 @@ import type { LegalBasis, PersonalCategoryName, ProcessingRestriction, + RetiredPersonalCategoryName, } from "../../modules/personal-data.ts"; import type { PersonRecipient } from "../../modules/recipient.ts"; import type { @@ -158,7 +159,7 @@ export interface TenantExportForgottenRecipient * counted under the categories forgotten, and under `persons` once nothing of theirs is left. */ readonly categories: readonly { - readonly name: PersonalCategoryName; + readonly name: PersonalCategoryName | RetiredPersonalCategoryName; readonly basis: LegalBasis | null; readonly persons: number; }[]; diff --git a/packages/core/src/modules/bounda-events.ts b/packages/core/src/modules/bounda-events.ts index a1619b42d..96dc4bd0e 100644 --- a/packages/core/src/modules/bounda-events.ts +++ b/packages/core/src/modules/bounda-events.ts @@ -3,6 +3,7 @@ import type { PersonalCategoryName, ProcessingRestriction, RestrictionGround, + RetiredPersonalCategoryName, } from "./personal-data.ts"; import type { NotifiedRecipient } from "./recipient.ts"; @@ -85,17 +86,17 @@ export interface PersonalDataForgottenPayload { * The categories forgotten: their fields read as `null` from then on. As a whole, every * category but those `retained`. */ - readonly categories: readonly PersonalCategoryName[]; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; /** * The categories kept under an erasure exemption instead, restricted until their retention ends, * when another `PersonalDataForgotten` names them in `expired`. */ - readonly retained: readonly PersonalCategoryName[]; + readonly retained: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; /** * The categories kept at an earlier forgetting whose retention ended: what was kept of them is * forgotten now. */ - readonly expired: readonly PersonalCategoryName[]; + readonly expired: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; /** * The fingerprints of the keys the forgetting covered, destroyed or retained, none when it * covered none: a key in force the person holds whose fingerprint is not here was given to them @@ -150,7 +151,7 @@ export interface ProcessingRestrictedPayload { /** * The categories restricted, `null` for the person as a whole. */ - readonly categories: readonly PersonalCategoryName[] | null; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] | null; /** * Every restriction the person has once this one is recorded, as `app.restrictions` reads them. */ @@ -177,7 +178,7 @@ export interface ProcessingRestrictionLiftAnnouncedPayload { /** * The categories lifted, `null` for every category the grounds cover. */ - readonly categories: readonly PersonalCategoryName[] | null; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] | null; /** * When the restriction is lifted, as an ISO timestamp. */ @@ -204,7 +205,7 @@ export interface ProcessingRestrictionLiftedPayload { /** * The categories lifted, `null` for every category the grounds covered. */ - readonly categories: readonly PersonalCategoryName[] | null; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] | null; /** * Every restriction the person still has, none once their processing is no longer restricted. */ @@ -252,7 +253,7 @@ export interface PersonalDataRedactedPayload { /** * The categories of the values redacted. */ - readonly categories: readonly PersonalCategoryName[]; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; /** * The scheduled commands whose payload held a value redacted: they would act on it, so they are * cancelled, as `forget` cancels them. @@ -289,7 +290,7 @@ export interface TenantForgottenPayload { /** * The categories the tenant's persons held keys of when it was forgotten, every one gone. */ - readonly categories: readonly PersonalCategoryName[]; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; /** * The recipients to tell of it (article 19): every port whose recipient was disclosed data of * any of the tenant's persons, or may have been, as the store recorded it when the event diff --git a/packages/core/src/modules/index.ts b/packages/core/src/modules/index.ts index 9ad8b2f70..62d25bd44 100644 --- a/packages/core/src/modules/index.ts +++ b/packages/core/src/modules/index.ts @@ -176,6 +176,8 @@ export type { RestrictionGround, RestrictionNotice, RestrictOptions, + RetiredPersonalCategoriesOf, + RetiredPersonalCategoryName, SpecialCategoryCondition, SpecialCategoryData, SpecialCategoryKind, diff --git a/packages/core/src/modules/personal-data.ts b/packages/core/src/modules/personal-data.ts index 7c8a4eab8..6dbf52246 100644 --- a/packages/core/src/modules/personal-data.ts +++ b/packages/core/src/modules/personal-data.ts @@ -1,6 +1,10 @@ import type { DEFAULT_PERSONAL_CATEGORY } from "../adapter/storage/personal-key-store.ts"; import type { DurationInput, RetentionInput } from "../contracts/duration.ts"; -import type { AppPersonalCategory, AppRegistry } from "../register/index.ts"; +import type { + AppPersonalCategory, + AppRegistry, + AppRetiredPersonalCategory, +} from "../register/index.ts"; /** * The lawful basis of processing a category of personal data, as article 6(1) of the GDPR names @@ -313,11 +317,20 @@ export interface PersonalDataModule { } /** - * A category of personal data `forget` takes and a forgetting names: one `bounda.personal-data.ts` - * declares, or `"default"`, that of the fields marked without one. + * A category of personal data a field is marked in, and that a port's calls, a recipient and an + * automated decision name: one `bounda.personal-data.ts` declares and has not retired, or + * `"default"`, that of the fields marked without one. */ export type PersonalCategoryName = AppPersonalCategory | typeof DEFAULT_PERSONAL_CATEGORY; +/** + * A category `bounda.personal-data.ts` retired: nothing marks or decides on it any more, while what + * was marked in it before is forgotten, restricted and lifted by its name, as `forget`, `restrict` + * and `unrestrict` take it beside a `PersonalCategoryName`, and every forgetting, restriction, + * redaction and export that reaches it names it. + */ +export type RetiredPersonalCategoryName = AppRetiredPersonalCategory; + /** * What `forget(personId, options)` takes besides the person. */ @@ -328,7 +341,7 @@ export interface ForgetOptions { * forgotten as a whole. Without it, every category is. A category an exemption of article 17(3) * applies to is kept, restricted, until its retention ends, either way. */ - readonly categories?: readonly PersonalCategoryName[]; + readonly categories?: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; /** * Forgets after an objection the app upheld (article 21), recorded with `reason: "objection"`: * of a category an objection reaches, only a `legal-obligation` or `legal-claims` exemption keeps @@ -599,7 +612,7 @@ export const RESTRICTION_BASES: readonly RestrictionBasis[] = [ */ export interface ProcessingRestriction { readonly ground: RestrictionGround; - readonly categories: readonly PersonalCategoryName[] | null; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] | null; readonly since: string; } @@ -649,7 +662,7 @@ export type RestrictOptions = * Restricts these categories of the person alone, as when they contest the accuracy of one * kind of data. Without it, the person as a whole is restricted, every category included. */ - readonly categories?: readonly PersonalCategoryName[]; + readonly categories?: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; } | ([Exclude] extends [never] ? { @@ -693,5 +706,5 @@ export interface UnrestrictOptions { * Lifts these categories alone from restrictions of categories; every category when omitted. A * restriction of the person as a whole is lifted as a whole. */ - readonly categories?: readonly PersonalCategoryName[]; + readonly categories?: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; } diff --git a/packages/core/src/modules/recipient.ts b/packages/core/src/modules/recipient.ts index f67f5eb87..d56cd46e8 100644 --- a/packages/core/src/modules/recipient.ts +++ b/packages/core/src/modules/recipient.ts @@ -7,7 +7,11 @@ import type { TenantForgottenEvent, } from "./bounda-events.ts"; import type { LegalRegime } from "./data-location.ts"; -import type { LegalBasis, PersonalCategoryName } from "./personal-data.ts"; +import type { + LegalBasis, + PersonalCategoryName, + RetiredPersonalCategoryName, +} from "./personal-data.ts"; /** * Who a recipient is to the controller, as the GDPR tells them apart: a `processor` that processes @@ -586,8 +590,8 @@ export type RecipientDeclaration */ export interface NotifiedRecipient { readonly port: string; - readonly categories: readonly PersonalCategoryName[]; - readonly retained: readonly PersonalCategoryName[]; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; + readonly retained: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; readonly presumed: boolean; } @@ -598,7 +602,7 @@ interface RecipientNoticeBase { /** * Of the categories disclosed to the recipient, those the change touches. */ - readonly categories: readonly PersonalCategoryName[]; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; /** * `true` when the disclosure is presumed rather than recorded. */ @@ -631,7 +635,7 @@ export type RecipientNoticeArgs< export type RecipientForgottenArgs = RecipientNoticeArgs< PersonalDataForgottenEvent, Ports, - { readonly retained: readonly PersonalCategoryName[] } + { readonly retained: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] } >; export type RecipientRestrictedArgs = RecipientNoticeArgs< @@ -753,7 +757,7 @@ export interface PersonRecipient { * Each category concerned, with its basis, `null` for the default category. */ readonly categories: readonly { - readonly name: PersonalCategoryName; + readonly name: PersonalCategoryName | RetiredPersonalCategoryName; readonly basis: LegalBasis | null; }[]; /** diff --git a/packages/core/src/register/index.ts b/packages/core/src/register/index.ts index 5624bf903..542b65302 100644 --- a/packages/core/src/register/index.ts +++ b/packages/core/src/register/index.ts @@ -21,7 +21,8 @@ import type { Registry } from "../modules/registry.ts"; * argument, and `defineConfig` and `createTestApp` check their `ports` against the * project's ports. It also registers `personalCategories`, the names of the categories * `bounda.personal-data.ts` declares, `never` without it, which `personal({ category })` and - * `forget(person, { categories })` take. + * `forget(person, { categories })` take, and `retiredPersonalCategories`, those it retired, which + * `forget` takes too. * A host adapter may register `env`, the type of the environment implementations receive in * `create`: `@bounda-dev/cloudflare` registers `Cloudflare.Env`. */ @@ -46,6 +47,16 @@ export type AppPersonalCategory = Register extends { ? C : string; +/** + * The categories of personal data the current project retired in `bounda.personal-data.ts`, as + * registered through {@link Register}: none without that file, or when no project is registered. + */ +export type AppRetiredPersonalCategory = Register extends { + readonly retiredPersonalCategories: infer C extends string; +} + ? C + : never; + type ValuesOf = Entries extends unknown ? Entries[keyof Entries] : never; type AggregateOf = ValuesOf; @@ -96,7 +107,7 @@ export type AppDeclaresPersonalData = Register extends { } ? true extends | RegistryDeclaresPersonalData - | ([AppPersonalCategory] extends [never] ? false : true) + | ([AppPersonalCategory | AppRetiredPersonalCategory] extends [never] ? false : true) ? true : false : false; diff --git a/packages/core/src/testing/expect-forgotten.ts b/packages/core/src/testing/expect-forgotten.ts index 5b3a80045..ed93070e6 100644 --- a/packages/core/src/testing/expect-forgotten.ts +++ b/packages/core/src/testing/expect-forgotten.ts @@ -9,7 +9,10 @@ import { needlesOf } from "../kernel/shared/value-search.ts"; import { isUnreadable } from "../kernel/status.ts"; import type { Witness } from "../kernel/witness.ts"; import { TENANT_FORGOTTEN_EVENT } from "../modules/bounda-events.ts"; -import type { PersonalCategoryName } from "../modules/personal-data.ts"; +import type { + PersonalCategoryName, + RetiredPersonalCategoryName, +} from "../modules/personal-data.ts"; import type { PersonData } from "./person-data.ts"; import { findIn, outsidePlaces, type Place, placesOfTable } from "./places.ts"; import { type Scope, scopesOf } from "./watched.ts"; @@ -89,7 +92,7 @@ export interface ExpectForgottenOptions { * person must hold no key in force of them. Without it, every category the person no longer * holds a key of. */ - readonly categories?: readonly PersonalCategoryName[]; + readonly categories?: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; } /** diff --git a/packages/core/test-types/fixtures/order-app-inferred/.bounda/register.d.ts b/packages/core/test-types/fixtures/order-app-inferred/.bounda/register.d.ts index edb4ecbd4..937ef68c8 100644 --- a/packages/core/test-types/fixtures/order-app-inferred/.bounda/register.d.ts +++ b/packages/core/test-types/fixtures/order-app-inferred/.bounda/register.d.ts @@ -1,5 +1,5 @@ import type { registry } from "./registry.ts"; -import type { PersonalCategory, PortsConfig, TestPorts } from "./types.ts"; +import type { PersonalCategory, PortsConfig, RetiredPersonalCategory, TestPorts } from "./types.ts"; declare module "@bounda-dev/core/register" { interface Register { @@ -7,5 +7,6 @@ declare module "@bounda-dev/core/register" { readonly ports: PortsConfig; readonly testPorts: TestPorts; readonly personalCategories: PersonalCategory; + readonly retiredPersonalCategories: RetiredPersonalCategory; } } diff --git a/packages/core/test-types/fixtures/order-app-inferred/.bounda/types.ts b/packages/core/test-types/fixtures/order-app-inferred/.bounda/types.ts index 7419daf15..fb49b8bf0 100644 --- a/packages/core/test-types/fixtures/order-app-inferred/.bounda/types.ts +++ b/packages/core/test-types/fixtures/order-app-inferred/.bounda/types.ts @@ -47,5 +47,6 @@ export type ReactionCommands = core.ReactionCommandsFacadeOf<{ type Expect = Check; export type PersonalCategory = never; +export type RetiredPersonalCategory = never; export type Queries = core.QueriesFacadeOf>; diff --git a/packages/core/test-types/fixtures/order-app/.bounda/register.d.ts b/packages/core/test-types/fixtures/order-app/.bounda/register.d.ts index edb4ecbd4..937ef68c8 100644 --- a/packages/core/test-types/fixtures/order-app/.bounda/register.d.ts +++ b/packages/core/test-types/fixtures/order-app/.bounda/register.d.ts @@ -1,5 +1,5 @@ import type { registry } from "./registry.ts"; -import type { PersonalCategory, PortsConfig, TestPorts } from "./types.ts"; +import type { PersonalCategory, PortsConfig, RetiredPersonalCategory, TestPorts } from "./types.ts"; declare module "@bounda-dev/core/register" { interface Register { @@ -7,5 +7,6 @@ declare module "@bounda-dev/core/register" { readonly ports: PortsConfig; readonly testPorts: TestPorts; readonly personalCategories: PersonalCategory; + readonly retiredPersonalCategories: RetiredPersonalCategory; } } diff --git a/packages/core/test-types/fixtures/order-app/.bounda/types.ts b/packages/core/test-types/fixtures/order-app/.bounda/types.ts index 77abaa8f5..ff13a9e9d 100644 --- a/packages/core/test-types/fixtures/order-app/.bounda/types.ts +++ b/packages/core/test-types/fixtures/order-app/.bounda/types.ts @@ -93,6 +93,7 @@ export type ReactionCommands = core.ReactionCommandsFacadeOf<{ type Expect = Check; export type PersonalCategory = core.PersonalCategoriesOf; +export type RetiredPersonalCategory = core.RetiredPersonalCategoriesOf; export type PersonalDataDeclaration = Expect>; export declare namespace PersonalData { diff --git a/packages/core/test-types/fixtures/order-app/bounda.personal-data.ts b/packages/core/test-types/fixtures/order-app/bounda.personal-data.ts index 67fe3e189..533943efd 100644 --- a/packages/core/test-types/fixtures/order-app/bounda.personal-data.ts +++ b/packages/core/test-types/fixtures/order-app/bounda.personal-data.ts @@ -20,6 +20,14 @@ export const categories = { sources: ["data-subject"], special: { kinds: ["health"], condition: "explicit-consent" }, }, + // Retired: no field is marked in it any more, and what was marked in it before stays. + loyalty: { + basis: "consent", + retention: "1y", + purposes: ["Reward the customer for earlier orders"], + sources: ["data-subject"], + retired: true, + }, } satisfies PersonalData.Categories; export const automatedDecisions = { diff --git a/packages/core/test-types/inference.test-d.ts b/packages/core/test-types/inference.test-d.ts index 2fbb0e292..bc11716ac 100644 --- a/packages/core/test-types/inference.test-d.ts +++ b/packages/core/test-types/inference.test-d.ts @@ -174,6 +174,8 @@ import type { RestrictOptions, RetentionInput, RetentionStatus, + RetiredPersonalCategoriesOf, + RetiredPersonalCategoryName, RetireTenantKeysAccess, RowOf, ScheduledDispatch, @@ -1181,9 +1183,9 @@ describe("personal data", () => { readonly personId: string; readonly reason: PersonalDataForgottenReason; readonly whole: boolean; - readonly categories: readonly PersonalCategoryName[]; - readonly retained: readonly PersonalCategoryName[]; - readonly expired: readonly PersonalCategoryName[]; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; + readonly retained: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; + readonly expired: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; readonly fingerprints?: readonly string[]; readonly cancelledCommands: readonly CancelledCommand[]; readonly removedDeadLetters: readonly RemovedDeadLetter[]; @@ -1191,13 +1193,30 @@ describe("personal data", () => { }>(); expectTypeOf().toEqualTypeOf<{ readonly port: string; - readonly categories: readonly PersonalCategoryName[]; - readonly retained: readonly PersonalCategoryName[]; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; + readonly retained: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; readonly presumed: boolean; }>(); + // A retired category is marked and decided on by nothing, and named where what was marked in + // it before is forgotten, restricted, lifted or told. expectTypeOf().toEqualTypeOf< "default" | "delivery" | "invoices" | "dietary" >(); + expectTypeOf().toEqualTypeOf<"loyalty">(); + expectTypeOf< + RetiredPersonalCategoriesOf + >().toEqualTypeOf<"loyalty">(); + expectTypeOf[number]>().toEqualTypeOf< + "default" | "delivery" | "invoices" | "dietary" | "loyalty" + >(); + expectTypeOf[number]>().toEqualTypeOf< + PersonalCategoryName | "loyalty" + >(); + expectTypeOf< + NonNullable< + Exclude["categories"] + >[number] + >().toEqualTypeOf(); expectTypeOf().toEqualTypeOf< "requested" | "objection" | "retention" >(); @@ -1353,7 +1372,13 @@ describe("personal data", () => { (personId: string, options?: ForgetOptions) => Promise >(); expectTypeOf().toEqualTypeOf<{ - readonly categories?: readonly ("default" | "delivery" | "invoices" | "dietary")[]; + readonly categories?: readonly ( + | "default" + | "delivery" + | "invoices" + | "dietary" + | "loyalty" + )[]; readonly objection?: boolean; }>(); expectTypeOf().toEqualTypeOf(); @@ -1506,7 +1531,7 @@ describe("personal data", () => { readonly transfer: RecipientTransfer | null; readonly status: "disclosed" | "presumed" | "declared"; readonly categories: readonly { - readonly name: PersonalCategoryName; + readonly name: PersonalCategoryName | RetiredPersonalCategoryName; readonly basis: LegalBasis | null; }[]; readonly firstDisclosedAt: string | null; @@ -1604,7 +1629,7 @@ describe("personal data", () => { expectTypeOf().toEqualTypeOf< | { readonly ground: "accuracy-contested" | "unlawful-processing" | "legal-claims"; - readonly categories?: readonly PersonalCategoryName[]; + readonly categories?: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; } | { readonly ground: "objection-pending"; readonly categories: readonly "default"[] } >(); @@ -1622,7 +1647,7 @@ describe("personal data", () => { expectTypeOf().toEqualTypeOf(); expectTypeOf().toEqualTypeOf<{ readonly ground: RestrictionGround; - readonly categories: readonly PersonalCategoryName[] | null; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] | null; readonly since: string; }>(); // @ts-expect-error a restriction needs its ground @@ -1667,7 +1692,7 @@ describe("personal data", () => { expectTypeOf().toEqualTypeOf<{ readonly personId: string; readonly events: readonly RedactedEvent[]; - readonly categories: readonly PersonalCategoryName[]; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; readonly cancelledCommands: readonly CancelledCommand[]; readonly removedDeadLetters: readonly RemovedDeadLetter[]; readonly recipients?: readonly NotifiedRecipient[]; @@ -1736,14 +1761,14 @@ describe("personal data", () => { expectTypeOf().toEqualTypeOf<{ readonly personId: string; readonly ground: RestrictionGround; - readonly categories: readonly PersonalCategoryName[] | null; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] | null; readonly restrictions: readonly ProcessingRestriction[]; readonly recipients?: readonly NotifiedRecipient[]; }>(); expectTypeOf().toEqualTypeOf<{ readonly personId: string; readonly grounds: readonly RestrictionGround[]; - readonly categories: readonly PersonalCategoryName[] | null; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] | null; readonly liftsAt: string; readonly recipients?: readonly NotifiedRecipient[]; }>(); @@ -1760,7 +1785,7 @@ describe("personal data", () => { expectTypeOf().toEqualTypeOf<{ readonly personId: string; readonly grounds: readonly RestrictionGround[]; - readonly categories: readonly PersonalCategoryName[] | null; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] | null; readonly restrictions: readonly ProcessingRestriction[]; readonly recipients?: readonly NotifiedRecipient[]; }>(); diff --git a/packages/core/test-types/negatives.test-d.ts b/packages/core/test-types/negatives.test-d.ts index 298c325fa..177446e42 100644 --- a/packages/core/test-types/negatives.test-d.ts +++ b/packages/core/test-types/negatives.test-d.ts @@ -258,15 +258,21 @@ describe("what does not compile", () => { note: personal(z.string(), { category: "delivery" }), // @ts-expect-error a misspelled category does not compile invoice: personal(z.string(), { category: "invoice" }), + // @ts-expect-error nor a category bounda.personal-data.ts retired + points: personal(z.string(), { category: "loyalty" }), }); void marks; const fields = ({ f }: FieldsArgs) => ({ // @ts-expect-error nor in a read model's view note: f.string().personal({ category: "deliveries" }), + // @ts-expect-error nor a retired one + points: f.string().personal({ category: "loyalty" }), }); void fields; const forget = (app: BoundaClient) => [ app.forget("c-1", { categories: ["default", "invoices"] }), + // A retired category still names what was marked in it. + app.forget("c-1", { categories: ["loyalty"] }), // @ts-expect-error nor in forget app.forget("c-1", { categories: ["profile"] }), ]; @@ -305,7 +311,10 @@ describe("what does not compile", () => { purposes: ["Serve the person"], sources: ["data-subject"], }; - void [year, weeks, unsaid, unbased, unbounded]; + const retired: PersonalDataCategory = { ...year, retired: true }; + // @ts-expect-error a category in use leaves retired out + const unretired: PersonalDataCategory = { ...year, retired: false }; + void [year, weeks, unsaid, unbased, unbounded, retired, unretired]; interface Profile { readonly basis: "consent"; readonly retention: "1d"; @@ -361,6 +370,10 @@ describe("what does not compile", () => { }; }; }; + type RetiredModule = { + readonly categories: { readonly profile: Profile & { readonly retired: true } }; + readonly automatedDecisions: { readonly scoring: Scoring }; + }; type GroundlessModule = { readonly categories: { readonly profile: Profile }; readonly automatedDecisions: { @@ -371,6 +384,8 @@ describe("what does not compile", () => { type Silent = Expect>; // @ts-expect-error a decision on a category the module does not declare type Undeclared = Expect>; + // @ts-expect-error a decision on a category the module retired + type Retired = Expect>; // @ts-expect-error a decision article 22(2) does not allow type Groundless = Expect>; const checks: [ @@ -382,6 +397,7 @@ describe("what does not compile", () => { Nothing?, Silent?, Undeclared?, + Retired?, Groundless?, ] = []; void checks; diff --git a/packages/core/test-types/recipients.test-d.ts b/packages/core/test-types/recipients.test-d.ts index cd933b305..2ac1a43f1 100644 --- a/packages/core/test-types/recipients.test-d.ts +++ b/packages/core/test-types/recipients.test-d.ts @@ -9,6 +9,7 @@ import type { RecipientDeclaration, RecipientModule, Registry, + RetiredPersonalCategoryName, } from "@bounda-dev/core"; import { describe, expectTypeOf, it } from "vitest"; import type { registry } from "./fixtures/order-app/.bounda/registry.ts"; @@ -77,7 +78,7 @@ describe("recipients", () => { Port.OnPersonalDataForgottenArgs["event"] >().toEqualTypeOf(); expectTypeOf().toEqualTypeOf< - readonly PersonalCategoryName[] + readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] >(); expectTypeOf< Port.OnProcessingRestrictedArgs["event"] @@ -92,7 +93,7 @@ describe("recipients", () => { Port.OnPersonalDataRedactedArgs["event"] >().toEqualTypeOf(); expectTypeOf().toEqualTypeOf< - readonly PersonalCategoryName[] + readonly (PersonalCategoryName | RetiredPersonalCategoryName)[] >(); expectTypeOf().toEqualTypeOf(); expectTypeOf().toEqualTypeOf(); diff --git a/packages/core/test-types/tenant-export.test-d.ts b/packages/core/test-types/tenant-export.test-d.ts index 3521147d9..0a6f083a4 100644 --- a/packages/core/test-types/tenant-export.test-d.ts +++ b/packages/core/test-types/tenant-export.test-d.ts @@ -16,6 +16,7 @@ import { type PersonRecipient, type ProcessingRestriction, type ReadTenantExportFunction, + type RetiredPersonalCategoryName, readTenantExport, type StoredEvent, TENANT_EXPORT_FORMAT, @@ -170,7 +171,7 @@ describe("the tenant export", () => { readonly declared: boolean; readonly persons: number; readonly categories: readonly { - readonly name: PersonalCategoryName; + readonly name: PersonalCategoryName | RetiredPersonalCategoryName; readonly basis: LegalBasis | null; readonly persons: number; }[]; diff --git a/packages/core/test-types/tenants.test-d.ts b/packages/core/test-types/tenants.test-d.ts index 7ef1fe336..ec0117399 100644 --- a/packages/core/test-types/tenants.test-d.ts +++ b/packages/core/test-types/tenants.test-d.ts @@ -43,6 +43,7 @@ import { type RemovedTenantKeyCopy, type RemoveKeyCopiesOptions, type RemoveStaleTenantKeysArgs, + type RetiredPersonalCategoryName, type RewrappedTenantKeys, type RewrapTenantKeysArgs, type RotateTenantKeyOptions, @@ -247,7 +248,7 @@ describe("the TenantForgotten event", () => { expectTypeOf(TENANT_FORGOTTEN_EVENT).toEqualTypeOf<"TenantForgotten">(); expectTypeOf().toEqualTypeOf<{ readonly tenant: string; - readonly categories: readonly PersonalCategoryName[]; + readonly categories: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; readonly recipients?: readonly NotifiedRecipient[]; }>(); expectTypeOf().toEqualTypeOf<"TenantForgotten">(); diff --git a/packages/core/test-types/testing.test-d.ts b/packages/core/test-types/testing.test-d.ts index 36338a56b..517d9caa5 100644 --- a/packages/core/test-types/testing.test-d.ts +++ b/packages/core/test-types/testing.test-d.ts @@ -109,7 +109,13 @@ describe("expectForgotten", () => { readonly values?: readonly unknown[]; readonly before?: PersonalDataExport; readonly places?: Readonly>; - readonly categories?: readonly ("default" | "delivery" | "invoices" | "dietary")[]; + readonly categories?: readonly ( + | "default" + | "delivery" + | "invoices" + | "dietary" + | "loyalty" + )[]; }>(); // @ts-expect-error a category bounda.personal-data.ts does not declare const misspelled: ExpectForgottenOptions = { categories: ["deliveries"] }; diff --git a/packages/react-router/src/personal-data-export.test.ts b/packages/react-router/src/personal-data-export.test.ts index a0cef48df..c61906e39 100644 --- a/packages/react-router/src/personal-data-export.test.ts +++ b/packages/react-router/src/personal-data-export.test.ts @@ -11,7 +11,7 @@ import { personalDataExportResponse } from "./personal-data-export.ts"; const header: PersonalDataExportPart = { kind: "header", header: { - version: 2, + version: 3, personId: "ada", exportedAt: "2026-01-01T00:00:00.000Z", position: 1, @@ -61,7 +61,7 @@ describe("personalDataExportResponse", () => { "cache-control": "no-store", }); expect(JSON.parse(await response.text())).toEqual({ - version: 2, + version: 3, personId: "ada", exportedAt: "2026-01-01T00:00:00.000Z", position: 1, diff --git a/packages/react-router/src/tenant-export.test.ts b/packages/react-router/src/tenant-export.test.ts index ecb9ebdf9..6cc330254 100644 --- a/packages/react-router/src/tenant-export.test.ts +++ b/packages/react-router/src/tenant-export.test.ts @@ -12,7 +12,7 @@ const header: TenantExportPart = { kind: "header", header: { format: "bounda.tenant-export", - version: 9, + version: 10, tenant: "acme", exportId: "x-1", exportedAt: "2026-01-01T00:00:00.000Z", From 8df1881fc44c989a3eeb2c74c8e2d820db9f8ae6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 11:36:12 +0100 Subject: [PATCH 12/33] feat(core)!: let redact reach any field of every event type, by what the stored event holds `RedactedFields.fields` offers the fields an event type marks now by name and takes any other. Every current event type and every lifecycle event that carries a process's state is a target, one that marks nothing now included. `redact` no longer refuses a field because its type does not mark it: it reaches each field by its envelope, as it does a retired type's, so a value sealed under an earlier mark is redacted. It refuses a field held in the clear the type does not mark now, one sealed for another person, one the event does not hold, and a stream and type the app knows nothing of, saying which. --- .../personal-data/redaction-details.test.ts | 105 +++++++++++++++--- .../personal-data/redaction-targets.test.ts | 56 ++++++---- .../kernel/personal-data/redaction-targets.ts | 67 ++++++----- .../src/kernel/personal-data/redaction.ts | 20 ++-- packages/core/src/modules/redaction.ts | 40 ++++--- packages/core/test-types/inference.test-d.ts | 25 +++-- 6 files changed, 215 insertions(+), 98 deletions(-) diff --git a/packages/core/src/kernel/personal-data/redaction-details.test.ts b/packages/core/src/kernel/personal-data/redaction-details.test.ts index faccba0fb..4117b2a97 100644 --- a/packages/core/src/kernel/personal-data/redaction-details.test.ts +++ b/packages/core/src/kernel/personal-data/redaction-details.test.ts @@ -437,9 +437,11 @@ describe("redact, in detail", () => { }); it("answers a redaction with nothing left as a command with no events, at the stream's version", async () => { - const { app, register, target } = await setUp(); + const { app, register, appendRaw, target } = await setUp(); const registered = await register("ana", "ana@old.example"); - expect(await app.redact("ana", { events: [target(registered, ["note"])] })).toEqual({ + // A marked field that holds null leaves nothing to seal. + const blank = await appendRaw("ana", "ana", null); + expect(await app.redact("ana", { events: [target(blank, ["email"])] })).toEqual({ scheduled: false, aggregateType: "bounda", aggregateId: "ana", @@ -459,11 +461,12 @@ describe("redact, in detail", () => { }); it("keeps the rest of the payload, names what it reached and logs counts alone", async () => { - const { app, register, target, redactions, events, logged } = await setUp(); + const { app, register, appendRaw, target, redactions, events, logged } = await setUp(); const registered = await register("ana", "ana@old.example"); await app.runUntilIdle(); + const blank = await appendRaw("ana", "ana", null); const moved = await app.redact("ana", { - events: [target(registered, ["email", "note"])], + events: [target(registered, ["email"]), target(blank, ["email"])], }); const [stored] = (await events()).filter(({ id }) => id === registered.id); expect(stored?.payload).toMatchObject({ plan: "pro" }); @@ -495,15 +498,25 @@ describe("redact, in detail", () => { }); it("records the redaction in the ledger before it commits, and nothing more when nothing was written after it", async () => { - const { app, clock, commands, register, target, ledgerRedactions, appendsOf, logged } = - await setUp(); + const { + app, + clock, + commands, + register, + appendRaw, + target, + ledgerRedactions, + appendsOf, + logged, + } = await setUp(); const registered = await register("ana", "ana@old.example"); + const blank = await appendRaw("ana", "ana", null); const redacted = await app.redact("ana", { - events: [target(registered, ["email", "note"])], + events: [target(registered, ["email"]), target(blank, ["email"])], }); await commands.correctEmail?.({ customerId: "ana", email: "ana@new.example" }); await app.runUntilIdle(); - // The intention asked for both fields; its commit copied what the event says it reached. + // The intention asked for both events; its commit copied what the event says it reached. const [intention, copy] = appendsOf(redacted.eventIds[0]); expect(intention).toEqual({ personId: "ana", @@ -511,9 +524,9 @@ describe("redact, in detail", () => { eventId: redacted.eventIds[0], forgottenAt: expect.any(String), reason: "requested", - redaction: { events: [target(registered, ["email", "note"])] }, + redaction: { events: [target(registered, ["email"]), target(blank, ["email"])] }, committed: false, - reached: { position: 1, generation: 0 }, + reached: { position: 2, generation: 0 }, }); expect(copy?.redaction).toEqual({ events: [target(registered, ["email"])] }); // A later round reads the entry again and finds the store holds it: nothing is committed. @@ -563,12 +576,15 @@ describe("redact, in detail", () => { expect(await scrubs()).toEqual([]); }); - it("leaves a value sealed for another person, or no value, as it is", async () => { + it("refuses a value sealed for another person, or a field the event does not hold, and leaves a null as it is", async () => { const { app, storage, register, appendRaw, target } = await setUp(); const bo = await register("bo", "bo@example.com"); const borrowed = await appendRaw("ana", "ana", (bo.payload as { email: unknown }).email); - expect((await app.redact("ana", { events: [target(borrowed, ["email"])] })).eventIds).toEqual( - [], + await expect(app.redact("ana", { events: [target(borrowed, ["email"])] })).rejects.toThrow( + `redact cannot reach the event ${borrowed.id}: it holds "email" sealed for another person`, + ); + await expect(app.redact("ana", { events: [target(borrowed, ["note"])] })).rejects.toThrow( + `redact cannot reach the event ${borrowed.id}: it holds no "note"`, ); const blank = await appendRaw("cy", "cy", null); expect((await app.redact("cy", { events: [target(blank, ["email"])] })).eventIds).toEqual([]); @@ -861,8 +877,6 @@ describe("redact, in detail", () => { it("redacts again only what an entry names that its event marks personal", async () => { const { app, clock, register, target, entries, redactions, events } = await setUp(); const registered = await register("ana", "ana@old.example"); - const first = await app.redact("ana", { events: [target(registered, ["note"])] }); - expect(first.eventIds).toEqual([]); const own = await app.redact("ana", { events: [target(registered, ["email"])] }); const [redaction] = await redactions(); if (redaction === undefined) throw new Error("not redacted"); @@ -1008,6 +1022,67 @@ describe("redact, in detail", () => { }); }); + it("reaches a field sealed under an earlier mark, of a type that marks it, or nothing, no more, and refuses one held in the clear", async () => { + const adapter = memory(); + const before = await createTestApp({ registry, adapter }); + await ( + before.app.commands as unknown as Record Promise> + ).registerCustomer?.({ customerId: "ana", email: "ana@old.example", note: "n", plan: "pro" }); + const [registered] = (await before.app.exportPersonalData("ana")).events; + if (registered === undefined) throw new Error("not registered"); + await before.app.stop(); + const customer = (registry.aggregates as unknown as Record>) + .customer; + const events = customer?.events as Record; + const marking = (marked: boolean) => + ({ + ...registry, + aggregates: { + customer: { + ...customer, + events: { + ...events, + customerRegistered: { + ...events.customerRegistered, + payload: ({ z, personal, notPersonal }: EventPayloadArgs) => + z.object({ + email: marked ? personal(z.string()) : notPersonal(z.string()), + note: notPersonal(z.string().optional()), + plan: notPersonal(z.string()), + }), + }, + }, + }, + }, + }) as unknown as Registry; + const target = { ...registered, fields: ["note"] } as never; + for (const marked of [true, false]) { + const after = await createTestApp({ registry: marking(marked), adapter }); + await expect( + after.app.redact("ana", { events: [{ ...registered, fields: ["plan"] }] as never }), + ).rejects.toThrow( + `redact cannot reach the event ${registered.id}: it holds "plan" in the clear`, + ); + if (marked) { + expect((await after.app.redact("ana", { events: [target] })).eventTypes).toEqual([ + "PersonalDataRedacted", + ]); + } else { + // Nothing marks the type now: its email, sealed under the mark it had, is reached too. + const redacted = await after.app.redact("ana", { + events: [{ ...registered, fields: ["email", "note"] }] as never, + }); + expect(redacted.eventTypes).toEqual(["PersonalDataRedacted"]); + } + await after.app.runUntilIdle(); + expect((await after.app.exportPersonalData("ana")).events[0]).toMatchObject({ + data: { email: marked ? "ana@old.example" : null, note: null }, + redacted: marked ? ["note"] : ["email", "note"], + }); + await after.app.stop(); + } + }); + it("hides the person in a rebuild that began before the redaction, then rebuilds once more", async () => { const { app, register, target, scrubs, logged } = await setUp(1); const registered = await register("ana", "ana@old.example"); diff --git a/packages/core/src/kernel/personal-data/redaction-targets.test.ts b/packages/core/src/kernel/personal-data/redaction-targets.test.ts index a33e63246..750538745 100644 --- a/packages/core/src/kernel/personal-data/redaction-targets.test.ts +++ b/packages/core/src/kernel/personal-data/redaction-targets.test.ts @@ -56,7 +56,9 @@ const registry = { const aggregates = buildAggregates({ registry, ports: {} }); const contact = { person: null, fields: ["contact"], categories: {} }; -const processes = { byName: { "customer.onboarding": { personal: contact } } } as never; +const processes = { + byName: { "customer.onboarding": { personal: contact }, "customer.reminder": { personal: null } }, +} as never; const registered = { aggregateType: "customer", @@ -114,42 +116,51 @@ describe("checkRedactionTargets", () => { } }); - it("refuses an event type that marks nothing it reaches, the lifecycle events without a state included", () => { - const cases: readonly [Record, string][] = [ - [{ aggregateType: "order", type: "OrderPlaced" }, "order.OrderPlaced"], - [{ type: "CustomerPaid" }, "customer.CustomerPaid"], - [{ type: "CustomerReferred" }, "customer.CustomerReferred"], - [{ type: "CustomerGone" }, "customer.CustomerGone"], + it("refuses a stream and type the app knows nothing of, saying why", () => { + const unknown = "the app has no such event type"; + const cases: readonly [Record, string, string][] = [ + [{ aggregateType: "order", type: "OrderPlaced" }, "order.OrderPlaced", unknown], + [{ type: "CustomerGone" }, "customer.CustomerGone", unknown], [ { aggregateType: "process:customer.onboarding", type: "ProcessCompleted" }, "process:customer.onboarding.ProcessCompleted", + "it carries no state of the process", ], [ { aggregateType: "process:customer.unknown", type: "ProcessHandled" }, "process:customer.unknown.ProcessHandled", + "the app runs no such process", ], ]; - for (const [changed, named] of cases) { + for (const [changed, named, why] of cases) { + const message = `cannot reach ${named}: ${why}`; const error = refusal([{ ...registered, ...changed }]); - expect(error.message).toBe(`redact cannot reach ${named}: it marks no field personal`); - expect(error.issues).toEqual([ - { path: ["events", 0], message: `cannot reach ${named}: it marks no field personal` }, - ]); + expect(error.message).toBe(`redact ${message}`); + expect(error.issues).toEqual([{ path: ["events", 0], message }]); } }); - it("refuses a field the event type does not mark personal", () => { - const error = refusal([{ ...registered, fields: ["email", "plan"] }]); - const message = 'cannot reach "plan" of customer.CustomerRegistered: it is not marked personal'; - expect(error.message).toBe(`redact ${message}`); - expect(error.issues).toEqual([{ path: ["events", 0, "fields"], message }]); + it("takes any field of every event type the app has, one that marks nothing now included, which the stored event's envelopes decide", () => { + const targets = [ + { ...registered, fields: ["email", "plan"] }, + { ...registered, id: "e-2", type: "CustomerPaid", fields: ["total"] }, + { ...registered, id: "e-3", type: "CustomerReferred", fields: ["referrer"] }, + { + ...registered, + id: "e-4", + aggregateType: "process:customer.reminder", + type: "ProcessStarted", + fields: ["note"], + }, + ]; + expect(checkRedactionTargets({ aggregates, processes, events: targets })).toEqual(targets); }); it("takes any field of a retired type, which the stored event's envelopes decide, and refuses one another aggregate retired", () => { const noted = { ...registered, type: "CustomerNoted", fields: ["text", "anything"] }; expect(checkRedactionTargets({ aggregates, processes, events: [noted] })).toEqual([noted]); expect(refusal([{ ...noted, aggregateType: "member" }]).message).toBe( - "redact cannot reach member.CustomerNoted: it marks no field personal", + "redact cannot reach member.CustomerNoted: the app has no such event type", ); }); @@ -199,11 +210,16 @@ describe("checkRedactionTargets", () => { }); describe("redactionReach", () => { - it("reads an event's marks, a lifecycle event's state's, and nothing for what it does not know", () => { + it("reads an event's marks, a lifecycle event's state's, none for one that marks nothing, and nothing for what it does not know", () => { const of = (aggregateType: string, type: string) => redactionReach({ aggregates, processes, aggregateType, type }); + const none = { marks: { person: null, fields: [], categories: {} } }; expect(of("customer", "CustomerRegistered")?.marks?.fields).toEqual(["email", "phone"]); - expect(of("customer", "CustomerPaid")).toBeNull(); + expect(of("customer", "CustomerPaid")).toEqual(none); + expect(of("customer", "CustomerReferred")).toEqual({ + marks: { person: "referrer", fields: [], categories: {} }, + }); + expect(of("process:customer.reminder", "ProcessHandled")).toEqual(none); expect(of("customer", "Unknown")).toBeNull(); expect(of("order", "OrderPlaced")).toBeNull(); for (const type of [ diff --git a/packages/core/src/kernel/personal-data/redaction-targets.ts b/packages/core/src/kernel/personal-data/redaction-targets.ts index 309397907..9704d4a75 100644 --- a/packages/core/src/kernel/personal-data/redaction-targets.ts +++ b/packages/core/src/kernel/personal-data/redaction-targets.ts @@ -15,9 +15,9 @@ export interface RedactionReachArgs { readonly type: string; } -// How a redaction finds the personal fields of an event: by what its type marks, or, with `marks` -// `null`, by the envelopes the stored event holds, for a type its aggregate retired, which no -// schema marks any more. +// How a redaction finds the personal fields of an event: by what its type marks now, or, with +// `marks` `null`, by the sets the store recorded, for a type its aggregate retired, which no schema +// marks any more. Every field is reached by its envelope first. export interface RedactionReach { readonly marks: PersonalMarks | null; } @@ -26,9 +26,11 @@ export interface RedactionReachFunction { (args: RedactionReachArgs): RedactionReach | null; } -// What an event of that stream and type marks: its payload's marks, or, for a process's lifecycle -// event that carries the state, the state's; its envelopes for a retired type; `null` for an -// event that marks nothing redact reaches. +const NO_MARKS: PersonalMarks = { person: null, fields: [], categories: {} }; + +// What an event of that stream and type marks now: its payload's marks, or, for a process's +// lifecycle event that carries the state, the state's, none for one that marks nothing; `null` +// marks for a retired type; `null` for a stream and type the app knows nothing of. export const redactionReach: RedactionReachFunction = ({ aggregates, processes, @@ -36,22 +38,38 @@ export const redactionReach: RedactionReachFunction = ({ type, }) => { const process = processOfStream(aggregateType); - const marks = - process === null - ? aggregates.byName[aggregateType]?.eventsByType[type]?.personal - : PROCESS_STATE_EVENTS.includes(type as ProcessStateEventType) - ? processes.byName[process]?.personal - : null; - if (marks !== undefined && marks !== null) return { marks }; - return aggregates.byName[aggregateType]?.retired.has(type) === true ? { marks: null } : null; + if (process !== null) { + const known = processes.byName[process]; + return known !== undefined && PROCESS_STATE_EVENTS.includes(type as ProcessStateEventType) + ? { marks: known.personal ?? NO_MARKS } + : null; + } + const aggregate = aggregates.byName[aggregateType]; + const event = aggregate?.eventsByType[type]; + if (event !== undefined) return { marks: event.personal ?? NO_MARKS }; + return aggregate?.retired.has(type) === true ? { marks: null } : null; +}; + +interface UnknownTargetArgs { + readonly processes: Pick; + readonly aggregateType: string; +} + +// Why `redactionReach` knows nothing of the target's stream and type. +const unknownTarget = ({ processes, aggregateType }: UnknownTargetArgs): string => { + const process = processOfStream(aggregateType); + if (process === null) return "the app has no such event type"; + return processes.byName[process] === undefined + ? "the app runs no such process" + : "it carries no state of the process"; }; export interface UnsealedForFunction { (holder: Readonly>, field: string, personId: string): string | null; } -// Why a redaction by envelope cannot reach the field, `null` when the event holds it sealed for -// the person: one held in the clear, or for another person, has no category a schema gives it. +// Why a redaction cannot reach the field by its envelope, `null` when the event holds it sealed +// for the person. export const unsealedFor: UnsealedForFunction = (holder, field, personId) => { const stored = holder[field]; if (stored === undefined) return `it holds no "${field}"`; @@ -77,9 +95,9 @@ const invalid = (path: readonly (string | number)[], message: string): Validatio new ValidationError(`redact ${message}`, [{ path: [...path], message }]); // The targets of `redact(person, { events })`, each event once with its fields once each, in the -// order asked. Throws `ValidationError` for none, for a target that is not one, for an event type -// that marks no personal field `redact` reaches, and for a field it does not mark `personal`. The -// fields of a retired type are checked against the stored event, by `checkReachable`. +// order asked. Throws `ValidationError` for none, for a target that is not one, and for a stream +// and type the app knows nothing of. Each field is checked against the stored event, by +// `checkReachable`. export const checkRedactionTargets: CheckRedactionTargetsFunction = ({ aggregates, processes, @@ -104,15 +122,10 @@ export const checkRedactionTargets: CheckRedactionTargetsFunction = ({ if (!Array.isArray(fields) || fields.length === 0 || !fields.every(isName)) { throw invalid([...path, "fields"], "needs the fields of each event to redact"); } - const reach = redactionReach({ aggregates, processes, aggregateType, type }); - if (reach === null || reach.marks?.fields.length === 0) { - throw invalid(path, `cannot reach ${aggregateType}.${type}: it marks no field personal`); - } - const unmarked = fields.find((field) => reach.marks?.fields.includes(field) === false); - if (unmarked !== undefined) { + if (redactionReach({ aggregates, processes, aggregateType, type }) === null) { throw invalid( - [...path, "fields"], - `cannot reach "${unmarked}" of ${aggregateType}.${type}: it is not marked personal`, + path, + `cannot reach ${aggregateType}.${type}: ${unknownTarget({ processes, aggregateType })}`, ); } const known = byId.get(id); diff --git a/packages/core/src/kernel/personal-data/redaction.ts b/packages/core/src/kernel/personal-data/redaction.ts index d107d4b69..5237b65c0 100644 --- a/packages/core/src/kernel/personal-data/redaction.ts +++ b/packages/core/src/kernel/personal-data/redaction.ts @@ -158,8 +158,10 @@ export interface CheckReachableFunction { } // Throws `ValidationError` for the first target `redactWithin` would refuse, before anything is -// recorded: a redaction refused never reaches the ledger, whose reconciliation would apply it. A -// store whose marks no longer settle a retired type refuses it as the start does. +// recorded: a redaction refused never reaches the ledger, whose reconciliation would apply it. Each +// field is reached sealed for the person, or held in the clear where the type marks it now or, for +// a retired type, where a set the store recorded marks it. A store whose marks no longer settle a +// retired type refuses it as the start does. export const checkReachable: CheckReachableFunction = async ({ eventStore, aggregates: started, @@ -176,12 +178,14 @@ export const checkReachable: CheckReachableFunction = async ({ }); const why = unreachable(event, target, personId); if (why !== null) throw refusal(target, why); + if (event === null) continue; const { aggregateType, type } = target; - const reach = redactionReach({ aggregates, processes, aggregateType, type }); - if (event === null || reach?.marks !== null) continue; - const holder = isRecord(event.payload) ? event.payload : {}; - // A value the sets recorded for the retired type mark, held in the clear, has their category. - const marks = eventMarksOf({ aggregates, event }); + const marks = + redactionReach({ aggregates, processes, aggregateType, type })?.marks ?? + eventMarksOf({ aggregates, event }); + const held = + processOfStream(aggregateType) === null ? event.payload : lifecycleStateOf(event.payload); + const holder = isRecord(held) ? held : {}; for (const field of target.fields) { const unsealed = unsealedFor(holder, field, personId); const marked = @@ -195,7 +199,7 @@ export const checkReachable: CheckReachableFunction = async ({ interface ReachedTarget { readonly event: StoredEvent; - // `null` for a type that marks nothing. + // `null` where nothing marks the event: a retired type no set the store recorded marks. readonly marks: PersonalMarks | null; // The payload, or, for a process's lifecycle event, the state it carries. readonly holder: Readonly>; diff --git a/packages/core/src/modules/redaction.ts b/packages/core/src/modules/redaction.ts index 942faaf64..1a00bcb90 100644 --- a/packages/core/src/modules/redaction.ts +++ b/packages/core/src/modules/redaction.ts @@ -14,8 +14,11 @@ export type ProcessStateEventType = /** * One event `redact` reaches: the event as the person's export lists it, by its stream, type and - * id, and the fields marked `personal` to seal for good, those of its payload, or of the state a - * process's lifecycle event carries. + * id, and the fields to seal for good, those of its payload, or of the state a process's lifecycle + * event carries. The fields its type marks `personal` now are offered by name; any other field is + * taken too, and reached when the stored event holds it sealed for the person, as under a mark an + * earlier version of the type had. `redact` refuses a field the event holds in the clear unless + * its type marks it now, one it holds sealed for another person, and one it does not hold. */ export interface RedactedFields< AggregateType extends string = string, @@ -26,24 +29,27 @@ export interface RedactedFields< readonly aggregateId: string; readonly type: Type; readonly id: string; - readonly fields: readonly Field[]; + readonly fields: readonly FieldName[]; } +// The fields marked now, offered by name, beside any other: `string` alone where any field is. +type FieldName = string extends Field ? string : Field | (string & {}); + type EventTargetsOf = { - [Key in keyof Events & string]: [PersonalPayloadFieldsOf] extends [never] - ? never - : RedactedFields, PersonalPayloadFieldsOf>; + [Key in keyof Events & string]: RedactedFields< + Aggregate, + TypeNameOf, + PersonalPayloadFieldsOf + >; }[keyof Events & string]; type ProcessTargetsOf = { [Key in keyof Processes & string]: Processes[Key] extends { readonly module: infer Module } - ? [PersonalStateFieldsOf] extends [never] - ? never - : RedactedFields< - `process:${Aggregate}.${Key}`, - ProcessStateEventType, - PersonalStateFieldsOf - > + ? RedactedFields< + `process:${Aggregate}.${Key}`, + ProcessStateEventType, + PersonalStateFieldsOf + > : never; }[keyof Processes & string]; @@ -57,10 +63,10 @@ type RetiredTargetsOf = Entry extends { : never; /** - * What `redact` takes of one event of the registry `R`: for each event type with personal fields, - * its aggregate, its type and the fields it marks; for each retired event type, its aggregate, - * its type and any fields; for each process whose state marks fields, its stream and the - * lifecycle events that carry the state. Any event and field names for the untyped `Registry`. + * What `redact` takes of one event of the registry `R`: for each event type, retired ones + * included, its aggregate and its type; for each process, its stream and the lifecycle events + * that carry its state; each with the fields to seal, those marked `personal` now offered by name. + * Any event and field names for the untyped `Registry`. */ export type RedactionTarget = Registry extends R ? RedactedFields diff --git a/packages/core/test-types/inference.test-d.ts b/packages/core/test-types/inference.test-d.ts index bc11716ac..59ef890ba 100644 --- a/packages/core/test-types/inference.test-d.ts +++ b/packages/core/test-types/inference.test-d.ts @@ -1661,7 +1661,7 @@ describe("personal data", () => { void app.unrestrict("c-1", { notice: "given" }); }); - it("lets every client redact the personal fields of a person's events, typed by event type", () => { + it("lets every client redact the fields of a person's events, offering those each event type marks personal", () => { expectTypeOf["redact"]>().toEqualTypeOf< (personId: string, options: RedactOptions) => Promise >(); @@ -1672,9 +1672,18 @@ describe("personal data", () => { expectTypeOf>().toEqualTypeOf< | RedactedFields<"customer", "CustomerRegistered", "email"> | RedactedFields<"order", "OrderPlaced", "note"> + | RedactedFields<"order", "OrderCancelled", never> + | RedactedFields<"order", "OrderPaid", never> | RedactedFields<"order", "OrderNoteAdded", string> | RedactedFields<"process:order.orderPayment", ProcessStateEventType, "contact"> >(); + // The fields an event type marks are offered by name, beside any other. + expectTypeOf< + Extract, { readonly type: "OrderPlaced" }>["fields"][number] + >().toEqualTypeOf<"note" | (string & {})>(); + expectTypeOf< + Extract, { readonly type: "OrderPaid" }>["fields"][number] + >().toEqualTypeOf(); expectTypeOf>().toEqualTypeOf(); expectTypeOf().toEqualTypeOf<{ readonly aggregateType: string; @@ -1700,18 +1709,12 @@ describe("personal data", () => { const placed = { aggregateType: "order", aggregateId: "o-1", id: "e-1" } as const; // @ts-expect-error a redaction names the events to reach void app.redact("c-1", {}); - // @ts-expect-error a field the event does not mark personal + // A field the event type marks no more, sealed under an earlier mark, of a type marking nothing + // now included: the stored event decides, and redact refuses one it holds in the clear. void app.redact("c-1", { events: [{ ...placed, type: "OrderPlaced", fields: ["total"] }] }); - // @ts-expect-error an event type that marks no personal field void app.redact("c-1", { events: [{ ...placed, type: "OrderPaid", fields: ["reference"] }] }); - const otherField = { - ...placed, - aggregateType: "customer", - type: "CustomerRegistered", - fields: ["note"], - } as const; - // @ts-expect-error a field of another event type - void app.redact("c-1", { events: [otherField] }); + // @ts-expect-error an event type the aggregate does not have + void app.redact("c-1", { events: [{ ...placed, type: "OrderShipped", fields: ["note"] }] }); const stateless = { ...placed, aggregateType: "process:order.orderPayment", From c29f76ed4b59c0736549b8f7281c264c7f7f5f61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 11:38:33 +0100 Subject: [PATCH 13/33] test(core): pin that a rebuild refuses a retired type whose recorded marks seal in a dropped category --- .../personal-data/retired-marks-app.test.ts | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts index f51eeca17..5bfa9388b 100644 --- a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts +++ b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts @@ -17,7 +17,9 @@ import { memory } from "../../memory/index.ts"; import { createMemoryTenantKeyStore } from "../../memory/tenant-key-store.ts"; import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; import type { Registry } from "../../modules/registry.ts"; +import type { FieldsArgs } from "../../modules/view.ts"; import { type BoundaApp, createApp } from "../app.ts"; +import { rebuildReadModel } from "../read-model/rebuild.ts"; import { ledgerFor } from "../test-support.ts"; import { BACKFILL_FOLLOW_INTERVAL_MS, BACKFILL_LEASE_MS } from "./backfill.ts"; import { categoryOf, isSealed } from "./crypto.ts"; @@ -507,7 +509,7 @@ describe.each(adapters)("the marks a start records, on %s", (_name, adapterOf) = await expect(prune()).resolves.toBeDefined(); }); - it("refuses to retire a type and drop the category its recorded marks seal in, in one deploy, naming both, and starts once the category is retired", async () => { + it("refuses to retire a type and drop the category its recorded marks seal in, in one deploy, naming both, at start, prune and rebuild, and starts once the category is retired", async () => { const adapter = adapterOf(); const first = await start(adapter, "invoices"); await send(first.app, "registerCustomer", { customerId: "c-1", name: "Ana" }); @@ -544,6 +546,23 @@ describe.each(adapters)("the marks a start records, on %s", (_name, adapterOf) = now: new Date(START.getTime() + 32 * 86_400_000), }), ).rejects.toThrow(refusal); + const customers = { + view: { + fields: ({ f }: FieldsArgs) => ({ customerId: f.string().primaryKey().notPersonal() }), + }, + projections: { customer: { customerRegistered: { project: () => undefined } } }, + queries: {}, + }; + await expect( + rebuildReadModel({ + registry: { ...registryOf("retired", "dropped"), readModels: { customers } } as never, + config: { + storage: adapter, + runtime: { personalData: { forgetLedger: { store: ledgerFor(adapter) } } }, + } as Config, + name: "customers", + }), + ).rejects.toThrow(refusal); const { app } = await start(adapter, "retired", undefined, { invoices: "retired" }); await app.runUntilIdle(); From ae1355d712b8caec66eab0ff25b18069cfa4d511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 11:39:35 +0100 Subject: [PATCH 14/33] fix(core): keep a redaction's fields one type, so a generic registry's targets stay assignable to RedactedFields --- packages/core/src/modules/redaction.ts | 5 +---- packages/core/test-types/inference.test-d.ts | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/core/src/modules/redaction.ts b/packages/core/src/modules/redaction.ts index 1a00bcb90..438e98bcd 100644 --- a/packages/core/src/modules/redaction.ts +++ b/packages/core/src/modules/redaction.ts @@ -29,12 +29,9 @@ export interface RedactedFields< readonly aggregateId: string; readonly type: Type; readonly id: string; - readonly fields: readonly FieldName[]; + readonly fields: readonly (Field | (string & {}))[]; } -// The fields marked now, offered by name, beside any other: `string` alone where any field is. -type FieldName = string extends Field ? string : Field | (string & {}); - type EventTargetsOf = { [Key in keyof Events & string]: RedactedFields< Aggregate, diff --git a/packages/core/test-types/inference.test-d.ts b/packages/core/test-types/inference.test-d.ts index 59ef890ba..41685f27a 100644 --- a/packages/core/test-types/inference.test-d.ts +++ b/packages/core/test-types/inference.test-d.ts @@ -1690,7 +1690,7 @@ describe("personal data", () => { readonly aggregateId: string; readonly type: string; readonly id: string; - readonly fields: readonly string[]; + readonly fields: readonly (string | (string & {}))[]; }>(); expectTypeOf().toEqualTypeOf< "ProcessStarted" | "ProcessHandled" | "ProcessDeadlineReached" | "ProcessTimedOut" From 48de3a0d00c4f9daa5ea6cb9aac4583fc7263469 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 11:40:45 +0100 Subject: [PATCH 15/33] docs(core): say where a retired personal-data category is named, in the public types that take or report it --- packages/core/src/modules/personal-data.ts | 23 +++++++++++-------- packages/core/src/testing/expect-forgotten.ts | 4 ++-- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/packages/core/src/modules/personal-data.ts b/packages/core/src/modules/personal-data.ts index 6dbf52246..d2b492e5f 100644 --- a/packages/core/src/modules/personal-data.ts +++ b/packages/core/src/modules/personal-data.ts @@ -324,10 +324,12 @@ export interface PersonalDataModule { export type PersonalCategoryName = AppPersonalCategory | typeof DEFAULT_PERSONAL_CATEGORY; /** - * A category `bounda.personal-data.ts` retired: nothing marks or decides on it any more, while what - * was marked in it before is forgotten, restricted and lifted by its name, as `forget`, `restrict` - * and `unrestrict` take it beside a `PersonalCategoryName`, and every forgetting, restriction, - * redaction and export that reaches it names it. + * A category `bounda.personal-data.ts` retired: nothing marks, decides on, returns or sends it any + * more, while what was marked in it before is kept under its retention and exemptions and is + * forgotten, restricted and lifted by its name, as `forget`, `restrict`, `unrestrict` and + * `expectForgotten` take it beside a `PersonalCategoryName`. Every forgetting, restriction, + * redaction, recipient notice and export that reaches it names it. `never` without retired + * categories. */ export type RetiredPersonalCategoryName = AppRetiredPersonalCategory; @@ -339,7 +341,8 @@ export interface ForgetOptions { * Forgets these categories of the person and nothing else, as when they withdraw a consent or * object to direct marketing: their keys go, the rest stays readable, and the person is not * forgotten as a whole. Without it, every category is. A category an exemption of article 17(3) - * applies to is kept, restricted, until its retention ends, either way. + * applies to is kept, restricted, until its retention ends, either way. A retired category is + * named as any other. */ readonly categories?: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; /** @@ -505,7 +508,8 @@ export type PersonalCategoriesOf = { string; /** - * The names of the categories a `bounda.personal-data.ts` module retired. + * The names of the categories a `bounda.personal-data.ts` module retired, those declared with + * `retired: true`, which `PersonalCategoriesOf` leaves out. */ export type RetiredPersonalCategoriesOf = { [Name in keyof CategoriesOf]: IsRetired[Name]> extends true @@ -660,7 +664,8 @@ export type RestrictOptions = readonly ground: Exclude; /** * Restricts these categories of the person alone, as when they contest the accuracy of one - * kind of data. Without it, the person as a whole is restricted, every category included. + * kind of data, a retired one included. Without it, the person as a whole is restricted, + * every category included. */ readonly categories?: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; } @@ -703,8 +708,8 @@ export interface UnrestrictOptions { */ readonly ground?: RestrictionGround; /** - * Lifts these categories alone from restrictions of categories; every category when omitted. A - * restriction of the person as a whole is lifted as a whole. + * Lifts these categories alone from restrictions of categories, a retired one included; every + * category when omitted. A restriction of the person as a whole is lifted as a whole. */ readonly categories?: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; } diff --git a/packages/core/src/testing/expect-forgotten.ts b/packages/core/src/testing/expect-forgotten.ts index ed93070e6..e4abeadbe 100644 --- a/packages/core/src/testing/expect-forgotten.ts +++ b/packages/core/src/testing/expect-forgotten.ts @@ -89,8 +89,8 @@ export interface ExpectForgottenOptions { /** * Checks only these categories, as after `forget(personId, { categories })`: what was sealed or * kept of the person in them, and the fields of `before` in them, are looked for, and the - * person must hold no key in force of them. Without it, every category the person no longer - * holds a key of. + * person must hold no key in force of them; a retired category is named as any other. Without + * it, every category the person no longer holds a key of. */ readonly categories?: readonly (PersonalCategoryName | RetiredPersonalCategoryName)[]; } From d80109a0722eb7c6b04a8dca5969aafee9a9ad39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 12:47:26 +0100 Subject: [PATCH 16/33] fix(core): seal a retired type's failures for whom the marks the store holds name when they are filed (EV2-ai) A delayed policy's dead letter and a subscriber's last failure named the person of a retired type's event by the sets of marks the start read. A walk of other code that caught up alone since may name another. Both now read the sets afresh; the letter's commit reads them again in its transaction, which runs one at a time with the one a walk records its sets sealed in, and seals the letter again when they name someone else. Policies and processes react to no retired type, so their letters never name one. --- packages/core/src/kernel/app.ts | 1 + .../src/kernel/dispatch/last-failures.test.ts | 33 +++++- .../core/src/kernel/dispatch/last-failures.ts | 12 +- .../kernel/personal-data/fresh-marks.test.ts | 36 ++++++ .../src/kernel/personal-data/fresh-marks.ts | 30 +++++ .../core/src/kernel/scheduler/worker.test.ts | 104 ++++++++++++++++++ packages/core/src/kernel/scheduler/worker.ts | 57 +++++++--- packages/core/src/kernel/test-support.ts | 67 +++++++++++ 8 files changed, 323 insertions(+), 17 deletions(-) create mode 100644 packages/core/src/kernel/personal-data/fresh-marks.test.ts diff --git a/packages/core/src/kernel/app.ts b/packages/core/src/kernel/app.ts index 05b86a747..568039f15 100644 --- a/packages/core/src/kernel/app.ts +++ b/packages/core/src/kernel/app.ts @@ -2306,6 +2306,7 @@ export const assembleApp: AssembleAppFunction = async ({ ...(storage.notifier === undefined ? {} : { notifier: storage.notifier }), lastFailures: createLastFailures({ store: written.subscriberFailures, + eventStore: storage.eventStore, aggregates, keys: storage.personalKeys, logger, diff --git a/packages/core/src/kernel/dispatch/last-failures.test.ts b/packages/core/src/kernel/dispatch/last-failures.test.ts index 08e7d658e..a981b572e 100644 --- a/packages/core/src/kernel/dispatch/last-failures.test.ts +++ b/packages/core/src/kernel/dispatch/last-failures.test.ts @@ -3,7 +3,13 @@ import { testMetadata } from "../../adapter/testing/fixtures.ts"; import type { StoredEvent } from "../../contracts/event.ts"; import { memory } from "../../memory/index.ts"; import { buildAggregates } from "../aggregate/build-aggregates.ts"; -import { createRecordingLogger, testWrapping } from "../test-support.ts"; +import { + createRecordingLogger, + retiredNote, + retiredNoteMarks, + retiredNoteRegistry, + testWrapping, +} from "../test-support.ts"; import { createLastFailures } from "./last-failures.ts"; const event: StoredEvent = { @@ -30,6 +36,7 @@ const setUp = async () => { }; const lastFailures = createLastFailures({ store: failing, + eventStore: storage.eventStore, aggregates: buildAggregates({ registry: { aggregates: {}, readModels: {} }, ports: {} }), keys, logger, @@ -61,6 +68,7 @@ describe("createLastFailures", () => { const storage = await memory().createStorage(); const lastFailures = createLastFailures({ store: storage.subscriberFailures, + eventStore: storage.eventStore, aggregates: buildAggregates({ registry: { aggregates: {}, readModels: {} }, ports: {} }), keys: testWrapping().over(storage.personalKeys), logger: createRecordingLogger("omit").logger, @@ -76,4 +84,27 @@ describe("createLastFailures", () => { errorMessage: "cannot total 5", }); }); + + it("names a retired type's failure by the sets the store holds when it records it, not those the start read", async () => { + const storage = await memory().createStorage(); + const { started, moved } = await retiredNoteMarks( + storage.eventStore, + buildAggregates({ registry: retiredNoteRegistry, ports: {} }), + ); + const lastFailures = createLastFailures({ + store: storage.subscriberFailures, + eventStore: storage.eventStore, + aggregates: started, + keys: testWrapping().over(storage.personalKeys), + logger: createRecordingLogger("omit").logger, + }); + await moved(); + await lastFailures.record({ + subscriber: "projection:x", + event: retiredNote, + error: new Error("cannot read the note"), + at: new Date("2026-01-01T00:00:00.000Z"), + }); + expect(await storage.subscriberFailures.get("projection:x")).toMatchObject({ person: "o-1" }); + }); }); diff --git a/packages/core/src/kernel/dispatch/last-failures.ts b/packages/core/src/kernel/dispatch/last-failures.ts index e32fc4475..2e26fae9e 100644 --- a/packages/core/src/kernel/dispatch/last-failures.ts +++ b/packages/core/src/kernel/dispatch/last-failures.ts @@ -1,3 +1,4 @@ +import type { EventStore } from "../../adapter/storage/event-store.ts"; import type { SubscriberFailureStore } from "../../adapter/storage/subscriber-failure-store.ts"; import { SchemaAheadError } from "../../contracts/errors.ts"; import type { StoredEvent } from "../../contracts/event.ts"; @@ -5,7 +6,7 @@ import type { Logger } from "../../contracts/logger.ts"; import type { AggregatesRuntime } from "../aggregate/runtime.ts"; import { sealError } from "../personal-data/errors.ts"; import { openedUnder } from "../personal-data/event-store.ts"; -import { personOfEvent } from "../personal-data/persons.ts"; +import { personOfEventNow } from "../personal-data/fresh-marks.ts"; import type { PersonalKeys } from "../personal-data/wrapped-keys.ts"; export interface RecordLastFailureArgs { @@ -36,6 +37,10 @@ export interface LastFailures { export interface CreateLastFailuresArgs { readonly store: SubscriberFailureStore; + /** + * Where the sets of marks a retired type's event names its person by are read, each time. + */ + readonly eventStore: Pick; readonly aggregates: AggregatesRuntime; readonly keys: PersonalKeys; readonly logger: Logger; @@ -47,6 +52,7 @@ export interface CreateLastFailuresFunction { export const createLastFailures: CreateLastFailuresFunction = ({ store, + eventStore, aggregates, keys, logger, @@ -57,7 +63,9 @@ export const createLastFailures: CreateLastFailuresFunction = ({ // nothing any more, names nobody, and a person without a key would seal the text for good. // An event newer code wrote is named by marks this code does not know, so by its writer. const person = - error instanceof SchemaAheadError ? event.person : personOfEvent({ aggregates, event }); + error instanceof SchemaAheadError + ? event.person + : await personOfEventNow({ eventStore, aggregates, event }); await store.record({ subscriber, position: event.position, diff --git a/packages/core/src/kernel/personal-data/fresh-marks.test.ts b/packages/core/src/kernel/personal-data/fresh-marks.test.ts new file mode 100644 index 000000000..d4fc900df --- /dev/null +++ b/packages/core/src/kernel/personal-data/fresh-marks.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { memory } from "../../memory/index.ts"; +import { buildAggregates } from "../aggregate/build-aggregates.ts"; +import { retiredNote, retiredNoteMarks, retiredNoteRegistry } from "../test-support.ts"; +import { personOfEventNow } from "./fresh-marks.ts"; +import { personOfEvent } from "./persons.ts"; + +const setUp = async () => { + const storage = await memory().createStorage(); + const aggregates = buildAggregates({ registry: retiredNoteRegistry, ports: {} }); + return { storage, ...(await retiredNoteMarks(storage.eventStore, aggregates)) }; +}; + +describe("personOfEventNow", () => { + it("names a retired type's person as the sets the store holds now name them, not as a start read them", async () => { + const { storage, started, moved } = await setUp(); + const now = () => + personOfEventNow({ eventStore: storage.eventStore, aggregates: started, event: retiredNote }); + expect(await now()).toBe("a-1"); + await moved(); + expect(personOfEvent({ aggregates: started, event: retiredNote })).toBe("a-1"); + expect(await now()).toBe("o-1"); + }); + + it("reads nothing for a type that is not retired, nor for an aggregate the app does not know", async () => { + const { started } = await setUp(); + const unread = { + marksOf: () => Promise.reject(new Error("read")), + types: () => Promise.reject(new Error("read")), + }; + const of = (event: typeof retiredNote) => + personOfEventNow({ eventStore: unread, aggregates: started, event }); + expect(await of({ ...retiredNote, type: "OrderPlaced" })).toBeNull(); + expect(await of({ ...retiredNote, aggregateType: "invoice" })).toBeNull(); + }); +}); diff --git a/packages/core/src/kernel/personal-data/fresh-marks.ts b/packages/core/src/kernel/personal-data/fresh-marks.ts index f78e01e7f..ea72fd1a5 100644 --- a/packages/core/src/kernel/personal-data/fresh-marks.ts +++ b/packages/core/src/kernel/personal-data/fresh-marks.ts @@ -1,6 +1,8 @@ import type { EventStore } from "../../adapter/storage/event-store.ts"; +import type { StoredEvent } from "../../contracts/event.ts"; import type { AggregatesRuntime } from "../aggregate/runtime.ts"; import { checkRetiredMarks } from "../aggregate/stored-types.ts"; +import { personOfEvent } from "./persons.ts"; import { withStoredMarks } from "./stored-marks.ts"; export interface WithFreshMarksArgs { @@ -29,3 +31,31 @@ export const withFreshMarks: WithFreshMarksFunction = async ({ eventStore, aggre checkRetiredMarks({ types: await eventStore.types(), aggregates: fresh }); return fresh; }; + +export interface PersonOfEventNowArgs extends WithFreshMarksArgs { + /** + * As it was handed out. + */ + readonly event: StoredEvent; +} + +export interface PersonOfEventNowFunction { + (args: PersonOfEventNowArgs): Promise; +} + +/** + * `personOfEvent`, a retired type's by the sets the store holds now, as `withFreshMarks` reads + * them: what a failure is sealed for. Reads nothing for any other type. + */ +export const personOfEventNow: PersonOfEventNowFunction = async ({ + eventStore, + aggregates, + event, +}) => + personOfEvent({ + aggregates: + aggregates.byName[event.aggregateType]?.retired.has(event.type) === true + ? await withFreshMarks({ eventStore, aggregates }) + : aggregates, + event, + }); diff --git a/packages/core/src/kernel/scheduler/worker.test.ts b/packages/core/src/kernel/scheduler/worker.test.ts index f28d6beb3..591682979 100644 --- a/packages/core/src/kernel/scheduler/worker.test.ts +++ b/packages/core/src/kernel/scheduler/worker.test.ts @@ -1,12 +1,17 @@ import { describe, expect, it, vi } from "vitest"; +import type { Adapter } from "../../adapter/adapter.ts"; +import type { EventStore } from "../../adapter/storage/event-store.ts"; import type { ClaimedCommand } from "../../adapter/storage/scheduler.ts"; +import { pendingEvent, testContext } from "../../adapter/testing/fixtures.ts"; import type { RuntimeConfig } from "../../config/types.ts"; import { ConcurrencyError, ValidationError } from "../../contracts/errors.ts"; +import { memory } from "../../memory/index.ts"; import { SCHEDULED_COMMAND_FAILED_EVENT } from "../../modules/bounda-events.ts"; import type { RejectFunction } from "../../modules/command.ts"; import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; import type { Registry } from "../../modules/registry.ts"; import { createTestApp } from "../../testing/index.ts"; +import { DELAYED_POLICY_COMMAND } from "../policy/delayed.ts"; import { createReactiveHarness } from "../reactive-harness.ts"; import { ATTRIBUTES, METRICS } from "../telemetry.ts"; import { installFakeTelemetry } from "../telemetry-fake.ts"; @@ -18,6 +23,9 @@ import { orderAggregateEntry, orderRegistry, placeOrderKeys, + retiredNote, + retiredNoteMarks, + retiredNoteRegistry, sentMessages, slowJob, } from "../test-support.ts"; @@ -1369,3 +1377,99 @@ describe("scheduled command payload", () => { expect(await harness.storage.scheduler.list()).toEqual([]); }); }); + +describe("a delayed policy's letter on a retired type's event", () => { + // The memory adapter, whose storage runs what `afterRead` holds once, after the next read of the + // marks outside a transaction returns. + const withAfterRead = () => { + const hooks: { afterRead?: () => Promise } = {}; + const base = memory(); + const adapter: Adapter = { + ...base, + createStorage: async () => { + const storage = await base.createStorage(); + const marksOf: EventStore["marksOf"] = async (args) => { + const read = await storage.eventStore.marksOf(args); + const hook = hooks.afterRead; + delete hooks.afterRead; + await hook?.(); + return read; + }; + return { + ...storage, + eventStore: new Proxy(storage.eventStore, { + get: (target, property, receiver) => + property === "marksOf" ? marksOf : Reflect.get(target, property, receiver), + }), + }; + }, + }; + return { adapter, hooks }; + }; + + // A run of a policy the registry no longer holds, on `retiredNote`, due now, which fails for good; + // the aggregates as a start read the marks, the agent's set sealed last. + const setUp = async (adapter: Adapter) => { + const harness = await createReactiveHarness({ registry: retiredNoteRegistry, adapter }); + await harness.storage.eventStore.append({ + aggregateType: "order", + aggregateId: "o-1", + expectedVersion: 0, + events: [ + pendingEvent({ + aggregateId: "o-1", + version: 1, + type: "OrderNoted", + payload: retiredNote.payload, + }), + ], + }); + const { started, moved } = await retiredNoteMarks( + harness.storage.eventStore, + harness.aggregates, + ); + Object.assign(harness.aggregates, { storedMarks: started.storedMarks }); + await harness.storage.scheduler.schedule({ + dedupeKey: `policy:order.noteReminder:${retiredNote.id}`, + command: { + type: DELAYED_POLICY_COMMAND, + aggregateId: "o-1", + payload: { + policy: "order.noteReminder", + eventId: retiredNote.id, + eventType: "OrderNoted", + aggregateType: "order", + position: retiredNote.position, + }, + }, + executeAt: harness.clock.now(), + scheduledAt: harness.clock.now(), + context: testContext, + }); + return { harness, moved }; + }; + + it("names whom the sets the store holds name when it files it, not those the start read", async () => { + const { harness, moved } = await setUp(memory()); + await moved(); + expect(await harness.worker.runOnce()).toBe(1); + expect(await harness.storage.deadLetterStore.list()).toMatchObject([ + { kind: "policy", handler: "order.noteReminder", person: "o-1" }, + ]); + }); + + it("is sealed again for whom they name once a walk of other code caught up alone between its sealing and its commit", async () => { + const { adapter, hooks } = withAfterRead(); + const { harness, moved } = await setUp(adapter); + hooks.afterRead = moved; + const renew = vi.spyOn(harness.storage.scheduler, "renew"); + expect(await harness.worker.runOnce()).toBe(1); + expect(hooks.afterRead).toBeUndefined(); + // It holds its claim before it files the letter again. + expect(renew).toHaveBeenCalledTimes(1); + expect(await harness.storage.deadLetterStore.list()).toMatchObject([ + { kind: "policy", handler: "order.noteReminder", person: "o-1" }, + ]); + expect(await harness.storage.scheduler.list()).toEqual([]); + }); +}); diff --git a/packages/core/src/kernel/scheduler/worker.ts b/packages/core/src/kernel/scheduler/worker.ts index be710add6..e43c00658 100644 --- a/packages/core/src/kernel/scheduler/worker.ts +++ b/packages/core/src/kernel/scheduler/worker.ts @@ -2,6 +2,7 @@ import type { DeadLetterErrorType, NewDeadLetter, } from "../../adapter/storage/dead-letter-store.ts"; +import type { EventStore } from "../../adapter/storage/event-store.ts"; import type { ClaimedCommand, ScheduledCommand } from "../../adapter/storage/scheduler.ts"; import type { ResolvedConfig, ResolvedRetryConfig } from "../../config/types.ts"; import type { Clock } from "../../contracts/clock.ts"; @@ -26,8 +27,8 @@ import type { PersonalDataBackfill } from "../personal-data/backfill.ts"; import { openCommandPayload } from "../personal-data/commands.ts"; import { sealError } from "../personal-data/errors.ts"; import { openedUnder } from "../personal-data/event-store.ts"; +import { personOfEventNow } from "../personal-data/fresh-marks.ts"; import type { ForgetIntentions } from "../personal-data/intention.ts"; -import { personOfEvent } from "../personal-data/persons.ts"; import type { ForgetLedgerReconciliation } from "../personal-data/reconciliation.ts"; import { REDACTION_SCRUB_COMMAND, type RedactionScrubPayload } from "../personal-data/redaction.ts"; import { restrictedPersonOf } from "../personal-data/refusal.ts"; @@ -201,6 +202,9 @@ class RenewFailed extends Error { } } +// Ends the commit that files a letter whose person the sets the store holds no longer name. +class MarksMoved extends Error {} + /** * Rounds a due deadline, or a restricted retry, waits for the reactive runners to catch up before * it runs anyway. @@ -395,16 +399,17 @@ export const createScheduledCommandWorker: CreateScheduledCommandWorkerFunction }; // Whom the entry's work names: the person of the event a delayed policy ran on, as its handler - // read it, or the one the payload was sealed for. - const personOf = ( + // read it and the sets `eventStore` holds name it, or the one the payload was sealed for. + const personOf = async ( entry: ScheduledCommand, event: StoredEvent | undefined, error: unknown, - ): string | null => { + eventStore: Pick, + ): Promise => { const refused = restrictedPersonOf(error); if (refused !== null) return refused; if (!delayedPolicies.isDelayedPolicy(entry)) return entry.persons?.[0]?.person ?? null; - return event === undefined ? null : personOfEvent({ aggregates, event }); + return event === undefined ? null : personOfEventNow({ eventStore, aggregates, event }); }; const letterOf = async ( @@ -414,7 +419,7 @@ export const createScheduledCommandWorker: CreateScheduledCommandWorkerFunction reason: DeadLetterErrorType, event: StoredEvent | undefined, ): Promise => { - const person = personOf(entry, event, error); + const person = await personOf(entry, event, error, storage.eventStore); // A scheduled command's payload needs nothing here: a forget cancels the command, so this run // has lost its claim and files no letter. const sealed = await sealError({ @@ -521,14 +526,38 @@ export const createScheduledCommandWorker: CreateScheduledCommandWorkerFunction }); return; } - const letter = await letterOf(entry, error, attempts, reason, event); - await settled(entry, async (unit) => { - if (!delayedPolicies.isDelayedPolicy(entry)) - await recordFailure(unit, entry, error, attempts); - await unit.deadLetterStore.add(letter); - await unit.scheduler.fail({ claim: entry, error: errorLabel(letter) }); - }); - dropped(entry, letter, error); + dropped(entry, await fileLetter(entry, error, attempts, reason, event), error); + }; + + // The letter is sealed for whom the sets the store holds name, read before it; the transaction + // that files it runs one at a time with the one a walk records its sets sealed in, so it reads + // them again, and a letter whose person they no longer name is sealed again. + const fileLetter = async ( + entry: ClaimedCommand, + error: unknown, + attempts: number, + reason: DeadLetterErrorType, + event: StoredEvent | undefined, + ): Promise => { + for (;;) { + const letter = await letterOf(entry, error, attempts, reason, event); + try { + await settled(entry, async (unit) => { + if (!delayedPolicies.isDelayedPolicy(entry)) + await recordFailure(unit, entry, error, attempts); + await unit.deadLetterStore.add(letter); + await unit.scheduler.fail({ claim: entry, error: errorLabel(letter) }); + unit.atCommit(async (transaction) => { + const person = await personOf(entry, event, error, transaction.eventStore); + if (person !== letter.person) throw new MarksMoved(); + }); + }); + return letter; + } catch (thrown) { + if (!(thrown instanceof MarksMoved)) throw thrown; + await renew(entry); + } + } }; const run = ( diff --git a/packages/core/src/kernel/test-support.ts b/packages/core/src/kernel/test-support.ts index 8cfb65752..5dc74b693 100644 --- a/packages/core/src/kernel/test-support.ts +++ b/packages/core/src/kernel/test-support.ts @@ -5,11 +5,13 @@ import type { ForgetLedger } from "../adapter/storage/forget-ledger.ts"; import type { PersonalKeyStore, StoredPersonalKey } from "../adapter/storage/personal-key-store.ts"; import type { TenancyStore } from "../adapter/storage/tenancy-store.ts"; import type { TenantKeyStore } from "../adapter/storage/tenant-key-store.ts"; +import { testMetadata } from "../adapter/testing/fixtures.ts"; import { selectImplementations } from "../config/ports.ts"; import { resolveConfig } from "../config/schema.ts"; import type { Config, ErrorText, PortsConfig, ResolvedConfig } from "../config/types.ts"; import { type Clock, createFixedClock, type FixedClock } from "../contracts/clock.ts"; import type { CommandRejection } from "../contracts/command.ts"; +import type { StoredEvent } from "../contracts/event.ts"; import { createSequentialIdGenerator, type IdGenerator } from "../contracts/ids.ts"; import { type LogFields, type Logger, silentLogger } from "../contracts/logger.ts"; import { memory } from "../memory/index.ts"; @@ -37,6 +39,7 @@ import { buildKeyWrapper, type CryptoKeyWrapper } from "./personal-data/key-wrap import { FORGET_LEDGER_STORE_MARK, landedRowIn, landedRowOf } from "./personal-data/landing.ts"; import { ephemeralMasterKey } from "./personal-data/master-key.ts"; import { marksFingerprint } from "./personal-data/resealing.ts"; +import { marksSetFingerprint, withStoredMarks } from "./personal-data/stored-marks.ts"; import { openTenantKeys, type TenantKeys } from "./personal-data/tenant-keys.ts"; import { type CategoryKey, @@ -791,3 +794,67 @@ export const racedAdapter: RacedAdapterFunction = (adapter, race) => { }); return { ...adapter, createStorage: async () => raced(await adapter.createStorage()) }; }; + +/** + * An order aggregate that retired `OrderNoted`, whose stored sets of marks name the note's person + * differently: by its `agentId`, or the order itself. + */ +export const retiredNoteRegistry: Registry = { + aggregates: { + order: { + events: { orderPlaced: { evolve: () => ({}) } }, + commands: {}, + retired: { orderNoted: { retired: true } }, + policies: {}, + processes: {}, + }, + }, + readModels: {}, +} as unknown as Registry; + +const noteSet = (person: string | null) => { + const marks = { person, fields: ["note"], categories: { note: "default" } }; + return { + aggregateType: "order", + type: "OrderNoted", + fingerprint: marksSetFingerprint(marks), + marks, + }; +}; + +/** + * A retired `OrderNoted` stored naming nobody, its note in the clear: the agent's by the set that + * names the agent, the order's by the one that names the order. + */ +export const retiredNote: StoredEvent = { + id: "order-o-1-1", + aggregateType: "order", + aggregateId: "o-1", + version: 1, + position: 1, + type: "OrderNoted", + payload: { agentId: "a-1", note: "call after five" }, + timestamp: "2026-01-01T00:00:00.000Z", + metadata: testMetadata, + person: null, +}; + +/** + * Records both sets of `retiredNote`'s type in `eventStore`, the agent's sealed last, and + * resolves to the aggregates as a start reads them, then to what moves the authority to the + * order's set, as a walk of other code that catches up alone does. + */ +export const retiredNoteMarks = async ( + eventStore: EventStore, + aggregates: AggregatesRuntime, +): Promise<{ readonly started: AggregatesRuntime; readonly moved: () => Promise }> => { + await eventStore.recordMarks({ + marks: [noteSet("agentId"), noteSet(null)], + at: "2026-01-01T00:00:00.000Z", + }); + await eventStore.recordSealed({ sets: [noteSet("agentId")], through: 1 }); + return { + started: withStoredMarks(aggregates, await eventStore.marksOf()), + moved: () => eventStore.recordSealed({ sets: [noteSet(null)], through: 2 }), + }; +}; From a2238f72b209bacc0256d44af5f0abc23b8419ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 12:49:44 +0100 Subject: [PATCH 17/33] refactor(core): name the categories the kernel writes as declared or retired, not declared only (EV2-ak) A forgetting, a restriction or a recipient notice may name a retired category; the casts that built their payloads said a declared one. --- .../core/src/kernel/personal-data/categories.ts | 7 +++++++ packages/core/src/kernel/personal-data/forget.ts | 13 +++++-------- .../src/kernel/personal-data/forgotten-tenant.ts | 6 +++--- packages/core/src/kernel/personal-data/redaction.ts | 6 ++---- .../core/src/kernel/personal-data/restriction.ts | 10 +++++----- .../src/kernel/personal-data/tenant-recipients.ts | 10 +++++----- packages/core/src/kernel/recipients/addressing.ts | 6 +++--- packages/core/src/kernel/recipients/listing.ts | 5 ++--- packages/core/src/kernel/recipients/notices.ts | 6 +++--- 9 files changed, 35 insertions(+), 34 deletions(-) diff --git a/packages/core/src/kernel/personal-data/categories.ts b/packages/core/src/kernel/personal-data/categories.ts index 6d8f5d62a..eb6ceda81 100644 --- a/packages/core/src/kernel/personal-data/categories.ts +++ b/packages/core/src/kernel/personal-data/categories.ts @@ -13,8 +13,10 @@ import { type ErasureExemption, LEGAL_BASES, type LegalBasis, + type PersonalCategoryName, type PersonalDataModule, type PersonalDataSource, + type RetiredPersonalCategoryName, SPECIAL_CATEGORY_CONDITIONS, SPECIAL_CATEGORY_KINDS, SPECIFIC_PURPOSES, @@ -26,6 +28,11 @@ import { import type { Registry } from "../../modules/registry.ts"; import { isRecord } from "../shared/merge-fields.ts"; +/** + * A category as the store names it: one the app declares, or one it retired. + */ +export type StoredCategoryName = PersonalCategoryName | RetiredPersonalCategoryName; + /** * A category as the runtime uses it: its basis, `null` for the default category, which declares * none, and its retention, `null` when nothing forgets it for inactivity, as the default category diff --git a/packages/core/src/kernel/personal-data/forget.ts b/packages/core/src/kernel/personal-data/forget.ts index 1b7f94b92..e81b0210f 100644 --- a/packages/core/src/kernel/personal-data/forget.ts +++ b/packages/core/src/kernel/personal-data/forget.ts @@ -14,11 +14,7 @@ import { type PersonalDataForgottenPayload, type PersonalDataForgottenReason, } from "../../modules/bounda-events.ts"; -import type { - ErasureExemption, - ForgetOptions, - PersonalCategoryName, -} from "../../modules/personal-data.ts"; +import type { ErasureExemption, ForgetOptions } from "../../modules/personal-data.ts"; import { scheduledCommandId } from "../command/pipeline.ts"; import { addressed } from "../recipients/addressing.ts"; import type { RecipientsRuntime } from "../recipients/build.ts"; @@ -33,6 +29,7 @@ import { objectable, type PersonalCategories, type PersonalCategory, + type StoredCategoryName, } from "./categories.ts"; import { coveredBy, @@ -264,11 +261,11 @@ export const forgetWithin: ForgetWithinFunction = async (args) => { categories: named.filter( (category) => gone.has(category) || (!retainedAfter.has(category) && !inForceAfter.has(category)), - ) as PersonalCategoryName[], + ) as StoredCategoryName[], retained: (scope.kind === "keys" ? [] - : named.filter((category) => retainedAfter.has(category))) as PersonalCategoryName[], - expired: [...expired] as PersonalCategoryName[], + : named.filter((category) => retainedAfter.has(category))) as StoredCategoryName[], + expired: [...expired] as StoredCategoryName[], fingerprints: [...asked.map(({ key }) => key.fingerprint), ...replaced], cancelledCommands: cancelled.map(({ dedupeKey, command }) => ({ commandId: scheduledCommandId(dedupeKey) ?? dedupeKey, diff --git a/packages/core/src/kernel/personal-data/forgotten-tenant.ts b/packages/core/src/kernel/personal-data/forgotten-tenant.ts index 038541e8f..2ee0e3530 100644 --- a/packages/core/src/kernel/personal-data/forgotten-tenant.ts +++ b/packages/core/src/kernel/personal-data/forgotten-tenant.ts @@ -13,7 +13,6 @@ import { TENANT_FORGOTTEN_EVENT, type TenantForgottenPayload, } from "../../modules/bounda-events.ts"; -import type { PersonalCategoryName } from "../../modules/personal-data.ts"; import type { NotifiedRecipient } from "../../modules/recipient.ts"; import type { Subscriber } from "../dispatch/dispatcher.ts"; import { projectionSubscriberName } from "../projection/runner.ts"; @@ -21,6 +20,7 @@ import { discloseAgain } from "../recipients/again.ts"; import { RECIPIENTS_SUBSCRIBER, type RecipientDelivery } from "../recipients/notices.ts"; import { appendSystemEvent } from "../system-events.ts"; import { appliedEntryOf } from "./applied-record.ts"; +import type { StoredCategoryName } from "./categories.ts"; import { landedCursorOf } from "./landing.ts"; import { discloseLeftAgain, type LedgersLeft } from "./ledgers-left.ts"; import { landedSince, type ReadLedger } from "./reconciled-reads.ts"; @@ -90,7 +90,7 @@ export const addressedTenant: AddressedTenantFunction = async (transaction, pres port, categories: [ ...new Set([...known, ...(presumed.get(port) ?? [])]), - ].sort() as PersonalCategoryName[], + ].sort() as StoredCategoryName[], retained: [], // Presumed to hold data no disclosure recorded: it may hold others' than `persons()` lists. presumed: presumed.has(port), @@ -287,7 +287,7 @@ export const settleTenantForgetting: SettleTenantForgettingFunction = async ({ const recipients = await addressedTenant(transaction, presumeAll ? ports : []); const payload: TenantForgottenPayload = { tenant, - categories: (await transaction.personalKeys.categories()) as PersonalCategoryName[], + categories: (await transaction.personalKeys.categories()) as StoredCategoryName[], ...(recipients.length === 0 ? {} : { recipients }), }; await appendSystemEvent({ diff --git a/packages/core/src/kernel/personal-data/redaction.ts b/packages/core/src/kernel/personal-data/redaction.ts index 5237b65c0..186002b7a 100644 --- a/packages/core/src/kernel/personal-data/redaction.ts +++ b/packages/core/src/kernel/personal-data/redaction.ts @@ -18,7 +18,6 @@ import { type RedactedEvent, type RemovedDeadLetter, } from "../../modules/bounda-events.ts"; -import type { PersonalCategoryName } from "../../modules/personal-data.ts"; import type { AggregatesRuntime } from "../aggregate/runtime.ts"; import { scheduledCommandId } from "../command/pipeline.ts"; import type { ProcessesRuntime } from "../process/build-processes.ts"; @@ -35,6 +34,7 @@ import { sameValueText, } from "../shared/value-search.ts"; import { appendSystemEvent } from "../system-events.ts"; +import type { StoredCategoryName } from "./categories.ts"; import { type KeyOfFunction, openCommandPayload, sealedKeys } from "./commands.ts"; import { categoryOf, @@ -627,9 +627,7 @@ export const redactWithin: RedactWithinFunction = async (args) => { const payload: PersonalDataRedactedPayload = { personId, events, - categories: [ - ...new Set(values.map(({ category }) => category)), - ].sort() as PersonalCategoryName[], + categories: [...new Set(values.map(({ category }) => category))].sort() as StoredCategoryName[], cancelledCommands, removedDeadLetters, }; diff --git a/packages/core/src/kernel/personal-data/restriction.ts b/packages/core/src/kernel/personal-data/restriction.ts index 311be3cf1..e3d079022 100644 --- a/packages/core/src/kernel/personal-data/restriction.ts +++ b/packages/core/src/kernel/personal-data/restriction.ts @@ -17,7 +17,6 @@ import { PROCESSING_RESTRICTION_LIFTED_EVENT, } from "../../modules/bounda-events.ts"; import { - type PersonalCategoryName, type ProcessingRestriction, RESTRICTION_GROUNDS, type RestrictionGround, @@ -36,6 +35,7 @@ import { type PersonalCategories, type PersonalCategory, pendsObjection, + type StoredCategoryName, } from "./categories.ts"; import type { ForgetIntentions } from "./intention.ts"; import { checkPersonId, throughFreeze, transactRetrying } from "./transact.ts"; @@ -86,7 +86,7 @@ export const processingRestrictionsOf: ProcessingRestrictionsOfFunction = (rows) const since = of.map((row) => row.since).sort()[0] as string; const categories = of.some((row) => row.category === null) ? null - : (of.map((row) => row.category as PersonalCategoryName).sort() as PersonalCategoryName[]); + : (of.map((row) => row.category as StoredCategoryName).sort() as StoredCategoryName[]); return [{ ground, categories, since }]; }); }; @@ -554,7 +554,7 @@ export const restrictProcessing: RestrictProcessingFunction = async ({ payload: { personId, ground, - categories: categories as readonly PersonalCategoryName[] | null, + categories: categories as readonly StoredCategoryName[] | null, restrictions: processingRestrictionsOf(after), }, }, @@ -592,7 +592,7 @@ const liftPlan = const payload = { personId, grounds: [...new Set(lifting.map((row) => row.ground))].sort(), - categories: categories as readonly PersonalCategoryName[] | null, + categories: categories as readonly StoredCategoryName[] | null, restrictions: processingRestrictionsOf(rows.filter((row) => !match(row))), }; return { @@ -669,7 +669,7 @@ export const unrestrictProcessing: UnrestrictProcessingFunction = async ({ payload: { personId, grounds, - categories: categories as readonly PersonalCategoryName[] | null, + categories: categories as readonly StoredCategoryName[] | null, liftsAt: new Date(Date.parse(at) + notice).toISOString(), }, }; diff --git a/packages/core/src/kernel/personal-data/tenant-recipients.ts b/packages/core/src/kernel/personal-data/tenant-recipients.ts index e85a37456..c996ed74c 100644 --- a/packages/core/src/kernel/personal-data/tenant-recipients.ts +++ b/packages/core/src/kernel/personal-data/tenant-recipients.ts @@ -1,10 +1,10 @@ import type { ForgottenRecipient } from "../../adapter/storage/recipient-store.ts"; import { transferText } from "../../adapter/storage/recipient-transfer.ts"; -import type { LegalBasis, PersonalCategoryName } from "../../modules/personal-data.ts"; +import type { LegalBasis } from "../../modules/personal-data.ts"; import type { CountryCode, PersonRecipient, RecipientKind } from "../../modules/recipient.ts"; import type { RecipientsRuntime } from "../recipients/build.ts"; import { recipientTransferOf } from "../recipients/transfer.ts"; -import type { PersonalCategories, PersonalCategory } from "./categories.ts"; +import type { PersonalCategories, PersonalCategory, StoredCategoryName } from "./categories.ts"; import type { TenantExportForgottenRecipient, TenantExportRecipient } from "./tenant-export.ts"; // The recipients the `person` parts list, summed as each page of them is built: it holds one entry @@ -81,7 +81,7 @@ export const tallyRecipients: TallyRecipientsFunction = ({ recipients, categorie ({ recipient, categories: named, persons, first, last }) => ({ ...recipient, categories: [...named.keys()].sort(byText).map((name) => ({ - name: name as PersonalCategoryName, + name: name as StoredCategoryName, basis: named.get(name) as LegalBasis | null, })), firstDisclosedAt: first, @@ -103,7 +103,7 @@ export const tallyRecipients: TallyRecipientsFunction = ({ recipients, categorie ...recipient, status: "declared", categories: [...declared.categories].sort(byText).map((name) => ({ - name: name as PersonalCategoryName, + name: name as StoredCategoryName, // `buildRecipients` refuses a declaration that names a category the app lacks. basis: (categories.of(name) as PersonalCategory).basis, })), @@ -175,7 +175,7 @@ export const forgottenRecipients: ForgottenRecipientsFunction = ({ ...recipient, persons, categories: [...named.keys()].sort(byText).map((name) => ({ - name: name as PersonalCategoryName, + name: name as StoredCategoryName, basis: categories.of(name)?.basis ?? null, persons: named.get(name) as number, })), diff --git a/packages/core/src/kernel/recipients/addressing.ts b/packages/core/src/kernel/recipients/addressing.ts index 6683029d7..103ab31b8 100644 --- a/packages/core/src/kernel/recipients/addressing.ts +++ b/packages/core/src/kernel/recipients/addressing.ts @@ -14,8 +14,8 @@ import { type ProcessingRestrictionLiftAnnouncedPayload, type ProcessingRestrictionLiftedPayload, } from "../../modules/bounda-events.ts"; -import type { PersonalCategoryName } from "../../modules/personal-data.ts"; import type { NotifiedRecipient } from "../../modules/recipient.ts"; +import type { StoredCategoryName } from "../personal-data/categories.ts"; /** * One of the runtime's events recipients are told of, with its payload as it would be appended. @@ -197,8 +197,8 @@ export const addressed: AddressedFunction = async (transaction, event) => { if (categories.length === 0 && retained.length === 0) continue; recipients.push({ port, - categories: categories as PersonalCategoryName[], - retained: retained as PersonalCategoryName[], + categories: categories as StoredCategoryName[], + retained: retained as StoredCategoryName[], presumed: ![...categories, ...retained].some((category) => known.has(category)), }); } diff --git a/packages/core/src/kernel/recipients/listing.ts b/packages/core/src/kernel/recipients/listing.ts index 20a44514d..04b5dcb27 100644 --- a/packages/core/src/kernel/recipients/listing.ts +++ b/packages/core/src/kernel/recipients/listing.ts @@ -5,14 +5,13 @@ import type { } from "../../adapter/storage/personal-key-store.ts"; import type { StoredDisclosure } from "../../adapter/storage/recipient-store.ts"; import { transferText } from "../../adapter/storage/recipient-transfer.ts"; -import type { PersonalCategoryName } from "../../modules/personal-data.ts"; import type { CountryCode, PersonRecipient, RecipientKind, RecipientTransfer, } from "../../modules/recipient.ts"; -import type { PersonalCategories } from "../personal-data/categories.ts"; +import type { PersonalCategories, StoredCategoryName } from "../personal-data/categories.ts"; import type { RecipientStatus } from "../status.ts"; import { presumedOf, presumedOfMany } from "./addressing.ts"; import type { RecipientsRuntime } from "./build.ts"; @@ -151,7 +150,7 @@ const recipientsFrom = ({ transfer: identity.transfer, status, categories: [...new Set(names)].sort().map((name) => ({ - name: name as PersonalCategoryName, + name: name as StoredCategoryName, basis: categories.of(name)?.basis ?? null, })), firstDisclosedAt: times.first, diff --git a/packages/core/src/kernel/recipients/notices.ts b/packages/core/src/kernel/recipients/notices.ts index 4dceb3a91..5fb92036d 100644 --- a/packages/core/src/kernel/recipients/notices.ts +++ b/packages/core/src/kernel/recipients/notices.ts @@ -10,7 +10,6 @@ import { type PersonalDataForgottenPayload, TENANT_FORGOTTEN_EVENT, } from "../../modules/bounda-events.ts"; -import type { PersonalCategoryName } from "../../modules/personal-data.ts"; import { type NotifiedRecipient, RECIPIENT_HANDLERS, @@ -19,6 +18,7 @@ import { import type { Subscriber } from "../dispatch/dispatcher.ts"; import type { AppStorage } from "../events/app-event-store.ts"; import { type RecordAccess, recorded } from "../personal-data/access.ts"; +import type { StoredCategoryName } from "../personal-data/categories.ts"; import { sealError } from "../personal-data/errors.ts"; import { keyedReturned } from "../personal-data/returned.ts"; import { bindReturns, type PortReturns } from "../ports/returns.ts"; @@ -83,8 +83,8 @@ export const presumedNotice: PresumedNoticeFunction = (recipient, event) => { if (categories.length === 0 && retained.length === 0) return undefined; return { port: recipient.port, - categories: categories as PersonalCategoryName[], - retained: retained as PersonalCategoryName[], + categories: categories as StoredCategoryName[], + retained: retained as StoredCategoryName[], presumed: true, }; }; From acbceafa376533e4f515bcc5ac7f56961a74a598 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 12:50:23 +0100 Subject: [PATCH 18/33] test(cli): pin that the inventory says a retired category is retired, end to end (EV2-al) --- .../.bounda/retired-registry.ts | 35 +++++++++++++++++++ packages/cli/src/run-inventory.test.ts | 20 +++++++++++ 2 files changed, 55 insertions(+) create mode 100644 packages/cli/src/fixtures/inventory-project/.bounda/retired-registry.ts diff --git a/packages/cli/src/fixtures/inventory-project/.bounda/retired-registry.ts b/packages/cli/src/fixtures/inventory-project/.bounda/retired-registry.ts new file mode 100644 index 000000000..a0ee7dc94 --- /dev/null +++ b/packages/cli/src/fixtures/inventory-project/.bounda/retired-registry.ts @@ -0,0 +1,35 @@ +import type { EventPayloadArgs, FieldsArgs, Registry } from "@bounda-dev/core"; + +export const registry = { + personalData: { automatedDecisions: {}, categories: { contact: { basis: "consent", retention: "730d", purposes: ["Serve the person"], sources: ["data-subject"] }, loyalty: { basis: "contract", retention: "2y", purposes: ["Reward the person"], sources: ["data-subject"], retired: true } } }, + aggregates: { + customer: { + events: { + customerRegistered: { + payload: ({ z, personal, notPersonal }: EventPayloadArgs) => + z.object({ + email: personal(z.email(), { category: "contact" }), + plan: notPersonal(z.string()), + seats: z.int(), + }), + begin: () => ({}), + }, + }, + commands: {}, + policies: {}, + processes: {}, + }, + }, + readModels: { + customers: { + view: { + fields: ({ f }: FieldsArgs) => ({ + customerId: f.string().primaryKey().person(), + email: f.string().personal({ category: "contact" }), + }), + }, + projections: {}, + queries: {}, + }, + }, +} as unknown as Registry; diff --git a/packages/cli/src/run-inventory.test.ts b/packages/cli/src/run-inventory.test.ts index 298f24179..e155d5c38 100644 --- a/packages/cli/src/run-inventory.test.ts +++ b/packages/cli/src/run-inventory.test.ts @@ -59,6 +59,26 @@ describe("bounda personal-data inventory", () => { expect(inventory.findings).toEqual([]); }); + it("says a retired category is retired, as JSON and as text", async () => { + const retired = [".bounda/retired-registry.ts"]; + const json = await cli(["personal-data", "inventory", "--json", "--registry", ...retired]); + expect(json.code).toBe(EXIT_OK); + const inventory = JSON.parse(json.stdout) as PersonalDataInventory; + expect( + inventory.categories.map(({ name, retired: isRetired }) => ({ name, retired: isRetired })), + ).toEqual( + expect.arrayContaining([ + { name: "contact", retired: false }, + { name: "loyalty", retired: true }, + ]), + ); + const text = await cli(["personal-data", "inventory", "--registry", ...retired]); + expect(text.code).toBe(EXIT_OK); + expect(text.stdout).toContain( + " loyalty (retired) contract forgotten 2y after last activity 0 fields", + ); + }); + it("prints it as a Markdown document", async () => { const { code, stdout } = await cli(["personal-data", "inventory", "--markdown"]); expect(code).toBe(EXIT_OK); From 8b438d3f42a59d6400d5550829f6dac301d6a493 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 13:11:48 +0100 Subject: [PATCH 19/33] fix(core,postgresql)!: record every category a stored write names, not only those keys were added in (EV2-aj) A category only a restriction, a forgetting, a redaction, a disclosure, a recipient declaration or a forget ledger entry named could be dropped from bounda.personal-data.ts without retiring it, leaving stored writes that name a category the app no longer knows. - PersonalKeyStore.recordCategories records categories in the catalogue, in the caller's transaction (memory, SQL; fenced as a write). - Runtime events, disclosures and recipient declarations record the categories they name in the transaction that writes them; forget ledger entries record theirs before the ledger takes them. - The unreleased migration (SQLite v16, PostgreSQL v17) backfills the catalogue from runtime events, restrictions, disclosures, declared recipients and forgotten counts (fillNamedCategoriesStatements). - The refusal now reads "categories the store has recorded". BREAKING CHANGE: an adapter's PersonalKeyStore implements recordCategories. --- packages/core/src/adapter/sql/index.ts | 3 + .../src/adapter/sql/personal-categories.ts | 132 +++++++++++++ .../src/adapter/sql/personal-key-store.ts | 10 +- .../core/src/adapter/sqlite/migrations.ts | 17 +- .../src/adapter/storage/personal-key-store.ts | 14 +- .../testing/personal-key-store.contract.ts | 12 ++ .../testing/storage-schema.contract.ts | 95 ++++++++++ .../testing/storage-transaction.contract.ts | 24 +++ packages/core/src/kernel/app.ts | 5 +- .../kernel/command/reaction-commands.test.ts | 2 + .../personal-data/applied-again.test.ts | 5 +- .../personal-data/applied-record.test.ts | 11 +- .../kernel/personal-data/categories.test.ts | 2 +- .../src/kernel/personal-data/categories.ts | 10 +- .../personal-data/category-ahead.test.ts | 4 +- .../src/kernel/personal-data/forget.test.ts | 4 +- .../core/src/kernel/personal-data/forget.ts | 1 + .../kernel/personal-data/forgotten-tenant.ts | 1 + .../kernel/personal-data/intention.test.ts | 63 ++++++- .../src/kernel/personal-data/intention.ts | 8 + .../personal-data/ledger-prune-app.test.ts | 2 +- .../named-categories-app.test.ts | 175 ++++++++++++++++++ .../personal-data/named-categories.test.ts | 83 +++++++++ .../kernel/personal-data/named-categories.ts | 42 +++++ .../personal-data/reconciliation.test.ts | 3 +- .../src/kernel/personal-data/redaction.ts | 1 + .../src/kernel/personal-data/restriction.ts | 2 + .../kernel/personal-data/retention.test.ts | 3 +- .../src/kernel/personal-data/wrapped-keys.ts | 1 + packages/core/src/kernel/reactive-harness.ts | 8 +- .../core/src/kernel/recipients/again.test.ts | 1 + packages/core/src/kernel/recipients/again.ts | 1 + .../core/src/kernel/recipients/gate.test.ts | 10 + packages/core/src/kernel/recipients/gate.ts | 1 + .../src/kernel/recipients/pending.test.ts | 30 ++- .../core/src/kernel/recipients/pending.ts | 21 ++- packages/core/src/kernel/scheduler/worker.ts | 1 + .../core/src/kernel/system-events.test.ts | 33 ++++ packages/core/src/kernel/system-events.ts | 9 + packages/core/src/kernel/test-support.ts | 15 +- .../core/src/memory/personal-key-store.ts | 3 + packages/core/src/memory/tenant-fence.ts | 1 + packages/core/src/memory/transaction.ts | 4 + packages/core/src/modules/personal-data.ts | 3 +- packages/postgresql/src/migrations.ts | 18 +- 45 files changed, 856 insertions(+), 38 deletions(-) create mode 100644 packages/core/src/kernel/personal-data/named-categories-app.test.ts create mode 100644 packages/core/src/kernel/personal-data/named-categories.test.ts create mode 100644 packages/core/src/kernel/personal-data/named-categories.ts diff --git a/packages/core/src/adapter/sql/index.ts b/packages/core/src/adapter/sql/index.ts index e5f1eaca9..b5ea6e6cf 100644 --- a/packages/core/src/adapter/sql/index.ts +++ b/packages/core/src/adapter/sql/index.ts @@ -130,12 +130,15 @@ export { export type { CreateSqlPersonStoreArgs, CreateSqlPersonStoreFunction } from "./person-store.ts"; export { createSqlPersonStore, WHOLE_PERSON } from "./person-store.ts"; export type { + FillNamedCategoriesStatementsArgs, + FillNamedCategoriesStatementsFunction, FillPersonalCategoriesStatementArgs, FillPersonalCategoriesStatementFunction, PersonalCategoriesTableStatementArgs, PersonalCategoriesTableStatementFunction, } from "./personal-categories.ts"; export { + fillNamedCategoriesStatements, fillPersonalCategoriesStatement, personalCategoriesTableStatement, } from "./personal-categories.ts"; diff --git a/packages/core/src/adapter/sql/personal-categories.ts b/packages/core/src/adapter/sql/personal-categories.ts index a7ce240c4..b52062967 100644 --- a/packages/core/src/adapter/sql/personal-categories.ts +++ b/packages/core/src/adapter/sql/personal-categories.ts @@ -1,3 +1,12 @@ +import { + BOUNDA_AGGREGATE, + PERSONAL_DATA_FORGOTTEN_EVENT, + PERSONAL_DATA_REDACTED_EVENT, + PROCESSING_RESTRICTED_EVENT, + PROCESSING_RESTRICTION_LIFT_ANNOUNCED_EVENT, + PROCESSING_RESTRICTION_LIFTED_EVENT, + TENANT_FORGOTTEN_EVENT, +} from "../../modules/bounda-events.ts"; import type { SqlDialect } from "./dialect.ts"; export interface PersonalCategoriesTableStatementArgs { @@ -45,3 +54,126 @@ export const fillPersonalCategoriesStatement: FillPersonalCategoriesStatementFun keys, }) => `INSERT INTO ${table} ("category") SELECT DISTINCT "category" FROM ${keys} WHERE TRUE ON CONFLICT DO NOTHING`; + +export interface FillNamedCategoriesStatementsArgs { + readonly dialect: Pick; + /** + * All already quoted. + */ + readonly table: string; + readonly events: string; + readonly restrictions: string; + readonly disclosures: string; + readonly recipients: string; + readonly forgottenRecipients: string; +} + +export interface FillNamedCategoriesStatementsFunction { + (args: FillNamedCategoriesStatementsArgs): readonly string[]; +} + +// The runtime's events whose payloads name categories, as `categoriesNamedBy` reads them. +const NAMING_TYPES = [ + PERSONAL_DATA_FORGOTTEN_EVENT, + PERSONAL_DATA_REDACTED_EVENT, + PROCESSING_RESTRICTED_EVENT, + PROCESSING_RESTRICTION_LIFT_ANNOUNCED_EVENT, + PROCESSING_RESTRICTION_LIFTED_EVENT, + TENANT_FORGOTTEN_EVENT, +]; + +interface JsonArray { + readonly from: string; + readonly where: string; +} + +// The elements of the array at `key` of `doc`, of the whole of `doc` when `key` is `null`, as rows +// of `alias`; none where it holds no array. +const arrayAt = ( + dialect: Pick, + doc: string, + key: string | null, + alias: string, +): JsonArray => { + if (dialect.name === "sqlite") { + const path = key === null ? "'$'" : `'$.${key}'`; + return { + from: `json_each(${doc}, ${path}) AS ${alias}`, + where: `json_type(${doc}, ${path}) = 'array'`, + }; + } + const value = key === null ? doc : `${doc}->'${key}'`; + return { + from: `jsonb_array_elements(CASE WHEN jsonb_typeof(${value}) = 'array' THEN ${value} ELSE '[]'::jsonb END) AS ${alias}("value")`, + where: "TRUE", + }; +}; + +const isKind = ( + dialect: Pick, + alias: string, + kind: "text" | "object", +): string => + dialect.name === "sqlite" + ? `${alias}."type" = '${kind}'` + : `jsonb_typeof(${alias}."value") = '${kind === "text" ? "string" : "object"}'`; + +const textOf = (dialect: Pick, alias: string): string => + dialect.name === "sqlite" ? `${alias}."value"` : `${alias}."value" #>> '{}'`; + +/** + * The statements that record in the catalogue every category a write the store holds names + * without a key, for the migration that makes those writes record theirs: the runtime's events, + * restrictions, disclosures, declared recipients and the counts of forgotten ones. + */ +export const fillNamedCategoriesStatements: FillNamedCategoriesStatementsFunction = ({ + dialect, + table, + events, + restrictions, + disclosures, + recipients, + forgottenRecipients, +}) => { + const insert = (select: string) => + `INSERT INTO ${table} ("category") SELECT DISTINCT ${select} ON CONFLICT DO NOTHING`; + const runtime = `e."aggregate_type" = '${BOUNDA_AGGREGATE}' AND e."type" IN (${NAMING_TYPES.map((type) => `'${type}'`).join(", ")})`; + const payload = `e."payload"`; + const listed = ["categories", "retained", "expired"].map((key) => { + const names = arrayAt(dialect, payload, key, "n"); + return insert( + `${textOf(dialect, "n")} FROM ${events} AS e, ${names.from} WHERE ${runtime} AND ${names.where} AND ${isKind(dialect, "n", "text")}`, + ); + }); + const nested = ( + [ + ["restrictions", "categories"], + ["recipients", "categories"], + ["recipients", "retained"], + ] as const + ).map(([outer, key]) => { + const entries = arrayAt(dialect, payload, outer, "o"); + const names = arrayAt(dialect, `o."value"`, key, "n"); + return insert( + `${textOf(dialect, "n")} FROM ${events} AS e, ${entries.from}, ${names.from} WHERE ${runtime} AND ${entries.where} AND ${isKind(dialect, "o", "object")} AND ${names.where} AND ${isKind(dialect, "n", "text")}`, + ); + }); + const declared = arrayAt( + dialect, + dialect.name === "sqlite" ? `r."categories"` : `r."categories"::jsonb`, + null, + "n", + ); + return [ + ...listed, + ...nested, + // The whole person is restricted under `''`, which names no category. + insert(`"category" FROM ${restrictions} WHERE "category" <> ''`), + insert(`"category" FROM ${disclosures} WHERE TRUE`), + insert( + `${textOf(dialect, "n")} FROM ${recipients} AS r, ${declared.from} WHERE ${declared.where} AND ${isKind(dialect, "n", "text")}`, + ), + // A count of every category is kept under `''`. + insert(`"category" FROM ${forgottenRecipients} WHERE "category" <> ''`), + ]; +}; diff --git a/packages/core/src/adapter/sql/personal-key-store.ts b/packages/core/src/adapter/sql/personal-key-store.ts index 6054f35f3..c9d75c80b 100644 --- a/packages/core/src/adapter/sql/personal-key-store.ts +++ b/packages/core/src/adapter/sql/personal-key-store.ts @@ -6,7 +6,7 @@ import type { } from "../storage/personal-key-store.ts"; import type { SqlDialect } from "./dialect.ts"; import { holdEndOf, holdOf, releasedBy as released } from "./hold.ts"; -import { byteOrder } from "./order.ts"; +import { byteOrder, codePointOrder } from "./order.ts"; import { WHOLE_PERSON } from "./person-store.ts"; import type { SqlExecutor } from "./sql-table.ts"; @@ -204,6 +204,14 @@ export const createSqlPersonalKeyStore: CreateSqlPersonalKeyStoreFunction = ({ (await db.all(`SELECT DISTINCT "category" FROM ${table} ORDER BY "category"`, [])).map( ({ category }) => String(category), ), + recordCategories: async (named) => { + for (const category of [...new Set(named)].sort(codePointOrder)) { + await db.run( + `INSERT INTO ${categories} ("category") VALUES (${p(1)}) ON CONFLICT DO NOTHING`, + [category], + ); + } + }, recordedCategories: async () => (await db.all(`SELECT "category" FROM ${categories} ORDER BY "category"${byCode}`, [])).map( ({ category }) => String(category), diff --git a/packages/core/src/adapter/sqlite/migrations.ts b/packages/core/src/adapter/sqlite/migrations.ts index 20e4daae2..8a711d728 100644 --- a/packages/core/src/adapter/sqlite/migrations.ts +++ b/packages/core/src/adapter/sqlite/migrations.ts @@ -39,6 +39,7 @@ import { schemaMigrationsTableFor, } from "../sql/migrations.ts"; import { + fillNamedCategoriesStatements, fillPersonalCategoriesStatement, personalCategoriesTableStatement, } from "../sql/personal-categories.ts"; @@ -315,8 +316,9 @@ const catalogue = async (tx: SqlTransaction, tables: StorageTables): Promise; /** - * Every category a key was ever added in, each once, in order, held or not: `add` records its - * category in the same transaction, and a removal keeps it. What a start reads to tell a - * category the app stopped declaring from one only newer code declares. + * Every category the store ever recorded, each once, in order, held or not: those a key was + * added in, since `add` records its category in the same transaction, and those + * `recordCategories` recorded; nothing removes one. What a start reads to tell a category the app + * stopped declaring from one only newer code declares. */ recordedCategories(): Promise; + /** + * Records each category as `add` records a key's, in the same transaction when called inside + * one: what a write that names a category with no key, as a restriction or a forgetting does, + * calls first, so `recordedCategories` names every category the store holds anything of. + * Recording one again changes nothing. + */ + recordCategories(categories: readonly string[]): Promise; /** * Removes every key of every person, and resolves to how many it removed: what forgetting the * tenant does, once its own key is gone. diff --git a/packages/core/src/adapter/testing/personal-key-store.contract.ts b/packages/core/src/adapter/testing/personal-key-store.contract.ts index 7b4274e05..77ed0b168 100644 --- a/packages/core/src/adapter/testing/personal-key-store.contract.ts +++ b/packages/core/src/adapter/testing/personal-key-store.contract.ts @@ -89,6 +89,18 @@ export const personalKeyStoreContract: PersonalKeyStoreContractFunction = ({ cre expect(await store.recordedCategories()).toEqual(["contact", D, "invoices"]); }); + it("records categories no key is added in with those keys are, each once, and keeps them", async () => { + await store.recordCategories(["marketing", "contact", "marketing"]); + expect(await store.recordedCategories()).toEqual(["contact", "marketing"]); + await store.add("c-1", "contact", stored("contact")); + await Promise.all([store.recordCategories(["profile"]), store.recordCategories(["profile"])]); + await store.recordCategories([]); + expect(await store.categories()).toEqual(["contact"]); + expect(await store.recordedCategories()).toEqual(["contact", "marketing", "profile"]); + await store.clear(); + expect(await store.recordedCategories()).toEqual(["contact", "marketing", "profile"]); + }); + it("forgets a key for good, and takes a new one for the same person afterwards", async () => { await store.add("c-1", D, stored("first")); expect(await store.remove("c-1", "f-first")).toBe(true); diff --git a/packages/core/src/adapter/testing/storage-schema.contract.ts b/packages/core/src/adapter/testing/storage-schema.contract.ts index e43c689e3..26491d969 100644 --- a/packages/core/src/adapter/testing/storage-schema.contract.ts +++ b/packages/core/src/adapter/testing/storage-schema.contract.ts @@ -692,6 +692,101 @@ export const storageSchemaContract: StorageSchemaContractFunction = ({ expect(await shapeOf(target, dialect)).toEqual(shape); }); + it("records in the catalogue, at the version that marks openings, every category the runtime's events, restrictions, disclosures, declared recipients and forgotten counts name", async () => { + const target = await create(); + const runtime = (aggregateId: string, type: string, payload: unknown) => ({ + ...pendingEvent({ aggregateType: "bounda", aggregateId, version: 1, type, payload }), + id: `${type}-${aggregateId}`, + metadata: { ...testMetadata, system: true }, + }); + const transfer = null; + await opened(target.adapter, async (storage) => { + for (const event of [ + runtime("c-1", "ProcessingRestricted", { + personId: "c-1", + ground: "accuracy-contested", + categories: ["listed"], + restrictions: [ + { ground: "accuracy-contested", categories: ["nested"] }, + { categories: null }, + ], + recipients: [{ port: "crm", categories: ["told"], retained: ["kept"] }], + }), + runtime("c-2", "PersonalDataForgotten", { retained: ["retained"], expired: ["expired"] }), + // Neither a kind of the runtime's that names categories, nor the runtime's aggregate. + runtime("c-3", "ScheduledCommandFailed", { categories: ["not-runtime-naming"] }), + { + ...pendingEvent({ aggregateId: "o-1", version: 1, payload: { categories: ["app"] } }), + id: "app-event", + }, + ]) { + await storage.eventStore.append({ + aggregateType: event.aggregateType, + aggregateId: event.aggregateId, + expectedVersion: 0, + events: [event], + }); + } + const since = new Date("2026-01-01T00:00:00.000Z"); + await storage.persons.restrict("c-1", { + ground: "accuracy-contested", + categories: ["restricted"], + since, + }); + await storage.persons.restrict("c-2", { + ground: "accuracy-contested", + categories: null, + since, + }); + const recipient = { + port: "crm", + recipient: "Acme", + kind: "processor", + country: "ES", + transfer, + }; + await storage.recipients.disclose( + [{ person: "c-1", ...recipient, category: "disclosed" }], + "2026-01-01T00:00:00.000Z", + ); + await storage.recipients.declare( + [{ port: "mailer", categories: ["declared"] }], + 0, + "2026-01-01T00:00:00.000Z", + ); + await storage.recipients.countForgotten([ + { ...recipient, status: "disclosed", category: "counted", persons: 2 }, + { ...recipient, status: "disclosed", category: null, persons: 3 }, + ]); + }); + const shape = await shapeOf(target, dialect); + // As the version before left the tables, where none of those writes recorded its categories. + const table = (name: string) => + `"${storageTableNameFor({ prefix: target.prefix, table: name })}"`; + await target.execute(`DELETE FROM ${table("personalCategories")}`); + await target.execute(`DROP TABLE ${table("eventMarks")}`); + await target.execute(`ALTER TABLE ${table("eventTypes")} DROP COLUMN "opened"`); + await target.execute(`ALTER TABLE ${table("deadLetters")} DROP COLUMN "instance_id"`); + await target.execute( + `DELETE FROM ${schemaMigrationsTableFor(target.prefix)} WHERE "scope" = 'storage' AND "version" >= ${OPENINGS[dialect]}`, + ); + await opened(target.adapter, async (storage) => { + expect(await storage.personalKeys.recordedCategories()).toEqual([ + "counted", + "declared", + "disclosed", + "expired", + "kept", + "listed", + "nested", + "restricted", + "retained", + "told", + ]); + }); + expect(await shapeOf(target, dialect)).toEqual(shape); + }); + it("adds, at its own version, the table of the forgotten persons each recipient was listed with, keeping everything else", async () => { const target = await create(); await opened(target.adapter, (storage) => storage.checkpointStore.set("projection:x", 3)); diff --git a/packages/core/src/adapter/testing/storage-transaction.contract.ts b/packages/core/src/adapter/testing/storage-transaction.contract.ts index 0fb7b64f2..cb9667cae 100644 --- a/packages/core/src/adapter/testing/storage-transaction.contract.ts +++ b/packages/core/src/adapter/testing/storage-transaction.contract.ts @@ -309,6 +309,30 @@ export const storageTransactionContract: StorageTransactionContractFunction = ({ expect(await storage.personalKeys.recordedCategories()).toEqual(["invoices"]); }); + it("records the categories it is told to with the rest, or not at all", async () => { + await expect( + storage.transact(async (transaction) => { + await transaction.personalKeys.recordCategories(["marketing", "profile"]); + expect(await transaction.personalKeys.recordedCategories()).toEqual([ + "marketing", + "profile", + ]); + throw new Error("boom"); + }), + ).rejects.toThrow("boom"); + expect(await storage.personalKeys.recordedCategories()).toEqual([]); + await storage.transact((transaction) => + transaction.personalKeys.recordCategories(["marketing"]), + ); + await expect( + storage.transact(async (transaction) => { + await transaction.personalKeys.recordCategories(["marketing", "profile"]); + throw new Error("boom"); + }), + ).rejects.toThrow("boom"); + expect(await storage.personalKeys.recordedCategories()).toEqual(["marketing"]); + }); + it("writes checkpoints with the rest, or not at all", async () => { await storage.checkpointStore.set("lease", 5); await storage.checkpointStore.set("gone", 2); diff --git a/packages/core/src/kernel/app.ts b/packages/core/src/kernel/app.ts index 568039f15..1e3d6c82f 100644 --- a/packages/core/src/kernel/app.ts +++ b/packages/core/src/kernel/app.ts @@ -1176,6 +1176,7 @@ export const assembleApp: AssembleAppFunction = async ({ } const intentions = createForgetIntentions({ ledger: forgetLedger?.store ?? null, + categories: adapted.personalKeys, ids, clock, logger, @@ -1855,7 +1856,9 @@ export const assembleApp: AssembleAppFunction = async ({ declaredRecipients = await written.recipients.declared(); } else { await writePending(adapted, true); - declaredRecipients = await writeDeclaration(written.recipients, declaration); + declaredRecipients = await written.transact((transaction) => + writeDeclaration(transaction, declaration), + ); } for (const { port, persons } of await written.recipients.summary()) { if (recipients.byPort[port] === undefined) { diff --git a/packages/core/src/kernel/command/reaction-commands.test.ts b/packages/core/src/kernel/command/reaction-commands.test.ts index 771e198f6..9b0a1b093 100644 --- a/packages/core/src/kernel/command/reaction-commands.test.ts +++ b/packages/core/src/kernel/command/reaction-commands.test.ts @@ -17,6 +17,7 @@ import { orderRegistry, slowJob, TEST_TENANT_KID, + unrecordedCategories, withoutLedger, } from "../test-support.ts"; import { createUnitOfWork } from "../unit-of-work/unit-of-work.ts"; @@ -85,6 +86,7 @@ const withLedger = async (categories = personalCategories) => { personalCategories: categories, batchSize: 10, intentions: createForgetIntentions({ + categories: unrecordedCategories, ledger: boundForgetLedger({ ledger: { readMark: async () => [], diff --git a/packages/core/src/kernel/personal-data/applied-again.test.ts b/packages/core/src/kernel/personal-data/applied-again.test.ts index 12117df53..dbeb22ad4 100644 --- a/packages/core/src/kernel/personal-data/applied-again.test.ts +++ b/packages/core/src/kernel/personal-data/applied-again.test.ts @@ -4,7 +4,7 @@ import { createFixedClock } from "../../contracts/clock.ts"; import { createSequentialIdGenerator } from "../../contracts/ids.ts"; import { silentLogger } from "../../contracts/logger.ts"; import { createMemoryForgetLedgers } from "../../memory/forget-ledger.ts"; -import { landedRowFor } from "../test-support.ts"; +import { landedRowFor, unrecordedCategories } from "../test-support.ts"; import { type ApplyEntriesAgainArgs, applyEntriesAgain, @@ -74,6 +74,7 @@ describe("applying entries again", () => { const clock = createFixedClock(new Date(CURSOR)); const ids = createSequentialIdGenerator({ prefix: "r" }); const intentions = createForgetIntentions({ + categories: unrecordedCategories, ledger: boundForgetLedger({ ledger, timeoutMs: 1_000, clock }), ids, clock, @@ -106,6 +107,7 @@ describe("applying entries again", () => { it("hands what redacts the records' intentions in place of its own, and nothing without it", async () => { const intentions = createForgetIntentions({ + categories: unrecordedCategories, ledger: null, ids: createSequentialIdGenerator(), clock: createFixedClock(new Date(CURSOR)), @@ -147,6 +149,7 @@ describe("applying entries again", () => { storage, ledger, intentions: createForgetIntentions({ + categories: unrecordedCategories, ledger: boundForgetLedger({ ledger, timeoutMs: 1_000, clock }), ids, clock, diff --git a/packages/core/src/kernel/personal-data/applied-record.test.ts b/packages/core/src/kernel/personal-data/applied-record.test.ts index 6ebb31e1c..05b31c122 100644 --- a/packages/core/src/kernel/personal-data/applied-record.test.ts +++ b/packages/core/src/kernel/personal-data/applied-record.test.ts @@ -4,7 +4,7 @@ import { createFixedClock } from "../../contracts/clock.ts"; import { ForgetLedgerUnavailableError } from "../../contracts/errors.ts"; import { createSequentialIdGenerator } from "../../contracts/ids.ts"; import { disclosureEntryId } from "../shared/idempotency-key.ts"; -import { createRecordingLogger } from "../test-support.ts"; +import { createRecordingLogger, unrecordedCategories } from "../test-support.ts"; import { appliedEntryOf, createApplicationRecords } from "./applied-record.ts"; import { boundForgetLedger } from "./forget-ledger.ts"; import { createForgetIntentions } from "./intention.ts"; @@ -54,6 +54,7 @@ const setUp = (refuse: (entries: readonly ForgetLedgerEntry[]) => boolean = () = const clock = createFixedClock(NOW); const { logger, entries: logs } = createRecordingLogger(); const intentions = createForgetIntentions({ + categories: unrecordedCategories, ledger: ledger, ids, clock, @@ -239,7 +240,13 @@ describe("the records of hand applications", () => { const clock = createFixedClock(NOW); const { logger, entries: logs } = createRecordingLogger(); const records = createApplicationRecords({ - intentions: createForgetIntentions({ ledger: null, ids, clock, logger }), + intentions: createForgetIntentions({ + ledger: null, + categories: unrecordedCategories, + ids, + clock, + logger, + }), ledger: null, ids, clock, diff --git a/packages/core/src/kernel/personal-data/categories.test.ts b/packages/core/src/kernel/personal-data/categories.test.ts index cf58b0080..a02432180 100644 --- a/packages/core/src/kernel/personal-data/categories.test.ts +++ b/packages/core/src/kernel/personal-data/categories.test.ts @@ -895,7 +895,7 @@ describe("checkRecordedCategories", () => { }); expect(check).toThrow(ConfigurationError); expect(check).toThrow( - 'bounda.personal-data.ts neither declares nor retires categories the store has recorded keys in: "legacy", "marketing". Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions', + 'bounda.personal-data.ts neither declares nor retires categories the store has recorded: "legacy", "marketing". Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions', ); }); }); diff --git a/packages/core/src/kernel/personal-data/categories.ts b/packages/core/src/kernel/personal-data/categories.ts index eb6ceda81..3c9e7c262 100644 --- a/packages/core/src/kernel/personal-data/categories.ts +++ b/packages/core/src/kernel/personal-data/categories.ts @@ -674,10 +674,10 @@ export interface CheckRecordedCategoriesFunction { } /** - * Throws `ConfigurationError` naming every category the store recorded keys in that the app - * neither declares nor retires: this code cannot tell one it dropped, whose keys forgetting it at - * once would destroy past their retention and exemptions, from one newer code declares, which - * keeps them. + * Throws `ConfigurationError` naming every category the store recorded, by a key or by a write that + * names it, that the app neither declares nor retires: this code cannot tell one it dropped, whose + * keys forgetting it at once would destroy past their retention and exemptions, and whose name + * stored restrictions and forgettings still hold, from one newer code declares, which keeps them. */ export const checkRecordedCategories: CheckRecordedCategoriesFunction = ({ categories, @@ -686,6 +686,6 @@ export const checkRecordedCategories: CheckRecordedCategoriesFunction = ({ const unknown = recorded.filter((name) => categories.of(name) === undefined); if (unknown.length === 0) return; throw new ConfigurationError( - `bounda.personal-data.ts neither declares nor retires categories the store has recorded keys in: ${unknown.map((name) => `"${name}"`).join(", ")}. Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions`, + `bounda.personal-data.ts neither declares nor retires categories the store has recorded: ${unknown.map((name) => `"${name}"`).join(", ")}. Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions`, ); }; diff --git a/packages/core/src/kernel/personal-data/category-ahead.test.ts b/packages/core/src/kernel/personal-data/category-ahead.test.ts index d3bf347de..9df85953a 100644 --- a/packages/core/src/kernel/personal-data/category-ahead.test.ts +++ b/packages/core/src/kernel/personal-data/category-ahead.test.ts @@ -160,7 +160,7 @@ describe("keys of a category only newer code declares", () => { await expect(started(adapter, registry)).rejects.toThrow( new ConfigurationError( - 'bounda.personal-data.ts neither declares nor retires categories the store has recorded keys in: "legacy". Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions', + 'bounda.personal-data.ts neither declares nor retires categories the store has recorded: "legacy". Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions', ), ); expect(await storage.personalKeys.get("c-1", "legacy")).toEqual(testPersonalKey("legacy")); @@ -175,7 +175,7 @@ describe("keys of a category only newer code declares", () => { await app.stop(); await expect(started(adapter, registry)).rejects.toThrow( - 'categories the store has recorded keys in: "profile"', + 'categories the store has recorded: "profile"', ); await expect(started(adapter, newer)).resolves.toBeDefined(); }); diff --git a/packages/core/src/kernel/personal-data/forget.test.ts b/packages/core/src/kernel/personal-data/forget.test.ts index acc4447b0..2877df49e 100644 --- a/packages/core/src/kernel/personal-data/forget.test.ts +++ b/packages/core/src/kernel/personal-data/forget.test.ts @@ -16,7 +16,7 @@ import { createSequentialIdGenerator } from "../../contracts/ids.ts"; import { memory } from "../../memory/index.ts"; import type { ForgetOptions, PersonalDataModule } from "../../modules/personal-data.ts"; import { NO_RECIPIENTS } from "../recipients/build.ts"; -import { createRecordingLogger, withoutLedger } from "../test-support.ts"; +import { createRecordingLogger, unrecordedCategories, withoutLedger } from "../test-support.ts"; import { buildPersonalCategories } from "./categories.ts"; import { forgetIntended, forgetPersonalData, forgetWithin, STALE_INTENTION } from "./forget.ts"; import { boundForgetLedger } from "./forget-ledger.ts"; @@ -544,6 +544,7 @@ describe("forgetPersonalData", () => { recipients: NO_RECIPIENTS, storage, intentions: createForgetIntentions({ + categories: unrecordedCategories, ledger: boundForgetLedger({ ledger: { readMark: async () => [], @@ -670,6 +671,7 @@ describe("forgetIntended", () => { const recorded: ForgetLedgerEntry[] = []; const clock = createFixedClock(); const intentions = createForgetIntentions({ + categories: unrecordedCategories, ledger: boundForgetLedger({ ledger: { readMark: async () => [], diff --git a/packages/core/src/kernel/personal-data/forget.ts b/packages/core/src/kernel/personal-data/forget.ts index e81b0210f..55e34ad5a 100644 --- a/packages/core/src/kernel/personal-data/forget.ts +++ b/packages/core/src/kernel/personal-data/forget.ts @@ -275,6 +275,7 @@ export const forgetWithin: ForgetWithinFunction = async (args) => { }; const event = await appendSystemEvent({ eventStore: transaction.eventStore, + categories: transaction.personalKeys, ids, clock, aggregateType: BOUNDA_AGGREGATE, diff --git a/packages/core/src/kernel/personal-data/forgotten-tenant.ts b/packages/core/src/kernel/personal-data/forgotten-tenant.ts index 2ee0e3530..44e5e67ab 100644 --- a/packages/core/src/kernel/personal-data/forgotten-tenant.ts +++ b/packages/core/src/kernel/personal-data/forgotten-tenant.ts @@ -292,6 +292,7 @@ export const settleTenantForgetting: SettleTenantForgettingFunction = async ({ }; await appendSystemEvent({ eventStore: transaction.eventStore, + categories: transaction.personalKeys, ids, clock, aggregateType: BOUNDA_AGGREGATE, diff --git a/packages/core/src/kernel/personal-data/intention.test.ts b/packages/core/src/kernel/personal-data/intention.test.ts index 066e19960..bcfe78835 100644 --- a/packages/core/src/kernel/personal-data/intention.test.ts +++ b/packages/core/src/kernel/personal-data/intention.test.ts @@ -9,8 +9,9 @@ import { } from "../../contracts/errors.ts"; import { createSequentialIdGenerator } from "../../contracts/ids.ts"; import { memory } from "../../memory/index.ts"; +import { PROCESSING_RESTRICTED_EVENT } from "../../modules/bounda-events.ts"; import { disclosureEntryId } from "../shared/idempotency-key.ts"; -import { createRecordingLogger } from "../test-support.ts"; +import { createRecordingLogger, unrecordedCategories } from "../test-support.ts"; import type { ForgetScope } from "./forget.ts"; import { type BoundedForgetLedger, boundForgetLedger } from "./forget-ledger.ts"; import { createForgetIntentions } from "./intention.ts"; @@ -23,6 +24,7 @@ const setUp = async ({ ledger }: { readonly ledger: BoundedForgetLedger | null } const storage = await memory().createStorage(); const { logger, entries: logs } = createRecordingLogger(); const intentions = createForgetIntentions({ + categories: storage.personalKeys, ledger, ids: createSequentialIdGenerator(), clock: createFixedClock(NOW), @@ -47,6 +49,63 @@ const recordingLedger = (append: (entries: readonly ForgetLedgerEntry[]) => Prom }); describe("the intentions of forgetting", () => { + it("record the categories each entry names in the store before the ledger takes it", async () => { + const storage = await memory().createStorage(); + const recordedWhenTaken: (readonly string[])[] = []; + const intentions = createForgetIntentions({ + categories: storage.personalKeys, + ledger: recordingLedger(async () => { + recordedWhenTaken.push(await storage.personalKeys.recordedCategories()); + }), + ids: createSequentialIdGenerator(), + clock: createFixedClock(NOW), + logger: createRecordingLogger().logger, + }); + await intentions.intend({ + personId: "c-1", + reason: "requested", + scope: { kind: "categories", categories: ["profile"] }, + keys: storage.personalKeys, + }); + await intentions.record({ + personId: "c-1", + categories: null, + eventId: "e-1", + forgottenAt: NOW.toISOString(), + reason: "requested", + restriction: { + type: PROCESSING_RESTRICTED_EVENT, + payload: { + personId: "c-1", + ground: "accuracy-contested", + categories: null, + restrictions: [ + { ground: "accuracy-contested", categories: ["marketing"], since: NOW.toISOString() }, + ], + }, + }, + }); + await intentions.disclose( + [ + { + person: "c-1", + port: "crm", + recipient: "Acme", + kind: "processor", + country: "ES", + transfer: null, + category: "contact", + }, + ], + NOW.toISOString(), + ); + expect(recordedWhenTaken).toEqual([ + ["profile"], + ["marketing", "profile"], + ["contact", "marketing", "profile"], + ]); + }); + it("record each in the ledger before they resolve, naming the keys in force their scope covers", async () => { const appended: ForgetLedgerEntry[] = []; const { storage, intentions } = await setUp({ @@ -271,6 +330,7 @@ describe("the intentions of forgetting", () => { }; const storage = await memory().createStorage(); const intentions = createForgetIntentions({ + categories: unrecordedCategories, ledger: ledger, ids: createSequentialIdGenerator(), clock: createFixedClock(NOW), @@ -314,6 +374,7 @@ describe("the intentions of forgetting", () => { const appended: ForgetLedgerEntry[] = []; const { logger, entries } = createRecordingLogger(); const intentions = createForgetIntentions({ + categories: unrecordedCategories, ledger: recordingLedger(async (written) => { appended.push(...written); }), diff --git a/packages/core/src/kernel/personal-data/intention.ts b/packages/core/src/kernel/personal-data/intention.ts index 99c20b9f9..b563a8034 100644 --- a/packages/core/src/kernel/personal-data/intention.ts +++ b/packages/core/src/kernel/personal-data/intention.ts @@ -16,6 +16,7 @@ import type { PersonalDataForgottenReason } from "../../modules/bounda-events.ts import { disclosureEntryId } from "../shared/idempotency-key.ts"; import type { ForgetScope } from "./forget.ts"; import type { BoundedForgetLedger } from "./forget-ledger.ts"; +import { categoriesOfEntry } from "./named-categories.ts"; // A disclosure as the ledger keeps it, with its transfer as it was first recorded, and whose data. export interface PersonLedgerDisclosure extends LedgerDisclosure { @@ -119,6 +120,11 @@ export interface CreateForgetIntentionsArgs { * `null` without a ledger: nothing is recorded, and no key is read for it. */ readonly ledger: BoundedForgetLedger | null; + /** + * Where the categories an entry names are recorded before the ledger takes it, so a start of + * code that dropped one refuses before the entry commits it. + */ + readonly categories: Pick; readonly ids: IdGenerator; readonly clock: Clock; readonly logger: Logger; @@ -140,6 +146,7 @@ export interface CreateForgetIntentionsFunction { */ export const createForgetIntentions: CreateForgetIntentionsFunction = ({ ledger, + categories, ids, clock, logger, @@ -148,6 +155,7 @@ export const createForgetIntentions: CreateForgetIntentionsFunction = ({ const append = async (entries: () => Promise): Promise => { if (ledger === null) return; const appended = await entries(); + await categories.recordCategories(appended.flatMap(categoriesOfEntry)); try { await ledger.append(appended); } catch (error) { diff --git a/packages/core/src/kernel/personal-data/ledger-prune-app.test.ts b/packages/core/src/kernel/personal-data/ledger-prune-app.test.ts index ebd59354c..499d6af71 100644 --- a/packages/core/src/kernel/personal-data/ledger-prune-app.test.ts +++ b/packages/core/src/kernel/personal-data/ledger-prune-app.test.ts @@ -819,7 +819,7 @@ describe("pruning, and listing what is stranded, by the categories the database testPersonalKey("legacy"), ); const refusal = - 'bounda.personal-data.ts neither declares nor retires categories the store has recorded keys in: "legacy"'; + 'bounda.personal-data.ts neither declares nor retires categories the store has recorded: "legacy"'; await expect( pruneTenantForgetLedger({ logger: silentLogger, registry, config, now: LATER }), ).rejects.toThrow(refusal); diff --git a/packages/core/src/kernel/personal-data/named-categories-app.test.ts b/packages/core/src/kernel/personal-data/named-categories-app.test.ts new file mode 100644 index 000000000..6e903bb05 --- /dev/null +++ b/packages/core/src/kernel/personal-data/named-categories-app.test.ts @@ -0,0 +1,175 @@ +import { afterEach, describe, expect, it } from "vitest"; +import type { Adapter } from "../../adapter/adapter.ts"; +import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; +import { createFixedClock } from "../../contracts/clock.ts"; +import { ConfigurationError } from "../../contracts/errors.ts"; +import { createSequentialIdGenerator } from "../../contracts/ids.ts"; +import { memory } from "../../memory/index.ts"; +import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; +import type { Registry } from "../../modules/registry.ts"; +import { createApp } from "../app.ts"; +import { ledgerFor } from "../test-support.ts"; + +const said = { purposes: ["Serve the person"], sources: ["data-subject"] }; + +// Whether the code declares `marketing`, and whether a recipient is told of it. +interface Deploy { + readonly marketing: boolean; + readonly mailer?: boolean; +} + +const told = async () => undefined; + +const registryOf = ({ marketing, mailer = false }: Deploy): Registry => + ({ + personalData: { + automatedDecisions: {}, + categories: { + contact: { basis: "consent", retention: "30d", ...said }, + ...(marketing ? { marketing: { basis: "consent", retention: "30d", ...said } } : {}), + }, + }, + aggregates: { + customer: { + state: { initialState: {} }, + events: { + noteTaken: { + payload: ({ z, personal }: EventPayloadArgs) => + z.object({ note: personal(z.string(), { category: "contact" as never }) }), + evolve: () => ({}), + }, + ...(marketing + ? { + topicChosen: { + payload: ({ z, personal }: EventPayloadArgs) => + z.object({ topic: personal(z.string(), { category: "marketing" as never }) }), + evolve: () => ({}), + }, + } + : {}), + }, + ...(mailer + ? { + ports: { mailer: { memory: { default: {} } } }, + recipients: { + mailer: { + recipient: { + name: "Mailchimp", + kind: "processor", + country: "DE", + categories: ["marketing"], + }, + onPersonalDataForgotten: told, + onProcessingRestricted: told, + onProcessingRestrictionLiftAnnounced: told, + onProcessingRestrictionLifted: told, + onPersonalDataRedacted: told, + onTenantForgotten: told, + }, + }, + } + : {}), + commands: { + takeNote: { + module: { + payload: ({ z, notPersonal }: CommandPayloadArgs) => + z.object({ customerId: notPersonal(z.string()), note: notPersonal(z.string()) }), + handler: ({ + command: { payload }, + events, + }: { + readonly command: { readonly payload: { readonly note: string } }; + readonly events: Record unknown>; + }) => [events.noteTaken?.({ note: payload.note })], + }, + }, + }, + policies: {}, + processes: {}, + }, + }, + readModels: {}, + }) as unknown as Registry; + +const stops: (() => Promise)[] = []; + +afterEach(async () => { + for (const stop of stops.splice(0).reverse()) await stop(); +}); + +let starts = 0; + +const started = async (adapter: Adapter, deploy: Deploy) => { + starts += 1; + const app = await createApp({ + registry: registryOf(deploy), + config: { + storage: adapter, + runtime: { personalData: { retention: "1y", forgetLedger: { store: ledgerFor(adapter) } } }, + }, + ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), + clock: createFixedClock(new Date("2026-03-01T00:00:00.000Z")), + }); + stops.push(() => app.stop()); + return app; +}; + +// A person who holds a key in `contact` alone, never one in `marketing`. +const noted = async (adapter: Adapter, deploy: Deploy) => { + const app = await started(adapter, deploy); + await ( + app.commands as unknown as Record Promise> + ).takeNote?.({ customerId: "c-1", note: "call after five" }); + await app.runUntilIdle(); + return app; +}; + +const DROPPED = new ConfigurationError( + 'bounda.personal-data.ts neither declares nor retires categories the store has recorded: "marketing". Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions', +); + +const adapters: readonly [string, () => Adapter][] = [ + ["memory", () => memory()], + ["SQLite (node:sqlite)", () => createNodeSqliteAdapter().adapter], +]; + +describe.each(adapters)("a category no key was added in, on %s", (_name, adapterOf) => { + it("is dropped by code that starts, when nothing the store holds names it", async () => { + const adapter = adapterOf(); + const app = await noted(adapter, { marketing: true }); + await app.stop(); + + await expect(started(adapter, { marketing: false })).resolves.toBeDefined(); + }); + + it("refuses the start of code that dropped it once a restriction named it, and starts once it is declared again", async () => { + const adapter = adapterOf(); + const storage = await adapter.createStorage(); + const app = await noted(adapter, { marketing: true }); + await app.restrict("c-1", { ground: "accuracy-contested", categories: ["marketing"] as never }); + await app.stop(); + expect(await storage.personalKeys.list("c-1")).not.toContainEqual( + expect.objectContaining({ category: "marketing" }), + ); + + await expect(started(adapter, { marketing: false })).rejects.toThrow(DROPPED); + await expect(started(adapter, { marketing: true })).resolves.toBeDefined(); + }); + + it("refuses the start of code that dropped it once a forgetting named it", async () => { + const adapter = adapterOf(); + const app = await noted(adapter, { marketing: true }); + await app.forget("c-1", { categories: ["marketing"] as never }); + await app.stop(); + + await expect(started(adapter, { marketing: false })).rejects.toThrow(DROPPED); + }); + + it("refuses the start of code that dropped it once a recipient was declared told of it", async () => { + const adapter = adapterOf(); + const app = await noted(adapter, { marketing: true, mailer: true }); + await app.stop(); + + await expect(started(adapter, { marketing: false })).rejects.toThrow(DROPPED); + }); +}); diff --git a/packages/core/src/kernel/personal-data/named-categories.test.ts b/packages/core/src/kernel/personal-data/named-categories.test.ts new file mode 100644 index 000000000..739f68856 --- /dev/null +++ b/packages/core/src/kernel/personal-data/named-categories.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from "vitest"; +import { PROCESSING_RESTRICTED_EVENT } from "../../modules/bounda-events.ts"; +import { categoriesNamedBy, categoriesOfEntry } from "./named-categories.ts"; + +describe("categoriesNamedBy", () => { + it("names every category a runtime event's payload names, each once, in code point order", () => { + expect( + categoriesNamedBy({ + categories: ["profile", "Contact"], + retained: ["invoices"], + expired: ["marketing"], + restrictions: [ + { ground: "accuracy-contested", categories: ["profile", "loyalty"] }, + { ground: "accuracy-contested", categories: null }, + ], + recipients: [ + { port: "crm", categories: ["contact"], retained: ["billing"] }, + { port: "mailer", categories: ["contact"] }, + ], + }), + ).toEqual(["Contact", "billing", "contact", "invoices", "loyalty", "marketing", "profile"]); + }); + + it("names none where a payload names none, or names them in no list", () => { + for (const payload of [ + undefined, + null, + "profile", + ["profile"], + {}, + { categories: null, restrictions: [{ categories: null }], recipients: null }, + { categories: "profile", retained: [1, null], restrictions: ["profile"], recipients: [3] }, + ]) { + expect(categoriesNamedBy(payload)).toEqual([]); + } + }); +}); + +describe("categoriesOfEntry", () => { + const entry = { + personId: "c-1", + categories: null, + eventId: "e-1", + forgottenAt: "2026-03-01T00:00:00.000Z", + reason: "requested", + } as const; + + it("names those an entry forgets, those its restriction names and its disclosure's, each once", () => { + expect( + categoriesOfEntry({ + ...entry, + categories: ["profile", "contact"], + restriction: { + type: PROCESSING_RESTRICTED_EVENT, + payload: { + personId: "c-1", + ground: "accuracy-contested", + categories: ["profile"], + restrictions: [ + { + ground: "accuracy-contested", + categories: ["marketing"], + since: "2026-03-01T00:00:00.000Z", + }, + ], + }, + }, + disclosure: { + port: "crm", + recipient: "Acme", + kind: "processor", + country: "ES", + transfer: null, + category: "billing", + }, + }), + ).toEqual(["billing", "contact", "marketing", "profile"]); + }); + + it("names none for an entry that forgets the whole person and records nothing else", () => { + expect(categoriesOfEntry(entry)).toEqual([]); + }); +}); diff --git a/packages/core/src/kernel/personal-data/named-categories.ts b/packages/core/src/kernel/personal-data/named-categories.ts new file mode 100644 index 000000000..3dd6f4566 --- /dev/null +++ b/packages/core/src/kernel/personal-data/named-categories.ts @@ -0,0 +1,42 @@ +import { codePointOrder } from "../../adapter/sql/order.ts"; +import type { ForgetLedgerEntry } from "../../adapter/storage/forget-ledger.ts"; +import { isRecord } from "../shared/merge-fields.ts"; + +export interface CategoriesNamedByFunction { + (payload: unknown): readonly string[]; +} + +const namesIn = (value: unknown): readonly string[] => + Array.isArray(value) ? value.filter((name): name is string => typeof name === "string") : []; + +const namesInEach = (value: unknown, fields: readonly string[]): readonly string[] => + Array.isArray(value) + ? value.flatMap((entry) => + isRecord(entry) ? fields.flatMap((field) => namesIn(entry[field])) : [], + ) + : []; + +const sorted = (names: readonly string[]): readonly string[] => + [...new Set(names)].sort(codePointOrder); + +export const categoriesNamedBy: CategoriesNamedByFunction = (payload) => + isRecord(payload) + ? sorted([ + ...namesIn(payload.categories), + ...namesIn(payload.retained), + ...namesIn(payload.expired), + ...namesInEach(payload.restrictions, ["categories"]), + ...namesInEach(payload.recipients, ["categories", "retained"]), + ]) + : []; + +export interface CategoriesOfEntryFunction { + (entry: ForgetLedgerEntry): readonly string[]; +} + +export const categoriesOfEntry: CategoriesOfEntryFunction = (entry) => + sorted([ + ...(entry.categories ?? []), + ...categoriesNamedBy(entry.restriction?.payload), + ...(entry.disclosure === undefined ? [] : [entry.disclosure.category]), + ]); diff --git a/packages/core/src/kernel/personal-data/reconciliation.test.ts b/packages/core/src/kernel/personal-data/reconciliation.test.ts index 37faa4e8c..d8b8a1b39 100644 --- a/packages/core/src/kernel/personal-data/reconciliation.test.ts +++ b/packages/core/src/kernel/personal-data/reconciliation.test.ts @@ -20,7 +20,7 @@ import { createMemoryForgetLedgers } from "../../memory/forget-ledger.ts"; import { memory } from "../../memory/index.ts"; import { NO_RECIPIENTS } from "../recipients/build.ts"; import { RESTORE_COVERED, RESTORE_GENERATION } from "../shared/restores.ts"; -import { createRecordingLogger, withoutLedger } from "../test-support.ts"; +import { createRecordingLogger, unrecordedCategories, withoutLedger } from "../test-support.ts"; import type { RecordAccess, RecordAccessArgs } from "./access.ts"; import { buildPersonalCategories } from "./categories.ts"; import { boundForgetLedger } from "./forget-ledger.ts"; @@ -1831,6 +1831,7 @@ describe("forgetAgain", () => { const clock = createFixedClock(NOW); let down = false; const intentions = createForgetIntentions({ + categories: unrecordedCategories, ledger: boundForgetLedger({ ledger: { readMark: async () => [], diff --git a/packages/core/src/kernel/personal-data/redaction.ts b/packages/core/src/kernel/personal-data/redaction.ts index 186002b7a..ae1c34ca8 100644 --- a/packages/core/src/kernel/personal-data/redaction.ts +++ b/packages/core/src/kernel/personal-data/redaction.ts @@ -633,6 +633,7 @@ export const redactWithin: RedactWithinFunction = async (args) => { }; const event = await appendSystemEvent({ eventStore: transaction.eventStore, + categories: transaction.personalKeys, ids, clock, aggregateType: BOUNDA_AGGREGATE, diff --git a/packages/core/src/kernel/personal-data/restriction.ts b/packages/core/src/kernel/personal-data/restriction.ts index e3d079022..4c4367d3e 100644 --- a/packages/core/src/kernel/personal-data/restriction.ts +++ b/packages/core/src/kernel/personal-data/restriction.ts @@ -470,6 +470,7 @@ const change = async ({ } const event = await appendSystemEvent({ eventStore: transaction.eventStore, + categories: transaction.personalKeys, ids, clock, aggregateType: BOUNDA_AGGREGATE, @@ -811,6 +812,7 @@ export const restrictAgain: RestrictAgainFunction = ({ if (!(await restrictionDue(transaction, entry))) return null; const event = await appendSystemEvent({ eventStore: transaction.eventStore, + categories: transaction.personalKeys, ids, clock, aggregateType: BOUNDA_AGGREGATE, diff --git a/packages/core/src/kernel/personal-data/retention.test.ts b/packages/core/src/kernel/personal-data/retention.test.ts index 196c08fcb..9b4d9de6a 100644 --- a/packages/core/src/kernel/personal-data/retention.test.ts +++ b/packages/core/src/kernel/personal-data/retention.test.ts @@ -16,7 +16,7 @@ import type { PersonalDataModule } from "../../modules/personal-data.ts"; import { NO_RECIPIENTS } from "../recipients/build.ts"; import { LEASE_MS } from "../shared/lease.ts"; import { tracer } from "../telemetry.ts"; -import { createRecordingLogger, withoutLedger } from "../test-support.ts"; +import { createRecordingLogger, unrecordedCategories, withoutLedger } from "../test-support.ts"; import { buildPersonalCategories, type PersonalCategories } from "./categories.ts"; import { forgetPersonalData } from "./forget.ts"; import { boundForgetLedger } from "./forget-ledger.ts"; @@ -1381,6 +1381,7 @@ describe("the retention and the forget ledger", () => { const recordingIntentions = (ids: IdGenerator, clock: FixedClock) => { const recorded: ForgetLedgerEntry[] = []; const intentions = createForgetIntentions({ + categories: unrecordedCategories, ledger: boundForgetLedger({ ledger: { readMark: async () => [], diff --git a/packages/core/src/kernel/personal-data/wrapped-keys.ts b/packages/core/src/kernel/personal-data/wrapped-keys.ts index 3223144cc..681124e18 100644 --- a/packages/core/src/kernel/personal-data/wrapped-keys.ts +++ b/packages/core/src/kernel/personal-data/wrapped-keys.ts @@ -465,6 +465,7 @@ export const createPersonalKeyWrapping: CreatePersonalKeyWrappingFunction = ({ kids: () => keys.kids(), categories: () => keys.categories(), recordedCategories: () => keys.recordedCategories(), + recordCategories: (named) => keys.recordCategories(named), clear: async () => { const removed = await keys.clear(); for (const fingerprint of [...kept.keys()]) drop(fingerprint); diff --git a/packages/core/src/kernel/reactive-harness.ts b/packages/core/src/kernel/reactive-harness.ts index 89088c39e..0d76ee40b 100644 --- a/packages/core/src/kernel/reactive-harness.ts +++ b/packages/core/src/kernel/reactive-harness.ts @@ -157,7 +157,13 @@ export const createReactiveHarness: CreateReactiveHarnessFunction = async ({ retention: config.runtime.personalData.retention, }); const recipients = buildRecipients({ registry, categories: personalCategories, ports }); - const intentions = createForgetIntentions({ ledger: null, ids, clock, logger }); + const intentions = createForgetIntentions({ + ledger: null, + categories: storage.personalKeys, + ids, + clock, + logger, + }); const policyExecutor = createPolicyExecutor({ tracer: tracer, aggregates, diff --git a/packages/core/src/kernel/recipients/again.test.ts b/packages/core/src/kernel/recipients/again.test.ts index 386cb2764..3f62c46f7 100644 --- a/packages/core/src/kernel/recipients/again.test.ts +++ b/packages/core/src/kernel/recipients/again.test.ts @@ -170,6 +170,7 @@ describe("discloseAgain", () => { lastAt: at, }, ]); + expect(await storage.personalKeys.recordedCategories()).toEqual(["contact"]); expect( await discloseAgain({ storage, diff --git a/packages/core/src/kernel/recipients/again.ts b/packages/core/src/kernel/recipients/again.ts index 674a82619..efb64c09d 100644 --- a/packages/core/src/kernel/recipients/again.ts +++ b/packages/core/src/kernel/recipients/again.ts @@ -89,6 +89,7 @@ export const discloseAgain: DiscloseAgainFunction = ({ ) { return false; } + await transaction.personalKeys.recordCategories([disclosure.category]); const added = await transaction.recipients.disclose( [{ person: personId, ...disclosure }], forgottenAt, diff --git a/packages/core/src/kernel/recipients/gate.test.ts b/packages/core/src/kernel/recipients/gate.test.ts index dfeb8b3ca..1791ed680 100644 --- a/packages/core/src/kernel/recipients/gate.test.ts +++ b/packages/core/src/kernel/recipients/gate.test.ts @@ -261,6 +261,16 @@ describe("createDisclosures", () => { expect(sent).toEqual(["ana", "ana"]); }); + it("records the category of what it discloses with the disclosure, though no key was added in it", async () => { + const bound = disclosuresOf().bind( + "customer", + { mailer: mailer([]) }, + run([{ person: "c-4", fingerprint: null, category: "contact", fence: undefined }]), + ) as { mailer: Mailer }; + await bound.mailer.send("ana"); + expect(await storage.personalKeys.recordedCategories()).toEqual(["contact"]); + }); + it("sends to the ledger a disclosure under the transfer the lists read now, when the store holds one to the same recipient that differs only in the decision an adequacy decision changed since, and none the store holds as it is", async () => { await key("c-1", "contact", "f-contact"); await key("c-2", "contact", "f-contact-2"); diff --git a/packages/core/src/kernel/recipients/gate.ts b/packages/core/src/kernel/recipients/gate.ts index 35343ed5c..a7c7a9340 100644 --- a/packages/core/src/kernel/recipients/gate.ts +++ b/packages/core/src/kernel/recipients/gate.ts @@ -200,6 +200,7 @@ export const createDisclosures: CreateDisclosuresFunction = ({ touches: [], basis: run.basis, }); + await transaction.personalKeys.recordCategories(disclosed.map(({ category }) => category)); await transaction.recipients.disclose(disclosed, at); return through; }); diff --git a/packages/core/src/kernel/recipients/pending.test.ts b/packages/core/src/kernel/recipients/pending.test.ts index 46a530a5a..9cdd82513 100644 --- a/packages/core/src/kernel/recipients/pending.test.ts +++ b/packages/core/src/kernel/recipients/pending.test.ts @@ -64,6 +64,12 @@ const PENDING: PendingRecipientDeclaration = { at: "2026-03-02T00:00:00.000Z", }; +// A recipient store alone, as `writeDeclaration` writes in, where what it records goes nowhere. +const alone = (recipients: RecipientStore) => ({ + recipients, + personalKeys: { recordCategories: async () => undefined }, +}); + // The same rows in two stores, one of which then writes the declaration. const stores = async (): Promise => { const pair = [createKeptRecipientStore().store, createKeptRecipientStore().store] as const; @@ -141,10 +147,26 @@ const readAll = async (store: RecipientStore) => ({ paged: await store.personsOf({ port: "customer.newsletter", after: "p-1", limit: 1 }), }); +describe("writeDeclaration", () => { + it("records the categories its ports name with the declaration, or neither", async () => { + const storage = await memory().createStorage(); + await expect( + storage.transact(async (transaction) => { + await writeDeclaration(transaction, PENDING); + throw new Error("refused"); + }), + ).rejects.toThrow("refused"); + expect(await storage.personalKeys.recordedCategories()).toEqual([]); + expect(await storage.recipients.declared()).toEqual([]); + await storage.transact((transaction) => writeDeclaration(transaction, PENDING)); + expect(await storage.personalKeys.recordedCategories()).toEqual(["contact", "profile"]); + }); +}); + describe("the recipients a pending declaration reads", () => { it("are those the store holds once it is written, for every reader", async () => { const [pending, written] = await stores(); - await writeDeclaration(written, PENDING); + await writeDeclaration(alone(written), PENDING); expect(await readAll(pendingRecipientsStore(pending, async () => [PENDING]))).toEqual( await readAll(written), ); @@ -180,8 +202,8 @@ describe("the recipients a pending declaration reads", () => { position: 9, at: "2026-03-03T00:00:00.000Z", }; - await writeDeclaration(written, PENDING); - await writeDeclaration(written, LATER); + await writeDeclaration(alone(written), PENDING); + await writeDeclaration(alone(written), LATER); const read = await readAll(pendingRecipientsStore(pending, async () => [PENDING, LATER])); expect(read).toEqual(await readAll(written)); expect( @@ -336,7 +358,7 @@ describe("writePendingRecipients", () => { const waiting = writePendingRecipients({ storage, pending, clock, wait: true }); // The other instance writes it meanwhile. await storage.transact(async (transaction) => { - await writeDeclaration(transaction.recipients, declaration("d-1", ["contact"])); + await writeDeclaration(transaction, declaration("d-1", ["contact"])); await transaction.inboxLedger.complete({ handler: RECIPIENT_DECLARATION_HANDLER, eventId: "d-1", diff --git a/packages/core/src/kernel/recipients/pending.ts b/packages/core/src/kernel/recipients/pending.ts index 598ecc150..6974a1d09 100644 --- a/packages/core/src/kernel/recipients/pending.ts +++ b/packages/core/src/kernel/recipients/pending.ts @@ -1,5 +1,6 @@ import type { Storage } from "../../adapter/adapter.ts"; import type { ClaimKey } from "../../adapter/storage/inbox-ledger.ts"; +import type { PersonalKeyStore } from "../../adapter/storage/personal-key-store.ts"; import { type DeclaredRecipient, disclosureKey, @@ -14,15 +15,23 @@ import type { TenantKeys } from "../personal-data/tenant-keys.ts"; export interface WriteDeclarationFunction { ( - store: Pick, + transaction: { + readonly recipients: Pick; + readonly personalKeys: Pick; + }, pending: Omit, ): Promise; } -// Resolves to every port declared, as `declare` does. -export const writeDeclaration: WriteDeclarationFunction = async (store, pending) => { - for (const { from, to } of pending.renames) await store.rename(from, to); - return store.declare(pending.ports, pending.position, pending.at); +// Resolves to every port declared, as `declare` does. A port is presumed told of its categories, +// so each is recorded with it. +export const writeDeclaration: WriteDeclarationFunction = async ( + { recipients, personalKeys }, + pending, +) => { + await personalKeys.recordCategories(pending.ports.flatMap(({ categories }) => categories)); + for (const { from, to } of pending.renames) await recipients.rename(from, to); + return recipients.declare(pending.ports, pending.position, pending.at); }; // Where the declarations a frozen tenant's starts could not write wait, read alike by every @@ -126,7 +135,7 @@ const heldElsewhere = async ( if (claimId === null) return (await storage.inboxLedger.get(key))?.status !== "succeeded"; try { await storage.transact(async (transaction) => { - await writeDeclaration(transaction.recipients, declaration); + await writeDeclaration(transaction, declaration); await transaction.inboxLedger.complete({ ...key, claimId }); }); } catch (error) { diff --git a/packages/core/src/kernel/scheduler/worker.ts b/packages/core/src/kernel/scheduler/worker.ts index e43c00658..5e3093736 100644 --- a/packages/core/src/kernel/scheduler/worker.ts +++ b/packages/core/src/kernel/scheduler/worker.ts @@ -384,6 +384,7 @@ export const createScheduledCommandWorker: CreateScheduledCommandWorkerFunction if (aggregateType === undefined) return; await appendSystemEvent({ eventStore: unit.eventStore, + categories: null, ids, clock, aggregateType, diff --git a/packages/core/src/kernel/system-events.test.ts b/packages/core/src/kernel/system-events.test.ts index a0da12fb8..f455b2f69 100644 --- a/packages/core/src/kernel/system-events.test.ts +++ b/packages/core/src/kernel/system-events.test.ts @@ -28,6 +28,7 @@ const setup = async () => { type: SCHEDULED_COMMAND_FAILED_EVENT, payload: { commandType: "PayOrder", error: "boom", attempts: 3 }, context, + categories: null, }); return { storage, append }; }; @@ -82,6 +83,7 @@ describe("appendSystemEvent", () => { payload: {}, context, person: "c-1", + categories: null, }); expect(appended.person).toBe("c-1"); expect( @@ -89,6 +91,36 @@ describe("appendSystemEvent", () => { ).toEqual([appended]); }); + it("records the categories its payload names before it appends it, where it is told to", async () => { + const storage = await memory().createStorage(); + const append = (categories: typeof storage.personalKeys | null) => + appendSystemEvent({ + eventStore: storage.eventStore, + ids: createSequentialIdGenerator(), + clock: createFixedClock(), + aggregateType: "bounda", + aggregateId: "c-1", + type: "ProcessingRestricted", + payload: { + categories: ["marketing"], + restrictions: [{ ground: "accuracy-contested", categories: ["profile", "marketing"] }], + recipients: [{ port: "crm", categories: ["contact"], retained: ["invoices"] }], + }, + context, + person: "c-1", + categories, + }); + await append(null); + expect(await storage.personalKeys.recordedCategories()).toEqual([]); + await append(storage.personalKeys); + expect(await storage.personalKeys.recordedCategories()).toEqual([ + "contact", + "invoices", + "marketing", + "profile", + ]); + }); + it("takes the id and timestamp set before it, when given", async () => { const storage = await memory().createStorage(); const appended = await appendSystemEvent({ @@ -101,6 +133,7 @@ describe("appendSystemEvent", () => { payload: {}, context, identity: { id: "intended", timestamp: "2026-01-02T03:04:05.000Z" }, + categories: null, }); expect(appended.id).toBe("intended"); expect(appended.timestamp).toBe("2026-01-02T03:04:05.000Z"); diff --git a/packages/core/src/kernel/system-events.ts b/packages/core/src/kernel/system-events.ts index f96b72288..92ecbc049 100644 --- a/packages/core/src/kernel/system-events.ts +++ b/packages/core/src/kernel/system-events.ts @@ -1,4 +1,5 @@ import type { EventStore } from "../adapter/storage/event-store.ts"; +import type { PersonalKeyStore } from "../adapter/storage/personal-key-store.ts"; import type { Clock } from "../contracts/clock.ts"; import type { StoredEvent } from "../contracts/event.ts"; import type { IdGenerator } from "../contracts/ids.ts"; @@ -13,6 +14,7 @@ import { SCHEDULED_COMMAND_FAILED_EVENT, TENANT_FORGOTTEN_EVENT, } from "../modules/bounda-events.ts"; +import { categoriesNamedBy } from "./personal-data/named-categories.ts"; import type { ErrorIdentity } from "./shared/retry.ts"; // Every event `appendSystemEvent` writes: those of the `bounda` aggregate, and @@ -57,6 +59,11 @@ export interface AppendSystemEventArgs { * from `ids` and `clock` when omitted. */ readonly identity?: { readonly id: string; readonly timestamp: string }; + /** + * Where the categories the payload names are recorded first, in the same transaction: the + * transaction's personal keys, `null` for an event that names none. + */ + readonly categories: Pick | null; } export interface AppendSystemEventFunction { @@ -79,7 +86,9 @@ export const appendSystemEvent: AppendSystemEventFunction = async ({ context, person = null, identity, + categories, }) => { + await categories?.recordCategories(categoriesNamedBy(payload)); const { version } = await eventStore.load({ aggregateType, aggregateId, diff --git a/packages/core/src/kernel/test-support.ts b/packages/core/src/kernel/test-support.ts index 5dc74b693..048b7c2e1 100644 --- a/packages/core/src/kernel/test-support.ts +++ b/packages/core/src/kernel/test-support.ts @@ -665,11 +665,24 @@ export interface WithoutLedgerArgs { readonly clock: Clock; } +/** + * Where a test that records no category in a store records the categories a ledger entry names. + */ +export const unrecordedCategories: Pick = { + recordCategories: async () => undefined, +}; + /** * The intentions of an app without a forget ledger: ids and times, nothing recorded. */ export const withoutLedger = ({ ids, clock }: WithoutLedgerArgs): ForgetIntentions => - createForgetIntentions({ ledger: null, ids, clock, logger: silentLogger }); + createForgetIntentions({ + ledger: null, + categories: unrecordedCategories, + ids, + clock, + logger: silentLogger, + }); /** * What read models seal with when no person has a key: what a test of read models without diff --git a/packages/core/src/memory/personal-key-store.ts b/packages/core/src/memory/personal-key-store.ts index 7d5441214..8f868310e 100644 --- a/packages/core/src/memory/personal-key-store.ts +++ b/packages/core/src/memory/personal-key-store.ts @@ -237,6 +237,9 @@ export const createKeptPersonalKeyStore: CreateKeptPersonalKeyStoreFunction = ({ a < b ? -1 : a > b ? 1 : 0, ), recordedCategories: async () => [...recorded.keys()].sort(), + recordCategories: async (named) => { + for (const category of named) recorded.set(category, (recorded.get(category) ?? 0) + 1); + }, clear: async () => { const removed = keys.size; keys.clear(); diff --git a/packages/core/src/memory/tenant-fence.ts b/packages/core/src/memory/tenant-fence.ts index f3ab025c6..d636c50c7 100644 --- a/packages/core/src/memory/tenant-fence.ts +++ b/packages/core/src/memory/tenant-fence.ts @@ -52,6 +52,7 @@ export const FENCED_WRITES = { "clear", "releaseHolds", "releaseDueHolds", + "recordCategories", ], persons: ["restrict", "unrestrict", "record", "hold", "releaseHolds"], recipients: [ diff --git a/packages/core/src/memory/transaction.ts b/packages/core/src/memory/transaction.ts index 246447e50..08e2b14a9 100644 --- a/packages/core/src/memory/transaction.ts +++ b/packages/core/src/memory/transaction.ts @@ -250,6 +250,10 @@ const trackedPersonalKeys = ( kids: () => personalKeys.kids(), categories: () => personalKeys.categories(), recordedCategories: () => personalKeys.recordedCategories(), + recordCategories: async (named) => { + await personalKeys.recordCategories(named); + for (const category of named) undos.push(() => unrecord(category)); + }, // Only once the tenant is forgotten, never inside a transaction. clear: () => personalKeys.clear(), // Only after a restore, never inside a transaction. diff --git a/packages/core/src/modules/personal-data.ts b/packages/core/src/modules/personal-data.ts index d2b492e5f..0c62f1a25 100644 --- a/packages/core/src/modules/personal-data.ts +++ b/packages/core/src/modules/personal-data.ts @@ -247,7 +247,8 @@ export interface PersonalDataCategory { /** * Retires the category: no field, call or decision names it any more, while what was marked in * it before stays under its retention and exemptions, never forgotten at once, and the exports - * say it is retired. A category the store recorded keys in is never dropped from + * say it is retired. A category the store recorded, by a key or by any write that named it, as a + * restriction, a forgetting or a recipient's declaration does, is never dropped from * `bounda.personal-data.ts`, which refuses the start: it is retired instead, and stays so. */ readonly retired?: true; diff --git a/packages/postgresql/src/migrations.ts b/packages/postgresql/src/migrations.ts index 824e47861..6631dd52e 100644 --- a/packages/postgresql/src/migrations.ts +++ b/packages/postgresql/src/migrations.ts @@ -4,6 +4,7 @@ import { eventMarksTableStatement, eventTypesTableStatement, fillEventTypesStatement, + fillNamedCategoriesStatements, fillOpenedEventTypesStatement, fillPersonalCategoriesStatement, forgetLedgerAppliedAgainStatement, @@ -340,8 +341,10 @@ const catalogue = async (tx: SqlTransaction, tables: StorageTables): Promise Date: Fri, 4 Dec 2026 12:48:59 +0100 Subject: [PATCH 20/33] docs: retire event types and personal-data categories, redact by envelope, and upgrade to 0.6.0 Changing events gains retiring an event type and what a start refuses, with every message. Personal data gains retiring a category, the recorded-categories refusal, sealing a retired type by recorded marks, redaction's five outcomes and the export, inventory and tenant-export versions. Adapters gain what an adapter of your own implements since 0.6.0; deployment, dead letters, conventions, CLI, errors, GDPR, limitations, read models and project layout follow. --- docs/src/content/docs/adapters/index.mdx | 26 +++ .../content/docs/guides/changing-events.md | 113 +++++++++++- docs/src/content/docs/guides/dead-letters.md | 9 +- docs/src/content/docs/guides/deployment.mdx | 33 ++++ docs/src/content/docs/guides/personal-data.md | 169 ++++++++++++++---- .../content/docs/guides/project-layout.mdx | 5 +- docs/src/content/docs/guides/read-models.md | 7 + docs/src/content/docs/reference/cli.md | 29 ++- .../src/content/docs/reference/conventions.md | 23 ++- docs/src/content/docs/reference/errors.md | 10 +- docs/src/content/docs/reference/gdpr.md | 14 +- .../src/content/docs/reference/limitations.md | 7 +- 12 files changed, 379 insertions(+), 66 deletions(-) diff --git a/docs/src/content/docs/adapters/index.mdx b/docs/src/content/docs/adapters/index.mdx index e27737a93..848c67431 100644 --- a/docs/src/content/docs/adapters/index.mdx +++ b/docs/src/content/docs/adapters/index.mdx @@ -176,6 +176,32 @@ SQL that names the read model's table by hand keeps writing to the live table du through `table`, and keep `client` for what `table` cannot say. ::: +## An adapter of your own + +An adapter implements the stores `@bounda-dev/core/adapter` declares and proves them with the +contracts of `@bounda-dev/core/adapter/testing`, `eventStoreContract`, `storageTransactionContract`, +`deadLetterStoreContract`, `storageSchemaContract` and the rest, which every adapter here passes. One +over a SQLite engine gets them all from [`createSqliteAdapter`](/adapters/sqlite/). Since 0.6.0, one +of its own also implements: + +- **The marks of each event type.** `EventStore.recordMarks` records each set of marks an event type + had, by aggregate type, type and fingerprint, once and never removed; `marksOf` reads them back in + the order they were first recorded, for one type or for every type; `recordSealed` raises a set's + `sealedThrough` to the position given, never lowers it, and clears it on the type's other sets + sealed no further, so the set sealed last holds the highest. Each is a write refused behind the + tenant's fence, as `append` is, and a transaction's event store stages them with the rest. +- **Which kinds opened a stream.** `StoredEventType.opened`, set once an event of the kind is + appended at version 1 of its stream, or a `reseal` writes one there, and never taken back. +- **The instance of a process letter.** `StoredDeadLetter.instanceId`, kept and read back as given. +- **Checkpoints in a transaction.** `StorageTransaction.checkpointStore` writes checkpoints with + the transaction's other writes, or not at all. Transactions run one at a time, so a checkpoint the + work reads is written by no other transaction until it ends: the runtime takes the backfill's + lease in one, and records a walk's sets sealed only in one that finds no lease of other marks taken + since the walk read them. + +An adapter written for an earlier Bounda does not type-check against 0.6.0 until it has the methods +and fields above, and does not pass the contracts until it keeps what they hold. + ## Which one to deploy | | SQLite and libSQL | PostgreSQL | Cloudflare | diff --git a/docs/src/content/docs/guides/changing-events.md b/docs/src/content/docs/guides/changing-events.md index d274141d8..a0b6cf365 100644 --- a/docs/src/content/docs/guides/changing-events.md +++ b/docs/src/content/docs/guides/changing-events.md @@ -96,9 +96,11 @@ A database written before the catalogue has it filled from its events when it mi - **At start.** An app, a [rebuild](/guides/deployment/#rebuilding-a-read-model) and the commands of the CLI that open the store read the catalogue, and refuse to start, with a - `ConfigurationError` naming each kind, while it holds an event this code cannot read: a schema - version past the one its upcasters reach, or a type of the runtime's own events, or of a - process's lifecycle, that this Bounda does not know. + `ConfigurationError` naming each kind, while it holds an event this code does not account for: + a schema version past the one its upcasters reach; a type of the runtime's own events, or of a + process's lifecycle, that this Bounda does not know; or a type of one of the app's aggregates + that no module of the aggregate names, neither an event nor a [retired](#retiring-an-event-type) + one. A type of an aggregate this code does not know at all is left alone. - **While it runs.** An event newer code wrote after the start, in a schema version past this code's or of a type it has no module for, is never read in a shape it does not know: every read that meets it rejects with a [`SchemaAheadError`](/reference/errors/#codes), `SCHEMA_AHEAD`. @@ -116,8 +118,8 @@ A database written before the catalogue has it filled from its events when it mi - **An event no Bounda wrote.** One this code cannot read whose kind the catalogue does not hold was written by something other than Bounda: reads reject with a `ConfigurationError` instead. -A kind of event the catalogue held at the start whose module the code no longer has is read as -stored, as before the catalogue: see [what is not covered yet](#what-is-not-covered-yet). +An event of a type its aggregate [retired](#retiring-an-event-type) is read as stored, in whatever +schema version wrote it. ## When to write one, and when not to @@ -128,6 +130,8 @@ stored, as before the catalogue: see [what is not covered yet](#what-is-not-cove `currency: "EUR"` above. - **Something that was never in the payload and cannot be derived**: not an upcaster. Introduce a new event type and keep handling the old one; upcasters transform, they do not invent. +- **An event the domain no longer records**: not an upcaster either. [Retire](#retiring-an-event-type) + its type. Upcasters are cheap but not free: they run on every read of an old event. An aggregate with thousands of old events re-runs the chain on every command, unless it takes @@ -135,11 +139,104 @@ thousands of old events re-runs the chain on every command, unless it takes it over the whole global stream once. Adding an upcaster retires the aggregate's snapshots, as any change to how its state is folded does. +## Retiring an event type + +An event the domain no longer records stays in the store: its events are facts, and the streams +that hold them are read for as long as the store lasts. Retiring its type says so. The module keeps +its file name and exports nothing but `retired`: + +```ts +// app/domain/order/order-noted.ts +export const retired = true; +``` + +Run `bounda generate` after the change, as for any module. From then on: + +- **Nothing new is written.** A retired type has no builder, no `+types` and no member in the + aggregate's events, so no command can append it. +- **A fold skips it.** `begin` and `evolve` never see it, so the aggregate's state is folded + without what it changed, and the aggregate's [snapshots](/concepts/long-streams/#snapshots) are + retired, as for any change to how its state is folded. +- **It is read as stored**, in whatever schema version wrote it. Its upcasters go with it: + `bounda generate` refuses an `.upcast.ts` next to a retired event. +- **Nothing reacts to it.** `bounda generate` refuses a process handler named after it, and a + policy or a projection named after it that exports no `on`, and boot refuses an `on`, or a + process `config` or `correlate`, that names it + (see [conventions](/reference/conventions/#what-the-generator-refuses)). A + [rebuild](/guides/deployment/#rebuilding-a-read-model) replays the stream without it. A run of a + delayed policy whose policy no longer handles its event's type, retired or not, is dropped and + settled, and the worker logs `delayed policy run dropped: the policy no longer handles its event`. + A process that failed on it can still be retried or discarded: its + [dead letter](/guides/dead-letters/#a-failed-process) names the instance. +- **Its personal data stays reachable.** What it holds sealed stays sealed under the person and + category its envelope names, and `forget`, the [export](/guides/personal-data/#exporting-a-persons-data) + and [`redact`](/guides/personal-data/#correcting-a-persons-data) reach it by that envelope. What it + still holds in the clear, written before its fields were marked, is sealed by the + [backfill](/guides/personal-data/#marking-a-field-later) as the type was marked when it had its + module, since no schema marks it any more. + +That last point is why a type is retired one deploy after the last one that had its module. Every +start records what each type it has a module for marks personal, its person field and the category +of each field, in the store's `bounda_event_marks`, once per set of marks: a retired type is sealed +by those. A start on a [frozen tenant](/guides/personal-data/#freezing-a-tenant) records them once +the tenant is thawed. So deploy the code that still has the module, start it once on every tenant +that holds the type, and retire it in the next deploy; when the marks of the type changed since its +events were written, let the backfill catch up first, as `personalDataBackfill.caughtUp` in +`app.getLag()` says. + +### What a start refuses + +An app, a rebuild, `bounda forget-ledger prune` and `bounda forget-ledger stranded` refuse to start +on a store they cannot account for, with a `ConfigurationError` that lists every problem, one a +line: + +``` +The store holds events this code does not account for: +- order.OrderNoted: no module of the aggregate "order" names it. Retire it: add order-noted.ts to the aggregate, exporting only `export const retired = true` +``` + +A type of one of the app's aggregates that no module names is one whose module was deleted: retire +it as the message says. A retired type is refused in the same list when its events opened streams of +an aggregate whose state `begin` sets up, since a fold that skips the event that opened a stream +leaves its state without what it began with: + +``` +- order.OrderOpened is retired, but it opened streams of "order", whose state begin sets up: a fold skips a retired event, so their state would lack what it began with. Keep a module that reads it, as its own does, instead of retiring it +``` + +A retired type whose events the store holds is then checked against the marks the store recorded: + +``` +The store holds events of retired types this code cannot seal: +- order.OrderNoted is retired, but no start recorded what it marks personal: deploy once with its module, on a tenant that is not frozen, then retire it +- order.OrderNoted is retired, and its recorded marks seal values in the category "notes", which bounda.personal-data.ts neither declares nor retires: declare it again, its whole declaration with retired: true +- order.OrderNoted is retired, but its recorded marks give "note" different categories (default, notes) and no backfill walk has sealed every value of it under one of them: deploy once with its module marking note in the category to keep, let the backfill catch up, then retire it +``` + +- **No marks recorded.** No start of this Bounda ran with the type's module, or none on a tenant + that was not frozen: put the module back for one deploy. +- **A category dropped.** The marks seal values in a category `bounda.personal-data.ts` no longer + declares, so nothing would say how long to keep them: [retire the + category](/guides/personal-data/#retiring-a-category) instead of deleting it. +- **Marks that disagree.** Different deploys marked a field in different categories, and the + values it still holds in the clear would be sealed under whichever the store recorded, not under + the one the last code meant. A set of marks under which a backfill walk last sealed the whole + store, with no instance on other marks running, settles it: deploy once with the module marking + the field in the category to keep, wait for `caughtUp`, then retire it. + +The backfill, an export and a redaction check a retired type again against the marks the store +holds when they run, since a walk of other code may have recorded more since the start: on such a +problem the backfill holds its walk and logs it, and an export or a redaction is refused with the +same message, as the next start is. + ## What is not covered yet -- **Renaming or removing an event type.** Upcasters change the payload, not the type. A stored - event whose module is gone still fails to fold; keep the module, even if its `evolve` changes - nothing (`() => ({})`). +- **Renaming an event type.** Upcasters change the payload, not the type, and a retired type is + skipped by every fold, so a new type that takes an old one's place does not see the events stored + under the old name. Keep the old module, even if its `evolve` changes nothing (`() => ({})`), for + as long as the state needs what those events said. The same holds for a type whose events opened + streams of an aggregate whose state `begin` sets up, which [cannot be + retired](#what-a-start-refuses). - **Renaming or retyping a field of a process state.** A process keeps its state in its own lifecycle events and parses it with its `state` schema whenever it loads an instance, so a field added with a default and a field taken out need nothing. A renamed or retyped field has no diff --git a/docs/src/content/docs/guides/dead-letters.md b/docs/src/content/docs/guides/dead-letters.md index 42eaf597f..28e2e60de 100644 --- a/docs/src/content/docs/guides/dead-letters.md +++ b/docs/src/content/docs/guides/dead-letters.md @@ -104,7 +104,8 @@ keys in memory has no text left to open. ## What a letter holds A letter records what gave up and why: its `kind` and `handler`, the event it was about (or the -dropped command, with its payload), how many `attempts` were made and when, the `errorType`, and +dropped command, with its payload), for a process the `instanceId` it failed in, how many +`attempts` were made and when, the `errorType`, and the error itself as `errorName` (its class, `ValidationError`) and `errorCode` (its [code](/reference/errors/), when it is one of Bounda's), with its `errorMessage` and `errorStack`. @@ -183,6 +184,12 @@ stay in its history, and the events that reach it afterwards are dropped, as for has ended. Only a discard does that: an instance whose letter is gone for any other reason keeps parking until its failure is retried. +A process's letter names the instance it failed in, `instanceId`, so a retry or a discard reaches +that instance without routing the event to one again. A process that failed on an event of a type +its aggregate [retired](/guides/changing-events/#retiring-an-event-type) since, which no longer +routes anywhere, is retried as any other: the event it failed on is let through, since no handler +of the process takes it any more, and what is parked behind it runs; or discarded, and abandoned. + The failure is state as well: `ProcessFailed` names its dead letter (`letterId`), and the two are written in the same transaction, with the claim of the event that failed. A failure that could not be written leaves nothing, and the handler runs again once its claim's lease expires. The diff --git a/docs/src/content/docs/guides/deployment.mdx b/docs/src/content/docs/guides/deployment.mdx index 0be7a881c..133ac2e64 100644 --- a/docs/src/content/docs/guides/deployment.mdx +++ b/docs/src/content/docs/guides/deployment.mdx @@ -287,10 +287,43 @@ event types tells each instance which events it can read never forgets keys the new code gave in it, refusing a forget with `SCHEMA_AHEAD` and holding its reactions and retention until the new code runs ([changing a category](/guides/personal-data/#changing-a-category)). +- A deploy that [retires an event type](/guides/changing-events/#retiring-an-event-type) comes + after one that ran with its module: every start records what each type marks personal, and a + retired type's values are sealed by those marks, so a start that finds none recorded is refused. + Deploy the code that still has the module, start it once on every tenant that holds the type, + then retire it. A personal-data category is [retired](/guides/personal-data/#retiring-a-category) + rather than deleted, in any deploy. - Roll forward, never back: once the new code wrote an event, only code that reads it can serve. To take the change back, deploy code that still reads the events, with the upcaster or the type kept, rather than the code before it. +### Upgrading to 0.6.0 + +0.6.0 migrates the storage tables, so stop every instance of the previous version first, as for +any release that migrates ([schema](#schema)). The migration adds `bounda_event_marks`, says in +`bounda_event_types` which kinds of event opened a stream, from the events at version 1 the store +holds, and names in each process's dead letter the instance it failed in, from the `ProcessFailed` +that names the letter. Then, before the first deploy that retires anything: + +- **Start once with every module.** Since a retired type is sealed by the marks a start recorded, + deploy 0.6.0 with every event module the store holds events of, start it on every tenant that is + not frozen, and retire types in a later deploy. +- **A type whose module is gone.** A store holding events of a type of one of the app's + aggregates that no module names refuses the start, naming it. Put its module back for that first + deploy, then retire it. +- **A category dropped from `bounda.personal-data.ts`.** Before 0.6.0 the worker destroyed the keys + of a category the file no longer declared; now a store that recorded it, by a key given in it or + a forgetting or a restriction that named it, refuses the start, naming it. Declare it again, its + whole declaration with `retired: true`. +- **Redactions that did nothing.** A redaction of a field the event does not hold, holds in the + clear unmarked or holds sealed for another person resolved without sealing anything; it is now + refused with `ValidationError` ([correcting a person's + data](/guides/personal-data/#correcting-a-persons-data)). +- **A start writes.** Every start records the marks of its event types the first time it meets + them, and one that marks personal data takes the backfill's lease, on a tenant open to writes. +- **An adapter of your own** implements what [0.6.0 adds](/adapters/#an-adapter-of-your-own) to + the stores, `StorageTransaction.checkpointStore` among them. + ## Rebuilding a read model A read model is derived data: when its projection had a bug, or its view lost a field or changed a diff --git a/docs/src/content/docs/guides/personal-data.md b/docs/src/content/docs/guides/personal-data.md index 48dc59d6a..4646cd6ce 100644 --- a/docs/src/content/docs/guides/personal-data.md +++ b/docs/src/content/docs/guides/personal-data.md @@ -181,7 +181,8 @@ export const payload = ({ z, personal, person }: Event.PayloadArgs) => ``` The generator registers the names, so a category the file does not declare, in `personal`, -`.personal` or `forget`, does not compile, and `.bounda/types.ts` fails to compile while the file +`.personal` or `forget`, does not compile, nor does one it [retired](#retiring-a-category) in +`personal` or `.personal`, and `.bounda/types.ts` fails to compile while the file declares a category `default` or one without a basis Bounda knows, a retention, a purpose or a source, or with [special or criminal data](#special-categories-and-criminal-data) it does not declare as Bounda reads it, while it does not export `automatedDecisions`, or while a decision lacks @@ -355,9 +356,10 @@ keeps past a forgetting that is processed for `direct-marketing`, which an objec A category's retention can change at any time: the sweep reads it as it runs, so a longer or a shorter one applies at once to every person, what a forgetting kept included. So does a basis, a -condition or a claim, and a category removed from the file: a key a forgetting kept is destroyed by -the next pass of the worker once no [exemption](#categories) keeps its category any more, with a -`PersonalDataForgotten` that names it in `expired`, since nothing allows keeping it any more. +condition or a claim: a key a forgetting kept is destroyed by the next pass of the worker once no +[exemption](#categories) keeps its category any more, with a `PersonalDataForgotten` that names it +in `expired`, since nothing allows keeping it any more. A category no field is marked in any more +is [retired](#retiring-a-category), not removed from the file. A field moved to another category, or out of a category into the default one or back, is sealed anew under the person's key of its new category by the [backfill](#marking-a-field-later), in every @@ -369,13 +371,16 @@ forgetting the new one does. A [remembered answer](#remembered-answers) sealed u marks, which may quote it, is erased, and a snapshot of its stream is dropped and folded again. A value no key opens any more, its person forgotten in its old category, stays as it is: it was forgotten already. Going back to -earlier marks walks the stream again too. +earlier marks walks the stream again too. An event of a [retired +type](/guides/changing-events/#retiring-an-event-type) has no marks of today to move to: what it +holds sealed stays in the category it was sealed under. A category a deploy adds is one the previous code does not know while the deploy rolls across instances, so it cannot tell whether the new code keeps a key given in it. The store records every -category a key was ever given in, and an instance reads that record when it starts: a category -recorded then that the app does not declare is one removed, forgotten as above, and one recorded -after the start is the new code's. Its keys are never taken by the previous code: a forget of a +category a key was ever given in, and every category a forgetting or a restriction named, and an +instance reads that record when it starts: a category recorded then that the app neither declares +nor retires refuses the start, as [below](#retiring-a-category), and one recorded after the start +is the new code's. Its keys are never taken by the previous code: a forget of a person as a whole, and a tenant's forget whatever `despiteLegalObligations` says, fails with [`SCHEMA_AHEAD`](/reference/errors/#codes) (`CategoryAheadError`, naming the category), forgetting nothing; a reaction's `forget` tries again every `dispatcher.backoff.baseDelay`; the @@ -384,6 +389,63 @@ that category; and the forget ledger's reconciliation waits for the new code to it forgot in that category, all spending none of their attempts. A forget of other categories goes ahead. Once the new code runs on every instance, the forget goes through: roll forward, never back. +### Retiring a category + +A category the app no longer collects anything in still holds what it collected: values sealed in +events, kept by a forgetting under an exemption, or told to recipients. Retiring it keeps its whole +declaration, its basis, retention, purposes, sources and exemptions, with `retired: true`: + +```ts +// bounda.personal-data.ts +export const categories = { + loyalty: { + basis: "consent", + retention: "730d", + purposes: ["Run the loyalty programme"], + sources: ["data-subject"], + retired: true, + }, + // … +} satisfies PersonalData.Categories; +``` + +- **Nothing new goes in it.** A retired category leaves `PersonalCategoryName`: a field marked in + it with `personal` or `.personal`, an [automated decision](#categories) on it, a + [recipient](#recipients) declared for it and a port whose + [`returnsPersonalData`](/guides/calling-the-outside-world/#personal-data-a-port-returns) names it + do not compile, and + the app refuses to start on them, recording nothing, for a project that skipped the type check: + ` is marked personal in the category "loyalty", which bounda.personal-data.ts retired: mark + it in a category in use`. `retired` takes `true` or nothing. +- **What it holds is kept as it says.** Its [retention](#each-category-for-its-own-time) forgets + each person's key in its time, its exemptions keep it past a forgetting, and `forget`, `restrict` + and `unrestrict` take its name, as [`expectForgotten`](#in-tests) does: those name a category as + `PersonalCategoryName | RetiredPersonalCategoryName`, both from `@bounda-dev/core`, and so does + every runtime event, export and record that names one. The [export](#exporting-a-persons-data) + and the tenant export describe it with `retired: true`, and `bounda personal-data inventory` + prints it as `loyalty (retired)`. +- **What moved out of it.** A field moved from it to a category in use is sealed anew there by the + [backfill](#marking-a-field-later), as for any move: once the walk catches up, what the retired + category holds is what a forgetting kept and what events of [retired + types](/guides/changing-events/#retiring-an-event-type) sealed in it. + +The entry stays in the file for good, as a retired event type's module does. The store records every +category a key was given in and every category a forgetting or a restriction named, and an app, a +`bounda forget-ledger prune` and a `bounda forget-ledger stranded` refuse to start on a database +that recorded one the file neither declares nor retires, with a `ConfigurationError` that names +each, forgetting nothing: + +``` +bounda.personal-data.ts neither declares nor retires categories the store has recorded: "loyalty". Newer code may declare them, or this code dropped them: deploy that code, or declare each again, its whole declaration with retired: true, which keeps what was marked in it under its retention and exemptions +``` + +This code cannot tell a category it dropped, whose keys forgetting at once would destroy before +their retention and past their exemptions, from one that newer code in a rolling deploy declares and +keeps. A category the store never recorded, which no key, forgetting or restriction ever named, may +be deleted from the file. A [retired event type](/guides/changing-events/#what-a-start-refuses) +whose recorded marks seal in a category the file neither declares nor retires is refused the same +way. + ## In a command's payload A command is stored too when it waits: dispatched with `delay`, retried by the scheduler after a @@ -533,7 +595,11 @@ holds sealed is opened, `null` where no key opens it any more, as the upcasters upcasters run, and the fields its schema marks today are sealed under the person it was sealed for, or else the one its current shape names, before it is written in place with the current schema version. A field an upcaster renamed or computed is sealed under its name of today, and one it -dropped is gone from the store. While an instance on other marks renews its lease, as one still +dropped is gone from the store. Nothing sealed is written back in the clear under a key the current +schema does not declare: a sealed value the upcasters carry there as it was stays sealed as it was, +and a value they make there from one is sealed in the default category; when +the upcasters cannot read an envelope where they expect a value, every such value the stored payload +did not hold as it is counts as made from one. While an instance on other marks renews its lease, as one still running the previous code in a rolling deploy, which may not know the current version, events are left in their stored shape and sealed as their marks say, and the walk goes back to the first it left once that instance has stopped; `caughtUp` waits for it. From then on an instance of the @@ -545,6 +611,23 @@ An answer remembered under an [`idempotencyKey`](/guides/idempotent-commands/) i marks of its day, which said whom it quotes and in which categories: one sealed under other marks is [erased](#remembered-answers) by the walk, its key kept taken until it expires. +An event of a [retired type](/guides/changing-events/#retiring-an-event-type) has no schema left to +say what it marks, so the walk seals what it holds in the clear by the marks the store recorded: +every start records, once per set, what each type it has a module for marks personal, in +`bounda_event_marks`, and a type keeps those sets once its module is gone. A field takes the category +every recorded set that marks it gives it; where sets disagree, the one of the set under which a +walk last sealed the whole store with no instance on other marks running, which the store keeps as +that set's `sealed_through`; where none settles it, the app refuses to start, as [a retired +type](/guides/changing-events/#what-a-start-refuses) says. The value is sealed for the person the +event names, or else the one that set's person field names, or else the one the newest set that +names somebody does; what is sealed already keeps its envelope. An app whose schemas mark nothing +any more, but whose store holds events of types an earlier deploy marked, still holds personal data: +it needs the [key wrapper](#where-the-keys-live) and the [forget ledger](#the-forget-ledger) as one +that marks fields does, and refuses to start without them, saying `The store holds events of types +an earlier deploy marked personal() or person(), so runtime.personalData.forgetLedger is required` +of the ledger and `The registry marks personal fields, or an earlier deploy did for events the store +holds, so runtime.personalData.keyWrapper must wrap their keys` of the key wrapper. + `app.getLag()` reports where the walk stands, `personalDataBackfill: { position, caughtUp }`, `null` for an app that marks nothing: `caughtUp` once the walk has sealed the stream up to its head and every scheduled command and dead letter as the marks of now say, which is when an export or a @@ -739,27 +822,27 @@ the whole export in memory: for a person with a long history, [stream it](#a-lon ```ts { - version: 1, + version: 3, personId: "c-42", exportedAt: "2026-03-01T10:00:00.000Z", position: 812, categories: { default: { basis: null, special: null, criminal: null, purposes: [], processedFor: [], - erasureExemptions: [], sources: [], retention: "730d", held: true, + erasureExemptions: [], sources: [], retention: "730d", retired: false, held: true, keptUntil: "2028-02-28T10:00:00.000Z", restrictedUntil: null }, profile: { basis: "contract", special: null, criminal: null, purposes: ["Run the customer's account"], processedFor: [], erasureExemptions: [], - sources: ["data-subject"], retention: "30d", held: true, + sources: ["data-subject"], retention: "30d", retired: false, held: true, keptUntil: "2026-03-30T10:00:00.000Z", restrictedUntil: null }, newsletter: { basis: "consent", special: null, criminal: null, purposes: ["Send the newsletter they signed up for"], processedFor: ["direct-marketing"], - erasureExemptions: [], sources: ["data-subject"], retention: "730d", held: false, - keptUntil: null, restrictedUntil: null }, + erasureExemptions: [], sources: ["data-subject"], retention: "730d", retired: false, + held: false, keptUntil: null, restrictedUntil: null }, invoices: { basis: "legal-obligation", special: null, criminal: null, purposes: ["Keep the invoices tax law requires"], processedFor: [], erasureExemptions: [{ exemption: "legal-obligation", article: "17(3)(b)" }], sources: ["data-subject", { kind: "third-party", name: "Stripe" }], retention: "6y", - held: true, keptUntil: "2032-02-28T10:00:00.000Z", restrictedUntil: null }, + retired: false, held: true, keptUntil: "2032-02-28T10:00:00.000Z", restrictedUntil: null }, }, rights: [ { right: "access", article: "15", categories: null }, @@ -848,7 +931,8 @@ the whole export in memory: for a person with a long history, [stream it](#a-lon else: a release that changes what a section holds, or adds one, numbers a new version. An export without it was written before Bounda numbered the format. Version 2 lists each recipient disclosed data with the transfer [kept with the disclosure](#what-a-disclosure-keeps), once under each -transfer, where version 1 derived it as the export was written. +transfer, where version 1 derived it as the export was written. Version 3 says of each category +whether it is [`retired`](#retiring-a-category). The export says everything article 15(1) of the GDPR asks besides the data, from what the app declares, so nothing has to be written by hand next to it: @@ -869,6 +953,7 @@ which declares none; its [`special`](#special-categories-and-criminal-data) cate their condition of article 9(2), and the authority it processes `criminal` data under, each `null` when it holds none; its `purposes`, those among them the GDPR has [rules for](#purposes-and-exemptions), `processedFor`, and its `sources`, none for the default category; +whether the app [`retired`](#retiring-a-category) it, collecting nothing in it any more; the `erasureExemptions` that keep it past their erasure, each with its point of article 17(3), none when erasure reaches it; how long it is kept after their last activity, its `retention`, `null` when nothing forgets it for inactivity; whether @@ -879,7 +964,11 @@ whole, and the category's own for one an exemption keeps past it, `null` when no they hold none; and, for a category an exemption kept past a forgetting, when what was kept goes, `restrictedUntil`. While they are [restricted](#restricting-processing), the retention waits for the restriction to be lifted, as `restrictions` shows, so either date is when it goes at the -soonest. Every record lists the category of each field of its `data` in `categories`. +soonest. Every record lists the category of each field of its `data` in `categories`. An event's +record holds the fields its type marks now and every other field the store holds sealed for the +person, each under the category its envelope names: an event of a [retired +type](/guides/changing-events/#retiring-an-event-type), or a field its type no longer marks, still +holds their data. `rights` lists their rights, each with its article and the categories it reaches, `null` for all of their data, from the basis each category declares: access, rectification, restriction and the @@ -1129,15 +1218,31 @@ await app.commands.correctEmail({ customerId: "c-42", email: "ana@new.example" } `redact` takes the events whose fields hold the wrong value, each as the person's [export](#exporting-a-persons-data) lists it, its `aggregateType`, `aggregateId`, `type` and `id`, -with the `fields` to seal, so an export record spread with `fields` is a target. The types say which -fields each event type marks `personal`: a field the type does not mark, or an event type that marks -none, does not compile, and a process's lifecycle events that carry its state, `ProcessStarted`, -`ProcessHandled`, `ProcessDeadlineReached` and `ProcessTimedOut` of the stream -`process:.`, take the fields its [state](#in-a-processs-state) marks. Every -event named must name the person: one the store does not hold, of another type or about another -person is refused with `ValidationError`, as are no events, no fields and an empty id, before -anything is redacted or recorded. Redact before you append the correction, so a copy of the old value a read model -quotes in a field is never confused with the new one. +with the `fields` to seal, so an export record spread with `fields` is a target. Every event type of +the app is one, a [retired](/guides/changing-events/#retiring-an-event-type) type and one that marks +nothing now included, and so are a process's lifecycle events that carry its state, +`ProcessStarted`, `ProcessHandled`, `ProcessDeadlineReached` and `ProcessTimedOut` of the stream +`process:.`, whose fields are its [state](#in-a-processs-state)'s. The types +offer by name the fields each marks `personal` and take any other name too, since a field no longer +marked may still hold the person's data sealed under earlier marks. What `redact` does with each +field depends on what the stored event holds in it: + +| The event holds the field | `redact` | +| --- | --- | +| sealed for the person | seals it for good | +| in the clear, where its type marks it now, or, for a retired type, where a set of marks the store recorded marks it | seals it for good, as the [backfill](#marking-a-field-later) would have sealed it | +| `null`, where it is marked so | leaves it: there is nothing to seal | +| in the clear otherwise | refuses: `it holds "plan" in the clear` | +| sealed for another person | refuses: `it holds "email" sealed for another person` | +| not at all | refuses: `it holds no "note"` | + +A refusal is a `ValidationError`, `redact cannot reach the event : `, and so is an event +the store does not hold, of another type or that does not name the person; a stream and type the app +knows nothing of is refused as `redact cannot reach .: the app has no such event +type`, `the app runs no such process` or `it carries no state of the process`; and so are no events, +no fields and an empty id. Anything refused is refused before anything is redacted or recorded. +Redact before you append the correction, so a copy of the old value a read model quotes in a field +is never confused with the new one. In one transaction it opens each field under the person's key and seals the value anew under a key made for the redaction and let go at once, in place, so from then on the field reads as `null`, as @@ -1206,7 +1311,8 @@ appends the correction names the person's consent, `app.commands.correctEmail(pa processRestricted: "consent" })`, before the restriction is lifted with `unrestrict`. A redaction is in the [forget ledger](#backups) before it commits, with the events and fields it was asked for, and a restore of a copy taken before it, or a commit that never happened, redacts them again -at the next reconciliation, under its own id and time. A redaction racing a +at the next reconciliation, under its own id and time, reaching each field sealed for the person by +its envelope, one its type no longer marks included. A redaction racing a forgetting is settled by whichever commits first, the other finding nothing left to open. Every [recipient](#recipients) that received data of the person in a category redacted is told, and a read model may project the event from `projections/bounda/personal-data-redacted.ts`, typed @@ -2230,14 +2336,15 @@ database. As JSON it is what `personalDataInventory` returns, `version` first: t format, `PERSONAL_DATA_INVENTORY_VERSION`, which a release that changes what a list holds, or adds one, raises, and which a record printed before Bounda numbered the format lacks. Version 2 adds the fields left unmarked and what an export holds back of each record, and names each field without a -basis in a finding of its own. The record lists: +basis in a finding of its own. Version 3 says of each category whether it is +[`retired`](#retiring-a-category). The record lists: - each [category](#categories), with its basis, the [special categories of data and the criminal data](#special-categories-and-criminal-data) it holds, with their condition or authority, its purposes and those the GDPR has [rules for](#purposes-and-exemptions), its sources, the ports whose calls [return its data](/guides/calling-the-outside-world/#personal-data-a-port-returns), how long after the person's last activity it is kept, the exemptions of article 17(3) that keep it - past erasure, and how many fields are in it; + past erasure, and how many fields are in it, a [retired](#retiring-a-category) one marked so; - each [automated decision](#categories) the app declares, with its categories, logic, significance, consequences, whether it profiles, its ground, the special data it decides on and its measures; @@ -3037,11 +3144,11 @@ then hands out, in this order: | Part | What it holds | | --- | --- | -| `header` | `format` (`"bounda.tenant-export"`) and `version` (`9`), the tenant, the export's `exportId`, `exportedAt`, the `position` of the stream's head when it began, `frozenAt`, `reached`, how far in the stream each read model's rows and the forget ledger's copy of it got, `forgetLedger` `null` without one, every category of the app as `bounda.personal-data.ts` declares it, with the `ports` whose `returnsPersonalData` says they return its data, the `transfers`, the stores kept in another jurisdiction as a person's export lists them, and every read model, in the order their rows come | +| `header` | `format` (`"bounda.tenant-export"`) and `version` (`10`), the tenant, the export's `exportId`, `exportedAt`, the `position` of the stream's head when it began, `frozenAt`, `reached`, how far in the stream each read model's rows and the forget ledger's copy of it got, `forgetLedger` `null` without one, every category of the app as `bounda.personal-data.ts` declares it, whether [`retired`](#retiring-a-category) included, with the `ports` whose `returnsPersonalData` says they return its data, the `transfers`, the stores kept in another jurisdiction as a person's export lists them, and every read model, in the order their rows come | | `person` | each person who holds a key, in force or kept, or whom the runtime keeps a record of, a restriction or, under a [retention](#retention), their activity, once, by id: `lastActiveAt`, `forgottenAt`, the categories they hold data of with `keptUntil` and `restrictedUntil`, their `restrictions`, and the [recipients](#recipients) of their data, as their own export lists them | | `recipient` | each recipient of the tenant's data, the `person` parts' recipients summed: one per port, identity it had then, its `country` and `transfer` included, and status, the categories concerned, the earliest and latest disclosure, and how many `persons` list it so; and each recipient the app declares that no person lists under its identity now, `declared`, for none | | `forgottenRecipient` | each recipient that persons since [forgotten](#forgetting-a-person) were listed with, one per port, identity it had then, its `country` and `transfer` included, and status, `disclosed` or `presumed`: how many `persons` forgettings took off it whole, and each category taken off it with its `basis` and how many `persons`; never whom, nor when | -| `event` | every event of the stream up to the header's `position`, as the handlers read it today: upcast, its whole `payload` opened, with its `metadata` and the `person` it names; `categories` names the category of each field marked `personal`, `restricted` the fields the controller may only keep, and `redacted` the fields a [redaction](#correcting-a-persons-data) sealed for good | +| `event` | every event of the stream up to the header's `position`, as the handlers read it today: upcast, its whole `payload` opened, with its `metadata` and the `person` it names; `categories` names the category of each field marked `personal`, `restricted` the fields the controller may only keep, each by the restrictions of the person its envelope names, and `redacted` the fields a [redaction](#correcting-a-persons-data) sealed for good | | `scheduledCommand` | every command waiting to run, its payload opened, with the `persons` it names | | `deadLetter` | every [dead letter](/guides/dead-letters/), whatever its status, its error's text and payload opened | | `subscriberFailure` | every subscriber's last failure, its text opened | diff --git a/docs/src/content/docs/guides/project-layout.mdx b/docs/src/content/docs/guides/project-layout.mdx index e86d98ec1..49d5c3ef3 100644 --- a/docs/src/content/docs/guides/project-layout.mdx +++ b/docs/src/content/docs/guides/project-layout.mdx @@ -85,7 +85,10 @@ of those folders. ## Aggregates: `app/domain//` A module at the root of the aggregate is an event when it exports `payload`, `begin` or `evolve`, -and nothing else at run time: those names are an event's alone. It is a port when +and nothing else at run time: those names are an event's alone. One that exports only +`retired = true` is an event type the domain no longer records, whose stored events stay +([retiring an event type](/guides/changing-events/#retiring-an-event-type)). A module there is a +port when `infrastructure/` holds a directory named after it. Anything else there, files and directories alike, is yours: a value object, a domain service, a helper the handlers import, which the generator leaves alone. `state.ts` and `.upcast.ts` are the only other names it reads. diff --git a/docs/src/content/docs/guides/read-models.md b/docs/src/content/docs/guides/read-models.md index 939e0354d..b37ae2a06 100644 --- a/docs/src/content/docs/guides/read-models.md +++ b/docs/src/content/docs/guides/read-models.md @@ -79,6 +79,13 @@ field naming whose each row is with `.person()`, or its view exports `holdsPerso when it keeps nothing of the person's: see [Personal data](/guides/personal-data/#personal-data-in-read-models). +An event type its aggregate [retired](/guides/changing-events/#retiring-an-event-type) is projected +by nothing: `bounda generate` refuses a projection named after it that exports no `on`, and boot +refuses an `on` that names it, so its projections go with it. What they wrote stays in the table +until the read model is [rebuilt](/guides/deployment/#rebuilding-a-read-model), which replays the +stream without the retired events; a rebuild is refused, as a start is, on a store holding a type no +module names. + ## The table Projections and queries receive `table`, typed from the view. `upsert` and `insert` take a whole diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index c2fd037e1..340a961fa 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -221,8 +221,11 @@ rebuilt read model "orderSummary": 48213 events, checkpoint at position 48213 ``` Use it after fixing a projection, and when a view loses a field or changes a field's type, which the -app refuses to do on start. Exit codes: `0` rebuilt, `1` bad arguments, `2` the project could not be -loaded, the read model is not in the registry, or a projection failed. +app refuses to do on start. It refuses, as a start does, a store holding events this code does not +account for, a type no module names or a retired type it cannot seal among them (see [what a start +refuses](/guides/changing-events/#what-a-start-refuses)). Exit codes: `0` rebuilt, `1` bad +arguments, `2` the project could not be loaded, the read model is not in the registry, the store +was refused, or a projection failed. ## `bounda dead-letters` @@ -549,7 +552,7 @@ Prints the record of processing activities of article 30 of the GDPR, as far as configuration say it: the categories of personal data with their basis, the special categories of data and the criminal data they hold, with their condition or authority, their purposes, those the GDPR has rules for, their sources, the ports whose calls return their data, their retention and the -exemptions of article 17(3) that keep them past erasure, the automated decisions, with the special data they decide on and their measures, every +exemptions of article 17(3) that keep them past erasure, a [retired](/guides/personal-data/#retiring-a-category) one printed as `name (retired)`, the automated decisions, with the special data they decide on and their measures, every event, command, process state and read model that holds personal data, whose and where, every recipient, what the runtime keeps about persons and for how long, with what a person's export holds back of it, the fields marked `notPersonal` and every field left unmarked. It loads the project as `bounda rebuild` does and opens no database; in a Cloudflare @@ -585,6 +588,9 @@ Categories for: Send the newsletter they signed up for from: the person processed for: direct-marketing + loyalty (retired) consent forgotten 2y after last activity 0 fields + for: Run the loyalty programme + from: the person invoices legal-obligation forgotten 6y after last activity 3 fields for: Keep the invoices tax law requires from: the person @@ -717,8 +723,10 @@ JSON, each as the person's export lists it, `aggregateType`, `aggregateId`, `typ the `fields` to seal, and prints `redacted 2 events of c-42`; blank lines are skipped. When what it lists reads as `null` already it prints `nothing of c-42 left to redact: what was listed reads as null already`. A line that is not such an object fails before booting, naming the line and never -what it holds; an event the store does not hold, that does not name the person, or a field its -type does not mark `personal` fails with `VALIDATION_FAILED` and nothing is redacted. Append the +what it holds; an event the store does not hold, that does not name the person, or a field it +holds in the clear unmarked, sealed for another person or not at all fails with `VALIDATION_FAILED` +and nothing is redacted (see [correcting a person's +data](/guides/personal-data/#correcting-a-persons-data)). Append the corrected value with the app's own command. ## `bounda forgotten` and `bounda forget --from` @@ -1056,8 +1064,12 @@ entry older than `keepFor` the database has yet to apply, as one a copy restored stopped lacks, and keeps it and every later one, so that copy is forgotten again at its next start; run it again after. A forgotten tenant's ledger is pruned past `keepFor` alone, as its app does. It opens the tenant's database as an app of the tenant does, through the tenant's keys, only when an -entry older than `keepFor` is there, and creates no table in a database without them. Running -instances of the tenant may run beside it. +entry older than `keepFor` is there, and creates no table in a database without them. It refuses a +tenant's database, as the tenant's app refuses it at start, while it holds events this code does not +[account for](/guides/changing-events/#what-a-start-refuses), or records a personal-data category +the code neither declares nor [retires](/guides/personal-data/#retiring-a-category): it judges what +to prune by the categories and the marks that database recorded. Running instances of the tenant +may run beside it. With `--all-tenants` it also prunes a tenant's entries in a store its configuration no longer names as its ledger, as one it named before its ledger moved, among @@ -1124,7 +1136,8 @@ application by hand, where its reconciliation reads, or the store is among its ` and holds it where the reconciliation reads that store; or in that ledger, from before there, unless a record of its application sits where the reconciliation reads. A store a definition opens only for another tenant is read through that tenant's ledger, as `--all-tenants` prunes it. A forgetting for inactivity is left to -the retention. The count goes to standard error, so standard output is the list alone: +the retention. It refuses a tenant's database as `bounda forget-ledger prune` does. The count goes +to standard error, so standard output is the list alone: ``` 2 entries of acme no app applies diff --git a/docs/src/content/docs/reference/conventions.md b/docs/src/content/docs/reference/conventions.md index 307568772..8619d5ceb 100644 --- a/docs/src/content/docs/reference/conventions.md +++ b/docs/src/content/docs/reference/conventions.md @@ -19,6 +19,7 @@ Names are kebab-case. `` is a name you choose. | --- | --- | | `app/domain//state.ts` | optional: `initialState`, and `aggregateId` (the payload field holding the id) | | `app/domain//.ts` | `payload` (optional), and `begin` for the event that opens the aggregate or `evolve`, or both; nothing else at run time | +| `app/domain//.ts`, retired | `retired = true` and nothing else: an event type the domain no longer records, whose stored events are read as stored and skipped by every fold (see [retiring an event type](/guides/changing-events/#retiring-an-event-type)) | | `app/domain//.upcast.ts` | `upcasts`, oldest version first, next to its event | | `app/domain//.ts` | `interface `, named after the file; it is a port because `infrastructure//` exists. For a port that sends personal data out, `recipient`, `satisfies Port.Recipient`, and the six handlers that tell it: `onPersonalDataForgotten`, `onProcessingRestricted`, `onProcessingRestrictionLiftAnnounced`, `onProcessingRestrictionLifted`, `onPersonalDataRedacted` and `onTenantForgotten` (see [Recipients](/guides/personal-data/#recipients)). For a port whose calls answer what can hold text, `returnsPersonalData`, `satisfies Port.ReturnsPersonalData`: whose personal data each call returns, or `false` (see [personal data a port returns](/guides/calling-the-outside-world/#personal-data-a-port-returns)) | | `app/domain//infrastructure//.ts` | `export default ... satisfies `, or `create`, typed as `CreateImplementation` | @@ -30,7 +31,7 @@ Names are kebab-case. `` is a name you choose. | `app/domain//processes//at-.ts`, `at-timeout.ts` | `handler` | | `app/domain//processes///on-.ts` | `handler`, for that aggregate's event | | `bounda.audit.ts`, at the project root | optional: `onPersonalDataAccess`, typed as `Audit.OnPersonalDataAccess`, where the [access log](/guides/personal-data/#who-opened-what) goes, and `onHostRejection`, typed as `Audit.OnHostRejection`, where the [host log](/guides/personal-data/#refused-requests) goes; without it, the host's logger | -| `bounda.personal-data.ts`, at the project root | optional: `categories`, `satisfies PersonalData.Categories`, the [categories of personal data](/guides/personal-data/#categories) with their basis, retention, purposes, sources, any special or criminal data, the purposes the GDPR has rules for and an exemption from erasure they claim, and `automatedDecisions`, `satisfies PersonalData.AutomatedDecisions`, `{}` for none; without it, every personal field is in the default category | +| `bounda.personal-data.ts`, at the project root | optional: `categories`, `satisfies PersonalData.Categories`, the [categories of personal data](/guides/personal-data/#categories) with their basis, retention, purposes, sources, any special or criminal data, the purposes the GDPR has rules for and an exemption from erasure they claim, `retired: true` on one no field is marked in any more, which keeps its declaration for good (see [retiring a category](/guides/personal-data/#retiring-a-category)), and `automatedDecisions`, `satisfies PersonalData.AutomatedDecisions`, `{}` for none; without it, every personal field is in the default category | | `app/read//view.ts` | `fields`; `.person()` on at most one field, `.personal()` on those that hold that person's data, `.notPersonal()` on those that hold none; `holdsPersonalData = false` (optional) to state it keeps nothing of anyone's data though it projects events with personal fields | | `app/read//projections//.ts` | `project`; `on` optional | | `app/read//projections/bounda/personal-data-forgotten.ts` | `project`, required once its view keeps a field in the clear with `.personal({ clear: true })`, or a projection of the read model sees a field marked `personal` and the view marks no field `.personal()` | @@ -56,7 +57,10 @@ does files that start with `_` or `.`, tests (`*.test.ts`, `*.test-d.ts`), decla - a process handler not named `on-.ts` or `at-.ts`, or one for an event its aggregate does not have; - a module at an aggregate's root that exports an event's function (`payload`, `begin`, `evolve`) - and something else besides, and an `.upcast.ts` with no event next to it; + and something else besides, or that exports `retired` and anything else, and an + `.upcast.ts` with no event next to it or next to a retired one; +- a process handler `on-.ts` of a retired event, and a policy or a projection that exports + no `on` and whose name gives a retired event: nothing reacts to one; - a port's module that exports a recipient's handler and no `recipient`; - a port whose module does not export an interface or a type alias named after it, a port directory with no implementation or with subdirectories, an implementation with no port, and a @@ -105,7 +109,8 @@ data rests on `explicit-consent`, or that is processed for `direct-marketing`; w declare, or decides on special data on a condition other than `explicit-consent` or `substantial-public-interest`, or without its `measures` (article 22(4)), and a category that `personal({ category })`, `.personal({ category })` or `forget` names and the file -does not declare does not compile where it is written. `Recipients` fails to compile while a +does not declare does not compile where it is written, nor does one it retired in `personal` or +`.personal`. `Recipients` fails to compile while a port's module declares a `recipient` and lacks one of its six handlers, naming the port and the event it tells, or while a method of the port answers something other than a promise; a `recipient` whose country is outside the European Economic Area and names no safeguard, or one @@ -119,7 +124,8 @@ Some rules need the modules themselves, so the app checks them when it is create `ConfigurationError`: - a policy or a projection whose trigger is not an event of the aggregate it listens to, the - runtime's own `bounda` included; an event, a command or a process `state` that marks two fields + runtime's own `bounda` included, or is a retired one, and a process whose `config`, handlers or + `correlate` name a retired event; an event, a command or a process `state` that marks two fields with `person`, and a process `state` that starts with a `personal` or `person` field set; a field given two of `personal`, `person` and `notPersonal`; a field or a column that can hold text and has none of them, and a payload or a state that holds text out of a mark's reach; @@ -153,8 +159,9 @@ Some rules need the modules themselves, so the app checks them when it is create decision without categories it declares, a `logic`, `significance` or `consequences` in words, a `profiling` that is true or false, or a ground article 22(2) names, `measures` that are not in words, or one on special data whose condition is neither `explicit-consent` nor - `substantial-public-interest`, or that gives no `measures`; a field - marked personal in a category the file does not declare; + `substantial-public-interest`, or that gives no `measures`; a `retired` that is not `true`; a + field marked personal, a decision, a recipient or a port's `returnsPersonalData` in a category the + file does not declare, or in one it retired; - a `payload`, `repository`, process `state` or `correlate` export that is not a function; - a configuration that names a port, an implementation, an aggregate or a read model that does not exist, or leaves out a port that has several implementations. @@ -182,8 +189,8 @@ and not failed on: | Path | Holds | | --- | --- | | `.bounda/registry.ts` | Every module, grouped as the runtime needs it, and `bounda.audit.ts` as `audit` and `bounda.personal-data.ts` as `personalData` when there are. `boot()` imports it | -| `.bounda/register.d.ts` | Registers the registry type, the type of the `ports` section and the names of the categories of personal data with `@bounda-dev/core/register`, so `boot()` and `BoundaApp` are typed for the project without a type argument, `defineConfig` checks the implementation names, and `personal({ category })` and `forget` check the categories | -| `.bounda/types.ts` | The state, events, ports, commands, rows and queries maps the `+types` build on, how each read model stores its fields (`FieldTypes`, which decides what its table filters each field by), one `Forgetting` check per read model, one `Classification` and one `Classification` check per aggregate and read model, one `Recipients` check per aggregate or read model whose ports declare recipients, one `PortReturns` check per aggregate or read model with ports, `PersonalCategory`, the names `bounda.personal-data.ts` declares, its `PersonalDataDeclaration` check, and the contracts the files at the project root import, which have no `+types`: `PersonalData` (`Categories`, `AutomatedDecisions`) and `Audit` (`OnPersonalDataAccess`, `OnHostRejection`), each when its file exists | +| `.bounda/register.d.ts` | Registers the registry type, the type of the `ports` section and the names of the categories of personal data, in use and retired, as `personalCategories` and `retiredPersonalCategories`, with `@bounda-dev/core/register`, so `boot()` and `BoundaApp` are typed for the project without a type argument, `defineConfig` checks the implementation names, and `personal({ category })` and `forget` check the categories | +| `.bounda/types.ts` | The state, events, ports, commands, rows and queries maps the `+types` build on, how each read model stores its fields (`FieldTypes`, which decides what its table filters each field by), one `Forgetting` check per read model, one `Classification` and one `Classification` check per aggregate and read model, one `Recipients` check per aggregate or read model whose ports declare recipients, one `PortReturns` check per aggregate or read model with ports, `PersonalCategory`, the names `bounda.personal-data.ts` declares in use, `RetiredPersonalCategory`, those it retired, both `never` without the file, its `PersonalDataDeclaration` check, and the contracts the files at the project root import, which have no `+types`: `PersonalData` (`Categories`, `AutomatedDecisions`) and `Audit` (`OnPersonalDataAccess`, `OnHostRejection`), each when its file exists | | `app/**/+types/.ts` | The argument types each module under `app/` imports; a port's: `Port.ReturnsPersonalData`, and, when it declares a `recipient`, `Port.Recipient` and its handlers' arguments. An implementation has none: it imports its port | They are derived from your code, so they are not versioned. `tsconfig.json` must include them as diff --git a/docs/src/content/docs/reference/errors.md b/docs/src/content/docs/reference/errors.md index 754eb9446..479fe415d 100644 --- a/docs/src/content/docs/reference/errors.md +++ b/docs/src/content/docs/reference/errors.md @@ -103,9 +103,13 @@ dead letter with `errorType: "retriable_exhausted"`. - **`INVALID_CONFIGURATION`** (`ConfigurationError`; terminal). `bounda.config.ts` or the registry is malformed: an unknown key, a port with no implementation chosen, a module missing an export. Thrown at boot, or when a handler reads a port a test left out. Also thrown at start by a - database whose Bounda tables a version before 0.2.0 created; by an app that declares personal - data, a field marked `personal()` or `person()`, a read model that projects - `PersonalDataForgotten` or a category in `bounda.personal-data.ts`, without + database whose Bounda tables a version before 0.2.0 created; by a store holding events this code + does not account for, a type no module names or a retired type it cannot seal among them ([what a + start refuses](/guides/changing-events/#what-a-start-refuses)), or that recorded a personal-data + category the app neither declares nor [retires](/guides/personal-data/#retiring-a-category); by + an app that declares personal data, a field marked `personal()` or `person()`, a read model that + projects `PersonalDataForgotten` or a category in `bounda.personal-data.ts`, or whose store holds + events of types an earlier deploy marked so, without [`runtime.personalData.forgetLedger`](/reference/configuration/#personal-data), over any storage but `memory()`, or with `formerForgetLedgers` alone; by a configuration that still sets `forgetLedger.strict`, which is gone: the ledger is always strict; and by a forget ledger, in diff --git a/docs/src/content/docs/reference/gdpr.md b/docs/src/content/docs/reference/gdpr.md index 5316aeb7e..b57960bd6 100644 --- a/docs/src/content/docs/reference/gdpr.md +++ b/docs/src/content/docs/reference/gdpr.md @@ -44,7 +44,10 @@ else, in a port's own store, a log, a file, another service, is the app's to ans [inactivity](/guides/personal-data/#inactivity), and a process forgets them when a [purpose of the domain ends](/guides/personal-data/#end-of-purpose). A category declares its retention or the app does not compile; the default category's is the app's setting, which has no - default, and the record of processing flags each field left in it, by name. What the runtime keeps of + default, and the record of processing flags each field left in it, by name. A category the app no + longer collects anything in is [retired](/guides/personal-data/#retiring-a-category), keeping its + declaration, never dropped: what it holds goes after its retention all the same, and a start + refuses a store that recorded a category the app neither declares nor retires. What the runtime keeps of its own work goes too: remembered answers after `runtime.commands.idempotencyKeyLifetime`, a subscriber's last failure once it is resolved, or its subscriber gone, for [`runtime.subscriberFailures.retention`](/reference/configuration/#subscriber-failures), 30 days @@ -175,7 +178,7 @@ answers every item of article 15(1) from what the app declares, nothing written | --- | --- | | confirmation that data is processed, and the data | every record that names the person, with the category of each field, and `held` per category | | (a) the purposes | each category's `purposes`, with its `basis` and, for special or criminal data, its `special` condition or `criminal` authority | -| (b) the categories of data | `categories`, with the special categories of data each holds | +| (b) the categories of data | `categories`, with the special categories of data each holds, and whether the app retired it | | (c) the recipients, and 15(2) the safeguards of a transfer | `recipients`, as `recipientsOf` lists them, a recipient once under each transfer the data went through, each `transfer` with its safeguard, article and legal regime, and `transfers`, the stores kept out of `storage`'s jurisdiction with their regime and safeguard | | (d) how long it is kept | each category's `retention`, `keptUntil` and `restrictedUntil` | | (e) rectification, erasure, restriction and objection | `rights` | @@ -235,7 +238,10 @@ read `null` in every copy restored from then on, removes the snapshots and remem that may quote them, cancels the scheduled commands that hold them and removes their dead letters, seals for good the error text that quotes them, and appends `PersonalDataRedacted`. Read models write over their copies, those that projected the events reached are rebuilt, and every recipient -that received data of a category redacted is told. `bounda redact --from ` does it +that received data of a category redacted is told. It reaches a field by what the stored event +holds: a value sealed for the person, in an event of a [retired +type](/guides/changing-events/#retiring-an-event-type) or a field no longer marked too, or a value +in the clear that its type marks; a field it cannot reach is refused before anything is sealed. `bounda redact --from ` does it from a terminal, and `expectRedacted` checks in a test that the old value is readable nowhere. Each call is [recorded](/guides/personal-data/#erasures-restrictions-and-redactions) in the access log with how many events and fields it sealed, naming no one. @@ -564,7 +570,7 @@ store the actor of every change. from the app's modules and configuration, opening no database: the categories with their basis, the special categories of data and the criminal data they hold, with their condition or authority, their purposes and those the GDPR has rules for, their sources and retention, and the exemptions of 17(3) -that keep them past erasure; the automated decisions; every event, command, process state and +that keep them past erasure, each retired one marked so; the automated decisions; every event, command, process state and read model that holds personal data, whose, how it is kept and where its copies go; the recipients, with their country and the regime, safeguard and article of a transfer; what the runtime keeps about persons and for how long, the dead letters, the subscribers' last failures and the remembered answers among it, with what an export diff --git a/docs/src/content/docs/reference/limitations.md b/docs/src/content/docs/reference/limitations.md index 76f736747..11404ab87 100644 --- a/docs/src/content/docs/reference/limitations.md +++ b/docs/src/content/docs/reference/limitations.md @@ -12,8 +12,11 @@ get today. Each item says why, so nobody discovers it the hard way: events, so a change to that shape has the same problem an event payload has, and no `state.upcast.ts` yet. See [Changing an event's shape](/guides/changing-events/#what-is-not-covered-yet). -- **Renaming or removing an event type.** Upcasters change a payload, not a type. Keep the module, - even if its `evolve` changes nothing. See +- **Renaming an event type.** Upcasters change a payload, not a type, and a + [retired](/guides/changing-events/#retiring-an-event-type) type is skipped by every fold, so a + new type does not take an old one's place in the streams that hold it. Keep the old module, even + if its `evolve` changes nothing; the same for a type whose events opened streams of an aggregate + whose state `begin` sets up, which cannot be retired. See [Changing an event's shape](/guides/changing-events/#what-is-not-covered-yet). - **One trace per request.** Spans carry `bounda.correlation_id` but a policy's span is a separate trace from the command's, because it runs in a later pass. See From 2c2548ce398ddb9dd3d6d7118b163c5c2d66fda0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 12:48:59 +0100 Subject: [PATCH 21/33] chore: changeset for retired event types and categories, and redaction by envelope --- .changeset/redact-by-envelope.md | 5 +++++ .changeset/retired-event-types.md | 7 +++++++ .changeset/retired-personal-categories.md | 6 ++++++ 3 files changed, 18 insertions(+) create mode 100644 .changeset/redact-by-envelope.md create mode 100644 .changeset/retired-event-types.md create mode 100644 .changeset/retired-personal-categories.md diff --git a/.changeset/redact-by-envelope.md b/.changeset/redact-by-envelope.md new file mode 100644 index 000000000..1d271f24a --- /dev/null +++ b/.changeset/redact-by-envelope.md @@ -0,0 +1,5 @@ +--- +"@bounda-dev/core": minor +--- + +`redact` reaches any field of every event type of the app, and of every process lifecycle event that carries its state, a retired type and one that marks nothing now included, by what the stored event holds: a value sealed for the person, or one in the clear where its type marks it, or, for a retired type, where a set of marks the store recorded does. `RedactedFields.fields` takes any field name, offering the marked ones by name, and only a stream and type the app knows nothing of is refused before the store is read. **Breaking:** a field the event does not hold, or holds sealed for another person, which a redaction passed over before, resolving without sealing it, is refused with `ValidationError` (`redact cannot reach the event : it holds no ""`, `… it holds "" sealed for another person`), nothing redacted or recorded; and a field its type does not mark, refused before whatever the event held, is reached when the event holds it sealed for the person and refused as `it holds "" in the clear` when it does not. The reconciliation of the forget ledger redacts again by each field's envelope, a field no longer marked included. The personal-data export lists every field the store holds sealed for the person under the category its envelope names, an event of a retired type and a field no longer marked included, and the tenant export restricts each field by the restrictions of the person its envelope names. diff --git a/.changeset/retired-event-types.md b/.changeset/retired-event-types.md new file mode 100644 index 000000000..6872eb02c --- /dev/null +++ b/.changeset/retired-event-types.md @@ -0,0 +1,7 @@ +--- +"@bounda-dev/core": minor +"@bounda-dev/cli": minor +"@bounda-dev/postgresql": minor +--- + +An aggregate retires an event type it no longer records with a module that exports only `export const retired = true`: the type has no builder, no `+types` and no member in the aggregate's events, every fold skips it, so the aggregate's snapshots are retired, and its events are read as stored in whatever schema version wrote them. `bounda generate` refuses such a module that exports anything else, an `.upcast.ts` next to it, and a process handler, a policy or a projection named after it, and boot refuses an `on`, a process `config` or a `correlate` that names it. A delayed policy run whose policy no longer handles its event's type, retired or not, is dropped and settled, with a warning. A process's dead letter names the instance it failed in, `instanceId`, so a process that failed on an event whose type was retired since is retried, letting the event through, or discarded. **Breaking:** an app, a rebuild, `bounda forget-ledger prune` and `bounda forget-ledger stranded` refuse with a `ConfigurationError` (`The store holds events this code does not account for:`) a store holding events of a type of one of the app's aggregates that no module names, which was read as stored before: retire it. They refuse too a retired type whose events opened streams of an aggregate whose state `begin` sets up: keep its module. Every start records what each event type it has a module for marks personal, once per set of marks, in the new `bounda_event_marks`, and the backfill seals what a retired type still holds in the clear by those marks, where they disagree under the set a walk last sealed the whole store under with no instance on other marks running, which the store keeps as `sealed_through`; a retired type no start recorded marks for, whose marks seal in a category `bounda.personal-data.ts` neither declares nor retires, or whose marks disagree with no such walk, is refused (`The store holds events of retired types this code cannot seal:`), at start and again by the backfill, an export and a redaction: deploy once with the module, on a tenant that is not frozen, before retiring it. An app whose store holds events of types an earlier deploy marked personal needs the key wrapper and the forget ledger even when its schemas mark nothing any more. The backfill never writes back in the clear what an upcaster carries, or makes from a sealed value, under a key the current schema does not declare, and its walk renews its lease while it is held, so instances on other marks see it running. A storage migration, on SQLite and PostgreSQL, adds `bounda_event_marks`, an `opened` column to `bounda_event_types`, filled from the events at version 1 the store holds, and an `instance_id` column to `bounda_dead_letters`, filled from the `ProcessFailed` that names each letter. Every start writes the marks it records the first time it meets them, and one that marks personal data takes the backfill's lease, on a tenant open to writes. **Breaking for an adapter of your own:** `EventStore` gains `recordMarks`, `marksOf` and `recordSealed`, which a transaction's event store stages with the rest; `StoredEventType` gains `opened`; `StoredDeadLetter` gains `instanceId`; and `StorageTransaction` gains `checkpointStore`, whose writes commit with the transaction's, transactions running one at a time. `eventStoreContract`, `storageTransactionContract`, `deadLetterStoreContract` and `storageSchemaContract` cover them. diff --git a/.changeset/retired-personal-categories.md b/.changeset/retired-personal-categories.md new file mode 100644 index 000000000..77328a29a --- /dev/null +++ b/.changeset/retired-personal-categories.md @@ -0,0 +1,6 @@ +--- +"@bounda-dev/core": minor +"@bounda-dev/cli": minor +--- + +A personal-data category the app no longer collects anything in is retired in `bounda.personal-data.ts`, its whole declaration kept with `retired: true`. It leaves `PersonalCategoryName`, so a field marked in it, an automated decision on it, a recipient declared for it and a port whose `returnsPersonalData` names it do not compile, and the app refuses to start on them; `forget`, `restrict`, `unrestrict` and `expectForgotten` take its name, typed `PersonalCategoryName | RetiredPersonalCategoryName`, as every runtime event and output that names a category is; and what it holds stays under its retention and exemptions. `RetiredPersonalCategoryName` and `RetiredPersonalCategoriesOf` are exported from `@bounda-dev/core`, and `AppRetiredPersonalCategory` from `@bounda-dev/core/register`. `bounda generate` writes `RetiredPersonalCategory` in `.bounda/types.ts` and registers `retiredPersonalCategories` in `.bounda/register.d.ts`: run it after upgrading. The personal-data export (`PERSONAL_DATA_EXPORT_VERSION` 3), the record of processing activities (`PERSONAL_DATA_INVENTORY_VERSION` 3) and the tenant export (`TENANT_EXPORT_VERSION` 10) say of each category whether it is `retired`, and `bounda personal-data inventory` prints one as `name (retired)`. **Breaking:** a category the store recorded, by a key given in it or a forgetting or a restriction that named it, and that the file neither declares nor retires, refuses the start, `bounda forget-ledger prune` and `bounda forget-ledger stranded` with a `ConfigurationError` naming it, forgetting nothing, where its keys were forgotten at once before: this code cannot tell a category it dropped from one newer code declares. Declare it again, its whole declaration with `retired: true`, and keep the entry for good. From 96e398d4a969256a04b058e968f0307f13d8d776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 16:02:59 +0100 Subject: [PATCH 22/33] fix(core): refuse a rebuild on a category the store recorded that the code neither declares nor retires A rebuild with no app checked the store's event types and the marks of its retired types as a start does, but not its recorded categories: code that dropped a category rebuilt where its start would be refused. --- docs/src/content/docs/reference/cli.md | 3 +- .../named-categories-app.test.ts | 51 +++++++++++++++++-- .../core/src/kernel/read-model/rebuild.ts | 25 +++++++-- 3 files changed, 69 insertions(+), 10 deletions(-) diff --git a/docs/src/content/docs/reference/cli.md b/docs/src/content/docs/reference/cli.md index 340a961fa..2fa0bb5da 100644 --- a/docs/src/content/docs/reference/cli.md +++ b/docs/src/content/docs/reference/cli.md @@ -223,7 +223,8 @@ rebuilt read model "orderSummary": 48213 events, checkpoint at position 48213 Use it after fixing a projection, and when a view loses a field or changes a field's type, which the app refuses to do on start. It refuses, as a start does, a store holding events this code does not account for, a type no module names or a retired type it cannot seal among them (see [what a start -refuses](/guides/changing-events/#what-a-start-refuses)). Exit codes: `0` rebuilt, `1` bad +refuses](/guides/changing-events/#what-a-start-refuses)), or that recorded a personal-data category +this code neither declares nor [retires](/guides/personal-data/#retiring-a-category). Exit codes: `0` rebuilt, `1` bad arguments, `2` the project could not be loaded, the read model is not in the registry, the store was refused, or a projection failed. diff --git a/packages/core/src/kernel/personal-data/named-categories-app.test.ts b/packages/core/src/kernel/personal-data/named-categories-app.test.ts index 6e903bb05..ed3505227 100644 --- a/packages/core/src/kernel/personal-data/named-categories-app.test.ts +++ b/packages/core/src/kernel/personal-data/named-categories-app.test.ts @@ -1,13 +1,17 @@ import { afterEach, describe, expect, it } from "vitest"; import type { Adapter } from "../../adapter/adapter.ts"; import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; +import type { Table } from "../../adapter/storage/table.ts"; import { createFixedClock } from "../../contracts/clock.ts"; import { ConfigurationError } from "../../contracts/errors.ts"; +import type { StoredEvent } from "../../contracts/event.ts"; import { createSequentialIdGenerator } from "../../contracts/ids.ts"; import { memory } from "../../memory/index.ts"; import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; import type { Registry } from "../../modules/registry.ts"; +import type { FieldsArgs } from "../../modules/view.ts"; import { createApp } from "../app.ts"; +import { rebuildReadModel } from "../read-model/rebuild.ts"; import { ledgerFor } from "../test-support.ts"; const said = { purposes: ["Serve the person"], sources: ["data-subject"] }; @@ -88,7 +92,30 @@ const registryOf = ({ marketing, mailer = false }: Deploy): Registry => processes: {}, }, }, - readModels: {}, + readModels: { + notes: { + view: { + fields: ({ f }: FieldsArgs) => ({ customerId: f.string().primaryKey().notPersonal() }), + holdsPersonalData: false, + }, + projections: { + customer: { + noteTaken: { + project: async ({ + event, + table, + }: { + event: StoredEvent; + table: Table<{ customerId: string }>; + }) => { + await table.upsert({ customerId: event.aggregateId }); + }, + }, + }, + }, + queries: {}, + }, + }, }) as unknown as Registry; const stops: (() => Promise)[] = []; @@ -99,14 +126,16 @@ afterEach(async () => { let starts = 0; +const configOf = (adapter: Adapter) => ({ + storage: adapter, + runtime: { personalData: { retention: "1y", forgetLedger: { store: ledgerFor(adapter) } } }, +}); + const started = async (adapter: Adapter, deploy: Deploy) => { starts += 1; const app = await createApp({ registry: registryOf(deploy), - config: { - storage: adapter, - runtime: { personalData: { retention: "1y", forgetLedger: { store: ledgerFor(adapter) } } }, - }, + config: configOf(adapter), ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), clock: createFixedClock(new Date("2026-03-01T00:00:00.000Z")), }); @@ -156,6 +185,18 @@ describe.each(adapters)("a category no key was added in, on %s", (_name, adapter await expect(started(adapter, { marketing: true })).resolves.toBeDefined(); }); + it("refuses a rebuild with no app of code that dropped it, as it refuses the start", async () => { + const adapter = adapterOf(); + const app = await noted(adapter, { marketing: true }); + await app.restrict("c-1", { ground: "accuracy-contested", categories: ["marketing"] as never }); + await app.stop(); + const rebuild = (deploy: Deploy) => + rebuildReadModel({ registry: registryOf(deploy), config: configOf(adapter), name: "notes" }); + + await expect(rebuild({ marketing: false })).rejects.toThrow(DROPPED); + await expect(rebuild({ marketing: true })).resolves.toBeDefined(); + }); + it("refuses the start of code that dropped it once a forgetting named it", async () => { const adapter = adapterOf(); const app = await noted(adapter, { marketing: true }); diff --git a/packages/core/src/kernel/read-model/rebuild.ts b/packages/core/src/kernel/read-model/rebuild.ts index 026fa9126..b0fad3392 100644 --- a/packages/core/src/kernel/read-model/rebuild.ts +++ b/packages/core/src/kernel/read-model/rebuild.ts @@ -26,7 +26,12 @@ import { import { PartialBatchError } from "../dispatch/delivery.ts"; import { appStorage } from "../events/app-event-store.ts"; import { epochMark, openDatabaseKey } from "../personal-data/blind-index.ts"; -import { categoryNamesOf } from "../personal-data/categories.ts"; +import { + type BuildPersonalCategoriesArgs, + buildPersonalCategories, + categoryNamesOf, + checkRecordedCategories, +} from "../personal-data/categories.ts"; import { openEncryptedFiles } from "../personal-data/encrypted-files.ts"; import { keySourcesOf, openKeyHierarchy } from "../personal-data/key-hierarchy.ts"; import { buildKeyWrapper } from "../personal-data/key-wrapper.ts"; @@ -215,7 +220,9 @@ export const resetReadModel: ResetReadModelFunction = async ({ readModel, adapte * the progress and rejects with the projection's error; a rebuild another call took over rejects * with `RebuildSupersededError`. An event newer code wrote pauses it instead, rejecting with * `SchemaAheadError`, and the next call, once that code runs, resumes it; a store that held such an - * event before the call refuses it with a `ConfigurationError`, as an app's start does. + * event before the call refuses it with a `ConfigurationError`, as an app's start does, and so does + * one holding events of a type this code does not account for or cannot seal, or that recorded a + * personal-data category this code neither declares nor retires. * * A rebuild that stops, because `maxEvents` ran out or the process died, resumes where it was on * the next call, unless the read model's fields or projections changed meanwhile: then it starts @@ -312,10 +319,13 @@ export interface RebuildReadModelWithArgs extends Omit => { const types = await storage.eventStore.types(); const stored = checkStoredTypes({ types, aggregates }); @@ -323,6 +333,11 @@ const checkedTypes = async ( types, aggregates: withStoredMarks(aggregates, await storage.eventStore.marksOf()), }); + const recorded = await storage.personalKeys.recordedCategories(); + checkRecordedCategories({ + categories: buildPersonalCategories({ module: registry.personalData, retention, recorded }), + recorded, + }); return stored; }; @@ -375,7 +390,9 @@ export const rebuildReadModelWith: RebuildReadModelWithFunction = async ({ aggregates, processes: { byName: {} }, wrapping, - stored: started ?? (await checkedTypes(storage, aggregates)), + stored: + started ?? + (await checkedTypes(storage, aggregates, registry, config.runtime.personalData.retention)), }); const layout = sealedLayoutOf({ readModel: name, From aaa6f0fffa5a4dff2a140ed1be759d91e635e460 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 16:03:00 +0100 Subject: [PATCH 23/33] docs: say every write that names a category records it, the rebuild refusal and recordCategories Widen what records a category to a key, restrictions and their lifts, forgettings, redactions, disclosures, recipient declarations and forget ledger entries; note that the migration records what stored writes name, so the first start after upgrading may refuse a category dropped earlier; and add PersonalKeyStore.recordCategories to an adapter of one's own and to the changeset. --- .changeset/retired-personal-categories.md | 3 ++- docs/src/content/docs/adapters/index.mdx | 5 +++++ docs/src/content/docs/guides/deployment.mdx | 7 +++++-- docs/src/content/docs/guides/personal-data.md | 18 ++++++++++-------- 4 files changed, 22 insertions(+), 11 deletions(-) diff --git a/.changeset/retired-personal-categories.md b/.changeset/retired-personal-categories.md index 77328a29a..4556ed6a2 100644 --- a/.changeset/retired-personal-categories.md +++ b/.changeset/retired-personal-categories.md @@ -1,6 +1,7 @@ --- "@bounda-dev/core": minor "@bounda-dev/cli": minor +"@bounda-dev/postgresql": minor --- -A personal-data category the app no longer collects anything in is retired in `bounda.personal-data.ts`, its whole declaration kept with `retired: true`. It leaves `PersonalCategoryName`, so a field marked in it, an automated decision on it, a recipient declared for it and a port whose `returnsPersonalData` names it do not compile, and the app refuses to start on them; `forget`, `restrict`, `unrestrict` and `expectForgotten` take its name, typed `PersonalCategoryName | RetiredPersonalCategoryName`, as every runtime event and output that names a category is; and what it holds stays under its retention and exemptions. `RetiredPersonalCategoryName` and `RetiredPersonalCategoriesOf` are exported from `@bounda-dev/core`, and `AppRetiredPersonalCategory` from `@bounda-dev/core/register`. `bounda generate` writes `RetiredPersonalCategory` in `.bounda/types.ts` and registers `retiredPersonalCategories` in `.bounda/register.d.ts`: run it after upgrading. The personal-data export (`PERSONAL_DATA_EXPORT_VERSION` 3), the record of processing activities (`PERSONAL_DATA_INVENTORY_VERSION` 3) and the tenant export (`TENANT_EXPORT_VERSION` 10) say of each category whether it is `retired`, and `bounda personal-data inventory` prints one as `name (retired)`. **Breaking:** a category the store recorded, by a key given in it or a forgetting or a restriction that named it, and that the file neither declares nor retires, refuses the start, `bounda forget-ledger prune` and `bounda forget-ledger stranded` with a `ConfigurationError` naming it, forgetting nothing, where its keys were forgotten at once before: this code cannot tell a category it dropped from one newer code declares. Declare it again, its whole declaration with `retired: true`, and keep the entry for good. +A personal-data category the app no longer collects anything in is retired in `bounda.personal-data.ts`, its whole declaration kept with `retired: true`. It leaves `PersonalCategoryName`, so a field marked in it, an automated decision on it, a recipient declared for it and a port whose `returnsPersonalData` names it do not compile, and the app refuses to start on them; `forget`, `restrict`, `unrestrict` and `expectForgotten` take its name, typed `PersonalCategoryName | RetiredPersonalCategoryName`, as every runtime event and output that names a category is; and what it holds stays under its retention and exemptions. `RetiredPersonalCategoryName` and `RetiredPersonalCategoriesOf` are exported from `@bounda-dev/core`, and `AppRetiredPersonalCategory` from `@bounda-dev/core/register`. `bounda generate` writes `RetiredPersonalCategory` in `.bounda/types.ts` and registers `retiredPersonalCategories` in `.bounda/register.d.ts`: run it after upgrading. The personal-data export (`PERSONAL_DATA_EXPORT_VERSION` 3), the record of processing activities (`PERSONAL_DATA_INVENTORY_VERSION` 3) and the tenant export (`TENANT_EXPORT_VERSION` 10) say of each category whether it is `retired`, and `bounda personal-data inventory` prints one as `name (retired)`. **Breaking:** a category the store recorded, by a key given in it or by a write it holds that names it (a restriction or its lifts, a forgetting of a person or of a tenant, a redaction, a disclosure, a recipient's declaration or an entry of the forget ledger), and that the file neither declares nor retires, refuses the start, a rebuild of a read model, `bounda forget-ledger prune` and `bounda forget-ledger stranded` with a `ConfigurationError` naming it, forgetting nothing, where its keys were forgotten at once before: this code cannot tell a category it dropped from one newer code declares. Declare it again, its whole declaration with `retired: true`, and keep the entry for good. The storage migration, on SQLite and PostgreSQL, records every category the restrictions, forgettings, redactions, disclosures and recipient declarations the store already holds name, so the first start after upgrading may refuse a category dropped earlier that only those named: retire it. **Breaking for an adapter of your own:** `PersonalKeyStore` gains `recordCategories`, which records categories as `add` records a key's, in the transaction when called inside one, refused behind the tenant's fence as any write is; `personalKeyStoreContract` and `storageTransactionContract` cover it, and `fillNamedCategoriesStatements`, from `@bounda-dev/core/adapter/sql`, gives a SQL adapter's migration the statements that record what the writes a store already holds name. diff --git a/docs/src/content/docs/adapters/index.mdx b/docs/src/content/docs/adapters/index.mdx index 848c67431..e05b98ac7 100644 --- a/docs/src/content/docs/adapters/index.mdx +++ b/docs/src/content/docs/adapters/index.mdx @@ -193,6 +193,11 @@ of its own also implements: - **Which kinds opened a stream.** `StoredEventType.opened`, set once an event of the kind is appended at version 1 of its stream, or a `reseal` writes one there, and never taken back. - **The instance of a process letter.** `StoredDeadLetter.instanceId`, kept and read back as given. +- **Categories a write names.** `PersonalKeyStore.recordCategories` records categories in the + catalogue `recordedCategories` reads, as `add` records a key's, in the transaction when called + inside one, and refused behind the tenant's fence as any write is; recording one again changes + nothing. A migration over SQL records those the writes a store already holds name with + `fillNamedCategoriesStatements`, from `@bounda-dev/core/adapter/sql`. - **Checkpoints in a transaction.** `StorageTransaction.checkpointStore` writes checkpoints with the transaction's other writes, or not at all. Transactions run one at a time, so a checkpoint the work reads is written by no other transaction until it ends: the runtime takes the backfill's diff --git a/docs/src/content/docs/guides/deployment.mdx b/docs/src/content/docs/guides/deployment.mdx index 133ac2e64..f107d4d13 100644 --- a/docs/src/content/docs/guides/deployment.mdx +++ b/docs/src/content/docs/guides/deployment.mdx @@ -312,8 +312,11 @@ that names the letter. Then, before the first deploy that retires anything: aggregates that no module names refuses the start, naming it. Put its module back for that first deploy, then retire it. - **A category dropped from `bounda.personal-data.ts`.** Before 0.6.0 the worker destroyed the keys - of a category the file no longer declared; now a store that recorded it, by a key given in it or - a forgetting or a restriction that named it, refuses the start, naming it. Declare it again, its + of a category the file no longer declared; now a store that recorded it, by a key given in it or a + write that [names it](/guides/personal-data/#changing-a-category), refuses the start, naming it. + The migration records every category the restrictions and their lifts, forgettings, redactions, + disclosures and recipient declarations the store already holds name, so the first start after + upgrading may refuse a category dropped earlier that only those named. Declare it again, its whole declaration with `retired: true`. - **Redactions that did nothing.** A redaction of a field the event does not hold, holds in the clear unmarked or holds sealed for another person resolved without sealing anything; it is now diff --git a/docs/src/content/docs/guides/personal-data.md b/docs/src/content/docs/guides/personal-data.md index 4646cd6ce..be47f746b 100644 --- a/docs/src/content/docs/guides/personal-data.md +++ b/docs/src/content/docs/guides/personal-data.md @@ -377,10 +377,11 @@ holds sealed stays in the category it was sealed under. A category a deploy adds is one the previous code does not know while the deploy rolls across instances, so it cannot tell whether the new code keeps a key given in it. The store records every -category a key was ever given in, and every category a forgetting or a restriction named, and an -instance reads that record when it starts: a category recorded then that the app neither declares -nor retires refuses the start, as [below](#retiring-a-category), and one recorded after the start -is the new code's. Its keys are never taken by the previous code: a forget of a +category a key was ever given in, and every category a write it holds names: a restriction and its +lifts, a forgetting of a person or of a tenant, a redaction, a disclosure, a recipient's +declaration and an entry of the forget ledger. An instance reads that record when it starts: a +category recorded then that the app neither declares nor retires refuses the start, as +[below](#retiring-a-category), and one recorded after the start is the new code's. Its keys are never taken by the previous code: a forget of a person as a whole, and a tenant's forget whatever `despiteLegalObligations` says, fails with [`SCHEMA_AHEAD`](/reference/errors/#codes) (`CategoryAheadError`, naming the category), forgetting nothing; a reaction's `forget` tries again every `dispatcher.backoff.baseDelay`; the @@ -430,8 +431,9 @@ export const categories = { types](/guides/changing-events/#retiring-an-event-type) sealed in it. The entry stays in the file for good, as a retired event type's module does. The store records every -category a key was given in and every category a forgetting or a restriction named, and an app, a -`bounda forget-ledger prune` and a `bounda forget-ledger stranded` refuse to start on a database +category a key was given in and every category a write it holds names, [as +above](#changing-a-category), and an app, a [rebuild](/guides/deployment/#rebuilding-a-read-model), +a `bounda forget-ledger prune` and a `bounda forget-ledger stranded` refuse to start on a database that recorded one the file neither declares nor retires, with a `ConfigurationError` that names each, forgetting nothing: @@ -441,8 +443,8 @@ bounda.personal-data.ts neither declares nor retires categories the store has re This code cannot tell a category it dropped, whose keys forgetting at once would destroy before their retention and past their exemptions, from one that newer code in a rolling deploy declares and -keeps. A category the store never recorded, which no key, forgetting or restriction ever named, may -be deleted from the file. A [retired event type](/guides/changing-events/#what-a-start-refuses) +keeps. A category the store never recorded, which no key and no write it holds ever named, may be +deleted from the file. A [retired event type](/guides/changing-events/#what-a-start-refuses) whose recorded marks seal in a category the file neither declares nor retires is refused the same way. From 987d8f040fd7b45e440bdc8e9e351a8c03124a9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 16:03:41 +0100 Subject: [PATCH 24/33] test(core): type the named-categories test's configuration as Config --- .../core/src/kernel/personal-data/named-categories-app.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/core/src/kernel/personal-data/named-categories-app.test.ts b/packages/core/src/kernel/personal-data/named-categories-app.test.ts index ed3505227..9efff08cb 100644 --- a/packages/core/src/kernel/personal-data/named-categories-app.test.ts +++ b/packages/core/src/kernel/personal-data/named-categories-app.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest"; import type { Adapter } from "../../adapter/adapter.ts"; import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; import type { Table } from "../../adapter/storage/table.ts"; +import type { Config } from "../../config/types.ts"; import { createFixedClock } from "../../contracts/clock.ts"; import { ConfigurationError } from "../../contracts/errors.ts"; import type { StoredEvent } from "../../contracts/event.ts"; @@ -126,7 +127,7 @@ afterEach(async () => { let starts = 0; -const configOf = (adapter: Adapter) => ({ +const configOf = (adapter: Adapter): Config => ({ storage: adapter, runtime: { personalData: { retention: "1y", forgetLedger: { store: ledgerFor(adapter) } } }, }); From 74a1ca01af7cb129834ca7c83706f90843749d82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 16:14:15 +0100 Subject: [PATCH 25/33] test(core): cover what the event-store wrappers pass through for marks, and drop the lease's unused checkpoint calls --- packages/core/src/kernel/aggregate/upcasting.test.ts | 4 ++++ packages/core/src/kernel/personal-data/backfill.ts | 3 --- .../core/src/kernel/personal-data/event-store.test.ts | 4 ++++ packages/core/src/kernel/shared/committed-events.test.ts | 9 +++++++++ packages/core/src/kernel/shared/lease.ts | 2 +- 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/core/src/kernel/aggregate/upcasting.test.ts b/packages/core/src/kernel/aggregate/upcasting.test.ts index 55b296d63..0bae65b98 100644 --- a/packages/core/src/kernel/aggregate/upcasting.test.ts +++ b/packages/core/src/kernel/aggregate/upcasting.test.ts @@ -178,6 +178,10 @@ describe("withUpcasting", () => { expect(await store.lastPosition()).toBe(2); await store.reseal([{ position: 2, payload: { method: "cash" }, person: "c-2" }]); expect((await raw.readOne({ ...stream, eventId: "e2" }))?.payload).toEqual({ method: "cash" }); + const marked = { aggregateType: "order", type: "OrderNoted", fingerprint: "f-1", marks: null }; + await store.recordMarks({ marks: [marked], at: "2026-01-01T00:00:00.000Z" }); + await store.recordSealed({ sets: [marked], through: 2 }); + expect(await raw.marksOf()).toMatchObject([{ ...marked, sealedThrough: 2 }]); }); const opened = async (held: readonly Parameters[0][] = []) => { diff --git a/packages/core/src/kernel/personal-data/backfill.ts b/packages/core/src/kernel/personal-data/backfill.ts index 4e5407186..257bc7fe7 100644 --- a/packages/core/src/kernel/personal-data/backfill.ts +++ b/packages/core/src/kernel/personal-data/backfill.ts @@ -207,9 +207,6 @@ export const createBackfillLease: CreateBackfillLeaseFunction = ({ return createLease({ checkpoints: { get: (row) => checkpointStore.get(row), - list: () => checkpointStore.list(), - set: (row, position) => checkpointStore.set(row, position), - remove: (row) => checkpointStore.remove(row), compareAndSet: (row, expected, position) => storage.transact((transaction) => transaction.checkpointStore.compareAndSet(row, expected, position), diff --git a/packages/core/src/kernel/personal-data/event-store.test.ts b/packages/core/src/kernel/personal-data/event-store.test.ts index 09ccc0536..7823a85b2 100644 --- a/packages/core/src/kernel/personal-data/event-store.test.ts +++ b/packages/core/src/kernel/personal-data/event-store.test.ts @@ -881,6 +881,10 @@ describe("withPersonalData", () => { expect( await storage.eventStore.readByPerson({ person: "c-9", afterPosition: 0, limit: 1 }), ).toMatchObject([{ payload: { as: "given" } }]); + const marked = { aggregateType: "order", type: "OrderNoted", fingerprint: "f-1", marks: null }; + await store.recordMarks({ marks: [marked], at: "2026-01-01T00:00:00.000Z" }); + await store.recordSealed({ sets: [marked], through: 2 }); + expect(await storage.eventStore.marksOf()).toMatchObject([{ ...marked, sealedThrough: 2 }]); }); it("names the person on the event it seals, with every marked field absent too, and reads their events by person", async () => { diff --git a/packages/core/src/kernel/shared/committed-events.test.ts b/packages/core/src/kernel/shared/committed-events.test.ts index e67edae0b..88fc346e2 100644 --- a/packages/core/src/kernel/shared/committed-events.test.ts +++ b/packages/core/src/kernel/shared/committed-events.test.ts @@ -25,6 +25,15 @@ const append = (aggregateId: string, version = 1) => ({ }); describe("withCommittedEvents", () => { + it("passes the marks of event types through to the store", async () => { + const inner = await memory().createStorage(); + const { eventStore } = withCommittedEvents({ storage: inner, committed: () => undefined }); + const marked = { aggregateType: "order", type: "OrderNoted", fingerprint: "f-1", marks: null }; + await eventStore.recordMarks({ marks: [marked], at: "2026-01-01T00:00:00.000Z" }); + await eventStore.recordSealed({ sets: [marked], through: 2 }); + expect(await inner.eventStore.marksOf()).toMatchObject([{ ...marked, sealedThrough: 2 }]); + }); + it("reports the events of an append outside a transaction once it resolved", async () => { const { storage, committed } = await setUp(); await storage.eventStore.append(append("o-1")); diff --git a/packages/core/src/kernel/shared/lease.ts b/packages/core/src/kernel/shared/lease.ts index 7c2098ad9..5492539f1 100644 --- a/packages/core/src/kernel/shared/lease.ts +++ b/packages/core/src/kernel/shared/lease.ts @@ -31,7 +31,7 @@ export interface Lease { } export interface CreateLeaseArgs { - readonly checkpoints: CheckpointStore; + readonly checkpoints: Pick; /** * The checkpoint row that keeps, in milliseconds, until when the lease is held. */ From fcdc9367cd11722c35a112b913caae572ec619a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 16:19:29 +0100 Subject: [PATCH 26/33] test(cli): pin the order of retired events and a foreign handler of no event beside a retired one --- packages/cli/src/generate/discover.test.ts | 4 ++++ packages/cli/src/generate/discover.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/generate/discover.test.ts b/packages/cli/src/generate/discover.test.ts index e69b1f569..4488cd67d 100644 --- a/packages/cli/src/generate/discover.test.ts +++ b/packages/cli/src/generate/discover.test.ts @@ -476,11 +476,13 @@ describe("discoverProject and retired event types", () => { "app/domain/order/order-placed.ts", ["app/domain/order/order-note-added.ts", RETIRED], ["app/domain/order/order-lost.ts", "const retired = true;\nexport { retired };\n"], + ["app/domain/order/order2-lost.ts", RETIRED], ]); const model = await discoverProject({ root }); const [order] = model.aggregates; expect(order?.events.map((event) => event.key)).toEqual(["orderPlaced"]); expect(order?.retired.map((event) => [event.key, event.typeName, event.relativePath])).toEqual([ + ["order2Lost", "Order2Lost", "app/domain/order/order2-lost.ts"], ["orderLost", "OrderLost", "app/domain/order/order-lost.ts"], ["orderNoteAdded", "OrderNoteAdded", "app/domain/order/order-note-added.ts"], ]); @@ -531,6 +533,7 @@ describe("discoverProject and retired event types", () => { "app/domain/order/processes/checkout/on-order-placed.ts", "app/domain/order/processes/checkout/on-order-note-added.ts", "app/domain/order/processes/checkout/payment/on-payment-captured.ts", + "app/domain/order/processes/checkout/payment/on-payment-lost.ts", "app/read/orders/view.ts", ["app/read/orders/projections/order/order-placed.ts", "export const project = () => {};\n"], [ @@ -545,6 +548,7 @@ describe("discoverProject and retired event types", () => { expect(await problemsOf(root)).toEqual([ 'app/domain/order/processes/checkout/on-order-note-added.ts: "orderNoteAdded" is a retired event of this aggregate, which nothing reacts to; delete the handler', 'app/domain/order/processes/checkout/payment/on-payment-captured.ts: "paymentCaptured" is a retired event of the aggregate "payment", which nothing reacts to; delete the handler', + 'app/domain/order/processes/checkout/payment/on-payment-lost.ts: "paymentLost" is not an event of the aggregate "payment"', 'app/domain/order/policies/payment/chase-on-payment-captured.ts: its name ends with "paymentCaptured", a retired event of "payment", which nothing reacts to; delete the policy or export "on"', 'app/domain/order/policies/remind-on-order-note-added.ts: its name ends with "orderNoteAdded", a retired event of "order", which nothing reacts to; delete the policy or export "on"', 'app/read/orders/projections/order/order-note-added.ts: "orderNoteAdded" is a retired event of "order", which nothing projects; delete the projection or export "on"', diff --git a/packages/cli/src/generate/discover.ts b/packages/cli/src/generate/discover.ts index 8690a6b12..3abe976f4 100644 --- a/packages/cli/src/generate/discover.ts +++ b/packages/cli/src/generate/discover.ts @@ -1002,7 +1002,7 @@ const checkRetiredTriggers = async ( for (const aggregate of aggregates) { for (const policy of aggregate.policies) { const source = byName.get(policy.source ?? aggregate.name); - if (source === undefined || source.retired.length === 0) continue; + if (source === undefined) continue; const type = policyTrigger({ key: policy.key, events: [...source.events, ...source.retired].map((event) => event.typeName), From a7f576016c25a95a59fe0d52f0b2cf44b9206b0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 17:00:09 +0100 Subject: [PATCH 27/33] test(core): kill the mutants left on the stores' marks and categories, the stored marks, the exports and the redaction targets Simplify three reads that could not change a result (a set's marks, an event type's openings, an event that names nobody), and keep a set that marks nothing as null in memory, as the SQL stores do. --- .../core/src/adapter/sql/event-marks.test.ts | 3 +- packages/core/src/adapter/sql/event-marks.ts | 8 +- packages/core/src/adapter/sql/event-types.ts | 2 +- .../adapter/sql/personal-categories.test.ts | 24 +++++ .../src/adapter/staged-event-store.test.ts | 44 ++++++++++ .../adapter/testing/event-store.contract.ts | 28 +++++- .../src/kernel/personal-data/export.test.ts | 87 ++++++++++++++++++- .../src/kernel/personal-data/persons.test.ts | 24 +++++ .../personal-data/redaction-targets.test.ts | 63 ++++++++++++++ .../kernel/personal-data/stored-marks.test.ts | 71 ++++++++++++++- .../src/kernel/personal-data/stored-marks.ts | 4 - .../tenant-export-stream.test.ts | 57 +++++++++++- packages/core/src/memory/event-store.ts | 9 +- packages/core/src/memory/memory.test.ts | 48 ++++++++++ 14 files changed, 449 insertions(+), 23 deletions(-) diff --git a/packages/core/src/adapter/sql/event-marks.test.ts b/packages/core/src/adapter/sql/event-marks.test.ts index 13a842b58..8c6b4e869 100644 --- a/packages/core/src/adapter/sql/event-marks.test.ts +++ b/packages/core/src/adapter/sql/event-marks.test.ts @@ -97,7 +97,7 @@ describe("recordMarksStatements", () => { expect(keys[1]?.[3]).not.toBeNull(); }); - it("splits the sets across statements within the parameters one carries, numbering each from the first", () => { + it("splits the sets across statements within the parameters one carries, numbering each from the first, row after row", () => { const perStatement = Math.floor(MAX_PARAMETERS_PER_STATEMENT / 5); const statements = recordMarksStatements({ dialect: postgresqlDialect, @@ -108,6 +108,7 @@ describe("recordMarksStatements", () => { at: AT, }); expect(statements.map(({ params }) => params.length)).toEqual([perStatement * 5, 5]); + expect(statements[0]?.sql).toContain("VALUES ($1, $2, $3, $4, $5), ($6, $7, $8, $9, $10), ("); expect(statements[1]?.sql).toBe( 'INSERT INTO "m" ("aggregate_type", "type", "fingerprint", "marks", "first_seen_at") VALUES ($1, $2, $3, $4, $5) ON CONFLICT ("aggregate_type", "type", "fingerprint") DO NOTHING', ); diff --git a/packages/core/src/adapter/sql/event-marks.ts b/packages/core/src/adapter/sql/event-marks.ts index ed7b2305e..977a06bd1 100644 --- a/packages/core/src/adapter/sql/event-marks.ts +++ b/packages/core/src/adapter/sql/event-marks.ts @@ -265,11 +265,9 @@ export const marksOfRow: MarksOfRowFunction = (row) => ({ type: String(row.type), fingerprint: String(row.fingerprint), marks: - row.marks === null || row.marks === undefined - ? null - : ((typeof row.marks === "string" - ? JSON.parse(row.marks) - : row.marks) as RecordedPersonalMarks), + typeof row.marks === "string" + ? (JSON.parse(row.marks) as RecordedPersonalMarks) + : ((row.marks ?? null) as RecordedPersonalMarks | null), firstSeenAt: String(row.first_seen_at), sealedThrough: row.sealed_through === null || row.sealed_through === undefined diff --git a/packages/core/src/adapter/sql/event-types.ts b/packages/core/src/adapter/sql/event-types.ts index d839ae982..3661d457b 100644 --- a/packages/core/src/adapter/sql/event-types.ts +++ b/packages/core/src/adapter/sql/event-types.ts @@ -220,5 +220,5 @@ export const eventTypeOfRow: EventTypeOfRowFunction = (row) => ({ aggregateType: String(row.aggregate_type), type: String(row.type), schemaVersion: Number(row.schema_version), - opened: typeof row.opened === "boolean" ? row.opened : Number(row.opened) !== 0, + opened: Number(row.opened) !== 0, }); diff --git a/packages/core/src/adapter/sql/personal-categories.test.ts b/packages/core/src/adapter/sql/personal-categories.test.ts index 82194a731..bfc4e8e81 100644 --- a/packages/core/src/adapter/sql/personal-categories.test.ts +++ b/packages/core/src/adapter/sql/personal-categories.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { postgresqlDialect, sqliteDialect } from "./dialect.ts"; import { + fillNamedCategoriesStatements, fillPersonalCategoriesStatement, personalCategoriesTableStatement, } from "./personal-categories.ts"; @@ -27,3 +28,26 @@ describe("fillPersonalCategoriesStatement", () => { ); }); }); + +describe("fillNamedCategoriesStatements", () => { + it("reads PostgreSQL's names out of jsonb: the arrays at a payload's keys and at an object's in one, and the recipients' categories cast from text, the strings of each alone", () => { + const sql = fillNamedCategoriesStatements({ + dialect: postgresqlDialect, + table: '"c"', + events: '"e"', + restrictions: '"r"', + disclosures: '"d"', + recipients: '"p"', + forgottenRecipients: '"f"', + }).join("\n"); + expect(sql).toContain( + `jsonb_array_elements(CASE WHEN jsonb_typeof(e."payload"->'restrictions') = 'array' THEN e."payload"->'restrictions' ELSE '[]'::jsonb END) AS o("value"), jsonb_array_elements(CASE WHEN jsonb_typeof(o."value"->'categories') = 'array' THEN o."value"->'categories' ELSE '[]'::jsonb END) AS n("value") WHERE`, + ); + expect(sql).toContain( + `AND TRUE AND jsonb_typeof(o."value") = 'object' AND TRUE AND jsonb_typeof(n."value") = 'string' ON CONFLICT DO NOTHING`, + ); + expect(sql).toContain( + `INSERT INTO "c" ("category") SELECT DISTINCT n."value" #>> '{}' FROM "p" AS r, jsonb_array_elements(CASE WHEN jsonb_typeof(r."categories"::jsonb) = 'array' THEN r."categories"::jsonb ELSE '[]'::jsonb END) AS n("value") WHERE TRUE AND jsonb_typeof(n."value") = 'string' ON CONFLICT DO NOTHING`, + ); + }); +}); diff --git a/packages/core/src/adapter/staged-event-store.test.ts b/packages/core/src/adapter/staged-event-store.test.ts index c3d04e639..c08be826d 100644 --- a/packages/core/src/adapter/staged-event-store.test.ts +++ b/packages/core/src/adapter/staged-event-store.test.ts @@ -331,6 +331,50 @@ describe("createStagedEventStore", () => { expect(customers).not.toHaveProperty("basis"); }); + it("adds to the base store's sets of marks each one staged it holds none of, once, as first staged, of the aggregate type and type asked alone", async () => { + const { base, staged } = await setUp(); + const marks = { person: "customerId", fields: ["email"], categories: { email: "contact" } }; + const set = (type: string, fingerprint: string, aggregateType = "order") => ({ + aggregateType, + type, + fingerprint, + marks, + }); + const T1 = "2026-01-01T00:00:00.000Z"; + const T2 = "2026-01-02T00:00:00.000Z"; + const T3 = "2026-01-03T00:00:00.000Z"; + await base.recordMarks({ marks: [set("OrderPlaced", "a")], at: T1 }); + await staged.recordMarks({ + marks: [set("OrderPlaced", "a"), set("OrderPlaced", "b"), set("OrderPaid", "x")], + at: T2, + }); + await staged.recordMarks({ + marks: [ + set("OrderPlaced", "b"), + set("OrderPlaced", "c"), + set("OrderPlaced", "z", "customer"), + ], + at: T3, + }); + expect(await staged.marksOf({ aggregateType: "order", type: "OrderPlaced" })).toEqual([ + { ...set("OrderPlaced", "a"), firstSeenAt: T1, sealedThrough: null }, + { ...set("OrderPlaced", "b"), firstSeenAt: T2, sealedThrough: null }, + { ...set("OrderPlaced", "c"), firstSeenAt: T3, sealedThrough: null }, + ]); + expect( + (await staged.marksOf()).map( + ({ aggregateType, type, fingerprint }) => `${aggregateType}.${type}:${fingerprint}`, + ), + ).toEqual([ + "order.OrderPlaced:a", + "order.OrderPaid:x", + "order.OrderPlaced:b", + "customer.OrderPlaced:z", + "order.OrderPlaced:c", + ]); + expect(await base.marksOf()).toHaveLength(1); + }); + it("names no basis for a stream whose first append named none, whatever the later ones say", async () => { const { staged } = await setUp(); await staged.append({ diff --git a/packages/core/src/adapter/testing/event-store.contract.ts b/packages/core/src/adapter/testing/event-store.contract.ts index 4ddb745c5..9d6c559ee 100644 --- a/packages/core/src/adapter/testing/event-store.contract.ts +++ b/packages/core/src/adapter/testing/event-store.contract.ts @@ -1441,12 +1441,14 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr ({ type, fingerprint, sealedThrough }) => `${type}:${fingerprint}:${sealedThrough}`, ); - it("raises a set's sealedThrough, never lowers it, and leaves a set not recorded as it is", async () => { + it("raises a set's sealedThrough, from none to position 0 too, never lowers it, and leaves a set not recorded as it is", async () => { await store.recordMarks({ marks: [marksOf("OrderPlaced", "a"), marksOf("OrderPaid", "x", null)], at: T1, }); expect(await sealedOf()).toEqual(["OrderPaid:x:null", "OrderPlaced:a:null"]); + await store.recordSealed({ sets: [keyOf("OrderPlaced", "a")], through: 0 }); + expect(await sealedOf()).toEqual(["OrderPaid:x:null", "OrderPlaced:a:0"]); await store.recordSealed({ sets: [keyOf("OrderPlaced", "a"), keyOf("OrderPlaced", "gone")], through: 5, @@ -1485,6 +1487,30 @@ export const eventStoreContract: EventStoreContractFunction = ({ create, concurr expect(await sealedOf()).toEqual(["OrderPaid:x:5", "OrderPlaced:a:6", "OrderPlaced:b:6"]); }); + it("clears nothing when no set given is recorded, nor the sets of another aggregate type's type of the same name", async () => { + await store.recordMarks({ + marks: [ + marksOf("OrderPlaced", "a"), + marksOf("OrderPaid", "x", null), + { ...marksOf("OrderPlaced", "c"), aggregateType: "customer" }, + ], + at: T1, + }); + await store.recordSealed({ sets: [keyOf("OrderPlaced", "a")], through: 5 }); + await store.recordSealed({ + sets: [{ ...keyOf("OrderPlaced", "c"), aggregateType: "customer" }], + through: 5, + }); + // Recorded, but as another type's set. + await store.recordSealed({ sets: [keyOf("OrderPlaced", "x")], through: 6 }); + expect( + (await store.marksOf()).map( + ({ aggregateType, type, fingerprint, sealedThrough }) => + `${aggregateType}.${type}:${fingerprint}:${sealedThrough}`, + ), + ).toEqual(["customer.OrderPlaced:c:5", "order.OrderPaid:x:null", "order.OrderPlaced:a:5"]); + }); + it("records sealed what a transaction records when it commits, shown to it before, and nothing when it rolls back", async () => { await store.recordMarks({ marks: [marksOf("OrderPlaced", "a"), marksOf("OrderPlaced", "b", OTHER_MARKS)], diff --git a/packages/core/src/kernel/personal-data/export.test.ts b/packages/core/src/kernel/personal-data/export.test.ts index 9fc6df09d..b272a6371 100644 --- a/packages/core/src/kernel/personal-data/export.test.ts +++ b/packages/core/src/kernel/personal-data/export.test.ts @@ -4,6 +4,7 @@ import { pendingEvent, testContext, testDeadLetter } from "../../adapter/testing import { resolveConfig } from "../../config/schema.ts"; import { createFixedClock } from "../../contracts/clock.ts"; import { ValidationError } from "../../contracts/errors.ts"; +import type { StoredEvent } from "../../contracts/event.ts"; import { silentLogger } from "../../contracts/logger.ts"; import { memory } from "../../memory/index.ts"; import type { CommandPayloadArgs, EventPayloadArgs } from "../../modules/payload.ts"; @@ -180,11 +181,32 @@ const exportedRights = [ { right: "complaint", article: "77", categories: null }, ]; -const setup = async () => { - const aggregates = buildAggregates({ registry, ports: {} }); +// Orders placed before their note was named a remark: an upcast renames it. +const renamed: Registry = { + ...registry, + aggregates: { + ...registry.aggregates, + order: { + ...registry.aggregates.order, + upcasts: { + orderPlaced: { + upcasts: [ + ({ remark, ...payload }: { readonly remark?: unknown }) => ({ + ...payload, + note: remark, + }), + ], + }, + }, + }, + }, +} as Registry; + +const setup = async (from: Registry = registry) => { + const aggregates = buildAggregates({ registry: from, ports: {} }); // A read model of its own adapter, as `readModels` in the configuration may give it. const readModels = await buildReadModels({ - registry, + registry: from, config: resolveConfig({ storage: memory(), readModels: { orderNotes: memory() } }), logger: silentLogger, }); @@ -470,6 +492,65 @@ describe("exportPersonalData", () => { ]); }); + it("hands the person what the store holds sealed for them that no mark names, under its envelope's category, and nothing sealed for someone else", async () => { + const { exportOf, register, written } = await setup(); + await register("c-1", "ana@example.com"); + await register("c-2", "bo@example.com"); + const [ana, bo] = await written.eventStore.readAll({ afterPosition: 0, limit: 10 }); + const envelope = (event: StoredEvent | undefined) => + (event?.payload as { email: unknown } | undefined)?.email; + // Written past the runtime: an envelope a payload carried in may name another person. + await written.eventStore.append({ + aggregateType: "order", + aggregateId: "o-1", + expectedVersion: 0, + events: [ + pendingEvent({ + aggregateId: "o-1", + version: 1, + person: "c-1", + payload: { customerId: "c-1", contact: envelope(ana), gift: envelope(bo), total: 10 }, + }), + ], + }); + const order = async (personId: string) => + (await exportOf(personId)).events.find(({ aggregateType }) => aggregateType === "order"); + const placed = await order("c-1"); + expect([placed?.data, placed?.categories]).toEqual([ + { contact: "ana@example.com" }, + { contact: "default" }, + ]); + expect(await order("c-2")).toBeUndefined(); + }); + + it("names no field an upcast took out of the payload, though the store held it sealed for the person", async () => { + const { exportOf, storage, written } = await setup(renamed); + const remark = await seal({ + key: await storage.personalKeys.create("c-1", "default"), + person: "c-1", + category: "default", + value: "ring twice", + }); + await written.eventStore.append({ + aggregateType: "order", + aggregateId: "o-1", + expectedVersion: 0, + events: [ + pendingEvent({ + aggregateId: "o-1", + version: 1, + person: "c-1", + payload: { customerId: "c-1", remark, total: 10 }, + }), + ], + }); + const [placed] = (await exportOf("c-1")).events; + expect([placed?.data, placed?.categories]).toEqual([ + { note: "ring twice" }, + { note: "invoices" }, + ]); + }); + it("includes the scheduled commands and dead letters that hold the person's fields, opened", async () => { const { exportOf, storage, sealedReminder, failure } = await setup(); const ana = await sealedReminder("c-1", "ana@example.com"); diff --git a/packages/core/src/kernel/personal-data/persons.test.ts b/packages/core/src/kernel/personal-data/persons.test.ts index fc2b4ed55..c37b1732f 100644 --- a/packages/core/src/kernel/personal-data/persons.test.ts +++ b/packages/core/src/kernel/personal-data/persons.test.ts @@ -5,6 +5,7 @@ import type { EventPayloadArgs } from "../../modules/payload.ts"; import type { Registry } from "../../modules/registry.ts"; import { buildAggregates } from "../aggregate/build-aggregates.ts"; import { personOfCommand, personOfEvent, personsOf, personTouchedByEvent } from "./persons.ts"; +import { withStoredMarks } from "./stored-marks.ts"; const registry: Registry = { aggregates: { @@ -198,6 +199,7 @@ describe("personOfEvent of a retired type", () => { expect(noted({ note: "in the clear" })).toBeNull(); expect(noted({ note: null })).toBeNull(); expect(noted("note")).toBeNull(); + expect(noted(null)).toBeNull(); expect( personOfEvent({ aggregates, @@ -205,6 +207,28 @@ describe("personOfEvent of a retired type", () => { }), ).toBeNull(); }); + + it("names, with nothing sealed, whom the sets the store recorded name while one field they mark holds a value", () => { + const recorded = withStoredMarks(aggregates, [ + { + aggregateType: "order", + type: "OrderNoted", + fingerprint: "f", + marks: { + person: "customerId", + fields: ["email", "note"], + categories: { email: "default", note: "default" }, + }, + firstSeenAt: "2026-01-01T00:00:00.000Z", + sealedThrough: null, + }, + ]); + const noted = (payload: unknown) => + personOfEvent({ aggregates: recorded, event: event(1, "OrderNoted", payload) }); + expect(noted({ customerId: "c-1", note: "in the clear" })).toBe("c-1"); + expect(noted({ customerId: "c-1", note: null })).toBeNull(); + expect(noted({ customerId: "c-1" })).toBeNull(); + }); }); describe("personTouchedByEvent", () => { diff --git a/packages/core/src/kernel/personal-data/redaction-targets.test.ts b/packages/core/src/kernel/personal-data/redaction-targets.test.ts index 750538745..787a66f41 100644 --- a/packages/core/src/kernel/personal-data/redaction-targets.test.ts +++ b/packages/core/src/kernel/personal-data/redaction-targets.test.ts @@ -1,8 +1,11 @@ import { describe, expect, it } from "vitest"; +import { pendingEvent } from "../../adapter/testing/fixtures.ts"; import { ValidationError } from "../../contracts/errors.ts"; +import { memory } from "../../memory/index.ts"; import type { EventPayloadArgs } from "../../modules/payload.ts"; import type { Registry } from "../../modules/registry.ts"; import { buildAggregates } from "../aggregate/build-aggregates.ts"; +import { checkReachable } from "./redaction.ts"; import { checkRedactionTargets, redactionReach, unsealedFor } from "./redaction-targets.ts"; const registry = { @@ -256,3 +259,63 @@ describe("unsealedFor", () => { expect(unsealedFor(holder, "gone", "c-1")).toBe('it holds no "gone"'); }); }); + +describe("checkReachable", () => { + it("reaches a retired type's field held in the clear only where a set the store recorded marks it for the person the event names", async () => { + const storage = await memory().createStorage(); + await storage.eventStore.recordMarks({ + marks: [ + { + aggregateType: "customer", + type: "CustomerNoted", + fingerprint: "f", + marks: { person: "authorId", fields: ["note"], categories: { note: "default" } }, + }, + ], + at: "2026-01-01T00:00:00.000Z", + }); + // Both name ana; the second's author field names bo, so no set marks its note for her. + for (const [version, authorId] of [ + [1, "ana"], + [2, "bo"], + ] as const) { + await storage.eventStore.append({ + aggregateType: "customer", + aggregateId: "c-1", + expectedVersion: version - 1, + events: [ + pendingEvent({ + aggregateType: "customer", + aggregateId: "c-1", + version, + type: "CustomerNoted", + id: `e-${version}`, + person: "ana", + payload: { authorId, note: "hi" }, + }), + ], + }); + } + const reach = (id: string) => + checkReachable({ + eventStore: storage.eventStore, + aggregates, + processes, + personId: "ana", + targets: [ + { + aggregateType: "customer", + aggregateId: "c-1", + type: "CustomerNoted", + id, + fields: ["note"], + }, + ], + }); + await expect(reach("e-1")).resolves.toBeUndefined(); + await expect(reach("e-2")).rejects.toThrow(ValidationError); + await expect(reach("e-2")).rejects.toThrow( + 'redact cannot reach the event e-2: it holds "note" in the clear', + ); + }); +}); diff --git a/packages/core/src/kernel/personal-data/stored-marks.test.ts b/packages/core/src/kernel/personal-data/stored-marks.test.ts index 71ae806c1..e420eeebd 100644 --- a/packages/core/src/kernel/personal-data/stored-marks.test.ts +++ b/packages/core/src/kernel/personal-data/stored-marks.test.ts @@ -5,8 +5,10 @@ import type { StoredEvent } from "../../contracts/event.ts"; import type { AggregatesRuntime } from "../aggregate/runtime.ts"; import type { PersonalMarks } from "./marks.ts"; import { + canonicalMarks, currentMarkSets, eventMarksOf, + marksAgree, marksSetFingerprint, NO_STORED_MARKS, retiredMarksOf, @@ -122,6 +124,44 @@ describe("unsettledFields", () => { }); }); +describe("marksAgree", () => { + it("agrees on a type while its sets, in the order recorded, and the set a walk sealed under last are the same, whatever another type holds", () => { + const first = set(null, { body: "default" }); + const second = set("authorId", { body: "invoices" }); + const sealedAt = ( + marks: PersonalMarks | null, + sealedThrough: number | null, + type = "MessagePosted", + ) => ({ + ...stored(type, marks), + sealedThrough, + }); + const agree = (read: readonly StoredEventTypeMarks[], now: readonly StoredEventTypeMarks[]) => + marksAgree({ + read: storedMarksOf(read), + now: storedMarksOf(now), + aggregateType: "conversation", + type: "MessagePosted", + }); + const recorded = [sealedAt(first, null), sealedAt(second, 4)]; + expect(agree(recorded, [sealedAt(first, null), sealedAt(second, 9)])).toBe(true); + expect(agree(recorded, [...recorded, sealedAt(null, null, "Other")])).toBe(true); + expect(agree(recorded, [sealedAt(first, null)])).toBe(false); + expect(agree(recorded, [...recorded, sealedAt(null, null)])).toBe(false); + expect(agree(recorded, [sealedAt(second, 4), sealedAt(first, null)])).toBe(false); + expect(agree(recorded, [sealedAt(first, 9), sealedAt(second, 4)])).toBe(false); + expect(agree(recorded, [sealedAt(first, null), sealedAt(second, null)])).toBe(false); + }); +}); + +describe("canonicalMarks", () => { + it("names whom the marks name and each field in order, one of the default category bare, as before categories existed", () => { + expect( + canonicalMarks(set("authorId", { phone: "invoices", body: DEFAULT_PERSONAL_CATEGORY })), + ).toEqual(["authorId", ["body", ["phone", "invoices"]]]); + }); +}); + describe("marksSetFingerprint", () => { it("is equal for equal marks in any order of fields, and tells a category, a person and no marks apart", () => { const fingerprint = marksSetFingerprint(set(null, { body: "default", phone: "invoices" })); @@ -302,10 +342,14 @@ describe("retiredMarksOf", () => { expect( retiredMarksOf({ sets, authority: null, event: event(sealedMotto, "ana") }).elsewhere, ).toEqual([]); - const noMotto = { authorId: "ana", body: "hi", motto: null }; - expect( - retiredMarksOf({ sets, authority: null, event: event(noMotto, "ana") }).elsewhere, - ).toEqual([]); + for (const noMotto of [ + { authorId: "ana", body: "hi", motto: null }, + { authorId: "ana", body: "hi" }, + ]) { + expect( + retiredMarksOf({ sets, authority: null, event: event(noMotto, "ana") }).elsewhere, + ).toEqual([]); + } }); it("names, for an event stored naming nobody, the person of the newest set that names somebody", () => { @@ -328,6 +372,25 @@ describe("retiredMarksOf", () => { }); }); + it("marks, of an event that names nobody whom no set names either, what every set settles, leaving in the clear what they give different categories", () => { + const sets = [ + set("authorId", { body: "default", phone: "invoices" }), + set("authorId", { body: "invoices", phone: "invoices" }), + ]; + const settledPhone = { + person: "authorId", + fields: ["phone"], + categories: { phone: "invoices" }, + }; + expect( + retiredMarksOf({ sets, authority: null, event: event({ body: "hi", phone: "555" }) }), + ).toEqual({ marks: settledPhone, elsewhere: ["body"] }); + expect(retiredMarksOf({ sets, authority: null, event: event({ phone: "555" }) })).toEqual({ + marks: settledPhone, + elsewhere: [], + }); + }); + it("marks nothing of an event whose person no set names, leaving every clear field it marks elsewhere", () => { const sets = [set("authorId", { body: "default" })]; expect( diff --git a/packages/core/src/kernel/personal-data/stored-marks.ts b/packages/core/src/kernel/personal-data/stored-marks.ts index f78fae5b9..986dce3a6 100644 --- a/packages/core/src/kernel/personal-data/stored-marks.ts +++ b/packages/core/src/kernel/personal-data/stored-marks.ts @@ -240,10 +240,6 @@ export const retiredMarksOf: RetiredMarksOfFunction = ({ sets, authority, event (authority === null ? null : named(authority)) ?? newestFirst.map(named).find((candidate) => candidate !== null) ?? null; - if (person === null) { - const { marks, unsettled } = settled(newestFirst, authority); - return { marks, elsewhere: unsettled.filter(clear) }; - } const own = newestFirst.filter((set) => named(set) === person); const { marks, unsettled } = own.length === 0 ? { marks: null, unsettled: [] } : settled(own, authority); diff --git a/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts b/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts index c4d450d9a..400515593 100644 --- a/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts +++ b/packages/core/src/kernel/personal-data/tenant-export-stream.test.ts @@ -463,7 +463,7 @@ describe("streamTenantExport", () => { expect((await order())?.restricted).toEqual(["contact"]); }); - it("names the fields of a process's lifecycle event its state marks, and none of a process it does not have", async () => { + it("names the fields of a process's lifecycle event its state marks, none of one that carries no state, and none of a process it does not have", async () => { const { exported, written } = await setup(); for (const process of ["customer.watch", "customer.gone"]) { await written.eventStore.append({ @@ -482,11 +482,26 @@ describe("streamTenantExport", () => { ], }); } + await written.eventStore.append({ + aggregateType: "process:customer.watch", + aggregateId: "c-1", + expectedVersion: 1, + events: [ + pendingEvent({ + aggregateType: "process:customer.watch", + aggregateId: "c-1", + version: 2, + type: "ProcessCompleted", + payload: { eventId: "e-1" }, + }), + ], + }); expect( of(await exported(), "event").map(({ event }) => [event.payload, event.categories]), ).toEqual([ [{ state: { email: "ana@example.com", step: 1 } }, { email: "default" }], [{ state: { email: "ana@example.com", step: 1 } }, {}], + [{ eventId: "e-1" }, {}], ]); }); @@ -524,6 +539,46 @@ describe("streamTenantExport", () => { ]); }); + it("restricts a field by a key a forgetting kept only when its own person's key that opened it was kept, whatever another person's in the event was", async () => { + const { exported, place, storage, written } = await setup(); + const keep = async (person: string) => { + const invoiceKey = (await storage.personalKeys.list(person)).find( + ({ category }) => category === "invoices", + ); + await storage.personalKeys.retain(person, invoiceKey?.key.fingerprint ?? "", { + since: "2026-01-10T00:00:00.000Z", + lastActiveAt: "2026-01-05T00:00:00.000Z", + }); + }; + await place("o-1", { customerId: "c-1", note: "ring twice", total: 10 }); + await keep("c-1"); + // Under the key ana holds in force since she came back. + await place("o-2", { customerId: "c-1", note: "back again", total: 20 }); + await place("o-3", { customerId: "c-2", note: "for bo", total: 30 }); + await keep("c-2"); + const [, back, forBo] = await written.eventStore.readAll({ afterPosition: 0, limit: 10 }); + const envelope = (event: StoredEvent | undefined) => + (event?.payload as { note: unknown } | undefined)?.note; + await written.eventStore.append({ + aggregateType: "order", + aggregateId: "o-4", + expectedVersion: 0, + events: [ + pendingEvent({ + aggregateId: "o-4", + version: 1, + person: "c-1", + payload: { customerId: "c-1", contact: envelope(back), gift: envelope(forBo), total: 40 }, + }), + ], + }); + const order = of(await exported(), "event").find(({ event }) => event.aggregateId === "o-4"); + expect(order?.event).toMatchObject({ + categories: { contact: "invoices", gift: "invoices" }, + restricted: ["gift"], + }); + }); + it("hands out every person once, from their keys and their records, in order, a page at a time", async () => { const { exported, register, restrict, storage } = await setup(); for (const person of ["c-3", "c-1", "c-5"]) await register(person, `${person}@example.com`); diff --git a/packages/core/src/memory/event-store.ts b/packages/core/src/memory/event-store.ts index 8f5064930..7e22234fc 100644 --- a/packages/core/src/memory/event-store.ts +++ b/packages/core/src/memory/event-store.ts @@ -113,7 +113,10 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ }; // The marks of event types, keyed by aggregate type, type and fingerprint, as JSON text so each // read is a fresh copy; a `Map` keeps them in the order recorded. - const marks = new Map & { readonly marks: string }>(); + const marks = new Map< + string, + Omit & { readonly marks: string | null } + >(); let reserved = 0; // Every position up to here is written or a gap: what readers see. let watermark = 0; @@ -269,7 +272,7 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ recordMarks: async ({ marks: sets, at }) => { const kept = sets.map((set) => ({ ...set, - marks: toJson(set.marks), + marks: set.marks === null ? null : toJson(set.marks), firstSeenAt: at, sealedThrough: null, })); @@ -290,7 +293,7 @@ export const createMemoryEventStore: CreateMemoryEventStoreFunction = ({ (set) => of === undefined || (set.aggregateType === of.aggregateType && set.type === of.type), ) - .map((set) => ({ ...set, marks: JSON.parse(set.marks) })), + .map((set) => ({ ...set, marks: set.marks === null ? null : JSON.parse(set.marks) })), recordSealed: async (args) => { const sealed = withSealed( [...marks.entries()].map(([key, set]) => ({ ...set, key })), diff --git a/packages/core/src/memory/memory.test.ts b/packages/core/src/memory/memory.test.ts index 17d52f0d2..ea182f513 100644 --- a/packages/core/src/memory/memory.test.ts +++ b/packages/core/src/memory/memory.test.ts @@ -682,6 +682,54 @@ describe("memory adapter", () => { ]); }); }); + + describe("the memory adapter's event marks, as inspected", () => { + it("shows a set that marks nothing as null, as the SQL adapters hold it, and reads it back so", async () => { + const adapter = memory(); + const storage = await adapter.createStorage(); + const nothing = { aggregateType: "order", type: "OrderPaid", fingerprint: "n", marks: null }; + await storage.eventStore.recordMarks({ marks: [nothing], at: "2026-03-01T00:00:00.000Z" }); + const tables = await adapter.inspect(); + expect(tables.find(({ store }) => store === "eventMarks")?.rows).toMatchObject([ + { fingerprint: "n", marks: null }, + ]); + expect(await storage.eventStore.marksOf()).toMatchObject([{ fingerprint: "n", marks: null }]); + }); + + it("numbers the sets from 1 in the order first recorded, as the SQL adapters' sequence does", async () => { + const adapter = memory(); + const storage = await adapter.createStorage(); + const marks = { person: "customerId", fields: ["email"], categories: { email: "contact" } }; + const set = (type: string, fingerprint: string) => ({ + aggregateType: "order", + type, + fingerprint, + marks, + }); + const T1 = "2026-03-01T00:00:00.000Z"; + const T2 = "2026-03-02T00:00:00.000Z"; + await storage.eventStore.recordMarks({ marks: [set("OrderPlaced", "b")], at: T1 }); + await storage.eventStore.recordMarks({ + marks: [set("OrderPlaced", "a"), set("OrderPaid", "x")], + at: T2, + }); + const row = (type: string, fingerprint: string, seq: number, firstSeenAt: string) => ({ + aggregate_type: "order", + type, + fingerprint, + marks: JSON.stringify(marks), + seq, + first_seen_at: firstSeenAt, + sealed_through: null, + }); + const tables = await adapter.inspect(); + expect(tables.find(({ store }) => store === "eventMarks")?.rows).toEqual([ + row("OrderPaid", "x", 2, T2), + row("OrderPlaced", "a", 3, T2), + row("OrderPlaced", "b", 1, T1), + ]); + }); + }); }); describe("memory()'s location", () => { From d4e68a9594c63153ad945ee21f7046987ee2339b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 17:00:09 +0100 Subject: [PATCH 28/33] fix(core): settle an old value written after a redaction in a stream of an aggregate or process this code no longer has The settle of a redaction looked only at events whose type this code reaches, so an instance of earlier code that wrote an old value into a kind this code reads as stored left it sealed under the person's key, where the tenant export opens it. Reach every event of the person by its envelopes. --- .../core/src/kernel/personal-data/redact.ts | 15 ++---- .../personal-data/redaction-details.test.ts | 46 +++++++++++++++++++ 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/packages/core/src/kernel/personal-data/redact.ts b/packages/core/src/kernel/personal-data/redact.ts index bea099f24..a1e5ba49f 100644 --- a/packages/core/src/kernel/personal-data/redact.ts +++ b/packages/core/src/kernel/personal-data/redact.ts @@ -35,7 +35,7 @@ import { redactWithin, scrubStores, } from "./redaction.ts"; -import { checkRedactionTargets, redactionReach } from "./redaction-targets.ts"; +import { checkRedactionTargets } from "./redaction-targets.ts"; import { checkPersonId, throughFreeze, transactRetrying } from "./transact.ts"; import type { PersonalKeys, PersonalKeyWrapping } from "./wrapped-keys.ts"; @@ -283,7 +283,8 @@ const openValues = async ( // The person's events appended after the redaction whose sealed fields hold an old value: a // command or a reaction that read it just before the redaction committed wrote it after, or an -// instance not yet upgraded wrote it in a type now retired. +// instance not yet upgraded wrote it in a type now retired, or of an aggregate or a process this +// code no longer has. Each is reached by its envelopes, whatever its type marks. const writtenSince = async ( redactions: Redactions, keys: PersonalKeys, @@ -291,7 +292,7 @@ const writtenSince = async ( equal: (value: unknown) => boolean, batchSize: number, ): Promise => { - const { storage, aggregates, processes } = redactions; + const { storage } = redactions; const found: RedactedEvent[] = []; const keyOf = sealedKeys(keys); for (let after = payload.position; ; ) { @@ -301,17 +302,11 @@ const writtenSince = async ( limit: batchSize, }); for (const event of batch) { - const reach = redactionReach({ - aggregates, - processes, - aggregateType: event.aggregateType, - type: event.type, - }); const holder = processOfStream(event.aggregateType) === null ? event.payload : lifecycleStateOf(event.payload); - if (reach === null || !isRecord(holder)) continue; + if (!isRecord(holder)) continue; const fields: string[] = []; for (const field of Object.keys(holder)) { const stored = holder[field]; diff --git a/packages/core/src/kernel/personal-data/redaction-details.test.ts b/packages/core/src/kernel/personal-data/redaction-details.test.ts index 4117b2a97..ca1ee0ef5 100644 --- a/packages/core/src/kernel/personal-data/redaction-details.test.ts +++ b/packages/core/src/kernel/personal-data/redaction-details.test.ts @@ -778,6 +778,52 @@ describe("redact, in detail", () => { expect(logged.filter(({ level }) => level === "warn")).toEqual([]); }); + it("settles an old value an instance of earlier code wrote after the redaction in a stream of an aggregate this code no longer has", async () => { + const adapter = memory(); + const mailing = (id: string, version: number, person: string, email: unknown) => ({ + aggregateType: "mailing", + aggregateId: "m-1", + expectedVersion: version - 1, + events: [ + pendingEvent({ + aggregateType: "mailing", + aggregateId: "m-1", + version, + type: "RecipientAdded", + payload: { email }, + id, + person, + }), + ], + }); + // Earlier code wrote the kind before this code started, so this code reads it as stored. + await (await adapter.createStorage()).eventStore.append(mailing("mailing-1", 1, "bob", "b")); + const { app, storage, register, target, redactions } = await setUp(undefined, adapter); + const registered = await register("ana", "ana@old.example"); + const stored = await storage.eventStore.readOne({ + aggregateType: "customer", + aggregateId: "ana", + eventId: registered.id, + }); + const old = (stored?.payload as { readonly email: unknown } | undefined)?.email; + expect(isSealed(old)).toBe(true); + await app.redact("ana", { events: [target(registered, ["email"])] }); + await storage.eventStore.append(mailing("mailing-2", 2, "ana", old)); + await app.runUntilIdle(); + const [, followUp] = await redactions(); + const reached = + (followUp?.payload as { events: readonly RedactedFields[] } | undefined)?.events ?? []; + expect(reached.map(({ aggregateType, type, fields }) => [aggregateType, type, fields])).toEqual( + [["mailing", "RecipientAdded", ["email"]]], + ); + const copied = await storage.eventStore.readOne({ + aggregateType: "mailing", + aggregateId: "m-1", + eventId: "mailing-2", + }); + expect((copied?.payload as { readonly email: unknown } | undefined)?.email).not.toEqual(old); + }); + it("cancels, and logs by id, a command holding an old value that work running at the redaction scheduled after it", async () => { const { app, storage, commands, register, target, logged, redactions } = await setUp(); const registered = await register("ana", "ana@old.example"); From 96e413be4c63777b3a0fc11e4dab5a7e2d6a2ea3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 17:00:23 +0100 Subject: [PATCH 29/33] docs: say a redaction settles an old value written after it in any event of the person --- .changeset/redact-by-envelope.md | 2 +- docs/src/content/docs/guides/personal-data.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.changeset/redact-by-envelope.md b/.changeset/redact-by-envelope.md index 1d271f24a..8a8c245ba 100644 --- a/.changeset/redact-by-envelope.md +++ b/.changeset/redact-by-envelope.md @@ -2,4 +2,4 @@ "@bounda-dev/core": minor --- -`redact` reaches any field of every event type of the app, and of every process lifecycle event that carries its state, a retired type and one that marks nothing now included, by what the stored event holds: a value sealed for the person, or one in the clear where its type marks it, or, for a retired type, where a set of marks the store recorded does. `RedactedFields.fields` takes any field name, offering the marked ones by name, and only a stream and type the app knows nothing of is refused before the store is read. **Breaking:** a field the event does not hold, or holds sealed for another person, which a redaction passed over before, resolving without sealing it, is refused with `ValidationError` (`redact cannot reach the event : it holds no ""`, `… it holds "" sealed for another person`), nothing redacted or recorded; and a field its type does not mark, refused before whatever the event held, is reached when the event holds it sealed for the person and refused as `it holds "" in the clear` when it does not. The reconciliation of the forget ledger redacts again by each field's envelope, a field no longer marked included. The personal-data export lists every field the store holds sealed for the person under the category its envelope names, an event of a retired type and a field no longer marked included, and the tenant export restricts each field by the restrictions of the person its envelope names. +`redact` reaches any field of every event type of the app, and of every process lifecycle event that carries its state, a retired type and one that marks nothing now included, by what the stored event holds: a value sealed for the person, or one in the clear where its type marks it, or, for a retired type, where a set of marks the store recorded does. `RedactedFields.fields` takes any field name, offering the marked ones by name, and only a stream and type the app knows nothing of is refused before the store is read. **Breaking:** a field the event does not hold, or holds sealed for another person, which a redaction passed over before, resolving without sealing it, is refused with `ValidationError` (`redact cannot reach the event : it holds no ""`, `… it holds "" sealed for another person`), nothing redacted or recorded; and a field its type does not mark, refused before whatever the event held, is reached when the event holds it sealed for the person and refused as `it holds "" in the clear` when it does not. The reconciliation of the forget ledger redacts again by each field's envelope, a field no longer marked included, and so does the settling of a redaction, for an old value work running at it wrote after it in any event of the person, of an aggregate or a process this code no longer has included. The personal-data export lists every field the store holds sealed for the person under the category its envelope names, an event of a retired type and a field no longer marked included, and the tenant export restricts each field by the restrictions of the person its envelope names. diff --git a/docs/src/content/docs/guides/personal-data.md b/docs/src/content/docs/guides/personal-data.md index be47f746b..a671cdeb8 100644 --- a/docs/src/content/docs/guides/personal-data.md +++ b/docs/src/content/docs/guides/personal-data.md @@ -1300,7 +1300,8 @@ the scheduler that names nobody, until every read model with personal fields, an one under way, has projected the redaction and every read model to rebuild has been rebuilt from after it, each on its own database included; the worker then removes it, and makes unreadable what work that read the old value just before the redaction committed wrote of it after: an event of the -person holding it gets a redaction of its own, a scheduled command or a dead letter goes as above, +person holding it sealed, whatever its type marks, one of a retired type or of an aggregate or a +process this code no longer has included, gets a redaction of its own, a scheduled command or a dead letter goes as above, and a subscriber's last failure on an event of theirs, or kept in the clear, that quotes it has its text sealed for good. The entry is part of the database, so a crash or a restart only pauses it; a read model that fails keeps it, and with it the old values, until it projects the redaction, and a From 19c4c8aa1f1b6c9d074341084a0e93ff7f056e0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 17:04:50 +0100 Subject: [PATCH 30/33] test(core): kill the mutants left on the backfill's recording of sets sealed, the hold's rest and resealing a retired type's events --- .../personal-data/backfill-walk.test.ts | 240 ++++++++++++++---- .../personal-data/reseal-batches.test.ts | 100 +++++++- .../kernel/personal-data/resealing.test.ts | 75 +++++- 3 files changed, 354 insertions(+), 61 deletions(-) diff --git a/packages/core/src/kernel/personal-data/backfill-walk.test.ts b/packages/core/src/kernel/personal-data/backfill-walk.test.ts index d6b0e713e..a5c4c71dd 100644 --- a/packages/core/src/kernel/personal-data/backfill-walk.test.ts +++ b/packages/core/src/kernel/personal-data/backfill-walk.test.ts @@ -185,6 +185,52 @@ const rows = async (storage: Storage) => .map(({ subscriber, position }) => [subscriber.slice(BACKFILL_PREFIX.length), position]), ); +const sealingCode = () => { + const customer = aggregates.byName.customer as AggregatesRuntime["byName"][string]; + const code = { + ...aggregates, + byName: { + customer: { + ...customer, + eventsByType: { + CustomerRegistered: { + ...customer.eventsByType.CustomerRegistered, + type: "CustomerRegistered", + }, + }, + }, + }, + } as unknown as AggregatesRuntime; + const [own] = currentMarkSets(code); + if (own === undefined) throw new Error("no set"); + return { code, own }; +}; + +// The storage whose next listing of the checkpoints runs what `meanwhile` was given once it read +// them, before the pass goes on. +const listingMeanwhile = (storage: Storage) => { + let next: (() => Promise) | null = null; + const listing: Storage = { + ...storage, + checkpointStore: { + ...storage.checkpointStore, + list: async () => { + const listed = await storage.checkpointStore.list(); + const run = next; + next = null; + await run?.(); + return listed; + }, + }, + }; + return { + listing, + meanwhile: (run: () => Promise) => { + next = run; + }, + }; +}; + describe("the backfill's walk", () => { it("walks a batch a pass, then the stores, and logs what it sealed once it catches up", async () => { const storage = await memory().createStorage(); @@ -648,6 +694,35 @@ describe("the backfill's walk", () => { expect(await backfill.nextDueAt()).toEqual(new Date(heldUntil)); }); + it("rests through a long hold a follow interval at a time, reading nothing of the store in between", async () => { + const base = await memory().createStorage(); + let down = false; + const storage: Storage = { + ...base, + checkpointStore: { + ...base.checkpointStore, + get: (subscriber) => + down + ? Promise.reject(new Error("checkpoints are down")) + : base.checkpointStore.get(subscriber), + }, + }; + await base.checkpointStore.set( + `${BACKFILL_PREFIX}m1:held-until`, + START.getTime() + 30 * BACKFILL_FOLLOW_INTERVAL_MS, + ); + const { logs, logger } = recording(); + const { backfill } = walker({ storage, logger }); + expect(await backfill.sweep(START)).toBe(0); + down = true; + const next = START.getTime() + BACKFILL_FOLLOW_INTERVAL_MS; + expect(await backfill.sweep(new Date(next - 1))).toBe(0); + expect(logs).toEqual([]); + down = false; + expect(await backfill.sweep(new Date(next))).toBe(0); + expect((await rows(base))["m1:lease"]).toBe(next + BACKFILL_LEASE_MS); + }); + it("pauses in this instance when the store cannot keep the hold", async () => { const base = await memory().createStorage(); let broken = true; @@ -959,23 +1034,7 @@ describe("the backfill's walk beside an instance on other marks", () => { it("records its sets sealed through its position once caught up with none running, and again once another walk recorded its own since", async () => { const storage = await memory().createStorage(); await append(storage, pending("customer", "c-1", "CustomerRegistered", { email: "a" })); - const customer = aggregates.byName.customer as AggregatesRuntime["byName"][string]; - const code = { - ...aggregates, - byName: { - customer: { - ...customer, - eventsByType: { - CustomerRegistered: { - ...customer.eventsByType.CustomerRegistered, - type: "CustomerRegistered", - }, - }, - }, - }, - } as unknown as AggregatesRuntime; - const [own] = currentMarkSets(code); - if (own === undefined) throw new Error("no set"); + const { code, own } = sealingCode(); const older = { ...own, fingerprint: "older", marks: null }; await storage.eventStore.recordMarks({ marks: [own, older], at: START.toISOString() }); await storage.checkpointStore.set( @@ -1006,47 +1065,95 @@ describe("the backfill's walk beside an instance on other marks", () => { expect(await sealed()).toEqual({ own: 1, older: null }); }); - it("records no set sealed once a walk on other marks took its lease after the pass read none running, and does once that lease lapsed", async () => { + it("tells the set of its type sealed furthest by aggregate, type and marks, and records its own again only once it is not", async () => { const storage = await memory().createStorage(); - await append(storage, pending("customer", "c-1", "CustomerRegistered", { email: "a" })); - const customer = aggregates.byName.customer as AggregatesRuntime["byName"][string]; - const code = { - ...aggregates, - byName: { - customer: { - ...customer, - eventsByType: { - CustomerRegistered: { - ...customer.eventsByType.CustomerRegistered, - type: "CustomerRegistered", - }, - }, - }, - }, - } as unknown as AggregatesRuntime; - const [own] = currentMarkSets(code); - if (own === undefined) throw new Error("no set"); + const { code, own } = sealingCode(); + const older = { ...own, fingerprint: "older", marks: null }; + // Recorded before its own: the same marks on a type of another aggregate and on another type + // of its own, those types under other marks too, which their walks sealed on the empty store, + // and its type's older set. + const alike = [ + { ...own, aggregateType: "client" }, + { ...own, type: "CustomerImported" }, + ]; + const unlike = alike.map((set) => ({ ...set, fingerprint: "older", marks: null })); + await storage.eventStore.recordMarks({ + marks: [...alike, ...unlike, older], + at: START.toISOString(), + }); await storage.eventStore.recordMarks({ marks: [own], at: START.toISOString() }); - // Runs once the pass read the rows of every walk, before it records anything. - let between: (() => Promise) | null = null; - const listing: Storage = { - ...storage, - checkpointStore: { - ...storage.checkpointStore, - list: async () => { - const listed = await storage.checkpointStore.list(); - const run = between; - between = null; + await storage.eventStore.recordSealed({ sets: unlike, through: 0 }); + const sealed = async () => + Object.fromEntries( + (await storage.eventStore.marksOf({ aggregateType: "customer", type: own.type })).map( + ({ fingerprint, sealedThrough }) => [ + fingerprint === own.fingerprint ? "own" : fingerprint, + sealedThrough, + ], + ), + ); + // Runs once the pass caught up, before it reads the sets to record. + let meanwhile: (() => Promise) | null = null; + const read = readingAll(storage.eventStore); + const { backfill, clock } = walker({ + storage, + code, + eventStore: { + ...read, + marksOf: async (of) => { + const run = meanwhile; + meanwhile = null; await run?.(); - return listed; + return read.marksOf(of); }, }, + }); + const pass = async (...events: PendingEvent[]) => { + await append(storage, ...events); + clock.advance(BACKFILL_FOLLOW_INTERVAL_MS); + await backfill.sweep(clock.now()); + }; + + await backfill.sweep(clock.now()); + expect(await sealed()).toEqual({ own: 0, older: null }); + await pass(pending("customer", "c-1", "CustomerRegistered", { email: "a" })); + expect(await sealed()).toEqual({ own: 0, older: null }); + + await storage.eventStore.recordSealed({ sets: [older], through: 1 }); + await pass(); + expect(await sealed()).toEqual({ own: 1, older: null }); + // A walk under the older set, stalled since the store was empty, records its set late. + await storage.eventStore.recordSealed({ sets: [older], through: 0 }); + await pass(); + expect(await sealed()).toEqual({ own: 1, older: 0 }); + + // One on a clock far behind walks an event written meanwhile, and records its set first. + meanwhile = async () => { + await append(storage, pending("customer", "c-2", "CustomerRegistered", { email: "b" })); + await storage.eventStore.recordSealed({ sets: [older], through: 2 }); }; + await pass(); + expect(await sealed()).toEqual({ own: 1, older: 2 }); + await pass(); + expect(await sealed()).toEqual({ own: 2, older: null }); + }); + + it("records no set sealed once a walk on other marks took its lease after the pass read none running, and does once that lease lapsed", async () => { + const storage = await memory().createStorage(); + await append(storage, pending("customer", "c-1", "CustomerRegistered", { email: "a" })); + const { code, own } = sealingCode(); + await storage.eventStore.recordMarks({ marks: [own], at: START.toISOString() }); + // A walk on other marks that stopped a follow interval ago, and takes its lease again. + await storage.checkpointStore.set( + `${BACKFILL_PREFIX}m2:lease`, + START.getTime() - BACKFILL_FOLLOW_INTERVAL_MS, + ); + const { listing, meanwhile } = listingMeanwhile(storage); const sealedThrough = async () => (await storage.eventStore.marksOf()).map(({ sealedThrough: through }) => through); const { backfill, clock } = walker({ storage: listing, code }); const retiring = createBackfillLease({ storage, marks: "m2", clock, logger: silentLogger }); - between = () => retiring.take(clock.now().getTime()); + meanwhile(() => retiring.take(clock.now().getTime())); await backfill.sweep(clock.now()); expect(await backfill.status()).toMatchObject({ caughtUp: true }); expect((await rows(storage))["m2:lease"]).toBe(START.getTime() + BACKFILL_LEASE_MS); @@ -1057,6 +1164,43 @@ describe("the backfill's walk beside an instance on other marks", () => { expect(await sealedThrough()).toEqual([1]); }); + it("records its sets sealed though rows besides the leases of other marks changed since the pass read them, its own lease among them, in whatever order the store lists them", async () => { + const base = await memory().createStorage(); + await append(base, pending("customer", "c-1", "CustomerRegistered", { email: "a" })); + const { code, own } = sealingCode(); + await base.eventStore.recordMarks({ marks: [own], at: START.toISOString() }); + for (const other of ["m2", "m3"]) { + await base.checkpointStore.set( + `${BACKFILL_PREFIX}${other}:lease`, + START.getTime() - BACKFILL_FOLLOW_INTERVAL_MS, + ); + } + const { listing, meanwhile } = listingMeanwhile( + transacting(base, (transaction) => ({ + ...transaction, + checkpointStore: { + ...transaction.checkpointStore, + list: async () => [...(await transaction.checkpointStore.list())].reverse(), + }, + })), + ); + const { backfill, clock } = walker({ storage: listing, code }); + // Half its lease spent meanwhile, the pass renews it as it goes through the stores; a walk on + // other marks that failed before it took its lease holds itself. + meanwhile(async () => { + clock.advance(BACKFILL_LEASE_MS / 2); + await base.checkpointStore.set(`${BACKFILL_PREFIX}m2:attempts`, 1); + await base.checkpointStore.set(`${BACKFILL_PREFIX}m2:held-until`, START.getTime() + HOLD_MS); + }); + await backfill.sweep(START); + expect((await rows(base))["m1:lease"]).toBe( + START.getTime() + BACKFILL_LEASE_MS / 2 + BACKFILL_LEASE_MS, + ); + expect((await base.eventStore.marksOf()).map(({ sealedThrough }) => sealedThrough)).toEqual([ + 1, + ]); + }); + it("is not caught up while a rewrite is left, and goes through the stores again after walking back", async () => { const storage = await memory().createStorage(); await append(storage, pending("contact", "c-1", "ContactAdded", { mail: "a" })); diff --git a/packages/core/src/kernel/personal-data/reseal-batches.test.ts b/packages/core/src/kernel/personal-data/reseal-batches.test.ts index af5cbafc5..081f31ab6 100644 --- a/packages/core/src/kernel/personal-data/reseal-batches.test.ts +++ b/packages/core/src/kernel/personal-data/reseal-batches.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import type { Storage } from "../../adapter/adapter.ts"; import type { NewDeadLetter } from "../../adapter/storage/dead-letter-store.ts"; -import type { PendingEvent } from "../../adapter/storage/event-store.ts"; +import type { PendingEvent, RecordedPersonalMarks } from "../../adapter/storage/event-store.ts"; import type { KeyedPerson, SealedValue } from "../../adapter/storage/personal-key-store.ts"; import { silentLogger } from "../../contracts/logger.ts"; import { memory } from "../../memory/index.ts"; @@ -15,7 +15,7 @@ import { sealedKeys } from "./commands.ts"; import { isSealed, seal, unseal } from "./crypto.ts"; import { openTextWith } from "./errors.ts"; import { createResealBatches } from "./reseal-batches.ts"; -import { NO_STORED_MARKS } from "./stored-marks.ts"; +import { marksSetFingerprint, NO_STORED_MARKS, storedMarksOf } from "./stored-marks.ts"; const metadata = { correlationId: "c", @@ -378,6 +378,102 @@ describe("resealing a process's lifecycle events", () => { }); }); +describe("resealing a retired type's events", () => { + const retiring = { + ...aggregates, + byName: { + ...aggregates.byName, + customer: { + ...aggregates.byName.customer, + retired: new Set(["CustomerImported", "CustomerMerged"]), + }, + }, + } as unknown as AggregatesRuntime; + const byAggregate: RecordedPersonalMarks = { person: null, fields: ["email"], categories: {} }; + const retired = async (sets: Readonly>) => { + const { storage, append } = await setup(false); + await storage.eventStore.recordMarks({ + marks: Object.entries(sets).flatMap(([type, recorded]) => + recorded.map((marks) => ({ + aggregateType: "customer", + type, + fingerprint: marksSetFingerprint(marks), + marks, + })), + ), + at: "2026-01-01T00:00:00.000Z", + }); + const reseal = createResealBatches({ + storage, + reading: storage.eventStore, + aggregates: retiring, + processes, + wrapping: testWrapping(), + atRest: null, + marks: "m1", + logger: silentLogger, + recordsActivity: false, + }); + const read = async () => storedMarksOf(await storage.eventStore.marksOf()); + return { storage, append, reseal, read }; + }; + + it("seals what its sets agree on, counting unsealable an event that holds a field they give different categories", async () => { + const { storage, append, reseal, read } = await retired({ + CustomerImported: [ + { person: null, fields: ["email", "phone"], categories: { email: "profile" } }, + byAggregate, + ], + }); + await append( + event("customer", "c-1", 1, "CustomerImported", { email: "ada@example.com", phone: "600" }), + ); + expect(await reseal.events(await all(storage), true, await read())).toEqual({ + resealed: 1, + discarded: 0, + unsealable: 1, + left: 0, + discardedTypes: new Set(), + unsealableTypes: new Set(["customer.CustomerImported"]), + }); + const [imported] = await all(storage); + expect(fieldOf(imported?.payload, "email")).toBe("ada@example.com"); + expect(isSealed(fieldOf(imported?.payload, "phone"))).toBe(true); + }); + + it("leaves every event of a person as it is, counting them left, once the sets of any of their retired types changed since they were read", async () => { + const { storage, append, reseal, read } = await retired({ + CustomerImported: [byAggregate], + CustomerMerged: [byAggregate], + }); + await append( + event("customer", "c-1", 1, "CustomerImported", { email: "ada@example.com" }), + event("customer", "c-1", 2, "CustomerMerged", { email: "ada@example.org" }), + ); + const before = await read(); + // A walk sealed every value of the first type under its set alone since. + await storage.eventStore.recordSealed({ + sets: [ + { + aggregateType: "customer", + type: "CustomerImported", + fingerprint: marksSetFingerprint(byAggregate), + }, + ], + through: 2, + }); + expect(await reseal.events(await all(storage), true, before)).toMatchObject({ + resealed: 0, + left: 2, + }); + expect((await all(storage)).map(({ person }) => person)).toEqual([null, null]); + expect(await reseal.events(await all(storage), true, await read())).toMatchObject({ + resealed: 2, + left: 0, + }); + }); +}); + describe("resealing scheduled commands", () => { it("seals each payload under its person, keeping the persons it named, and counts what names nobody", async () => { const { storage, reseal, append, opened } = await setup(); diff --git a/packages/core/src/kernel/personal-data/resealing.test.ts b/packages/core/src/kernel/personal-data/resealing.test.ts index 4a1d0d5a8..c451988db 100644 --- a/packages/core/src/kernel/personal-data/resealing.test.ts +++ b/packages/core/src/kernel/personal-data/resealing.test.ts @@ -340,6 +340,32 @@ describe("planEventReseal", () => { ); expect(instance.person).toBe("s-1"); }); + + it("seals anew under its category's key a value the state of a process lifecycle event holds sealed under another", async () => { + const key = await openedKey(await newStoredKey()); + const email = await seal({ key, person: "c-1", category: "default", value: "a@b.c" }); + const planned = planEventReseal({ + event: event({ + aggregateType: "process:signup.onboarding", + aggregateId: "s-1", + type: "ProcessHandled", + payload: { step: "x", state: { customerId: "c-1", email } }, + person: "c-1", + }), + ...runtimes({ + process: { person: "customerId", fields: ["email"], categories: { email: "profile" } }, + }), + }); + if (planned === null || planned === "unsealable") throw new Error("no plan"); + const opened = await planned.opened(async (sealed) => ({ + value: await unseal({ key, sealed }), + })); + if (opened === null) throw new Error("nothing to seal"); + expect(opened).toMatchObject({ categories: ["profile"], movedFrom: [key.fingerprint] }); + const { state } = (await opened.seal(() => key)) as { state: Record }; + expect(categoryOf(state.email as never)).toBe("profile"); + expect(await unseal({ key, sealed: state.email as never })).toBe("a@b.c"); + }); }); describe("planPayloadReseal", () => { @@ -766,21 +792,24 @@ describe("planEventReseal of a retired type", () => { expect(categoryOf(value.phone as never)).toBe("default"); }); - it("leaves in the clear, unsealable, a field its sets give different categories with no walk sealed under one of them last", async () => { + it("leaves in the clear, unsealable, a field its sets give different categories with no walk sealed under one of them last, and the whole event when it names nobody", async () => { const { aggregates, processes } = retiredWith([ { person: null, fields: ["email", "phone"], categories: { email: "profile" } }, { person: null, fields: ["email"], categories: {} }, ]); - const plan = planEventReseal({ - event: event({ payload: { email: "ana@example.com", phone: "600" } }), - aggregates, - processes, - }); + const payload = { email: "ana@example.com", phone: "600" }; + const plan = planEventReseal({ event: event({ payload }), aggregates, processes }); expect(plan).toMatchObject({ unsealable: true }); const sealed = await sealedWith(plan); const value = sealed.value as Record; expect(value.email).toBe("ana@example.com"); expect(value.phone).toMatchObject({ $personal: { person: "c-1" } }); + + const byField = retiredWith([ + { person: "customerId", fields: ["email", "phone"], categories: { email: "profile" } }, + { person: "customerId", fields: ["email"], categories: {} }, + ]); + expect(planEventReseal({ event: event({ payload }), ...byField })).toBe("unsealable"); }); it("leaves what it holds sealed as it is, under whatever category, since no schema says which is its own", async () => { @@ -822,6 +851,12 @@ describe("planEventReseal of a retired type", () => { processes, }), ).toBe("unsealable"); + expect( + planEventReseal({ + event: event({ person: "c-1", payload: { customerId: "c-2", address: "Bilbao" } }), + ...retiredWith([{ person: "customerId", fields: ["address"], categories: {} }]), + }), + ).toBe("unsealable"); }); }); @@ -932,7 +967,7 @@ describe("planUpcastReseal", () => { expect(isSealed(rewritten?.email)).toBe(true); }); - const reshaping = (upcast: (payload: Record) => unknown) => + const reshaping = (upcast: (payload: Record) => unknown, marks: PersonalMarks) => ({ byName: { customer: { @@ -940,7 +975,7 @@ describe("planUpcastReseal", () => { eventsByType: { CustomerRegistered: { type: "CustomerRegistered", - personal: marked, + personal: marks, schema: z.object({ customerId: z.string(), email: z.string().nullable() }), schemaVersion: 2, upcasts: [upcast], @@ -958,12 +993,13 @@ describe("planUpcastReseal", () => { const rewrittenBy = async ( upcast: (payload: Record) => unknown, payload: (sealed: (value: string) => Promise) => Promise, + marks: PersonalMarks = marked, ) => { const key = await openedKey(await newStoredKey()); const stored = await payload((value) => seal({ key, person: "c-1", category: "default", value }), ); - const planned = plan(reshaping(upcast), { person: "c-1", payload: stored }); + const planned = plan(reshaping(upcast, marks), { person: "c-1", payload: stored }); if (planned === null || planned === "unsealable" || "bare" in planned) { throw new Error("no plan"); } @@ -994,7 +1030,7 @@ describe("planUpcastReseal", () => { expect(JSON.stringify(rewritten)).not.toContain("call after 5"); }); - it("seals in the default category what the upcasts make, under a key the current schema does not declare, of a value they opened", async () => { + it("seals in the default category what the upcasts make, under a key the current schema does not declare, of a value they opened, and each marked field in its own", async () => { const { key, opened, rewritten } = await rewrittenBy( (payload) => ({ customerId: payload.customerId, @@ -1003,8 +1039,10 @@ describe("planUpcastReseal", () => { source: "web", }), async (sealed) => ({ customerId: "c-1", mail: await sealed("ana@example.com") }), + { ...marked, categories: { email: "profile" } }, ); - expect(opened.categories).toEqual(["default"]); + expect(opened.categories).toEqual(["profile", "default"]); + expect(categoryOf(rewritten.email as never)).toBe("profile"); expect(rewritten.domain).toMatchObject({ $personal: { person: "c-1" } }); expect(categoryOf(rewritten.domain as never)).toBe("default"); expect(await unseal({ key, sealed: rewritten.domain as never })).toBe("example.com"); @@ -1028,4 +1066,19 @@ describe("planUpcastReseal", () => { expect(rewritten.kept).toBe(7); expect(JSON.stringify(rewritten)).not.toContain("example.com"); }); + + it("seals no marked field the current shape leaves out, and writes a shape the upcasts make no object of as they make it", async () => { + const left = await rewrittenBy( + (payload) => ({ customerId: payload.customerId }), + async () => ({ customerId: "c-1" }), + ); + expect(left.opened.categories).toEqual([]); + expect(left.rewritten).toEqual({ customerId: "c-1" }); + const unshaped = await rewrittenBy( + () => null, + async (sealed) => ({ customerId: "c-1", mail: await sealed("ana@example.com") }), + ); + expect(unshaped.opened.categories).toEqual([]); + expect(unshaped.rewritten).toBeNull(); + }); }); From 58ee95a97824d9ce2680ded700c060c561d1901d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 17:06:27 +0100 Subject: [PATCH 31/33] test(core): kill the mutants left on a start's checks of retired types, forgotten tenants, delayed runs, process letters and the unit of work's marks --- .../kernel/personal-data/fresh-marks.test.ts | 29 ++++ .../personal-data/retired-marks-app.test.ts | 124 +++++++++++++++++- .../core/src/kernel/policy/delayed.test.ts | 40 +++++- .../core/src/kernel/process/runner.test.ts | 50 +++++++ .../kernel/unit-of-work/unit-of-work.test.ts | 24 ++++ 5 files changed, 264 insertions(+), 3 deletions(-) diff --git a/packages/core/src/kernel/personal-data/fresh-marks.test.ts b/packages/core/src/kernel/personal-data/fresh-marks.test.ts index d4fc900df..8a4605be1 100644 --- a/packages/core/src/kernel/personal-data/fresh-marks.test.ts +++ b/packages/core/src/kernel/personal-data/fresh-marks.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { memory } from "../../memory/index.ts"; +import type { Registry } from "../../modules/registry.ts"; import { buildAggregates } from "../aggregate/build-aggregates.ts"; import { retiredNote, retiredNoteMarks, retiredNoteRegistry } from "../test-support.ts"; import { personOfEventNow } from "./fresh-marks.ts"; @@ -22,6 +23,34 @@ describe("personOfEventNow", () => { expect(await now()).toBe("o-1"); }); + it("reads the sets the store holds now beside an aggregate that retires nothing", async () => { + const storage = await memory().createStorage(); + const registry = { + ...retiredNoteRegistry, + aggregates: { + ...retiredNoteRegistry.aggregates, + invoice: { + events: { invoiceIssued: { evolve: () => ({}) } }, + commands: {}, + policies: {}, + processes: {}, + }, + }, + } as unknown as Registry; + const { started, moved } = await retiredNoteMarks( + storage.eventStore, + buildAggregates({ registry, ports: {} }), + ); + await moved(); + expect( + await personOfEventNow({ + eventStore: storage.eventStore, + aggregates: started, + event: retiredNote, + }), + ).toBe("o-1"); + }); + it("reads nothing for a type that is not retired, nor for an aggregate the app does not know", async () => { const { started } = await setUp(); const unread = { diff --git a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts index 5bfa9388b..ac0aa06e2 100644 --- a/packages/core/src/kernel/personal-data/retired-marks-app.test.ts +++ b/packages/core/src/kernel/personal-data/retired-marks-app.test.ts @@ -9,7 +9,7 @@ import type { SealedValue } from "../../adapter/storage/personal-key-store.ts"; import { pendingEvent } from "../../adapter/testing/fixtures.ts"; import type { Config } from "../../config/types.ts"; import { type Clock, createFixedClock } from "../../contracts/clock.ts"; -import { ConfigurationError } from "../../contracts/errors.ts"; +import { ConfigurationError, TenantForgottenError } from "../../contracts/errors.ts"; import type { StoredEvent } from "../../contracts/event.ts"; import { createSequentialIdGenerator } from "../../contracts/ids.ts"; import { type Logger, silentLogger } from "../../contracts/logger.ts"; @@ -27,6 +27,7 @@ import type { ExportedEvent } from "./export.ts"; import { RECORDED_PERSONAL_DATA } from "./ledger-in-force.ts"; import { pruneTenantForgetLedger } from "./ledger-prune.ts"; import { masterKey } from "./master-key.ts"; +import { listStrandedForgetLedgerEntries } from "./stranded.ts"; import { defineTenantKeyStore } from "./tenant-key-source.ts"; import { DEFAULT_TENANT } from "./tenant-keys.ts"; @@ -610,7 +611,7 @@ describe.each(adapters)("the marks a start records, on %s", (_name, adapterOf) = expect(await setsOf(adapter)).toEqual([emailOnly, asInvoice]); }); - it("records nothing on a forgotten tenant, nor refuses a retired type there that no start recorded marks for", async () => { + it("records nothing on a forgotten tenant, nor refuses a retired type there that no start recorded marks for, at start or listing what is stranded", async () => { const adapter = adapterOf(); const first = await start(adapter, "clear"); await note(first.app, "c-1", "call after five"); @@ -635,6 +636,112 @@ describe.each(adapters)("the marks a start records, on %s", (_name, adapterOf) = await (await start(adapter, "invoices")).stop(); await (await start(adapter, "retired")).stop(); expect(await (await storageOf(adapter)).eventStore.marksOf()).toEqual(before); + await expect( + listStrandedForgetLedgerEntries({ + registry: registryOf("retired"), + config: { + storage: adapter, + runtime: { personalData: { forgetLedger: { store: ledgerFor(adapter) } } }, + } as Config, + now: START, + }), + ).resolves.toEqual({ tenant: DEFAULT_TENANT, entries: [], unreached: [] }); + }); +}); + +describe("a forgotten tenant's start on a database of its own", () => { + const env = { + BOUNDA_MASTER_KEY: Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64"), + }; + + const onFile = () => { + const directory = mkdtempSync(join(tmpdir(), "bounda-retired-marks-")); + directories.push(directory); + const tenantKeys = createMemoryTenantKeyStore(); + const ledger = memory(); + const file = (name: string) => join(directory, name); + // Without keys, the code names neither a key wrapper nor a tenant key store. + const startOn = async (name: string, registry: Registry, keys = true) => { + starts += 1; + const sqlite = createNodeSqliteAdapter(file(name)); + const close = (): void => { + if (sqlite.db.isOpen) sqlite.db.close(); + }; + try { + const app = await createApp({ + registry, + config: { + storage: sqlite.adapter, + runtime: { + personalData: keys + ? { + keyWrapper: masterKey({ from: "BOUNDA_MASTER_KEY" }), + tenantKeys: defineTenantKeyStore(() => tenantKeys), + forgetLedger: { store: ledger }, + } + : {}, + }, + } as Config, + env, + clock: createFixedClock(START), + ids: createSequentialIdGenerator({ prefix: `app-${starts}` }), + logger: silentLogger, + }); + const stop = async (): Promise => { + await app.stop(); + close(); + }; + stops.unshift(stop); + return { app, adapter: sqlite.adapter, db: sqlite.db, stop }; + } catch (error) { + close(); + throw error; + } + }; + return { file, startOn }; + }; + + // A `ReminderSent` written past the runtime, of a type no start recorded marks for. + const reminded = async (adapter: Adapter, version: number) => + (await storageOf(adapter)).eventStore.append({ + aggregateType: "customer", + aggregateId: "c-1", + expectedVersion: version - 1, + events: [ + pendingEvent({ + aggregateType: "customer", + aggregateId: "c-1", + version, + type: "ReminderSent", + payload: { channel: "post" }, + }), + ], + }); + + it("starts forgotten on a copy from before the forgetting, as its keys tell it, recording no marks there nor refusing a retired type", async () => { + const at = onFile(); + const first = await at.startOn("store.db", registryOf("clear")); + await note(first.app, "c-1", "call after five"); + await reminded(first.adapter, 2); + first.db.exec(`VACUUM INTO '${at.file("copy.db")}'`); + await first.app.forgetTenant(DEFAULT_TENANT, { despiteLegalObligations: true }); + await first.stop(); + + const restored = await at.startOn("copy.db", registryOf("invoices")); + await expect(restored.app.exportPersonalData("c-1")).rejects.toThrow(TenantForgottenError); + expect(await setsOf(restored.adapter)).toEqual([emailOnly]); + }); + + it("refuses code that names no keys as forgotten, where only the database's fence tells it, before a retired type no start recorded marks for", async () => { + const at = onFile(); + const unmarked = registryOf("retired", "dropped"); + const first = await at.startOn("store.db", unmarked); + await send(first.app, "registerCustomer", { customerId: "c-1", name: "Ada" }); + await reminded(first.adapter, 2); + await first.app.forgetTenant(DEFAULT_TENANT, { despiteLegalObligations: true }); + await first.stop(); + + await expect(at.startOn("store.db", unmarked, false)).rejects.toThrow(TenantForgottenError); }); }); @@ -781,6 +888,19 @@ describe.each(adapters)( expect(categoryOf(noteOf(second) as never)).toBe("invoices"); }); + it("holds the set it checked it against from its start: a walk of other code that catches up after it records no set sealed", async () => { + const adapter = adapterOf(); + const { deploy, clock } = deploys(() => adapter); + await deploy("default", (app) => note(app, "c-1", "call after five")); + await deploy("clear", (app) => note(app, "c-2", "prefers email")); + await deploy("invoices", walked); + const other = await start(adapter, "default", clock); + + await start(adapter, "retired", clock); + await other.app.runUntilIdle(); + expect(await sealedLast(adapter)).toEqual([false, false, true]); + }); + it("holds its walk, refuses redactions and exports, and the next start, once a walk of other code caught up alone while its lease had lapsed", async () => { const adapter = adapterOf(); const { deploy, clock } = deploys(() => adapter); diff --git a/packages/core/src/kernel/policy/delayed.test.ts b/packages/core/src/kernel/policy/delayed.test.ts index 98432a7d1..ee36b4894 100644 --- a/packages/core/src/kernel/policy/delayed.test.ts +++ b/packages/core/src/kernel/policy/delayed.test.ts @@ -34,7 +34,16 @@ let failures: { readonly left: number; readonly error: () => Error } = { error: () => new Error("network"), }; -const registryWith = (delay: string | number = "1m"): Registry => ({ +// An aggregate with an event of the same name as the order's. +const ledger = { + events: { orderPlaced: { evolve: ({ state }: { state: object }) => state } }, + commands: {}, + policies: {}, + processes: {}, +}; + +// With `source`, the policy reacts to the ledger's `OrderPlaced` instead of the order's. +const registryWith = (delay: string | number = "1m", source?: "ledger"): Registry => ({ aggregates: { order: { ...orderAggregateEntry(), @@ -51,6 +60,7 @@ const registryWith = (delay: string | number = "1m"): Registry => ({ await commands.archiveOrder?.({ orderId: event.aggregateId }); }, }, + ...(source === undefined ? {} : { source }), }, }, ports: { @@ -58,6 +68,7 @@ const registryWith = (delay: string | number = "1m"): Registry => ({ mailer: { memory: { default: { send: (run: Run) => runs.push(run) } } }, }, }, + ...(source === undefined ? {} : { ledger }), }, readModels: {}, }); @@ -399,6 +410,33 @@ describe("delayed policies", () => { expect(runs).toEqual([]); }); + it("drop, warning, a run whose policy now reacts to another aggregate's event of the same name", async () => { + runs.length = 0; + const adapter = memory(); + const before = await createReactiveHarness({ registry: registryWith(), adapter }); + await before.pipeline.dispatch({ type: "PlaceOrder", payload: { orderId: "o-1", total: 10 } }); + await before.dispatcher.runUntilIdle(); + const { logger, entries } = createRecordingLogger("omit"); + const after = await createReactiveHarness({ + registry: registryWith("1m", "ledger"), + adapter, + logger, + }); + after.clock.advance(60_000); + expect(await after.worker.runOnce()).toBe(1); + expect(runs).toEqual([]); + expect( + entries.filter(({ message }) => message.startsWith("delayed policy run dropped")), + ).toMatchObject([ + { + level: "warn", + fields: { policy: "order.remindOnOrderPlaced", eventType: "order.OrderPlaced" }, + }, + ]); + expect(await after.storage.scheduler.list()).toEqual([]); + expect(await after.storage.deadLetterStore.count()).toBe(0); + }); + it("defer a run whose event newer code wrote, or whose command meets such an event, by the dispatcher's base delay, counting no attempt, and run it once that code runs", async () => { runs.length = 0; failures = { left: 0, error: () => new Error("network") }; diff --git a/packages/core/src/kernel/process/runner.test.ts b/packages/core/src/kernel/process/runner.test.ts index 2c8211686..ac7c88837 100644 --- a/packages/core/src/kernel/process/runner.test.ts +++ b/packages/core/src/kernel/process/runner.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { createNodeSqliteAdapter } from "../../adapter/sqlite/node-sqlite.ts"; import { resolveConfig } from "../../config/schema.ts"; import type { ResolvedConfig } from "../../config/types.ts"; import { ValidationError } from "../../contracts/errors.ts"; @@ -1566,6 +1567,55 @@ describe("processes that listen to other aggregates", () => { ); }); + it.each([ + ["memory", () => memory()], + ["SQLite (node:sqlite)", () => createNodeSqliteAdapter().adapter], + ])( + "count as still parked, for a letter of an event correlate could not place, nothing until correlate places it, then what waits on its instance, on %s", + async (_name, adapterOf) => { + seen.length = 0; + const unplaced = new Set(["p-2"]); + const harness = await createReactiveHarness({ + adapter: adapterOf(), + registry: withCorrelate( + { + payment: { + PaymentFailed: (event) => { + if (unplaced.has((event as unknown as StoredEvent).aggregateId)) { + throw new Error("no order id yet"); + } + return event.payload.orderId; + }, + PaymentSettled: (event) => event.payload.orderId, + }, + }, + () => ({ failures: "many" }), + ), + }); + await harness.pipeline.dispatch({ + type: "PlaceOrder", + payload: { orderId: "o-1", total: 10 }, + }); + for (const paymentId of ["p-1", "p-2", "p-3"]) { + await harness.pipeline.dispatch({ + type: "FailPayment", + payload: { paymentId, orderId: "o-1", reason: paymentId }, + }); + await harness.dispatcher.runUntilIdle(); + } + const letters = await harness.storage.deadLetterStore.list(); + const failed = letters.find(({ aggregateId }) => aggregateId === "p-1"); + const unplacedLetter = letters.find(({ aggregateId }) => aggregateId === "p-2"); + if (failed === undefined || unplacedLetter === undefined) throw new Error("no letters"); + expect(unplacedLetter.instanceId).toBeUndefined(); + expect(await harness.processes.stillParked(unplacedLetter)).toBe(0); + unplaced.clear(); + const waiting = await harness.processes.stillParked(failed); + expect(waiting).toBeGreaterThan(0); + expect(await harness.processes.stillParked(unplacedLetter)).toBe(waiting); + }, + ); + it("fail a handler for good when it returns a state its schema refuses", async () => { seen.length = 0; const harness = await createReactiveHarness({ diff --git a/packages/core/src/kernel/unit-of-work/unit-of-work.test.ts b/packages/core/src/kernel/unit-of-work/unit-of-work.test.ts index 1a6a4a6d9..59241628b 100644 --- a/packages/core/src/kernel/unit-of-work/unit-of-work.test.ts +++ b/packages/core/src/kernel/unit-of-work/unit-of-work.test.ts @@ -316,6 +316,30 @@ describe("createUnitOfWork", () => { ).toMatchObject([{ payload: { total: 9 } }]); }); + it("writes the marks it records, and the sets it records sealed, at commit, each staged alone, and nothing before", async () => { + const storage = await memory().createStorage(); + const set = { + aggregateType: "order", + type: "OrderNoted", + fingerprint: "noted", + marks: { person: null, fields: ["note"], categories: { note: "default" } }, + }; + const marking = createUnitOfWork({ storage }); + await marking.eventStore.recordMarks({ marks: [set], at: now.toISOString() }); + expect(await storage.eventStore.marksOf()).toEqual([]); + await marking.commit(); + expect(await storage.eventStore.marksOf()).toMatchObject([ + { fingerprint: "noted", sealedThrough: null }, + ]); + const sealing = createUnitOfWork({ storage }); + await sealing.eventStore.recordSealed({ sets: [set], through: 3 }); + expect(await storage.eventStore.marksOf()).toMatchObject([{ sealedThrough: null }]); + await sealing.commit(); + expect(await storage.eventStore.marksOf()).toMatchObject([ + { fingerprint: "noted", sealedThrough: 3 }, + ]); + }); + it("opens no transaction when nothing was staged", async () => { const storage = await memory().createStorage(); const transact = storage.transact.bind(storage); From 0cd5bfd121471651b686c18d46b8204f2d318f8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 17:14:24 +0100 Subject: [PATCH 32/33] chore: raise the coverage thresholds for lines and branches --- vitest.config.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vitest.config.ts b/vitest.config.ts index 95e88021e..c2916d3e7 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -14,10 +14,10 @@ export default defineConfig({ // Coverage must not decrease: these sit just under the whole suite's figures, the margin // for the few branches whose coverage depends on timing. Raise them when coverage rises. thresholds: { - lines: 98.9, + lines: 99.0, statements: 98.6, functions: 97.8, - branches: 96.1, + branches: 96.2, }, }, }, From 186fe8d1a18f81cafcdd31cfa8da6b136558bd9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Be=C3=B1at=20Espi=C3=B1a?= Date: Fri, 4 Dec 2026 17:42:33 +0100 Subject: [PATCH 33/33] test(cli): compare the emitted registry's path with forward slashes, as Windows writes it with backslashes --- packages/cli/src/generate/emit/emit.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/generate/emit/emit.test.ts b/packages/cli/src/generate/emit/emit.test.ts index 377fce044..ca538572e 100644 --- a/packages/cli/src/generate/emit/emit.test.ts +++ b/packages/cli/src/generate/emit/emit.test.ts @@ -263,7 +263,9 @@ describe("emitRegistry", () => { ], }; const files = emitProject({ model: withRetired }); - const registry = files.find((file) => file.path === "/project/.bounda/registry.ts")?.content; + const registry = files.find( + (file) => slashed(file.path) === "/project/.bounda/registry.ts", + )?.content; expect(registry).toContain('import * as delayed from "../app/domain/shipment/delayed.ts";'); expect(registry).toContain( [ @@ -274,7 +276,7 @@ describe("emitRegistry", () => { ].join("\n"), ); expect(files.map((file) => file.path)).toEqual(emitProject({ model }).map((file) => file.path)); - const types = files.find((file) => file.path === "/project/.bounda/types.ts")?.content; + const types = files.find((file) => slashed(file.path) === "/project/.bounda/types.ts")?.content; expect(types).not.toContain("Delayed"); expect(emitRegistry({ model, path: "/project/.bounda/registry.ts" }).content).not.toContain( "retired",