Skip to content

Commit 1074c04

Browse files
committed
fix(service-automation): a name two packages ship keeps defaultActive; ask the loader's default once per armed body
L2 delta on 5fe7b81 (S3, N8-N11): - S3: the registration check asks whether ANY package's loader set holds the name (`isShippedFlowName`: the one owner, else each package that may hold it, asked per package), so a co-held name's bodies register with the key on every re-sync, upgrade and third holder; dry run and the stored pass agree. The refusal stands only when no package ships the name. - N9: the package default reader is asked once per armed body (a WeakMap keyed by the body registerFlow armed), not on every isFlowEnabled. - N8: the changeset names setPackagedFlowDefaultSource and PackagedFlowDefaultSource and states the fail-open behaviour without a reader; the reader's duck-typed protocol read is pinned through the real protocol in the first-boot-pull integration harness. - N11: FlowSchema JSDoc sentence reworded. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ADHkmPTavMbXsRBw7f7fCb
1 parent 5fe7b81 commit 1074c04

5 files changed

Lines changed: 142 additions & 18 deletions

File tree

‎.changeset/34655-flow-default-active.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,8 @@ Only a flow a package ships has the packaged-flow switch, so:
2121
- `POST /api/v1/automation/:name/clone` drops `defaultActive` from the copy, which is written switched off by its own `status` as before;
2222
- an unmanaged install copies `defaultActive: false` as `status: 'obsolete'` (unless the status already disarms the flow) and drops the key, so the copy arrives switched off.
2323

