From 1cf80b3430138d45199ab5dfa70ed1315f3d58b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 22:59:32 +0000 Subject: [PATCH] fix(service-automation): hash a flow's run identity without the served provenance stamps A flow bound to a package reaches registerFlow stamped with _packageId by the read, while the write door strips _packageId, _packageVersion and _provenance before it stores and hashes the body. flowContentChecksum now drops those three, so a run's flow_checksum equals the checksum its sys_metadata_history row is keyed by. The _lock family is stored and stays hashed. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9 --- .../39388-flow-checksum-served-stamps.md | 14 ++ ...um-served-stamps-39388.integration.test.ts | 143 ++++++++++++++++++ .../service-automation/src/flow-identity.ts | 41 ++++- 3 files changed, 193 insertions(+), 5 deletions(-) create mode 100644 .changeset/39388-flow-checksum-served-stamps.md create mode 100644 packages/services/service-automation/src/flow-checksum-served-stamps-39388.integration.test.ts diff --git a/.changeset/39388-flow-checksum-served-stamps.md b/.changeset/39388-flow-checksum-served-stamps.md new file mode 100644 index 00000000000..6555494d6a6 --- /dev/null +++ b/.changeset/39388-flow-checksum-served-stamps.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-automation': patch +--- + +fix(service-automation): a run of a flow saved into a package records the checksum its version history row is keyed by + +Clause-②: no +Metadata-protocol: none + +Who sees it: anyone running a flow that is saved into a package (Studio, `PUT /meta/flow/:name` with a package, a package install). + +- **A waiting run of a package-bound flow now records its version's real checksum.** The run used to hash the flow body as the server serves it, which carries the package stamp (`_packageId`) the stored body does not. Its `flow_checksum` then named no version in the flow's history, so after a restart or a new save the run could not find the version it started on and resumed on the current one, or not at all. +- **The checksum drops only the read-time provenance stamps** (`_packageId`, `_packageVersion`, `_provenance`), the three the metadata save door never stores. A flow's lock (`_lock` and its family) is stored and stays part of the checksum. A flow with no package keeps exactly the checksum it had. +- Runs already parked with the old checksum are not migrated. diff --git a/packages/services/service-automation/src/flow-checksum-served-stamps-39388.integration.test.ts b/packages/services/service-automation/src/flow-checksum-served-stamps-39388.integration.test.ts new file mode 100644 index 00000000000..a4265ef5d55 --- /dev/null +++ b/packages/services/service-automation/src/flow-checksum-served-stamps-39388.integration.test.ts @@ -0,0 +1,143 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #39388 — a package-bound flow's run records the checksum its history row is + * keyed by. + * + * The run-identity pinning (#28405, ADR-0146 D9 item 4) holds that a run + * records the checksum of the flow version it ran, and that checksum is the + * one the version's `sys_metadata_history` row is keyed by: a resume finds the + * body again by that hash. The body the engine is handed for a flow bound to a + * package is a SERVED body, and the read stamps the derived ADR-0010 + * provenance on it (`_packageId`; `_packageVersion` and `_provenance` where an + * artifact or a hydration states them), which the write door strips before it + * stores and hashes the body. Hashed as handed over, the run's checksum named + * no history row. + * + * One kernel over sqlite, the real metadata protocol (the producer behind + * `PUT /meta/flow/:name`) and the real engine: a flow saved into an authored + * package parks a run, and the run row's `flow_checksum` is compared with the + * history row the save wrote — never with a hash this test computes. A loose + * (package-less) flow is pinned beside it, unchanged. + * + * Its own file, not a describe in `flow-version-pinning.integration.test.ts` + * (the suite's shared harness): that file is held by another open change. + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; + +import { AutomationServicePlugin } from './plugin.js'; +import type { AutomationEngine } from './engine.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +/** `ObjectStackProtocolImplementation`'s save door — what `PUT /meta/flow/:name` calls. */ +interface MetadataWriteDoors { + saveMetaItem(request: { type: string; name: string; item: unknown; packageId?: string }): Promise; +} + +const SYSTEM = { isSystem: true } as never; +/** An authored package the package-bound save goes into, as `POST /packages` installs one. */ +const PKG = 'app.expenses'; + +/** start → a screen with one required field (the run parks) → end. */ +function reviewFlow(name: string) { + return { + name, + label: 'Expense review', + type: 'screen', + version: 1, + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { + id: 'approve', + type: 'screen', + label: 'Approve', + config: { fields: [{ name: 'decision', label: 'Decision', type: 'text', required: true }] }, + }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'approve' }, + { id: 'e2', source: 'approve', target: 'end' }, + ], + }; +} + +describe('[#39388] a run of a package-bound flow records the checksum its history row is keyed by', () => { + let kernel: ObjectKernel | undefined; + + afterEach(async () => { + try { await kernel?.shutdown(); } catch { /* noop */ } + kernel = undefined; + }); + + async function boot() { + kernel = new ObjectKernel({ logger: { level: 'fatal' }, gracefulShutdown: false } as never); + await kernel.use(new ObjectQLPlugin()); + await kernel.use({ + name: 'test.sqlite-memory', type: 'standard', version: '1.0.0', dependencies: [], + async init(ctx: { registerService(name: string, service: unknown): void }) { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.connect(); + ctx.registerService('driver.default', driver); + }, + async start() {}, + } as never); + await kernel.use(new AutomationServicePlugin()); + await kernel.bootstrap(); + const ql = kernel.getService('objectql'); + await installDefaultOrganization(ql); + (ql.registry as unknown as { installPackage(m: object, how: string): void }) + .installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app', namespace: 'expenses' }, 'authored'); + return { + ql, + automation: kernel.getService('automation'), + protocol: kernel.getService('protocol'), + }; + } + + /** The checksum the save keyed the flow's one history row by, and the parked run's recorded identity. */ + async function parkAndRead(life: Awaited>, name: string) { + await vi.waitFor(async () => { + expect((await life.automation.getFlow(name))?.version).toBe(1); + }, { timeout: 3000, interval: 20 }); + const run = await life.automation.execute(name, {} as never); + expect(run.status).toBe('paused'); + const history = await life.ql.find('sys_metadata_history', { + where: { type: 'flow', name }, context: SYSTEM, + }) as Array>; + expect(history, 'the save wrote one history row').toHaveLength(1); + const parked = await life.ql.findOne('sys_automation_run', { where: { id: run.runId }, context: SYSTEM }); + return { historyChecksum: history[0]!.checksum, runChecksum: parked?.flow_checksum }; + } + + it('a flow saved into a package: the run checksum is its history row\'s, though the armed body is stamped with the package', async () => { + const life = await boot(); + const name = 'expense_review_pkg'; + await life.protocol.saveMetaItem({ type: 'flow', name, item: reviewFlow(name), packageId: PKG }); + + const { historyChecksum, runChecksum } = await parkAndRead(life, name); + expect(historyChecksum).toMatch(/^sha256:/); + expect(runChecksum).toBe(historyChecksum); + }); + + it('a loose (package-less) flow: the run checksum is its history row\'s, as before', async () => { + const life = await boot(); + const name = 'expense_review_loose'; + // The loose row is laid straight into the store once (no history row), + // and the save below runs in place: a package-less CREATE is not the + // door this pin is about (ADR-0070 D1 moves it to refusal). + await life.ql.insert('sys_metadata', { + type: 'flow', name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', + state: 'active', version: 0, metadata: JSON.stringify({ ...reviewFlow(name), version: 0 }), + }, { context: SYSTEM } as never); + await life.protocol.saveMetaItem({ type: 'flow', name, item: reviewFlow(name) }); + + const { historyChecksum, runChecksum } = await parkAndRead(life, name); + expect(historyChecksum).toMatch(/^sha256:/); + expect(runChecksum).toBe(historyChecksum); + }); +}); diff --git a/packages/services/service-automation/src/flow-identity.ts b/packages/services/service-automation/src/flow-identity.ts index 3703e519ea9..8d9cc8dae7f 100644 --- a/packages/services/service-automation/src/flow-identity.ts +++ b/packages/services/service-automation/src/flow-identity.ts @@ -2,6 +2,35 @@ import { hashSpec } from '@objectstack/metadata-core'; +/** + * [#39388] The top-level keys a SERVED flow body can carry that its stored + * body never does: the three derived ADR-0010 provenance stamps. The metadata + * write door removes exactly these before it persists a body and hashes it + * (`DERIVED_PROVENANCE_KEYS` / `stripDerivedProvenance` in + * `@objectstack/metadata-protocol`'s `protocol-package-bindings.ts`, module + * private), and the read side stamps them back from the package binding or the + * artifact on every read. So a flow bound to a package reaches + * `registerFlow` stamped `_packageId`, while its `sys_metadata` and + * `sys_metadata_history` checksum is of the body without it. + * + * ⛔ Not the `_lock*` family: a lock is author-declarable and the write door + * persists it, so it is part of the stored body and of its checksum. ⛔ Nor + * `METADATA_READ_DECORATIONS` (`@objectstack/spec/kernel`): the flow schema + * is closed, so a body carrying one is refused by `registerFlow` before any + * checksum is taken. + */ +const SERVED_PROVENANCE_STAMPS = ['_packageId', '_packageVersion', '_provenance'] as const; + +/** `definition` without {@link SERVED_PROVENANCE_STAMPS}; the same reference when it carries none. */ +function withoutServedStamps(definition: unknown): unknown { + if (!definition || typeof definition !== 'object' || Array.isArray(definition)) return definition; + const body = definition as Record; + if (!SERVED_PROVENANCE_STAMPS.some((key) => key in body)) return definition; + const authored = { ...body }; + for (const key of SERVED_PROVENANCE_STAMPS) delete authored[key]; + return authored; +} + /** * [#28405, ADR-0146 D9 item 4] The content identity of a flow body, as a run * records it at start (`SuspendedRun.flowChecksum`) and a resume looks @@ -9,10 +38,12 @@ import { hashSpec } from '@objectstack/metadata-core'; * * It is the value the metadata repository stores in `sys_metadata.checksum` * and keys `sys_metadata_history` by — `hashSpec(body, 'flow')` — computed the - * same way here, over the body exactly as it was handed to `registerFlow` - * (the stored body, for a flow the protocol's execution read serves), so a - * stored version is found again by `getByHash`. A code-loaded body has no - * history row, and gets an equal hash computed the same way. + * same way here, over the body handed to `registerFlow` (the stored body, for + * a flow the protocol's execution read serves) less the provenance stamps the + * read adds and the write never stores ({@link SERVED_PROVENANCE_STAMPS}, + * #39388), so a stored version is found again by `getByHash` whether or not + * the flow is bound to a package. A code-loaded body has no history row, and + * gets a hash computed the same way. * * `FlowSchema.version` is not this: it is an author integer that two bodies * can share, and an unbumped edit keeps. @@ -23,7 +54,7 @@ import { hashSpec } from '@objectstack/metadata-core'; */ export function flowContentChecksum(definition: unknown): string | undefined { try { - return hashSpec(definition, 'flow'); + return hashSpec(withoutServedStamps(definition), 'flow'); } catch { return undefined; }