Skip to content

Commit 05656d7

Browse files
committed
fix(service-automation): re-read a held override's package default at every re-sync
L2 S4 on #34793: the package default cached per armed body outlived a change to the loader's set. The metadata:reloaded re-sync keeps a body the metadata-mutation sync armed from the same stored row (and one whose re-registration threw), and a declared override's stored body does not change with its base, so a hot upgrade that flipped the base's defaultActive left the previous version's default in force with no ledger row: on to off kept running, off to on stayed off. AutomationEngine.refreshPackagedFlowDefaults() replaces the cache and sends each held flow whose armed body is not the loader's own back through the arming gate when its enablement moved; the plugin calls it at every re-sync. The cache docblock says when the default is re-read. The same drop covers a body rollbackFlow puts back (L2 N13). Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX
1 parent 96a99d0 commit 05656d7

3 files changed

Lines changed: 239 additions & 7 deletions

File tree

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

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3143,11 +3143,16 @@ export class AutomationEngine implements IAutomationService {
31433143
private packagedFlowDefaultSource?: PackagedFlowDefaultSource;
31443144
/**
31453145
* [#34655, L2 N9] What {@link packagedFlowDefaultSource} answered for an
3146-
* armed body, asked once per registration: keyed by the body
3147-
* {@link registerFlow} armed, so every re-registration (the
3148-
* `metadata:reloaded` re-sync after an upgrade re-registers the winner)
3149-
* asks again, and {@link isFlowEnabled} never reads the loader's set.
3150-
* Replaced whenever either reader is attached.
3146+
* armed body, so {@link isFlowEnabled} never reads the loader's set:
3147+
* keyed by the body {@link registerFlow} armed, which is a new object on
3148+
* every registration, so a registration asks again. A re-sync does not
3149+
* always re-register (L2 S4: the `metadata:reloaded` re-sync keeps a body
3150+
* the metadata-mutation sync armed from the same stored row, and keeps
3151+
* the body it had when a re-registration throws), and the answer depends
3152+
* on the loader's set, not on the body. So the map is replaced whenever
3153+
* either reader is attached and at every re-sync
3154+
* ({@link refreshPackagedFlowDefaults}), which also re-judges the flows
3155+
* whose answer moved.
31513156
*/
31523157
private packagedFlowDefaults = new WeakMap<FlowParsed, { readonly value: boolean | undefined }>();
31533158
/**
@@ -6373,7 +6378,9 @@ export class AutomationEngine implements IAutomationService {
63736378
* With no reader attached, only an armed loader's body answers.
63746379
*
63756380
* [L2 N9] The reader's answer is asked once per armed body
6376-
* ({@link packagedFlowDefaults}), not on every {@link isFlowEnabled}.
6381+
* ({@link packagedFlowDefaults}), not on every {@link isFlowEnabled},
6382+
* and asked again after each change to the loader's set
6383+
* ({@link refreshPackagedFlowDefaults}).
63776384
*/
63786385
private packagedFlowDefault(key: string): boolean | undefined {
63796386
const armed = this.flows.get(key);
@@ -6389,6 +6396,48 @@ export class AutomationEngine implements IAutomationService {
63896396
return value;
63906397
}
63916398

6399+
/**
6400+
* [#34655, L2 S4] The loader's set may have changed (a package installed,
6401+
* upgraded or removed): forget every default {@link packagedFlowDefault}
6402+
* cached, and send each held flow whose armed body is NOT the loader's
6403+
* own (a declared `.custom` override, a `runtime` body under a held name)
6404+
* back through the arming gate when its enablement moved. Returns the
6405+
* keys it moved.
6406+
*
6407+
* The cache is keyed by the armed body, and a re-sync does not always
6408+
* re-register: the automation plugin's `metadata:reloaded` re-sync keeps
6409+
* the body the metadata-mutation sync armed from the same stored row, and
6410+
* keeps the body it had when a re-registration throws. An override's
6411+
* stored body does not change when its base is upgraded, so without this
6412+
* the default read from the previous version's body would stay until the
6413+
* next registration of that flow or a restart: a flow the new version
6414+
* ships off would keep running, and one it ships on would stay off. The
6415+
* plugin calls this at every re-sync; a body {@link rollbackFlow} puts
6416+
* back is asked again too, since the map it was cached in is gone.
6417+
*
6418+
* A loader-armed flow reads its own body's declaration and is never
6419+
* cached, so it is not re-judged here: its re-registration is what moves
6420+
* it. An activation ledger row decides before any default is read, so a
6421+
* flow an administrator switched does not move.
6422+
*/
6423+
refreshPackagedFlowDefaults(): string[] {
6424+
const before = new Map<string, boolean>();
6425+
for (const [key, armed] of this.flows) {
6426+
if (this.flowArms.get(armed)?.source !== 'package') before.set(key, this.isFlowEnabled(key));
6427+
}
6428+
this.packagedFlowDefaults = new WeakMap();
6429+
const moved: string[] = [];
6430+
for (const [key, wasEnabled] of before) {
6431+
if (this.isFlowEnabled(key) === wasEnabled) continue;
6432+
if (wasEnabled) this.deactivateFlowTrigger(key);
6433+
else this.activateFlowTrigger(key);
6434+
moved.push(key);
6435+
}
6436+
// [#20725, ADR-0126 §7.3] The callers of a subflow that moved, through the same gate.
6437+
for (const key of moved) this.rejudgeSubflowCallers(key);
6438+
return moved;
6439+
}
6440+
63926441
/**
63936442
* [ADR-0150 D3] Attach the reader over the one package-scoped resolver
63946443
* ({@link FlowNameResolver}). The automation plugin calls this at `init()`

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

Lines changed: 176 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88
// environment.
99

1010
import { describe, it, expect, vi } from 'vitest';
11+
import { LiteKernel } from '@objectstack/core';
12+
import type { Plugin, PluginContext } from '@objectstack/core';
1113
import { AutomationEngine } from './engine.js';
1214
import type { FlowTrigger, FlowTriggerBinding } from './engine.js';
1315
import { InMemoryFlowActivationStore } from './flow-activation-store.js';
1416
import { registerSubflowNode } from './builtin/subflow-node.js';
15-
import { packagedFlowDefaultReader } from './plugin.js';
17+
import { AutomationServicePlugin, packagedFlowDefaultReader } from './plugin.js';
1618
import type { AutomationContext } from '@objectstack/spec/contracts';
1719

1820
function createTestLogger(): any {
@@ -445,6 +447,179 @@ describe('#34655 (seat ruling on S2) — a declared `.custom` override does not
445447
expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: true });
446448
expect(reader).toHaveBeenCalledTimes(asked + 1);
447449
});
450+
451+
it('(L2 S4) a change to the loader\'s set reaches a held override with no ledger row, both ways', async () => {
452+
const defaults: Record<string, boolean | undefined> = { draft_contract: false };
453+
const { engine, isBound } = bootWithLoaderDefaults(defaults);
454+
engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'customized' }), OVERRIDE);
455+
expect(isBound('draft_contract')).toBe(false);
456+
457+
// The base is upgraded to ship it on; the held override body is not re-registered.
458+
defaults.draft_contract = undefined;
459+
expect(engine.refreshPackagedFlowDefaults()).toEqual(['draft_contract']);
460+
expect(isBound('draft_contract')).toBe(true);
461+
expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: true, bound: true });
462+
expect((await engine.execute('draft_contract')).success).toBe(true);
463+
464+
// And back to off.
465+
defaults.draft_contract = false;
466+
expect(engine.refreshPackagedFlowDefaults()).toEqual(['draft_contract']);
467+
expect(isBound('draft_contract')).toBe(false);
468+
expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: false });
469+
expect((await engine.execute('draft_contract')).code).toBe('FLOW_DISABLED');
470+
});
471+
472+
it('(L2 S4) CONTROL: the refresh moves nothing a ledger row or the loader\'s own body decides', async () => {
473+
const defaults: Record<string, boolean | undefined> = { draft_contract: undefined, on_absent: undefined };
474+
const { engine, isBound } = bootWithLoaderDefaults(defaults);
475+
engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'customized' }), OVERRIDE);
476+
await engine.toggleFlow('draft_contract', false);
477+
engine.registerFlow('on_absent', packagedFlow('on_absent', { defaultActive: false }), PULL);
478+
expect(isBound('draft_contract')).toBe(false);
479+
expect(isBound('on_absent')).toBe(false);
480+
481+
// The reader flips both; the row decides the override, the loader's body decides its own flow.
482+
defaults.draft_contract = true;
483+
defaults.on_absent = true;
484+
expect(engine.refreshPackagedFlowDefaults()).toEqual([]);
485+
expect(isBound('draft_contract')).toBe(false);
486+
expect(isBound('on_absent')).toBe(false);
487+
});
488+
489+
it('(L2 N13) a body rolled back from the history reads the default of the set installed now', async () => {
490+
const defaults: Record<string, boolean | undefined> = { draft_contract: false };
491+
const { engine } = bootWithLoaderDefaults(defaults);
492+
engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'v1' }), OVERRIDE);
493+
engine.registerFlow('draft_contract', packagedFlow('draft_contract', { description: 'v2', version: 2 }), OVERRIDE);
494+
const [first] = engine.getFlowVersionHistory('draft_contract').map((h) => h.version);
495+
expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: false });
496+
497+
defaults.draft_contract = undefined;
498+
engine.refreshPackagedFlowDefaults();
499+
engine.rollbackFlow('draft_contract', first);
500+
expect(((await engine.getFlow('draft_contract')) as { description?: string } | null)?.description).toBe('v1');
501+
expect(stateOf(engine, 'draft_contract')).toMatchObject({ enabled: true });
502+
});
503+
});
504+
505+
describe('#34655 (L2 S4) — a hot upgrade that flips the base\'s default reaches an override the mutation sync armed', () => {
506+
const BASE = 'com.acme.crm';
507+
const FLOW = 'draft_contract';
508+
/** The pair's declared override, as the protocol's view serves it in the base's slot. */
509+
const served = (label: string) =>
510+
packagedFlow(FLOW, { label, _packageId: BASE, overrides: { package: BASE, basedOn: '1.0.0' } });
511+
512+
/**
513+
* The automation plugin over a protocol stand-in: the view serves the
514+
* override, the loader's set holds the base's own body with `baseDefault`,
515+
* and the test raises the mutation signal and `metadata:reloaded`. No
516+
* activation ledger: no row decides.
517+
*/
518+
async function bootComposition(baseDefault: boolean | undefined) {
519+
const state = { view: [served('OVERRIDE')], baseDefault };
520+
const listeners: Array<(evt: { type: string; name: string; state: string; organizationId?: string | null }) => void> = [];
521+
const captured: { ctx?: PluginContext } = {};
522+
const kernel = new LiteKernel({ logger: { level: 'silent' } } as never);
523+
kernel.use({
524+
name: 'fake-composition',
525+
version: '1.0.0',
526+
async init(ctx: PluginContext) {
527+
captured.ctx = ctx;
528+
const register = (ctx as unknown as { registerService(n: string, s: unknown): void }).registerService;
529+
register('objectql', { registry: { listItems: () => [], getObject: () => undefined } });
530+
register('protocol', {
531+
packagedArtifactOwner: (r: { type: string; name: string }) => (r.type === 'flow' && r.name === FLOW ? BASE : undefined),
532+
shippedArtifactsOf: (type: string, name: string) =>
533+
type === 'flow' && name === FLOW
534+
? [packagedFlow(FLOW, {
535+
label: 'BASE',
536+
_packageId: BASE,
537+
...(state.baseDefault === undefined ? {} : { defaultActive: state.baseDefault }),
538+
})]
539+
: [],
540+
async getMetaItemsForExecution(q: { type: string }) {
541+
return { items: q.type === 'flow' ? state.view : [] };
542+
},
543+
onMetadataMutation(listener: (typeof listeners)[number]) {
544+
listeners.push(listener);
545+
return () => listeners.splice(listeners.indexOf(listener), 1);
546+
},
547+
});
548+
},
549+
} as Plugin);
550+
kernel.use(new AutomationServicePlugin({ suspendedRunStore: 'memory' }));
551+
await kernel.bootstrap();
552+
const engine = kernel.getService<AutomationEngine>('automation');
553+
const recordChange = recordingTrigger('record_change');
554+
engine.registerTrigger(recordChange.trigger);
555+
const armedLabel = async () => ((await engine.getFlow(FLOW)) as { label?: string } | null)?.label;
556+
return {
557+
kernel,
558+
engine,
559+
isBound: recordChange.isBound,
560+
registrations: () => engine.getFlowVersionHistory(FLOW).length,
561+
/** A direct active save of the override (no reload): the mutation sync arms it and marks its slot. */
562+
async saveOverride(label: string) {
563+
state.view = [served(label)];
564+
listeners.forEach((l) => l({ type: 'flow', name: FLOW, state: 'active', organizationId: null }));
565+
await vi.waitFor(async () => expect(await armedLabel()).toBe(label));
566+
},
567+
/** A hot upgrade of the base package: its own body's declaration moves, then the reload. */
568+
async upgradeBase(next: boolean | undefined) {
569+
state.baseDefault = next;
570+
await captured.ctx!.trigger('metadata:reloaded', { changed: [`app/${BASE}`] });
571+
},
572+
};
573+
}
574+
575+
it('the base moves from on to off: the override stops', async () => {
576+
const c = await bootComposition(undefined);
577+
try {
578+
await c.saveOverride('OVERRIDE-2');
579+
expect(c.isBound(FLOW)).toBe(true);
580+
const registrations = c.registrations();
581+
582+
await c.upgradeBase(false);
583+
expect(c.registrations(), 'the re-sync kept the body the mutation sync armed').toBe(registrations);
584+
expect(c.isBound(FLOW)).toBe(false);
585+
expect(stateOf(c.engine, FLOW)).toMatchObject({ enabled: false });
586+
expect((await c.engine.execute(FLOW)).code).toBe('FLOW_DISABLED');
587+
} finally {
588+
await c.kernel.shutdown();
589+
}
590+
});
591+
592+
it('the base moves from off to on: the override starts', async () => {
593+
const c = await bootComposition(false);
594+
try {
595+
await c.saveOverride('OVERRIDE-2');
596+
expect(c.isBound(FLOW)).toBe(false);
597+
const registrations = c.registrations();
598+
599+
await c.upgradeBase(true);
600+
expect(c.registrations(), 'the re-sync kept the body the mutation sync armed').toBe(registrations);
601+
expect(c.isBound(FLOW)).toBe(true);
602+
expect(stateOf(c.engine, FLOW)).toMatchObject({ enabled: true, bound: true });
603+
expect((await c.engine.execute(FLOW)).success).toBe(true);
604+
} finally {
605+
await c.kernel.shutdown();
606+
}
607+
});
608+
609+
it('CONTROL: a reload that leaves the base\'s declaration as it was moves nothing', async () => {
610+
const c = await bootComposition(false);
611+
try {
612+
await c.saveOverride('OVERRIDE-2');
613+
const registrations = c.registrations();
614+
615+
await c.upgradeBase(false);
616+
expect(c.registrations()).toBe(registrations);
617+
expect(c.isBound(FLOW)).toBe(false);
618+
expect((await c.engine.execute(FLOW)).code).toBe('FLOW_DISABLED');
619+
} finally {
620+
await c.kernel.shutdown();
621+
}
622+
});
448623
});
449624

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

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6216,6 +6216,14 @@ export class AutomationServicePlugin implements Plugin {
62166216
}
62176217
}
62186218
this.syncedFlowNames = freshNames;
6219+
// [#34655, L2 S4] A reload may have changed the loader's set (a hot
6220+
// upgrade of a base package), and the loop above keeps some bodies it
6221+
// did not re-register: a winner the mutation sync armed from this same
6222+
// stored row, and one whose re-registration threw. A declared
6223+
// override's stored body does not change with its base, so the
6224+
// package default the engine read for it must be read again here, not
6225+
// only when a body is registered.
6226+
this.engine.refreshPackagedFlowDefaults();
62196227
// [#21725] Every mark is spent: from here on this re-sync's
62206228
// registrations are the ones the engine holds.
62216229
this.mutationArmedFlows.clear();

0 commit comments

Comments
 (0)