diff --git a/.changeset/33893-served-holder-keeps-slot-key.md b/.changeset/33893-served-holder-keeps-slot-key.md new file mode 100644 index 00000000000..9f0ee5aa668 --- /dev/null +++ b/.changeset/33893-served-holder-keeps-slot-key.md @@ -0,0 +1,15 @@ +--- +'@objectstack/service-automation': patch +--- + +fix(service-automation): the served holder of a flow name a disabled package also ships keeps its slot key and its trigger + +Clause-②: no +Metadata-protocol: none + +When two packages ship a flow of the same name and one of them is disabled, the engine holds the served package's flow in its own slot, filed under `PACKAGE/NAME`. Two paths lost that slot's trigger: + +- At boot, with one holder disabled, only the served holder's flow is pulled. Its slot was filed under the bare name and declined as if the other package's body had been refused, so its trigger never ran, behind a warning that named a refused body. +- At runtime, the re-sync that follows a disable withdraws the disabled holder's slot. The served slot was moved to the bare name and its trigger binding was stopped, and not armed again. + +Now a disable moves no key: in both cases the served holder's slot stays under `PACKAGE/NAME`, armed, and runs on its trigger; the bare name reaches it as the name's one served holder. When the other package is enabled again, its re-sync registers both packages' flows, in either order, and both slots end armed on their triggers. The warning about a refused body is said only once another package's body of the name is recorded as refused. When the other package is uninstalled, the name goes back to its bare key, as before. Before its slot is withdrawn, that happens at the withdrawal. After the withdrawal, it happens the first time the engine registers the served holder's flow again, fires its trigger or is asked for the name. Every bare entry (`execute`, `getFlow`, removal, version history, rollback, the bare inbound hook, credentials) then serves the name as one package's, and a re-sync that fails leaves no flow unreachable. diff --git a/.changeset/33905-disabled-sole-holder-flow.md b/.changeset/33905-disabled-sole-holder-flow.md new file mode 100644 index 00000000000..6c1f5dde3ef --- /dev/null +++ b/.changeset/33905-disabled-sole-holder-flow.md @@ -0,0 +1,31 @@ +--- +'@objectstack/service-automation': patch +--- + +fix(service-automation)!: a flow whose only holder's package is disabled is not run by its trigger, and the engine's bare entries answer as for no flow (ADR-0150 D3) + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a deployment where a package that alone ships a flow name is disabled while the automation engine still holds that flow (the re-sync that follows a disable failed or did not run): the flow no longer runs, and the bare entries no longer serve it. Before this release it kept running and was served. + +What moves, for such a flow, while its package is disabled: + +- Its trigger binding (record-change, schedule, time-relative, or an api inbound hook's queued post) ran the flow. Now nothing runs and no run-history row is written; the skip is logged once at `info` per slot. +- `execute(name, …)`, by any caller, a `subflow` or `map` node's call included, ran the flow. It now answers `{ success: false, error: "Flow 'NAME' not found" }`, the answer for a flow the engine does not hold. +- `getFlow(name)` answered the flow. It now answers `null`, so the bare HTTP doors that ask it first (`GET /automation/NAME`, `POST /automation/NAME/trigger`, `POST /automation/trigger/NAME`, `POST /automation/NAME/toggle`, `POST /automation/NAME/clone`, `GET /automation/NAME/runs`) answer `404`, which is what the namespaced address `/automation/NAMESPACE/NAME…` already answered. +- `toggleFlow(name, …)` switched the flow. It now rejects with `Flow 'NAME' not found`. + +Three HTTP write doors ask `getFlow` whether the name is held, and move with it for such a flow. These answers were read from the runtime source; the engine's half of the clone answer was measured. Each holds only where the door's earlier checks, such as the packaged-base and authoring rules, let the request through. + +- `POST /automation/SOURCE/clone`, with the flow's name as the new name: the taken-name probe refused the copy with `409`. It now finds no flow and lets the copy through. The engine files the copy's body in the disabled package's slot of the name, and once the package is enabled again its trigger runs the copy's body until the next re-sync. That is the answer the door already gives once the disable's re-sync has withdrawn the flow, so the door accepts nothing the normal path refuses. +- A definition write (`POST /automation`, `PUT /automation/NAME`) or a clone that the engine accepts and that is then refused (an unknown `notify` channel, a refused landing, a refused save) put back the definition the engine held. It now has nothing to put back, so it removes the name's registration. A `PUT` body that leaves out a stored credential no longer keeps the one the engine held. +- `DELETE /automation/NAME` answered a deletion. It still removes the engine's registration, but now answers `404` unless a stored row was removed. + +Remedy: enable the package. Its flow runs on its trigger again with no re-arm, and the bare entries serve it again. + +An event that fires while the package is disabled is dropped, not replayed when the package is enabled again. + +Nothing durable moves: the slot key, run keys, the trigger binding, the dispatch holder, credentials and the version history stay judged over every holder. Resuming a run parked before the disable is not decided here. A flow no package ships (the environment's own, or one registered straight into the engine) answers as before. diff --git a/packages/runtime/src/domains/automation-addressed-route.test.ts b/packages/runtime/src/domains/automation-addressed-route.test.ts index 65b7251a8cd..747056ae0d8 100644 --- a/packages/runtime/src/domains/automation-addressed-route.test.ts +++ b/packages/runtime/src/domains/automation-addressed-route.test.ts @@ -636,3 +636,86 @@ describe('[#33386] the by-name doors judge the served holders of a name two pack }); }); }); + +/** + * [ADR-0150 D3, #33905] A flow name one package holds, that package disabled, + * over a real `SchemaRegistry`: its namespaced address is refused `404` at + * admission, before the service is asked. The bare path reaches the engine, + * whose bare entries now answer as for a flow it does not hold (`getFlow` + * `null`, pinned in service-automation's `flow-slots-per-package.test.ts`), + * so each bare door answers what the address answers. The service here + * answers as the engine does for such a flow. + */ +describe('[#33905] a flow whose only holder\'s package is disabled: the bare door answers as its namespaced address (404)', () => { + function registryHolding(disabled: boolean) { + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + registry.installPackage({ id: CRM, name: CRM, version: '1.0.0', type: 'app', namespace: 'crm' } as never, 'code'); + registry.registerItem('flow', { name: 'solo', _packageId: CRM }, 'name' as never, CRM); + if (disabled) registry.disablePackage(CRM); + return registry; + } + + function dispatcherOver(registry: SchemaRegistry, held: boolean) { + const automation = { + handlerReady: true, + getFlow: vi.fn(async (name: string) => (held && name === 'solo' ? { name } : null)), + execute: vi.fn(async (name: string) => (held ? { success: true, output: {} } : { success: false, error: `Flow '${name}' not found` })), + toggleFlow: vi.fn(async (name: string) => { if (!held) throw new Error(`Flow '${name}' not found`); }), + listRunsPage: vi.fn(async () => ({ runs: [] as unknown[], hasMore: false })), + getActionDescriptors: vi.fn(() => []), + getFlowRuntimeStates: vi.fn(() => []), + }; + const services: Record = { automation, objectql: { registry } }; + const resolve = (name: string) => services[name]; + const kernel: any = { getService: resolve, getServiceAsync: async (name: string) => resolve(name), context: { getService: resolve } }; + const dispatcher = new HttpDispatcher(kernel); + const call = async (path: string, method: string, body: unknown = {}) => { + const answered = await dispatcher.handleAutomation(path, method, body, { request: {}, executionContext: ADMIN } as any, {}); + return { status: answered.response?.status ?? 200, body: answered.response?.body as any }; + }; + return { call, automation }; + } + + const DOORS: ReadonlyArray = [ + ['/solo', '/crm/solo', 'GET', {}], + ['/solo/trigger', '/crm/solo/trigger', 'POST', {}], + ['/trigger/solo', '/trigger/crm/solo', 'POST', {}], + ['/solo/toggle', '/crm/solo/toggle', 'POST', { enabled: false }], + ['/solo/runs', '/crm/solo/runs', 'GET', {}], + ]; + + it('each bare door answers 404 as its namespaced address does; nothing runs or switches (FROM: the bare door served the flow)', async () => { + const { call, automation } = dispatcherOver(registryHolding(true), false); + for (const [bare, addressed, method, body] of DOORS) { + const viaAddress = await call(addressed, method, body); + const viaBare = await call(bare, method, body); + expect([bare, viaBare.status, codeOf(viaBare)]).toEqual([bare, 404, codeOf(viaAddress)]); + expect([addressed, viaAddress.status]).toEqual([addressed, 404]); + } + expect(automation.execute).not.toHaveBeenCalled(); + expect(automation.toggleFlow).not.toHaveBeenCalled(); + expect(automation.listRunsPage).not.toHaveBeenCalled(); + }); + + it('the clone door with the flow as its source answers 404 as its namespaced address does; nothing is registered (FROM: the source was copied)', async () => { + const { call, automation } = dispatcherOver(registryHolding(true), false); + const registerFlow = vi.fn(); + (automation as Record).registerFlow = registerFlow; + const viaAddress = await call('/crm/solo/clone', 'POST', { name: 'solo_copy', label: 'Solo copy' }); + const viaBare = await call('/solo/clone', 'POST', { name: 'solo_copy', label: 'Solo copy' }); + expect([viaBare.status, codeOf(viaBare)]).toEqual([404, codeOf(viaAddress)]); + expect(viaAddress.status).toBe(404); + expect(registerFlow).not.toHaveBeenCalled(); + }); + + it('CONTROL — the package enabled: the address is its bare path, and both serve the flow', async () => { + const { call } = dispatcherOver(registryHolding(false), true); + for (const [bare, addressed, method, body] of DOORS) { + const viaAddress = await call(addressed, method, body); + const viaBare = await call(bare, method, body); + expect([bare, viaBare.status]).toEqual([bare, 200]); + expect([addressed, viaAddress.status]).toEqual([addressed, 200]); + } + }); +}); diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index a1b58d9187b..fa3b9b694dc 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2938,8 +2938,15 @@ export class AutomationEngine implements IAutomationService { */ // [#32183, R4-G] `heldByMany` reads every holder, a disabled package's // included: a disable keeps that package's slot armed, so it never folds - // a shared name back to one bare entry (`main`'s answer). - private readonly flowSlots = new FlowSlotTable((name) => this.durableFlowHolder(name)?.status === 'refused'); + // a shared name back to one bare entry (`main`'s answer). [#33893; + // amendment 7] `coHeldByDisabled`: so is the key of a holder whose + // co-holders are disabled, which the boot pull files alone and a disabled + // co-holder's withdrawal leaves alone; it keeps its qualified key until the + // registry no longer holds the name twice ({@link placeFlowSlot} folds it). + private readonly flowSlots = new FlowSlotTable( + (name) => this.durableFlowHolder(name)?.status === 'refused', + (name) => this.durableFlowHolder(name)?.status === 'refused' && this.flowHolder(name)?.status !== 'refused', + ); /** [#31696] Slot keys whose trigger decline ({@link activateFlowTrigger}) has been said. */ private readonly sharedSlotTriggerWarned = new Set(); /** @@ -4199,7 +4206,14 @@ export class AutomationEngine implements IAutomationService { // holds under two packages (the other's body refused, M1) still holds // the bare key, which would read as the name's one holder: it is not // armed, behind this warning, and runs when called by its package. - if (this.loneSharedFlowKey(this.flowSlotName(flowName)) === flowName) { + // [#33893] Both served ({@link loneSharedFlowKey}): beside a disabled + // co-holder the slot is the name's one served holder, filed under its + // qualified key, and is armed; the warning names no refused body. + // Filed under its qualified key, it is declined only once another + // package's body of the name was refused (recorded): a co-holder the + // re-sync has not registered yet is no refusal. + const slotName = this.flowSlotName(flowName); + if (this.loneSharedFlowKey(slotName) === flowName && (flowName === slotName || this.flowRefusals.has(slotName))) { if (!this.sharedSlotTriggerWarned.has(flowName)) { this.sharedSlotTriggerWarned.add(flowName); this.logger.warn( @@ -4421,24 +4435,30 @@ export class AutomationEngine implements IAutomationService { * nothing (`undefined`): the binding under its new key fires it once. A * slot of an unshared name runs through {@link execute}, as before. * - * [ADR-0150 D3, #33748; seat ruling 6884403301, amendment 3] A slot of a - * name two packages hold whose package is disabled is not dispatched: no - * flow, no run, never another slot's. Asked when the trigger fires, not - * when it was armed: a runtime disable leaves the slot armed (a disable is - * reversible and moves no key, amendment 7), so the slot dispatches again - * the moment its package is enabled, with no re-arm. + * [ADR-0150 D3, #33748; seat ruling 6884403301, amendment 3] A slot whose + * package is disabled is not dispatched: no flow, no run, never another + * slot's. Asked when the trigger fires, not when it was armed: a runtime + * disable leaves the slot armed (a disable is reversible and moves no key, + * amendment 7), so the slot dispatches again the moment its package is + * enabled, with no re-arm. [#33905] The same for the slot of a name one + * package holds (ADR-0150 D3: a disabled package holds no name), which the + * re-sync of the disable withdraws on the normal path; a package-less slot + * is no package's, and runs as before. */ private triggerRun(armedKey: string): (ctx: AutomationContext) => Promise { const slot = this.flowSlots.slot(armedKey); return async (ctx) => { - const key = slot ? this.flowSlots.keyOf(slot.name, slot.packageId) : armedKey; + let key = slot ? this.flowSlots.keyOf(slot.name, slot.packageId) : armedKey; if (key === undefined && !isSlotKeySpelling(armedKey)) return this.execute(armedKey, ctx); if (key === undefined || (key !== armedKey && !this.boundFlowTriggers.has(armedKey))) { this.logger.debug(`Trigger fired flow '${armedKey}' after it moved or left and was released: not run.`); return undefined; } - if (!slot || !this.flowSlots.isShared(slot.name)) return this.execute(key, ctx); - if (slot.packageId !== null) { + // [#33893] A lone slot left under its qualified key (its disabled + // co-holder since uninstalled) folds back here, and this run goes + // to where it lands. + if (slot && this.settleFlowName(slot.name)) key = this.flowKeyNow(key); + if (slot && slot.packageId !== null) { const said = qualifiedFlowKey(slot.packageId, slot.name); if (this.isDisabledHolderSlot(slot.name, slot.packageId)) { // Said once per slot while its package stays disabled, at @@ -4458,6 +4478,7 @@ export class AutomationEngine implements IAutomationService { } this.disabledHolderDispatchSaid.delete(said); } + if (!slot || !this.flowSlots.isShared(slot.name)) return this.execute(key, ctx); // A trigger seeds `params.flowName` with the key it was armed // under; the run reads its flow's name there, never a slot key. const params = ctx.params as Record | undefined; @@ -5063,7 +5084,12 @@ export class AutomationEngine implements IAutomationService { return keys[0] ?? this.flowSlots.add({ packageId: null, name }).key; } const own = this.flowSlots.keyOf(name, packageId); - if (own !== undefined) return own; + if (own !== undefined) { + // [#33893] A lone slot kept under its qualified key beside a + // disabled co-holder folds back once that holder is gone (the + // uninstall's re-sync re-registers this one). + return this.settleFlowName(name) ? this.flowKeyNow(own) : own; + } const packageless = this.flowSlots.keyOf(name, null); if (packageless !== undefined) { this.flowSlots.adopt(packageless, packageId); @@ -5072,8 +5098,17 @@ export class AutomationEngine implements IAutomationService { const incumbents = this.flowSlots.slotsOf(name); const incumbent = incumbents.length === 1 ? incumbents[0].packageId : null; if (incumbent !== null && this.flowHoldersSealed) this.bindPackagelessActivation(name, incumbent); + const incumbentKey = incumbents.length === 1 ? this.flowSlots.keyOf(name, incumbent) : undefined; const { key, moved } = this.flowSlots.add({ packageId, name }); this.moveFlowRecords(moved); + // [#33893] An incumbent already under its qualified key (filed so + // beside a disabled co-holder) moves no key as its co-holder returns, + // so the move's re-arm is done here: the M1 decline it may have taken + // while it was the name's one slot no longer applies. + if (incumbentKey !== undefined && incumbentKey !== name && moved.length === 0 && this.flows.has(incumbentKey)) { + this.sharedSlotTriggerWarned.delete(incumbentKey); + this.activateFlowTrigger(incumbentKey); + } if (incumbent !== null && !this.flowHoldersSealed) this.flowLedgerDisabled.refusePackagelessBind(name, incumbent); return key; } @@ -5271,9 +5306,14 @@ export class AutomationEngine implements IAutomationService { ): { key: string } | { refusal: PackageScopedRefusal } | { absent: true } { // [#31696] A slot key is no flow's name: it names no flow here. if (isSlotKeySpelling(name)) return { key: unfiledFlowKey(name) }; + this.settleFlowName(name); if (!this.flowSlots.isShared(name)) { const refusal = this.flowNameRefusal(name, callerPackageId); - return refusal ? { refusal } : { key: name }; + if (refusal) return { refusal }; + // [#33905] Its one holder's package is disabled: no flow, as for a + // name two packages hold that no served holder reaches. + if (options?.durable !== true && this.isDisabledSoleHolder(name)) return { absent: true }; + return { key: name }; } const resolution = this.flowNameResolver?.(name, callerPackageId, options?.durable === true ? { includeDisabledPackages: true } : { servedCaller: true }); @@ -5301,6 +5341,7 @@ export class AutomationEngine implements IAutomationService { */ private bareFlowKey(name: string): string | undefined { if (isSlotKeySpelling(name)) return undefined; + this.settleFlowName(name); if (!this.flowSlots.isShared(name)) return name; throw new PackageScopedNameRefusedError(this.sharedFlowNameRefusal(name, null)); } @@ -5312,11 +5353,15 @@ export class AutomationEngine implements IAutomationService { * a name two slots hold is its one served holder's slot, refused naming * the served holders when two or more serve it, and `undefined` (no flow) * when none does. Seat ruling 6884403301, amendment 9: these entries move - * with the doors. + * with the doors. [#33905] A name one package holds whose package is + * disabled is no flow here either ({@link isDisabledSoleHolder}): the + * entries answer as for a flow this engine does not hold, which is the + * namespaced address's answer. */ private servedBareFlowKey(name: string): string | undefined { if (isSlotKeySpelling(name)) return undefined; - if (!this.flowSlots.isShared(name)) return name; + this.settleFlowName(name); + if (!this.flowSlots.isShared(name)) return this.isDisabledSoleHolder(name) ? undefined : name; const resolved = this.resolveFlowKey(name, null); if ('refusal' in resolved) throw new PackageScopedNameRefusedError(resolved.refusal); return 'key' in resolved ? resolved.key : undefined; @@ -5341,6 +5386,20 @@ export class AutomationEngine implements IAutomationService { return resolver(name, packageId, { servedCaller: true })?.status === 'not-found'; } + /** + * [ADR-0150 D3, #33905; #28117 ruling A] Is the one slot of the unshared + * name `name` held by a package that is disabled now + * ({@link isDisabledHolderSlot})? A package-less slot, or none, is not: + * a flow registered straight into the engine, or the environment's own, + * is no package's to disable. Only the entries that read or run a flow + * ask it; the durable reads (slot and run keys, {@link flowDispatchHolder}, + * credentials, history) stay judged over every holder (amendment 7). + */ + private isDisabledSoleHolder(name: string): boolean { + const packageId = this.flowSlotPackage(name); + return packageId !== undefined && this.isDisabledHolderSlot(name, packageId); + } + /** [#31696] The package of the slot `key` files, or `undefined` (a package-less slot, or none). */ private flowSlotPackage(key: string): string | undefined { return this.flowSlots.slot(key)?.packageId ?? undefined; @@ -5357,10 +5416,28 @@ export class AutomationEngine implements IAutomationService { return keys.length > 0 ? keys : [name]; } - /** [M1] The key of `name`'s one slot while the registry holds `name` under two packages, else `undefined`. */ + /** + * [M1] The key of `name`'s one slot while the registry holds `name` under + * two packages SERVED, so another served package's body of it is not held + * here (refused), else `undefined`. [#33893] A co-holder that is only + * disabled is no M1: the slot is the name's one served holder, keeps its + * qualified key (amendment 7) and is armed, and no body was refused. + */ private loneSharedFlowKey(name: string): string | undefined { const keys = this.flowSlots.keysOf(name); - return keys.length === 1 && this.flowSlots.isShared(name) ? keys[0] : undefined; + return keys.length === 1 && this.flowSlots.isShared(name) && this.flowHolder(name)?.status === 'refused' ? keys[0] : undefined; + } + + /** + * [#33893] Fold `name`'s lone slot back to the bare name if it is still + * under its qualified key while the registry no longer holds the name + * twice ({@link FlowSlotTable.settle}), moving its records and trigger. + * True when it moved. + */ + private settleFlowName(name: string): boolean { + const moved = this.flowSlots.settle(name); + this.moveFlowRecords(moved); + return moved.length > 0; } /** [#31696] Is `key` the key of a slot whose name another slot holds too? */ @@ -5618,7 +5695,10 @@ export class AutomationEngine implements IAutomationService { }; withdrawFlow.call(host, name); // [#31696] The slot goes with its flow; a name left with one slot - // files it under the bare name again. + // files it under the bare name again. [#33893] Not while the registry + // still holds the name under a disabled package (the re-sync of a + // disable withdraws its slot): the served holder keeps its key and + // its binding (amendment 7). this.moveFlowRecords(this.flowSlots.remove(name)); } @@ -5647,6 +5727,10 @@ export class AutomationEngine implements IAutomationService { }; recordFlowRefusal.call(host, name, error); if (lone !== undefined) this.deactivateFlowTrigger(lone); + // [#33893] A lone slot under its qualified key was armed while the + // co-holder was not yet registered; asked again, it takes the decline + // and says it. + if (lone !== undefined && lone !== name) this.activateFlowTrigger(lone); } /** @@ -5826,6 +5910,8 @@ export class AutomationEngine implements IAutomationService { * [#31696] Refused (409, naming both) for a name two packages serve: see * {@link getFlowSlot}. [#33386] Judged over the served holders * ({@link servedBareFlowKey}): one served holder's flow, `null` when none. + * [#33905] `null` too for a name one package holds whose package is + * disabled. */ async getFlow(name: string): Promise { const key = this.servedBareFlowKey(name); @@ -5960,6 +6046,7 @@ export class AutomationEngine implements IAutomationService { | { readonly status: 'unadmitted' } | { readonly status: 'refused'; readonly candidates: PackageScopedRefusal['candidates'] } { if (isSlotKeySpelling(flowName) || flowName.startsWith('\u0000')) return { status: 'unadmitted' }; + this.settleFlowName(flowName); if (!this.flowSlots.isShared(flowName)) return undefined; if (address === undefined) return { status: 'refused', candidates: this.sharedFlowNameRefusal(flowName, null).candidates }; const environment = address.qualifier === ENVIRONMENT_ADDRESS_SEGMENT; @@ -7651,6 +7738,7 @@ export class AutomationEngine implements IAutomationService { const resolved = this.resolveFlowKey(flowName, this.flowCallerPackage(context)); if ('refusal' in resolved) return { success: false, error: resolved.refusal.message }; // [#33386] No served holder reaches the name: as for a flow this engine does not hold. + // [#33905] Nor does a disabled package's flow of a name it holds alone. if ('absent' in resolved) return { success: false, error: `Flow '${flowName}' not found` }; return this.executeKey(resolved.key, context, startTime); } diff --git a/packages/services/service-automation/src/flow-slots-per-package.test.ts b/packages/services/service-automation/src/flow-slots-per-package.test.ts index 5d24798de88..d6691c41185 100644 --- a/packages/services/service-automation/src/flow-slots-per-package.test.ts +++ b/packages/services/service-automation/src/flow-slots-per-package.test.ts @@ -1078,8 +1078,8 @@ describe('[#33386] a run of a name two slots hold judges the served holders', () * dispatches it again with no re-arm. A boot disable arms nothing of the * disabled package; the re-sync that arms it on enable makes it dispatch. * The slot keys, the bindings and the dispatch holder do not move - * (amendment 7). A name one package holds: its trigger answers as on `main` - * today (CONTROL). + * (amendment 7). [#33905] A name one package holds is judged the same way + * (ADR-0150 D3: a disabled package holds no name). */ describe('[#33748] a trigger binding does not dispatch a slot whose package is disabled', () => { const tagOf = (packageId: string) => packageId.split('.').pop()!; @@ -1186,12 +1186,348 @@ describe('[#33748] a trigger binding does not dispatch a slot whose package is d expect(skipSaid()).toEqual([]); }); - it('CONTROL — a name one package holds: its trigger answers as on `main` today, disabled or not', async () => { + it('[#33905] a name one package holds, disabled at runtime with its slot left armed: not dispatched, said once; re-enabled, it dispatches with no re-arm (FROM: dispatched while disabled)', async () => { ship(P1, triggered('solo', 'alpha')); expect([...armed.keys()]).toEqual(['solo']); expect(await fireAll()).toEqual(['alpha']); + const bindings = engine.getActiveTriggerBindings(); + const startedBefore = [...started]; + registry.disablePackage(P1); + expect(await fireAll()).toEqual([]); + expect(await fireAll()).toEqual([]); + expect(skipSaid()).toHaveLength(1); + expect(skipSaid()[0][1]).toMatchObject({ flow: 'solo', package: P1, slot: 'solo' }); + expect(engineLogger.error).not.toHaveBeenCalled(); + // Amendment 7: the slot stays armed under its key, nothing released. + expect(engine.flowSlotKey(P1, 'solo')).toBe('solo'); + expect(engine.getActiveTriggerBindings()).toEqual(bindings); + + registry.enablePackage(P1); + expect(await fireAll()).toEqual(['alpha']); + expect(started).toEqual(startedBefore); + registry.disablePackage(P1); + expect(await fireAll()).toEqual([]); + expect(skipSaid()).toHaveLength(2); + }); +}); + +/** + * [ADR-0150 D3, #33905; #28117 ruling A] A flow whose only holder's package + * is disabled, while the engine still holds its slot (a disable whose re-sync + * failed or did not run): the engine's bare entries that read or run a flow + * (`execute`, `getFlow`, `toggleFlow`) answer as for a flow this engine does + * not hold, which is what the namespaced address answers (404). The durable + * reads stay judged over every holder (amendment 7): the slot key, the + * dispatch holder and the version history do not move. A package-less flow, + * and an engine with no resolver attached, are CONTROLs. + */ +describe('[#33905] the bare entries of a flow whose only holder\'s package is disabled', () => { + const unheld = async (name: string) => ({ + run: await engine.execute(name), + read: await engine.getFlow(name), + toggle: await engine.toggleFlow(name, false).then(() => 'switched', (err: Error) => err.message), + }); + + it('execute, getFlow and toggleFlow answer as for a name the engine does not hold (FROM: served); re-enabled, they serve it again', async () => { + ship(P1, leaf('solo', 'p1')); + registry.disablePackage(P1); + const answers = await unheld('solo'); + const nothing = await unheld('nope'); + expect(answers).toEqual({ ...nothing, run: { ...nothing.run, error: "Flow 'solo' not found" }, toggle: "Flow 'solo' not found" }); + expect(answers.read).toBeNull(); + expect(answers.run.success).toBe(false); + expect(ran).toEqual([]); + // Amendment 7: the durable reads are judged over every holder, unmoved. + expect(engine.flowSlotKey(P1, 'solo')).toBe('solo'); + expect(engine.flowDispatchHolder('solo')).toEqual({ packageId: P1, claimBare: true }); + expect(engine.getFlowVersionHistory('solo')).toHaveLength(1); + + registry.enablePackage(P1); + expect((await engine.execute('solo')).success).toBe(true); + expect(ran).toEqual(['p1']); + expect(await engine.getFlow('solo')).toMatchObject({ name: 'solo' }); + await expect(engine.toggleFlow('solo', false)).resolves.toBeUndefined(); + }); + + it('a subflow call by the bare name reaches no flow while the package is disabled (FROM: ran)', async () => { + ship(P1, leaf('solo', 'p1')); + engine.registerFlow('go', caller('go', 'solo')); + registry.disablePackage(P1); + expect((await engine.execute('go')).success).toBe(false); + expect(ran).toEqual([]); + registry.enablePackage(P1); + expect((await engine.execute('go')).success).toBe(true); + expect(ran).toEqual(['p1']); + }); + + it('CONTROL — a package-less flow (the environment\'s own, registered straight into the engine) is no package\'s: served while a package is disabled', async () => { + ship(P1, leaf('solo', 'p1')); + engine.registerFlow('env_flow', leaf('env_flow', 'env')); + registry.disablePackage(P1); + expect((await engine.execute('env_flow')).success).toBe(true); + expect(await engine.getFlow('env_flow')).toMatchObject({ name: 'env_flow' }); + expect(ran).toEqual(['env']); + }); + + it('CONTROL — with no resolver attached nothing is disabled: the flow is served as before', async () => { + ship(P1, leaf('solo', 'p1')); + engine.setFlowNameResolver(undefined); + registry.disablePackage(P1); + expect((await engine.execute('solo')).success).toBe(true); + expect(await engine.getFlow('solo')).toMatchObject({ name: 'solo' }); + expect(ran).toEqual(['p1']); + }); +}); + +/** + * [ADR-0150 D3/D4, #33893; seat ruling 6884403301, amendment 7] A disable is + * reversible and moves no key. The served holder of a name a disabled + * package co-holds keeps its slot under `PACKAGE/NAME`, armed, and its + * trigger dispatches: when the boot pull registers it alone (the disabled + * holder's flows not pulled), and when the disable's re-sync withdraws the + * disabled holder's slot. The M1 decline and its warning stay for a body + * that really was refused (the `[M1]` pins above). A holder that leaves the + * registry (an uninstall) folds the name back to its bare key, as before + * (CONTROL). + */ +describe('[#33893] the served holder of a name a disabled package co-holds keeps its qualified key, armed', () => { + const tagOf = (packageId: string) => packageId.split('.').pop()!; + let armed: Map Promise>; + let started: string[]; + let stopped: string[]; + + beforeEach(() => { + armed = new Map(); + started = []; + stopped = []; + engine.registerTrigger({ + type: 'record_change', + start: (b: { flowName: string }, callback: (c: unknown) => Promise) => { + started.push(b.flowName); + armed.set(b.flowName, callback); + }, + stop: (key: string) => { + stopped.push(key); + armed.delete(key); + }, + } as unknown as FlowTrigger); + }); + + async function fireAll(): Promise { + ran = []; + for (const [key, callback] of [...armed]) await callback({ params: { flowName: key } }); + return [...ran].sort(); + } + + /** The registry holds `body` under `packageId` (its loader set too); the engine is not handed it. */ + function heldOnly(packageId: string, body: { name: string }): void { + registry.registerItem('flow', { ...body, _packageId: packageId }, 'name' as never, packageId); + loaderSets[body.name] = [...new Set([...(loaderSets[body.name] ?? []), packageId])]; + } + + /** The pull (or the re-sync) hands the engine package `packageId`'s flow, as precedence arms a name two packages hold. */ + function pull(packageId: string, body: { name: string }): void { + engine.registerFlow(body.name, body, { source: 'package', packageId, holder: packageId }); + } + + const refusedBodyWarned = () => engineLogger.warn.mock.calls.filter(([message]: [string]) => /whose body was refused/.test(message)); + + it('FlowSlotTable: beside a disabled co-holder the first slot is filed qualified, and a co-holder\'s removal moves no key', () => { + let coHeldByDisabled = true; + const slots = new FlowSlotTable(() => true, () => coHeldByDisabled); + expect(slots.add({ packageId: P1, name: 'f' })).toEqual({ key: `${P1}/f`, moved: [] }); + expect(slots.isShared('f')).toBe(true); + expect(slots.add({ packageId: P2, name: 'f' })).toEqual({ key: `${P2}/f`, moved: [] }); + expect(slots.remove(`${P2}/f`)).toEqual([]); + expect(slots.keyOf('f', P1)).toBe(`${P1}/f`); + // CONTROL: with no disabled co-holder the removal folds the name back, as before. + slots.add({ packageId: P2, name: 'f' }); + coHeldByDisabled = false; + expect(slots.remove(`${P2}/f`)).toEqual([{ from: `${P1}/f`, to: 'f' }]); + + // The disabled co-holder uninstalled: the lone qualified slot is no longer shared, and settles back to the bare name. + let many = true; + const kept = new FlowSlotTable(() => many, () => many); + kept.add({ packageId: P1, name: 'g' }); + expect(kept.settle('g')).toEqual([]); + many = false; + expect(kept.isShared('g')).toBe(false); + expect(kept.settle('g')).toEqual([{ from: `${P1}/g`, to: 'g' }]); + expect(kept.keyOf('g', P1)).toBe('g'); + expect(kept.settle('g')).toEqual([]); + }); + + describe.each([[P1, P2], [P2, P1]].map((order) => [order.map(tagOf).join(' then '), order] as const))('registry holds %s', (_o, order) => { + it.each([[P1, P2], [P2, P1]])('boot disable, %s disabled: the served holder is filed under PACKAGE/NAME, armed and dispatched, with no warning (FROM: bare key, declined behind the refused-body warning)', async (off, on) => { + for (const holder of order) heldOnly(holder, triggered('t', tagOf(holder))); + registry.disablePackage(off); + pull(on, triggered('t', tagOf(on))); + + expect(engine.flowSlotKey(on, 't')).toBe(`${on}/t`); + expect(started).toEqual([`${on}/t`]); + expect(await fireAll()).toEqual([tagOf(on)]); + expect(refusedBodyWarned()).toEqual([]); + expect(engine.flowDispatchHolder(`${on}/t`)).toEqual({ packageId: on, claimBare: false, name: 't' }); + expect(engine.getFlowRegistration('t')).toEqual({ state: 'registered' }); + // The bare name reaches its one served holder. + ran = []; + expect((await engine.execute('t')).success).toBe(true); + expect(ran).toEqual([tagOf(on)]); + + // Enabled, the re-sync registers the other holder: no key moves, nothing is re-armed. + registry.enablePackage(off); + pull(off, triggered('t', tagOf(off))); + expect(started).toEqual([`${on}/t`, `${off}/t`]); + expect(stopped).toEqual([]); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + }); + + it.each([[P1, P2], [P2, P1]])('runtime disable of %s, then the re-sync withdraws its slot: the served holder keeps its key and binding and dispatches (FROM: re-keyed to the bare name, its binding stopped)', async (off, on) => { + for (const holder of order) ship(holder, triggered('t', tagOf(holder))); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + started = []; + stopped = []; + + registry.disablePackage(off); + engine.withdrawFlowSlot(off, 't'); + expect(engine.flowSlotKey(on, 't')).toBe(`${on}/t`); + expect(engine.flowSlotKey(off, 't')).toBeUndefined(); + expect(stopped).toEqual([`${off}/t`]); + expect([...armed.keys()]).toEqual([`${on}/t`]); + expect(await fireAll()).toEqual([tagOf(on)]); + expect(refusedBodyWarned()).toEqual([]); + expect(engine.flowDispatchHolder(`${on}/t`)).toEqual({ packageId: on, claimBare: false, name: 't' }); + + registry.enablePackage(off); + pull(off, triggered('t', tagOf(off))); + expect(started).toEqual([`${off}/t`]); + expect(stopped).toEqual([`${off}/t`]); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + }); + }); + + it.each([ + ['runtime disable, then the re-sync withdraws its slot', 'runtime'], + ['boot disable (the pull hands the engine the served holder only)', 'boot'], + ] as const)('%s, then the disabled holder is uninstalled: its re-sync folds the served holder back to the bare name, and every bare entry serves it (FROM: stuck under PACKAGE/NAME, the bare entries refused a name one package holds)', async (_label, path) => { + if (path === 'runtime') { + ship(P1, triggered('t', 'alpha')); + ship(P2, triggered('t', 'beta')); + registry.disablePackage(P2); + engine.withdrawFlowSlot(P2, 't'); + } else { + heldOnly(P1, triggered('t', 'alpha')); + heldOnly(P2, triggered('t', 'beta')); + registry.disablePackage(P2); + pull(P1, triggered('t', 'alpha')); + } + expect(engine.flowSlotKey(P1, 't')).toBe(`${P1}/t`); + + // The uninstall: the registry and the loader set drop P2, and the + // uninstall's re-sync re-registers the name's one holder. + registry.unregisterItemsByPackage(P2); + loaderSets.t = [P1]; + engine.registerFlow('t', triggered('t', 'alpha'), { source: 'package', packageId: P1 }); + + expect(engine.flowSlotKey(P1, 't')).toBe('t'); + expect([...armed.keys()]).toEqual(['t']); + expect(await fireAll()).toEqual(['alpha']); + expect(engine.inboundHookSlot('t')).toBeUndefined(); + expect(engine.getFlowVersionHistory('t')).toHaveLength(2); + ran = []; + expect((await engine.execute('t')).success).toBe(true); + expect(ran).toEqual(['alpha']); + expect(() => engine.unregisterFlow('t')).not.toThrow(); + expect(await engine.getFlow('t')).toBeNull(); + expect([...armed.keys()]).toEqual([]); + }); + + /** The disable both ways: the boot pull hands the engine the served holder only, or both are shipped and the re-sync withdraws the disabled one's slot. */ + function disableBeside(path: 'boot' | 'runtime', off: string, on: string): void { + if (path === 'boot') { + for (const holder of [P1, P2]) heldOnly(holder, triggered('t', tagOf(holder))); + registry.disablePackage(off); + pull(on, triggered('t', tagOf(on))); + } else { + for (const holder of [P1, P2]) ship(holder, triggered('t', tagOf(holder))); + registry.disablePackage(off); + engine.withdrawFlowSlot(off, 't'); + } + } + + describe.each(['boot', 'runtime'] as const)('%s disable, then the enable\'s re-sync registers every contender', (path) => { + it.each([ + [P1, P2, 'served holder first'], + [P2, P1, 'served holder first'], + [P1, P2, 'returning holder first'], + [P2, P1, 'returning holder first'], + ])('%s disabled, %s served, %s: both slots armed and dispatched, no refused-body warning (FROM: the served holder declined behind it and never re-armed)', async (off, on, order) => { + disableBeside(path, off, on); + expect(engine.flowSlotKey(on, 't')).toBe(`${on}/t`); + + registry.enablePackage(off); + const contenders = order === 'served holder first' ? [on, off] : [off, on]; + for (const holder of contenders) pull(holder, triggered('t', tagOf(holder))); + + expect([...armed.keys()].sort()).toEqual([`${P1}/t`, `${P2}/t`]); + expect(await fireAll()).toEqual([tagOf(P1), tagOf(P2)].sort()); + expect(refusedBodyWarned()).toEqual([]); + }); + }); + + it('CONTROL — the returning holder\'s body really is refused: the served one is declined behind the warning, once; registered after all, both are armed', async () => { + disableBeside('runtime', P2, P1); + registry.enablePackage(P2); + pull(P1, triggered('t', 'alpha')); + expect([...armed.keys()]).toEqual([`${P1}/t`]); + + engine.recordFlowRefusal('t', new Error('refused body')); + expect([...armed.keys()]).toEqual([]); + expect(refusedBodyWarned()).toHaveLength(1); + + pull(P2, triggered('t', 'beta')); + expect([...armed.keys()].sort()).toEqual([`${P1}/t`, `${P2}/t`]); + expect(await fireAll()).toEqual(['alpha', 'beta']); + expect(refusedBodyWarned()).toHaveLength(1); + }); + + describe('the stretch between the uninstall and the re-sync\'s registration (no re-registration at all: a failed re-sync read)', () => { + function uninstalled(): void { + disableBeside('runtime', P2, P1); + registry.unregisterItemsByPackage(P2); + loaderSets.t = [P1]; + expect(engine.flowSlotKey(P1, 't')).toBe(`${P1}/t`); + } + + it('first touched by its trigger: the event runs the flow, and the slot folds back to the bare name with its binding (FROM: execute was asked a slot key and ran nothing)', async () => { + uninstalled(); + expect(await fireAll()).toEqual(['alpha']); + expect(engine.flowSlotKey(P1, 't')).toBe('t'); + expect([...armed.keys()]).toEqual(['t']); + expect(await fireAll()).toEqual(['alpha']); + }); + + it('first touched by a bare entry: each one serves the name (FROM: no flow under the bare name)', async () => { + uninstalled(); + expect(engine.inboundHookSlot('t')).toBeUndefined(); + expect(engine.flowSlotKey(P1, 't')).toBe('t'); + expect(await engine.getFlow('t')).toMatchObject({ name: 't' }); + expect(engine.getFlowVersionHistory('t')).toHaveLength(1); + ran = []; + expect((await engine.execute('t')).success).toBe(true); + expect(ran).toEqual(['alpha']); + expect([...armed.keys()]).toEqual(['t']); + }); + }); + + it('CONTROL — the other holder uninstalled before its slot is withdrawn: the name folds back to its bare key, as before', async () => { + ship(P1, triggered('t', 'alpha')); + ship(P2, triggered('t', 'beta')); + registry.unregisterItemsByPackage(P2); + engine.withdrawFlowSlot(P2, 't'); + expect(engine.flowSlotKey(P1, 't')).toBe('t'); + expect([...armed.keys()]).toEqual(['t']); expect(await fireAll()).toEqual(['alpha']); - expect(skipSaid()).toEqual([]); }); }); diff --git a/packages/services/service-automation/src/flow-slots.ts b/packages/services/service-automation/src/flow-slots.ts index 07af5e5b7c3..25dc8534882 100644 --- a/packages/services/service-automation/src/flow-slots.ts +++ b/packages/services/service-automation/src/flow-slots.ts @@ -15,6 +15,17 @@ * when a name gains or loses its second slot; {@link FlowSlotTable.add} and * {@link FlowSlotTable.remove} answer which keys moved. * + * [#33893; seat ruling 6884403301, amendment 7] A disable is reversible and + * moves no key. While the registry holds a name under two or more packages + * and the others are disabled (`coHeldByDisabled`), a package's lone slot of + * the name is filed, and stays, under its qualified key: the first holder + * the boot pull registers beside a disabled one, and the holder a disabled + * one's withdrawal leaves behind. Once the registry no longer holds the name + * twice (the disabled holder uninstalled), it folds back to the bare name + * ({@link FlowSlotTable.settle}) the first time the engine places it, fires it + * or reads its name: one keying rule, so a name one package holds is never + * read as shared. + * * Invariant (D4): a package-less slot never sits beside a package slot. A * package arriving for a name a package-less slot holds takes it over * ({@link FlowSlotTable.adopt}), and a package-less registration of a name one @@ -65,8 +76,14 @@ export interface FlowKeyMove { /** The slots one engine holds, and the key each is filed under. */ export class FlowSlotTable { - /** [M1] `heldByMany(name)`: the registry holds `name` under two or more packages (the resolver refuses it with no package). */ - constructor(private readonly heldByMany?: (name: string) => boolean) {} + /** + * @param heldByMany [M1] the registry holds `name` under two or more packages (the resolver refuses it with no package). + * @param coHeldByDisabled [#33893] it does, and at most one of them is served: a lone package slot keeps its qualified key. + */ + constructor( + private readonly heldByMany?: (name: string) => boolean, + private readonly coHeldByDisabled?: (name: string) => boolean, + ) {} private readonly byKey = new Map(); /** name → (package id, `''` for none) → key */ @@ -98,12 +115,27 @@ export class FlowSlotTable { return size > 1 || (size === 1 && this.heldByMany?.(name) === true); } + /** + * [#33893] The name's lone slot, filed under its qualified key beside a + * disabled co-holder, goes back to the bare name once the registry no + * longer holds the name twice: the move answered, or none. + */ + settle(name: string): FlowKeyMove[] { + const packages = this.byName.get(name); + if (packages?.size !== 1) return []; + const [[onlyPackage, onlyKey]] = [...packages]; + if (onlyKey === name || this.heldByMany?.(name) === true) return []; + this.rekey(onlyKey, name); + packages.set(onlyPackage, name); + return [{ from: onlyKey, to: name }]; + } + /** Every key, in arrival order. */ keys(): string[] { return [...this.byKey.keys()]; } - /** File the slot `(packageId, name)`: its key, and the name's lone slot's move to its qualified key, if any. */ + /** File the slot `(packageId, name)`: its key (qualified for the first one too when `coHeldByDisabled`), and the name's lone slot's move to its qualified key, if any. */ add(slot: FlowSlot): { key: string; moved: FlowKeyMove[] } { const packages = this.byName.get(slot.name) ?? new Map(); const moved: FlowKeyMove[] = []; @@ -116,14 +148,15 @@ export class FlowSlotTable { moved.push({ from: onlyKey, to }); } } - const key = packages.size === 0 || slot.packageId === null ? slot.name : qualifiedFlowKey(slot.packageId, slot.name); + const lone = packages.size === 0 && this.coHeldByDisabled?.(slot.name) !== true; + const key = lone || slot.packageId === null ? slot.name : qualifiedFlowKey(slot.packageId, slot.name); packages.set(slot.packageId ?? '', key); this.byName.set(slot.name, packages); this.byKey.set(key, slot); return { key, moved }; } - /** Drop the slot `key` files: a name left with one slot files it under the bare name again (the move answered). */ + /** Drop the slot `key` files: a name left with one slot files it under the bare name again (the move answered), [#33893] unless `coHeldByDisabled`. */ remove(key: string): FlowKeyMove[] { const slot = this.byKey.get(key); if (!slot) return []; @@ -137,6 +170,8 @@ export class FlowSlotTable { if (packages.size !== 1) return []; const [[onlyPackage, onlyKey]] = [...packages]; if (onlyKey === slot.name) return []; + // [#33893] A disabled holder's slot leaving moves no key of the others. + if (this.coHeldByDisabled?.(slot.name) === true) return []; this.rekey(onlyKey, slot.name); packages.set(onlyPackage, slot.name); return [{ from: onlyKey, to: slot.name }];