24+
A name two packages ship is a package's flow too: each holder's body registers with the key, on every re-sync and upgrade, and the refusal above is only for a name no package ships.
25+
26+
For hosts that compose the engine themselves, `AutomationEngine.setPackagedFlowDefaultSource(source)` and its `PackagedFlowDefaultSource` type are new public API. The automation plugin attaches the reader (it asks the metadata protocol for the package's own body); it is how the engine reads the package's default while a declared `.custom` override is armed in the package's place, and it is asked once per registration, not on every enablement read. An engine composed without a reader reads the default only off an armed package body, so while an override is armed a flow its package ships off runs (fail-open): such an engine cannot see the package's body, and treating an unknown default as on keeps the behaviour every packaged flow had before this release instead of switching off a flow no package was seen to declare off.
27+
2428
ADR-0126 §4 carries an amendment note: "absence of a row means the packaged default" now reads the default a packaged flow declares; the ledger's shape is unchanged.

‎packages/services/service-automation/src/engine.ts‎

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3136,6 +3136,15 @@ export class AutomationEngine implements IAutomationService {
31363136
private packagedFlowSource?: PackagedFlowSource;
31373137
/** [#34655] The reader over the loader's bodies' defaults — see {@link setPackagedFlowDefaultSource}. */
31383138
private packagedFlowDefaultSource?: PackagedFlowDefaultSource;
3139+
/**
3140+
* [#34655, L2 N9] What {@link packagedFlowDefaultSource} answered for an
3141+
* armed body, asked once per registration: keyed by the body
3142+
* {@link registerFlow} armed, so every re-registration (the
3143+
* `metadata:reloaded` re-sync after an upgrade re-registers the winner)
3144+
* asks again, and {@link isFlowEnabled} never reads the loader's set.
3145+
* Replaced whenever either reader is attached.
3146+
*/
3147+
private packagedFlowDefaults = new WeakMap<FlowParsed, { readonly value: boolean | undefined }>();
31393148
/**
31403149
* [ADR-0150 D3] The reader that answers which item a bare flow name means
31413150
* for a caller — see {@link setFlowNameResolver}. `undefined` until a host
@@ -6132,6 +6141,7 @@ export class AutomationEngine implements IAutomationService {
61326141
*/
61336142
setPackagedFlowSource(source: PackagedFlowSource | undefined): void {
61346143
this.packagedFlowSource = source;
6144+
this.packagedFlowDefaults = new WeakMap();
61356145
}
61366146

61376147
/**
@@ -6145,6 +6155,7 @@ export class AutomationEngine implements IAutomationService {
61456155
*/
61466156
setPackagedFlowDefaultSource(source: PackagedFlowDefaultSource | undefined): void {
61476157
this.packagedFlowDefaultSource = source;
6158+
this.packagedFlowDefaults = new WeakMap();
61486159
}
61496160

61506161
/**
@@ -6288,9 +6299,9 @@ export class AutomationEngine implements IAutomationService {
62886299
* has no such switch: its switch is its own `status`, so the key could
62896300
* only be a declaration the engine does not honour.
62906301
*
6291-
* A flow is packaged when the loader's set holds its name
6292-
* ({@link packagedFlowOwner}, the question the toggle door asks); every
6293-
* other flow is the environment's. Judged by NAME, never by the arm a
6302+
* A flow is packaged when any package's loader set holds its name
6303+
* ({@link isShippedFlowName}: the loader's own answer, a name two
6304+
* packages hold included); every other flow is the environment's. Judged by NAME, never by the arm a
62946305
* registration names, because it is one of the {@link registrationChecks}
62956306
* (#23317): {@link registerFlow} throws it, {@link dryRun} refuses a draft
62966307
* for it, and the stored pass ({@link canonicalizeStoredFlow}) lists a
@@ -6306,7 +6317,7 @@ export class AutomationEngine implements IAutomationService {
63066317
* to arm it, and the stored pass names it.
63076318
*/
63086319
private refuseUnpackagedDefaultActive(flowName: string, flow: FlowParsed): RegistrationCheckRefusal | undefined {
6309-
if (flow.defaultActive === undefined || this.isPackagedFlow(flowName)) return undefined;
6320+
if (flow.defaultActive === undefined || this.isShippedFlowName(flowName, flow)) return undefined;
63106321
const why =
63116322
`'${flowName}' declares defaultActive, which is the default of the switch an administrator turns a ` +
63126323
`PACKAGED flow on and off with, and '${flowName}' was authored in this deployment, not shipped by a ` +
@@ -6318,6 +6329,27 @@ export class AutomationEngine implements IAutomationService {
63186329
};
63196330
}
63206331

6332+
/**
6333+
* [#34655, L2 S3] Does ANY package's loader set hold a flow `name`? The
6334+
* question {@link refuseUnpackagedDefaultActive} asks — not "is there ONE
6335+
* owner": {@link packagedFlowOwner} answers none for a bare name two
6336+
* packages hold (ADR-0150 D4), and a package's body re-registered under
6337+
* such a name (a re-sync, a hot upgrade, a third holder arriving) is
6338+
* still a package's. Every answer is the loader's own, asked per package
6339+
* ({@link packagedFlowSlotOwner}) of each package that may hold it: the
6340+
* packages whose slots hold the name now, and the package the body names
6341+
* itself as (`_packageId`). The stamp is only which package to ASK; a
6342+
* stamp naming a package that ships no such flow answers no.
6343+
*/
6344+
private isShippedFlowName(name: string, flow: FlowParsed): boolean {
6345+
if (this.isPackagedFlow(name)) return true;
6346+
const bare = this.flowSlots.slot(name)?.name ?? name;
6347+
const stamped = (flow as { _packageId?: unknown })._packageId;
6348+
const candidates = new Set<string>(typeof stamped === 'string' && stamped !== '' ? [stamped] : []);
6349+
for (const slot of this.flowSlots.slotsOf(bare)) if (slot.packageId !== null) candidates.add(slot.packageId);
6350+
return [...candidates].some((packageId) => this.packagedFlowSlotOwner(bare, packageId) !== undefined);
6351+
}
6352+
63216353
/**
63226354
* [#34655, ADR-0126 §4, seat ruling on S2] The `defaultActive` the
63236355
* PACKAGE declares for the flow held under `key`, or `undefined` for none
@@ -6330,14 +6362,22 @@ export class AutomationEngine implements IAutomationService {
63306362
* writes `false` does not switch off a flow its package ships on. The
63316363
* administrator's switch (the activation ledger) decides either way.
63326364
* With no reader attached, only an armed loader's body answers.
6365+
*
6366+
* [L2 N9] The reader's answer is asked once per armed body
6367+
* ({@link packagedFlowDefaults}), not on every {@link isFlowEnabled}.
63336368
*/
63346369
private packagedFlowDefault(key: string): boolean | undefined {
63356370
const armed = this.flows.get(key);
63366371
if (!armed) return undefined;
63376372
if (this.flowArms.get(armed)?.source === 'package') return armed.defaultActive;
6373+
const source = this.packagedFlowDefaultSource;
6374+
if (source === undefined) return undefined;
6375+
const asked = this.packagedFlowDefaults.get(armed);
6376+
if (asked !== undefined) return asked.value;
63386377
const owner = this.packagedFlowOwner(key);
6339-
if (owner === undefined) return undefined;
6340-
return this.packagedFlowDefaultSource?.(this.flowSlots.slot(key)?.name ?? key, owner);
6378+
const value = owner === undefined ? undefined : source(this.flowSlots.slot(key)?.name ?? key, owner);
6379+
this.packagedFlowDefaults.set(armed, { value });
6380+
return value;
63416381
}
63426382

63436383
/**

‎packages/services/service-automation/src/flow-declared-override-first-boot-pull.integration.test.ts‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import { SqlDriver } from '@objectstack/driver-sql';
4646
import { SysMetadataActivation } from '@objectstack/platform-objects';
4747
import { defineStack } from '@objectstack/spec';
4848
import type { AutomationContext } from '@objectstack/spec/contracts';
49-
import { AutomationServicePlugin } from './plugin.js';
49+
import { AutomationServicePlugin, packagedFlowDefaultReader } from './plugin.js';
5050
import type { AutomationEngine, FlowTrigger, FlowTriggerBinding } from './engine.js';
5151
import { installDefaultOrganization } from './default-organization.testkit.js';
5252

@@ -83,13 +83,13 @@ const pluginManifest = (id: string) => ({
8383
name: 'crm',
8484
});
8585

86-
/** The shipping package: one object and the base flow over it. */
87-
const shippingStack = () =>
86+
/** The shipping package: one object and the base flow over it (`base`: more keys on that flow). */
87+
const shippingStack = (base: Record<string, unknown> = {}) =>
8888
defineStack(
8989
{
9090
manifest: pluginManifest(BASE),
9191
objects: [{ name: TICKET, label: 'Ticket', fields: { title: { name: 'title', label: 'Title', type: 'text' } } }],
92-
flows: [ticketFlow('BASE')],
92+
flows: [ticketFlow('BASE', base)],
9393
} as never,
9494
{ strict: false },
9595
) as Record<string, unknown>;
@@ -183,6 +183,7 @@ async function boot(
183183
start: (ql: ObjectQL, automation: AutomationEngine) => Promise<void>,
184184
second: Second = 'none',
185185
ledger = false,
186+
base: Record<string, unknown> = {},
186187
) {
187188
const kernel = new ObjectKernel({ logger: { level: 'fatal' }, gracefulShutdown: false } as never);
188189
kernels.push(kernel);
@@ -210,7 +211,7 @@ async function boot(
210211
const manifests = ctx.getService<{ register(m: unknown): Promise<void> }>('manifest');
211212
const registerStack = (stack: Record<string, unknown>) => manifests.register({ ...(stack.manifest as object), ...stack });
212213
if (second === 'before') await registerStack(otherStack());
213-
if (!second.startsWith('installed-both')) await registerStack(shippingStack());
214+
if (!second.startsWith('installed-both')) await registerStack(shippingStack(base));
214215
if (second === 'after') await registerStack(otherStack());
215216
if (second.startsWith('installed-')) {
216217
ctx.hook('kernel:ready', async () => {
@@ -238,17 +239,18 @@ async function measuredBoot(
238239
rows: readonly Row[],
239240
start: (ql: ObjectQL, automation: AutomationEngine) => Promise<void>,
240241
second: Second = 'none',
242+
base: Record<string, unknown> = {},
241243
) {
242244
const dir = mkdtempSync(join(tmpdir(), 'qa-28717-'));
243245
dirs.push(dir);
244246
const file = join(dir, 'store.db');
245247
const first = await boot(file, async (ql) => {
246248
for (const row of rows) await ql.insert('sys_metadata', storedRow(row), { context: SYS } as never);
247-
});
249+
}, 'none', false, base);
248250
await first.kernel.shutdown();
249251
kernels.splice(kernels.indexOf(first.kernel), 1);
250252
const warn = vi.spyOn(ObjectLogger.prototype, 'warn');
251-
const measured = await boot(file, start, second);
253+
const measured = await boot(file, start, second, false, base);
252254
const collisionCalls = warn.mock.calls
253255
.filter(([message]) => String(message).includes('Flow name collision') && String(message).includes(`'${FLOW}'`));
254256
const collisions = collisionCalls.map(([message]) => String(message));
@@ -312,6 +314,22 @@ describe('[#28717] a declared .custom flow override is armed from the first boot
312314
expect(((await automation.getFlow(FLOW)) as { label?: string } | null)?.label).toBe('BASE');
313315
});
314316

317+
it('[#34655, L2 N8] the base ships `defaultActive: false`: the armed override, which omits the key, stays off — read through the real protocol', async () => {
318+
let armedAtPull: string | undefined;
319+
const { fired, automation, kernel } = await measuredBoot(['override'], async (ql, engine) => {
320+
armedAtPull = ((await engine.getFlow(FLOW)) as { label?: string } | null)?.label;
321+
await insertTicket(ql, 'shipped off');
322+
}, 'none', { defaultActive: false });
323+
expect(armedAtPull).toBe('OVERRIDE');
324+
// The package's own body, as the protocol's every-shipper read serves it (no mock: the duck-typed
325+
// `shippedArtifactsOf` that `packagedFlowDefaultReader` asks).
326+
const read = packagedFlowDefaultReader({ getService: (name: string) => kernel.getService(name) } as never);
327+
expect(read(FLOW, BASE)).toBe(false);
328+
expect(read(FLOW, PAIR), 'control: the pair ships no body of its own').toBeUndefined();
329+
expect(automation.getFlowRuntimeStates().find((s) => s.name === FLOW)).toMatchObject({ enabled: false });
330+
expect(fired).toEqual([]);
331+
});
332+
315333
it('control: with only the override, it is armed from the boot pull with no receipt and no warning (#28412)', async () => {
316334
let armedAtPull: string | undefined;
317335
const { fired, automation, collisions } = await measuredBoot(['override'], async (ql, engine) => {

‎packages/services/service-automation/src/flow-default-active-34655.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,50 @@ describe('#34655 — `defaultActive` is refused on a flow authored in the enviro
343343
});
344344
});
345345

346+
describe('#34655 (L2 S3) — a name two packages hold keeps the key: the check asks whether ANY package holds it', () => {
347+
/** Each name's loader sets, as the plugin's reader answers them (one owner by name; each package's own question). */
348+
function bootCoHeld(loaderSets: Record<string, readonly string[]>) {
349+
const booted = boot();
350+
booted.engine.setPackagedFlowSource((name, packageId) => {
351+
const holders = loaderSets[name] ?? [];
352+
if (packageId !== undefined) return holders.includes(packageId) ? packageId : undefined;
353+
return holders.length === 1 ? holders[0] : undefined;
354+
});
355+
return booted;
356+
}
357+
/** Package `packageId`'s own body of `name`, armed in its own slot as precedence arms a co-held name. */
358+
const ship = (engine: AutomationEngine, packageId: string, name: string, extra: Record<string, unknown> = {}) =>
359+
engine.registerFlow(name, packagedFlow(name, { _packageId: packageId, ...extra }), { source: 'package', packageId, holder: packageId });
360+
361+
it('both holders, a re-sync and a third holder register with the key, true and false', () => {
362+
const { engine } = bootCoHeld({ co_held: ['crm', 'erp', 'hr'] });
363+
expect(engine.packagedFlowOwner('co_held'), 'control: the bare name has no ONE owner').toBeUndefined();
364+
expect(() => ship(engine, 'crm', 'co_held', { defaultActive: false })).not.toThrow();
365+
expect(() => ship(engine, 'erp', 'co_held', { defaultActive: true })).not.toThrow();
366+
// The `metadata:reloaded` re-sync / a hot upgrade re-registers a holder's body.
367+
expect(() => ship(engine, 'crm', 'co_held', { defaultActive: false, version: 2 })).not.toThrow();
368+
expect(() => ship(engine, 'hr', 'co_held', { defaultActive: false })).not.toThrow();
369+
expect(engine.getFlowRuntimeStates().filter((s) => s.name === 'co_held')).toHaveLength(3);
370+
});
371+
372+
it('a dry run and the stored pass agree: no refusal for a co-held name', async () => {
373+
const { engine } = bootCoHeld({ co_held: ['crm', 'erp'] });
374+
ship(engine, 'crm', 'co_held', { defaultActive: false });
375+
ship(engine, 'erp', 'co_held');
376+
const body = packagedFlow('co_held', { _packageId: 'erp', defaultActive: true });
377+
expect(engine.canonicalizeStoredFlow('co_held', body).todos).toEqual([]);
378+
const dry = await engine.dryRun(body, { userId: 'usr_maker' }).then(() => undefined, (e: Error) => e.message);
379+
expect(dry ?? '').not.toContain('declares defaultActive');
380+
});
381+
382+
it('CONTROL: the refusal still stands when no package holds the name, whatever package the body names itself as', () => {
383+
const { engine } = bootCoHeld({ co_held: ['crm', 'erp'] });
384+
const forged = packagedFlow('loose_flow', { _packageId: 'crm', defaultActive: false });
385+
expect(() => engine.registerFlow('loose_flow', forged)).toThrow(/^Flow 'loose_flow' declares defaultActive/);
386+
expect(engine.canonicalizeStoredFlow('loose_flow', forged).todos.map((t) => t.path)).toEqual(['flows[0].defaultActive']);
387+
});
388+
});
389+
346390
describe('#34655 (seat ruling on S2) — a declared `.custom` override does not move the package\'s default', () => {
347391
/** The pair's declared override, as the boot pull arms it in the base's place. */
348392
const OVERRIDE = { source: 'override', packageId: 'crm.custom' } as const;
@@ -382,6 +426,25 @@ describe('#34655 (seat ruling on S2) — a declared `.custom` override does not
382426
engine.registerFlow('draft_contract', packagedFlow('draft_contract', { defaultActive: false }), PULL);
383427
expect(isBound('draft_contract')).toBe(false);
384428
});
429+
430+
it('(L2 N9) the loader\'s set is asked once per armed body, not on every enablement read', async () => {
431+
const { engine } = boot();
432+
const reader = vi.fn((name: string, packageId: string) => (packageId === 'crm' && name === 'draft_contract' ? false : undefined));
433+
engine.setPackagedFlowDefaultSource(reader);
434+
engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'customized' }), OVERRIDE);
435+
const asked = reader.mock.calls.length;
436+
expect(asked).toBe(1);
437+
for (let i = 0; i < 5; i++) {
438+
expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: false });
439+
expect((await engine.execute('draft_contract')).code).toBe('FLOW_DISABLED');
440+
}
441+
expect(reader).toHaveBeenCalledTimes(asked);
442+
// A re-registration (the re-sync after an upgrade) asks again, once.
443+
reader.mockImplementation(() => undefined);
444+
engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'customized', version: 2 }), OVERRIDE);
445+
expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: true });
446+
expect(reader).toHaveBeenCalledTimes(asked + 1);
447+
});
385448
});
386449

