Skip to content

Commit 1324973

Browse files
fix(service-automation): a package-bound flow's run records the checksum its history row is keyed by (#39431)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DMmPgXVVfb8MdCS5amdMX6N)_ Fixes #39388 repo:objectstack@os-elon-musk · os-elon-musk · session_016WV4czHUJLmdQAqm4fdDs9 Clause-②: no Metadata-protocol: none ## 维护者速读 - 运行打进软件包的流程时,挂起的运行现在记下的版本校验和与该流程版本历史里的那一行一致;改动前它多算了服务端读取时加上的包标记,永远对不上;未打包的流程不变。 - 属于流程运行版本固定(重启或改版后,挂起的运行仍按它开始时的版本跑完),替所有用软件包承载流程的作者解决;另一个正在进行的改动会让每个新流程都绑定到软件包。 - 碰到的是有挂起运行、且流程绑在软件包上的用户:修复前这类运行在重启或再次保存后找不回原版本;此改动只改一个计算,可直接撤回。已按旧值记录的运行不迁移(尚无生产客户)。 - 无 ## What changes `flowContentChecksum` (service-automation `flow-identity.ts`) is the identity a run records (`flow_checksum`) and a resume looks its body up by in `sys_metadata_history` (`getByHash`). It hashed the body handed to `registerFlow`. For a flow bound to a package, that body is a served body: the read stamps `_packageId` on it. The metadata write door strips `_packageId`, `_packageVersion` and `_provenance` (`DERIVED_PROVENANCE_KEYS` / `stripDerivedProvenance`, `metadata-protocol` `protocol-package-bindings.ts`) before it stores the body and hashes it into `sys_metadata.checksum` and the history row. So the run's checksum named no history row. The checksum now drops exactly those three derived provenance stamps before `hashSpec(body, 'flow')`: - **Measured**, not assumed: on the publish path the body `registerFlow` receives carries `_packageId` and nothing else beyond the stored history body (a one-off spy on `registerFlow` in this suite's package-bound case; diagnostic removed). - **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. Dropping it would break the match in the other direction. - **Not `METADATA_READ_DECORATIONS`.** The flow schema is closed, so a body carrying `_diagnostics` and the rest is refused by `registerFlow` before any checksum is taken. - **One list, not reused.** The write door's list is module-private in `@objectstack/metadata-protocol` and the claim's file surface is `flow-identity.ts`. The three keys are spelled once more there, and the docblock names the write door's list as the authority (see Acceptance notes). Every reader of the identity goes through this one function (`registerFlow` → `flowChecksums`), or stores the history checksum as given (`recoverStoredFlow`). The approvals run-body witness compares the engine against itself. A loose (package-less) flow carries no stamp, so its checksum is unchanged. Per the maintainer rule, runs recorded with the old checksum are not migrated. ## Read first 1. `packages/services/service-automation/src/flow-identity.ts`: the whole change. The risk is the key set. Compare it with `DERIVED_PROVENANCE_KEYS` in `packages/metadata-protocol/src/protocol-package-bindings.ts` and the strip at `protocol-save.ts` (`request.item = stripDerivedProvenance(request.item)`). 2. `packages/services/service-automation/src/flow-checksum-served-stamps-39388.integration.test.ts`: the pin. It compares the run row's `flow_checksum` with the history row the real save wrote, never with a hash the test computes. ## Two-minute verification `pnpm --filter @objectstack/service-automation exec vitest run --maxWorkers=2 src/flow-checksum-served-stamps-39388.integration.test.ts` should show 2 passed. Change `hashSpec(withoutServedStamps(definition), 'flow')` back to `hashSpec(definition, 'flow')` and the package-bound case goes red, with two different `sha256:` values. ## Tests - New pin, its own file (the shared harness `flow-version-pinning.integration.test.ts` is held by open PR 39386, so the claim excludes it): one kernel over sqlite, the real metadata protocol save, the real engine. - A flow saved into an authored package parks a run, and the run's `flow_checksum` equals its v1 history row's checksum. - A loose flow is pinned beside it, unchanged. Its row is laid in the store first and the save runs in place, so the pin holds whether or not a package-less create is refused. - Red first, on `f32b7d6d` (before the fix): package-bound case failed, `expected 'sha256:19e1044b…' to be 'sha256:061e7f8c…'`; loose case passed. - Ablation at `1cf80b34` (`scripts/ablation-replace.mjs`, anchor hit 1 → 0, blob `8d9cc8da` → `d54ffdf1`): package-bound red with the same two hashes, loose green; restored blob == HEAD, `git diff HEAD` empty. - `pnpm --filter @objectstack/service-automation exec vitest run --maxWorkers=2` at `1cf80b34`: 307 files, 4560 tests passed. - `pnpm --filter @objectstack/service-automation typecheck` at `1cf80b34`: exit 0 (tsc and `check:test-typecheck` OK). - Consumer spot check: `pnpm --filter @objectstack/plugin-approvals exec vitest run --maxWorkers=2 src/flow-route.integration.test.ts` against a rebuilt service-automation `dist`: 58 passed. ## Acceptance notes - **Drift risk, noted and not filed.** The three keys are spelled in `flow-identity.ts` and in metadata-protocol's module-private `DERIVED_PROVENANCE_KEYS`. If the write door ever strips a fourth served key, this list must follow it. Exporting the write door's list from `@objectstack/metadata-protocol` and importing it here would remove the second spelling. That change is outside this claim's file surface. - **Prose that now reads one step short:** comments still describe the identity as "`hashSpec(body, 'flow')`": `run-body-witness.ts` (plugin-approvals), `run-flow-checksum.ts`, `engine-resume.ts`, `sys-automation-run.object.ts`. They are still true of the stored body and out of surface, so they are not edited here. - The card's other half (the version-pinning suite's resume-after-restart with a package installed before boot) belongs to open PR 39386's suite and is not in this PR. ## Verification Local gates: the families `node scripts/pm/dispatch-gates.mjs --commands` derived for this diff at `1cf80b34`. Readings are in the report comment on the card. CI runs every family on the PR. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4czHUJLmdQAqm4fdDs9)_ <!-- signed: repo:objectstack@os-elon-musk · os-elon-musk · session_016WV4czHUJLmdQAqm4fdDs9 --> Co-authored-by: Claude <noreply@anthropic.com>
1 parent c9ea363 commit 1324973

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)