Skip to content

Commit 1cf80b3

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9
1 parent f32b7d6 commit 1cf80b3

3 files changed

Lines changed: 193 additions & 5 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/service-automation': patch
3+
---
4+
5+
fix(service-automation): a run of a flow saved into a package records the checksum its version history row is keyed by
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Who sees it: anyone running a flow that is saved into a package (Studio, `PUT /meta/flow/:name` with a package, a package install).
11+
12+
- **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.
13+
- **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.
14+
- Runs already parked with the old checksum are not migrated.
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #39388 — a package-bound flow's run records the checksum its history row is
5+
* keyed by.
6+
*
7+
* The run-identity pinning (#28405, ADR-0146 D9 item 4) holds that a run
8+
* records the checksum of the flow version it ran, and that checksum is the
9+
* one the version's `sys_metadata_history` row is keyed by: a resume finds the
10+
* body again by that hash. The body the engine is handed for a flow bound to a
11+
* package is a SERVED body, and the read stamps the derived ADR-0010
12+
* provenance on it (`_packageId`; `_packageVersion` and `_provenance` where an
13+
* artifact or a hydration states them), which the write door strips before it
14+
* stores and hashes the body. Hashed as handed over, the run's checksum named
15+
* no history row.
16+
*
17+
* One kernel over sqlite, the real metadata protocol (the producer behind
18+
* `PUT /meta/flow/:name`) and the real engine: a flow saved into an authored
19+
* package parks a run, and the run row's `flow_checksum` is compared with the
20+
* history row the save wrote — never with a hash this test computes. A loose
21+
* (package-less) flow is pinned beside it, unchanged.
22+
*
23+
* Its own file, not a describe in `flow-version-pinning.integration.test.ts`
24+
* (the suite's shared harness): that file is held by another open change.
25+
*/
26+
27+
import { describe, it, expect, afterEach, vi } from 'vitest';
28+
import { ObjectKernel } from '@objectstack/core';
29+
import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql';
30+
import { SqlDriver } from '@objectstack/driver-sql';
31+
32+
import { AutomationServicePlugin } from './plugin.js';
33+
import type { AutomationEngine } from './engine.js';
34+
import { installDefaultOrganization } from './default-organization.testkit.js';
35+
36+
/** `ObjectStackProtocolImplementation`'s save door — what `PUT /meta/flow/:name` calls. */
37+
interface MetadataWriteDoors {
38+
saveMetaItem(request: { type: string; name: string; item: unknown; packageId?: string }): Promise<unknown>;
39+
}
40+
41+
const SYSTEM = { isSystem: true } as never;
42+
/** An authored package the package-bound save goes into, as `POST /packages` installs one. */
43+
const PKG = 'app.expenses';
44+
45+
/** start → a screen with one required field (the run parks) → end. */
46+
function reviewFlow(name: string) {
47+
return {
48+
name,
49+
label: 'Expense review',
50+
type: 'screen',
51+
version: 1,
52+
nodes: [
53+
{ id: 'start', type: 'start', label: 'Start' },
54+
{
55+
id: 'approve',
56+
type: 'screen',
57+
label: 'Approve',
58+
config: { fields: [{ name: 'decision', label: 'Decision', type: 'text', required: true }] },
59+
},
60+
{ id: 'end', type: 'end', label: 'End' },
61+
],
62+
edges: [
63+
{ id: 'e1', source: 'start', target: 'approve' },
64+
{ id: 'e2', source: 'approve', target: 'end' },
65+
],
66+
};
67+
}
68+
69+
describe('[#39388] a run of a package-bound flow records the checksum its history row is keyed by', () => {
70+
let kernel: ObjectKernel | undefined;
71+
72+
afterEach(async () => {
73+
try { await kernel?.shutdown(); } catch { /* noop */ }
74+
kernel = undefined;
75+
});
76+
77+
async function boot() {
78+
kernel = new ObjectKernel({ logger: { level: 'fatal' }, gracefulShutdown: false } as never);
79+
await kernel.use(new ObjectQLPlugin());
80+
await kernel.use({
81+
name: 'test.sqlite-memory', type: 'standard', version: '1.0.0', dependencies: [],
82+
async init(ctx: { registerService(name: string, service: unknown): void }) {
83+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
84+
await driver.connect();
85+
ctx.registerService('driver.default', driver);
86+
},
87+
async start() {},
88+
} as never);
89+
await kernel.use(new AutomationServicePlugin());
90+
await kernel.bootstrap();
91+
const ql = kernel.getService<ObjectQL>('objectql');
92+
await installDefaultOrganization(ql);
93+
(ql.registry as unknown as { installPackage(m: object, how: string): void })
94+
.installPackage({ id: PKG, name: PKG, version: '1.0.0', type: 'app', namespace: 'expenses' }, 'authored');
95+
return {
96+
ql,
97+
automation: kernel.getService<AutomationEngine>('automation'),
98+
protocol: kernel.getService<MetadataWriteDoors>('protocol'),
99+
};
100+
}
101+
102+
/** The checksum the save keyed the flow's one history row by, and the parked run's recorded identity. */
103+
async function parkAndRead(life: Awaited<ReturnType<typeof boot>>, name: string) {
104+
await vi.waitFor(async () => {
105+
expect((await life.automation.getFlow(name))?.version).toBe(1);
106+
}, { timeout: 3000, interval: 20 });
107+
const run = await life.automation.execute(name, {} as never);
108+
expect(run.status).toBe('paused');
109+
const history = await life.ql.find('sys_metadata_history', {
110+
where: { type: 'flow', name }, context: SYSTEM,
111+
}) as Array<Record<string, unknown>>;
112+
expect(history, 'the save wrote one history row').toHaveLength(1);
113+
const parked = await life.ql.findOne('sys_automation_run', { where: { id: run.runId }, context: SYSTEM });
114+
return { historyChecksum: history[0]!.checksum, runChecksum: parked?.flow_checksum };
115+
}
116+
117+
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 () => {
118+
const life = await boot();
119+
const name = 'expense_review_pkg';
120+
await life.protocol.saveMetaItem({ type: 'flow', name, item: reviewFlow(name), packageId: PKG });
121+
122+
const { historyChecksum, runChecksum } = await parkAndRead(life, name);
123+
expect(historyChecksum).toMatch(/^sha256:/);
124+
expect(runChecksum).toBe(historyChecksum);
125+
});
126+
127+
it('a loose (package-less) flow: the run checksum is its history row\'s, as before', async () => {
128+
const life = await boot();
129+
const name = 'expense_review_loose';
130+
// The loose row is laid straight into the store once (no history row),
131+
// and the save below runs in place: a package-less CREATE is not the
132+
// door this pin is about (ADR-0070 D1 moves it to refusal).
133+
await life.ql.insert('sys_metadata', {
134+
type: 'flow', name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge',
135+
state: 'active', version: 0, metadata: JSON.stringify({ ...reviewFlow(name), version: 0 }),
136+
}, { context: SYSTEM } as never);
137+
await life.protocol.saveMetaItem({ type: 'flow', name, item: reviewFlow(name) });
138+
139+
const { historyChecksum, runChecksum } = await parkAndRead(life, name);
140+
expect(historyChecksum).toMatch(/^sha256:/);
141+
expect(runChecksum).toBe(historyChecksum);
142+
});
143+
});

‎packages/services/service-automation/src/flow-identity.ts‎

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,48 @@
22

33
import { hashSpec } from '@objectstack/metadata-core';
44

5+
/**
6+
* [#39388] The top-level keys a SERVED flow body can carry that its stored
7+
* body never does: the three derived ADR-0010 provenance stamps. The metadata
8+
* write door removes exactly these before it persists a body and hashes it
9+
* (`DERIVED_PROVENANCE_KEYS` / `stripDerivedProvenance` in
10+
* `@objectstack/metadata-protocol`'s `protocol-package-bindings.ts`, module
11+
* private), and the read side stamps them back from the package binding or the
12+
* artifact on every read. So a flow bound to a package reaches
13+
* `registerFlow` stamped `_packageId`, while its `sys_metadata` and
14+
* `sys_metadata_history` checksum is of the body without it.
15+
*
16+
* ⛔ Not the `_lock*` family: a lock is author-declarable and the write door
17+
* persists it, so it is part of the stored body and of its checksum. ⛔ Nor
18+
* `METADATA_READ_DECORATIONS` (`@objectstack/spec/kernel`): the flow schema
19+
* is closed, so a body carrying one is refused by `registerFlow` before any
20+
* checksum is taken.
21+
*/
22+
const SERVED_PROVENANCE_STAMPS = ['_packageId', '_packageVersion', '_provenance'] as const;
23+
24+
/** `definition` without {@link SERVED_PROVENANCE_STAMPS}; the same reference when it carries none. */
25+
function withoutServedStamps(definition: unknown): unknown {
26+
if (!definition || typeof definition !== 'object' || Array.isArray(definition)) return definition;
27+
const body = definition as Record<string, unknown>;
28+
if (!SERVED_PROVENANCE_STAMPS.some((key) => key in body)) return definition;
29+
const authored = { ...body };
30+
for (const key of SERVED_PROVENANCE_STAMPS) delete authored[key];
31+
return authored;
32+
}
33+
534
/**
635
* [#28405, ADR-0146 D9 item 4] The content identity of a flow body, as a run
736
* records it at start (`SuspendedRun.flowChecksum`) and a resume looks
837
* its body up by.
938
*
1039
* It is the value the metadata repository stores in `sys_metadata.checksum`
1140
* and keys `sys_metadata_history` by — `hashSpec(body, 'flow')` — computed the
12-
* same way here, over the body exactly as it was handed to `registerFlow`
13-
* (the stored body, for a flow the protocol's execution read serves), so a
14-
* stored version is found again by `getByHash`. A code-loaded body has no
15-
* history row, and gets an equal hash computed the same way.
41+
* same way here, over the body handed to `registerFlow` (the stored body, for
42+
* a flow the protocol's execution read serves) less the provenance stamps the
43+
* read adds and the write never stores ({@link SERVED_PROVENANCE_STAMPS},
44+
* #39388), so a stored version is found again by `getByHash` whether or not
45+
* the flow is bound to a package. A code-loaded body has no history row, and
46+
* gets a hash computed the same way.
1647
*
1748
* `FlowSchema.version` is not this: it is an author integer that two bodies
1849
* can share, and an unbumped edit keeps.
@@ -23,7 +54,7 @@ import { hashSpec } from '@objectstack/metadata-core';
2354
*/
2455
export function flowContentChecksum(definition: unknown): string | undefined {
2556
try {
26-
return hashSpec(definition, 'flow');
57+
return hashSpec(withoutServedStamps(definition), 'flow');
2758
} catch {
2859
return undefined;
2960
}

0 commit comments

Comments
 (0)