387450
describe('#34655 — packagedFlowDefaultReader reads the package\'s own body off the loader\'s set', () => {

‎packages/spec/src/automation/flow.zod.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,11 +1197,10 @@ export const FlowSchema = lazySchema(() => strictObject(
11971197
* administrator may turn on as `status: 'active', defaultActive: false`.
11981198
*
11991199
* Only a flow a package ships has that switch. A flow authored in the
1200-
* environment is switched by its `status`, so registering one that
1201-
* declares `defaultActive` is refused (and a dry run of one, and the stored
1202-
* pass lists a stored one); a clone of a packaged flow drops
1203-
* the key, and an unmanaged install copies `defaultActive: false` as
1204-
* `status: 'obsolete'`.
1200+
* environment is switched by its `status`: registering one that declares
1201+
* `defaultActive` is refused, a dry run of one is refused, and the stored
1202+
* pass lists a stored one. A clone of a packaged flow drops the key, and an
1203+
* unmanaged install copies `defaultActive: false` as `status: 'obsolete'`.
12051204
*/
12061205
defaultActive: z.boolean().optional().describe('Packaged flows only: `false` ships the flow switched off, so it is not armed on an installation until an administrator turns it on with the packaged-flow switch (the activation ledger); the administrator\'s choice, once made, wins over this default across restarts and upgrades. Absent or `true`: switched on. `status` stays the author\'s switch: `obsolete`/`invalid` disarm the flow everywhere. A flow authored in the environment is switched by `status` and may not declare this key.'),
12071206

0 commit comments

Comments
 (0)