Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(workflow-recipes): address PR #752 review findings

Alfredo Lopez84b55fd368d5
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index f2d9bb5a5..babf05655 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.365",
+ "version": "0.1.366",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.365",
+ "version": "0.1.366",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index df23a6dda..24f71133c 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.365",
+ "version": "0.1.366",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/reconciler/k8sErrors.ts b/workflow-recipes/src/reconciler/k8sErrors.ts
index ed419c37e..1e2cb2add 100644
--- a/workflow-recipes/src/reconciler/k8sErrors.ts
+++ b/workflow-recipes/src/reconciler/k8sErrors.ts
@@ -171,3 +171,38 @@ export function isRetryableInfraError(error: unknown): boolean {
// raw substring inclusion, so operator-controlled text can't self-heal.
return messageIndicatesTransientTransport(messageOf(error))
}
+
+/**
+ * Thrown by a reconcile step that failed for a transient reason (e.g. a DNS
+ * SERVFAIL/timeout while resolving egress FQDNs) rather than a permanent
+ * misconfiguration. The top-level reconcile catch maps this to the non-terminal
+ * `degraded` phase so the periodic reconcile retries and the recipe self-heals
+ * once the underlying dependency recovers — instead of bricking it at the
+ * terminal `failed` phase, which is never retried.
+ */
+export class RetryableReconcileError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message)
+ this.name = 'RetryableReconcileError'
+ // Preserve the underlying error so logs (and any `.cause`-walking
+ // classifier such as isRetryableInfraError's collectSocketCodes) can still
+ // see the original transport/HTTP signal even though we re-message it for
+ // the recipe status. Re-wrapping with `: ${String(error)}` alone would
+ // flatten the chain and discard `.code`/`.cause`.
+ if (options && 'cause' in options) {
+ ;(this as { cause?: unknown }).cause = options.cause
+ }
+ }
+}
+
+/**
+ * A read-first apply read 404, its POST got a 409, and the re-read of the
+ * object that won the race is a 404 again. There is nothing to replace and no
+ * live object to judge, so the pass stops and asks for a fresh reconciliation
+ * instead of guessing with a second POST or a PUT that can only 404.
+ */
+export class ResourceVanishedAfterConflictError extends RetryableReconcileError {
+ constructor(label: string, options?: { cause?: unknown }) {
+ super(`${label} disappeared after create conflict; a fresh reconciliation is required`, options)
+ }
+}
diff --git a/workflow-recipes/src/reconciler/mcpDelegation.test.ts b/workflow-recipes/src/reconciler/mcpDelegation.test.ts
index 2ae4f152d..4d9819a22 100644
--- a/workflow-recipes/src/reconciler/mcpDelegation.test.ts
+++ b/workflow-recipes/src/reconciler/mcpDelegation.test.ts
@@ -22,6 +22,7 @@ import {
waitForNetworkReady,
} from './mcpDelegation'
import type { SecretAccess } from './resourceBuilder'
+import { SPEC_HASH_ANNOTATION, stampSpecHash } from './specHash'
import { privateWorkflowContextName } from './workflowContext'
// ─── Test Helpers ─────────────────────────────────────────────────────
@@ -3220,7 +3221,12 @@ describe('Issue #637 — transport Secret ownership gate', () => {
describe('transport Service read-first apply', () => {
type LiveService = {
- metadata: { name: string; resourceVersion?: string; annotations?: Record<string, string> }
+ metadata: {
+ name: string
+ resourceVersion?: string
+ annotations?: Record<string, string>
+ ownerReferences?: Array<{ controller?: boolean; uid?: string }>
+ }
spec: { clusterIP?: string; ports?: Array<{ port: number }> }
}
const NS = 'mcp-server'
@@ -3292,13 +3298,22 @@ describe('transport Service read-first apply', () => {
await delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())
clear()
- await delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())
-
- // Witness: the gate read the live Service before deciding not to write.
- expect(coreApi.readNamespacedService).toHaveBeenCalledTimes(1)
- expect(coreApi.readNamespacedService).toHaveBeenCalledWith({ name: NAME, namespace: NS })
- expect(coreApi.createNamespacedService).toHaveBeenCalledTimes(0)
- expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(0)
+ const infoLog = captureLogger('info')
+ try {
+ await delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())
+
+ // Witness: the gate read the live Service before deciding not to write,
+ // and the skip is logged at the same level as the other skip logs.
+ expect(coreApi.readNamespacedService).toHaveBeenCalledTimes(1)
+ expect(coreApi.readNamespacedService).toHaveBeenCalledWith({ name: NAME, namespace: NS })
+ expect(infoLog).toHaveBeenCalledWith('Transport Service unchanged; skipping update', {
+ service: NAME,
+ })
+ expect(coreApi.createNamespacedService).toHaveBeenCalledTimes(0)
+ expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(0)
+ } finally {
+ infoLog.mockRestore()
+ }
})
it('replaces a changed transport Service once, keeping the live clusterIP', async () => {
@@ -3316,6 +3331,36 @@ describe('transport Service read-first apply', () => {
expect(live()!.spec.ports![0].port).toBe(3100)
})
+ it('rewrites a hash-unchanged transport Service whose controller ownerReference uid no longer matches the recipe', async () => {
+ const { deps, coreApi, clear } = serviceDeps()
+ // ownerReferences are only set when the Service shares the recipe namespace.
+ const recipeWithUid = (uid: string) => {
+ const recipe = makeRecipe()
+ recipe.metadata = { ...recipe.metadata, namespace: NS, uid }
+ return recipe
+ }
+ const controllerUid = (body: LiveService) =>
+ body.metadata.ownerReferences?.find(ref => ref.controller)?.uid
+ await delegateTransportWorkloads(deps, recipeWithUid('uid-old'), NS, new Map())
+ expect(coreApi.createNamespacedService).toHaveBeenCalledTimes(1)
+ clear()
+
+ // The recipe was deleted and recreated under the same name.
+ await delegateTransportWorkloads(deps, recipeWithUid('uid-new'), NS, new Map())
+
+ expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(1)
+ expect(controllerUid(coreApi.replaceNamespacedService.mock.calls[0][0].body)).toBe('uid-new')
+ expect(coreApi.readNamespacedService).toHaveBeenCalledWith({ name: NAME, namespace: NS })
+ expect(coreApi.createNamespacedService).toHaveBeenCalledTimes(0)
+ clear()
+
+ await delegateTransportWorkloads(deps, recipeWithUid('uid-new'), NS, new Map())
+
+ expect(coreApi.readNamespacedService).toHaveBeenCalledTimes(1)
+ expect(coreApi.createNamespacedService).toHaveBeenCalledTimes(0)
+ expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(0)
+ })
+
it('skips the write when another writer created the desired Service between read and POST', async () => {
const { deps, coreApi, clear } = serviceDeps()
await delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())
@@ -3330,4 +3375,112 @@ describe('transport Service read-first apply', () => {
expect(coreApi.readNamespacedService).toHaveBeenCalledTimes(2)
expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(0)
})
+
+ it('replaces a different race winner carrying its resourceVersion and clusterIP', async () => {
+ const { deps, coreApi, clear, live } = serviceDeps()
+ await delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())
+ // Another writer won the race with its own Service: other port, no hash.
+ const winner = live()!
+ winner.metadata.resourceVersion = '7'
+ winner.metadata.annotations = {}
+ winner.spec.clusterIP = '10.1.1.1'
+ winner.spec.ports = [{ port: 9999 }]
+ clear()
+ // The gate read misses the object the other writer is about to create.
+ coreApi.readNamespacedService.mockRejectedValueOnce({ code: 404 })
+
+ await delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())
+
+ expect(coreApi.createNamespacedService).toHaveBeenCalledTimes(1)
+ expect(coreApi.readNamespacedService).toHaveBeenCalledTimes(2)
+ expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(1)
+ const recipe = makeRecipe()
+ const desired = buildTransportService(recipe.spec.workloads![0], recipe, NS)!
+ const expectedHash = stampSpecHash(desired)
+ const body = coreApi.replaceNamespacedService.mock.calls[0][0].body
+ expect(body.metadata.resourceVersion).toBe('7')
+ expect(body.spec.clusterIP).toBe('10.1.1.1')
+ expect(body.metadata.annotations?.[SPEC_HASH_ANNOTATION]).toBe(expectedHash)
+ expect(live()!.spec.ports![0].port).toBe(recipe.spec.workloads![0].port)
+ })
+
+ it('propagates a non-404 transport Service read error without writing', async () => {
+ const errorLog = captureLogger('error')
+ try {
+ const { deps, coreApi } = serviceDeps()
+ coreApi.readNamespacedService.mockRejectedValueOnce({ code: 503 })
+
+ await expect(delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())).rejects.toThrow(
+ 'Delegation failed for workload(s)'
+ )
+
+ // Witness: the gate performed its read and the 503 is the reported cause.
+ expect(coreApi.readNamespacedService).toHaveBeenCalledTimes(1)
+ expect(coreApi.readNamespacedService).toHaveBeenCalledWith({ name: NAME, namespace: NS })
+ expect(errorLog).toHaveBeenCalledWith(
+ 'Failed to delegate workload',
+ expect.objectContaining({ error: { code: 503 } })
+ )
+ expect(coreApi.createNamespacedService).toHaveBeenCalledTimes(0)
+ expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(0)
+ } finally {
+ errorLog.mockRestore()
+ }
+ })
+
+ it('raises a retryable error, without a PUT, for a Service that vanished after a create conflict', async () => {
+ const errorLog = captureLogger('error')
+ try {
+ const { deps, coreApi, clear } = serviceDeps()
+ await delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())
+ clear()
+ // Both reads miss while the POST between them collides with an object
+ // that is gone again by the conflict re-read.
+ coreApi.readNamespacedService.mockRejectedValueOnce({ code: 404 })
+ coreApi.readNamespacedService.mockRejectedValueOnce({ code: 404 })
+
+ await expect(delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())).rejects.toThrow(
+ 'Delegation failed for workload(s)'
+ )
+
+ // Witness: gate read, POST, conflict re-read, in that order.
+ const reads = coreApi.readNamespacedService.mock.invocationCallOrder
+ const post = coreApi.createNamespacedService.mock.invocationCallOrder[0]
+ expect(coreApi.readNamespacedService).toHaveBeenCalledTimes(2)
+ expect(reads[0]).toBeLessThan(post)
+ expect(post).toBeLessThan(reads[1])
+ expect(errorLog).toHaveBeenCalledWith(
+ 'Failed to delegate workload',
+ expect.objectContaining({
+ error: expect.objectContaining({
+ name: 'RetryableReconcileError',
+ message: expect.stringContaining(
+ 'disappeared after create conflict; a fresh reconciliation is required'
+ ),
+ }),
+ })
+ )
+ expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(0)
+ } finally {
+ errorLog.mockRestore()
+ }
+ })
+
+ it('does not write a replaced transport Service again on the next pass', async () => {
+ const { deps, coreApi, clear } = serviceDeps()
+ await delegateTransportWorkloads(deps, makeRecipe(), NS, new Map())
+ const changed = makeRecipe()
+ changed.spec.workloads![0].port = 3100
+ await delegateTransportWorkloads(deps, changed, NS, new Map())
+ expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(1)
+ clear()
+
+ await delegateTransportWorkloads(deps, changed, NS, new Map())
+
+ // Witness: the gate read the replaced Service before deciding not to write.
+ expect(coreApi.readNamespacedService).toHaveBeenCalledTimes(1)
+ expect(coreApi.readNamespacedService).toHaveBeenCalledWith({ name: NAME, namespace: NS })
+ expect(coreApi.createNamespacedService).toHaveBeenCalledTimes(0)
+ expect(coreApi.replaceNamespacedService).toHaveBeenCalledTimes(0)
+ })
})
diff --git a/workflow-recipes/src/reconciler/mcpDelegation.ts b/workflow-recipes/src/reconciler/mcpDelegation.ts
index efc6e9352..b898560f7 100644
--- a/workflow-recipes/src/reconciler/mcpDelegation.ts
+++ b/workflow-recipes/src/reconciler/mcpDelegation.ts
@@ -24,7 +24,7 @@ import { createLogger } from '../observability/logger'
import type { Logger } from '../observability/logger'
import { WorkflowRecipeCRD, WorkloadDef } from '../types'
import { CRD_GROUP, CRD_VERSION } from './crdConstants'
-import { getErrorCode } from './k8sErrors'
+import { ResourceVanishedAfterConflictError, getErrorCode } from './k8sErrors'
import {
ownerRef,
resolveWorkloadResourceName,
@@ -32,7 +32,7 @@ import {
workloadLabels,
} from './resourceBuilder'
import type { SecretAccess } from './resourceBuilder'
-import { specHashUnchanged, stampSpecHash } from './specHash'
+import { controllerOwnerUidMatches, specHashUnchanged, stampSpecHash } from './specHash'
import { effectiveWorkflowContextRef, privateWorkflowContextName } from './workflowContext'
// ─── Constants ───────────────────────────────────────────────────────
@@ -588,8 +588,11 @@ export function buildTransportService(
* alone, so a steady-state reconcile sends neither POST nor PUT. An absent
* Service is created; a 409 on that create means another writer got there
* between the read and the POST, so the gate is re-evaluated against the object
- * it wrote. A changed Service is replaced carrying the live resourceVersion and
- * clusterIP (spec.clusterIP is immutable once assigned).
+ * it wrote; if that object is already gone, a retryable error asks for a fresh
+ * pass. A changed Service is replaced carrying the live resourceVersion and
+ * clusterIP (spec.clusterIP is immutable once assigned). Any read failure other
+ * than a 404 propagates: the replace needs the live resourceVersion and
+ * clusterIP, which a failed read cannot provide.
*/
async function ensureTransportService(
deps: DelegationDeps,
@@ -616,11 +619,18 @@ async function ensureTransportService(
} catch (error) {
if (getErrorCode(error) !== 409) throw error
}
- existing = await deps.coreApi.readNamespacedService({ name, namespace })
+ try {
+ existing = await deps.coreApi.readNamespacedService({ name, namespace })
+ } catch (error) {
+ if (getErrorCode(error) !== 404) throw error
+ throw new ResourceVanishedAfterConflictError(`transport Service "${name}" in ${namespace}`, {
+ cause: error,
+ })
+ }
}
- if (specHashUnchanged(svc, existing)) {
- log.debug('Transport Service unchanged; skipping update', { service: name })
+ if (specHashUnchanged(svc, existing) && controllerOwnerUidMatches(svc, existing)) {
+ log.info('Transport Service unchanged; skipping update', { service: name })
return
}
diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.ts
index c5b9c87e0..fbb200aa6 100644
--- a/workflow-recipes/src/reconciler/reconciler.test.ts
+++ b/workflow-recipes/src/reconciler/reconciler.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as k8s from '@kubernetes/client-node'
+import { ObjectSerializer } from '@kubernetes/client-node/dist/gen/models/ObjectSerializer'
import { loadAll } from 'js-yaml'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
@@ -1131,6 +1132,13 @@ describe('WorkflowRecipeReconciler', () => {
}
const first = await rec.reconcile({ ...recipe, status: { phase: 'active' } })
expect(first.phase, `${lane}/${failure}`).toBe('degraded')
+ if (failure === 'read-disappearance') {
+ // The UI lane replaces through applyOwnedRecipeNetworkPolicy; the
+ // workload lane converges through its own create-conflict path.
+ expect(first.message, `${lane}/${failure}`).toMatch(
+ lane === 'ui' ? /disappeared before replace/ : /still absent after create conflict/
+ )
+ }
expect(first.requeueAfterMs).toBe(TRANSIENT_REQUEUE_BASE_MS)
await rec.patchStatus(recipe, first)
const persisted =
@@ -1470,7 +1478,7 @@ describe('WorkflowRecipeReconciler', () => {
it('does not requeue at a fixed interval', async () => {
const result = await reconcileAwaitingPolicy()
- expect(result.requeueFixedInterval).not.toBe(true)
+ expect(result.requeueFixedInterval).toBe(false)
})
it('still requeues, on the transient backoff base', async () => {
@@ -2684,6 +2692,42 @@ describe('WorkflowRecipeReconciler', () => {
expect(mockAppsApi.replaceNamespacedDeployment).toHaveBeenCalledTimes(0)
})
+ it('sends no PUT when another writer created the desired Deployment between read and POST', async () => {
+ const recipe = makeRecipe()
+ const store = deploymentStore()
+ await ensureDeployment(recipe.spec.workloads![0], recipe)
+ const live = store.live()!
+ mockAppsApi.readNamespacedDeployment.mockClear()
+ mockAppsApi.createNamespacedDeployment.mockClear()
+ mockAppsApi.replaceNamespacedDeployment.mockClear()
+ // The gate read misses the object the other writer is about to create.
+ mockAppsApi.readNamespacedDeployment.mockRejectedValueOnce({ code: 404 })
+
+ await ensureDeployment(recipe.spec.workloads![0], recipe)
+
+ expect(mockAppsApi.createNamespacedDeployment).toHaveBeenCalledTimes(1)
+ // Witness: the conflict re-read the winner before deciding not to write.
+ expect(mockAppsApi.readNamespacedDeployment).toHaveBeenCalledTimes(2)
+ expect(mockAppsApi.readNamespacedDeployment).toHaveBeenLastCalledWith({
+ name: live.metadata.name,
+ namespace: live.metadata.namespace,
+ })
+ expect(mockAppsApi.replaceNamespacedDeployment).toHaveBeenCalledTimes(0)
+ })
+
+ it('creates a Deployment whose gate read resolves to nothing', async () => {
+ const recipe = makeRecipe()
+ const store = deploymentStore()
+ mockAppsApi.readNamespacedDeployment.mockResolvedValueOnce(null)
+
+ await ensureDeployment(recipe.spec.workloads![0], recipe)
+
+ expect(mockAppsApi.readNamespacedDeployment).toHaveBeenCalledTimes(1)
+ expect(mockAppsApi.createNamespacedDeployment).toHaveBeenCalledTimes(1)
+ expect(store.live()).not.toBeNull()
+ expect(mockAppsApi.replaceNamespacedDeployment).toHaveBeenCalledTimes(0)
+ })
+
// The POST is mocked to 409 only so that the pre-read-first code reaches
// the gate at all; with the read first, it must never be sent.
it('propagates an unclassifiable gate-read error and writes nothing', async () => {
@@ -2725,6 +2769,7 @@ describe('WorkflowRecipeReconciler', () => {
it.each([
['an apiserver 500', { code: 500 }],
+ ['an apiserver 403', { code: 403 }],
[
'a transport reset',
Object.assign(new Error('connect ECONNRESET 10.0.0.1:443'), { code: 'ECONNRESET' }),
@@ -2861,6 +2906,159 @@ describe('WorkflowRecipeReconciler', () => {
expect(postsOf(mockCoreApi.createNamespacedConfigMap, name)).toBe(0)
expect(putsOf(mockCoreApi.replaceNamespacedConfigMap, name)).toBe(0)
})
+
+ describe('a resource ConfigMap that vanished between create conflict and re-read', () => {
+ const res = { id: 'cfg', type: 'configmap' as const, data: { k: 'v' } }
+ const recipe = () =>
+ makeRecipe({
+ spec: {
+ workloads: [
+ { id: 'app', type: 'deployment', image: 'nginx:1.30.1-alpine', port: 8080 },
+ ],
+ resources: [res],
+ },
+ })
+ // Both the gate read and the conflict re-read miss the ConfigMap, while
+ // the POST between them collides with an object that is gone again.
+ const vanishAfterConflict = async (r: WorkflowRecipeCRD) => {
+ const name = (await import('./resourceBuilder')).resolveResourceName(r, res.id)
+ const storeRead = mockCoreApi.readNamespacedConfigMap.getMockImplementation()!
+ const storeCreate = mockCoreApi.createNamespacedConfigMap.getMockImplementation()!
+ mockCoreApi.readNamespacedConfigMap.mockImplementation(
+ async (args: { name: string; namespace: string }) => {
+ if (args.name === name) throw { code: 404 }
+ return storeRead(args)
+ }
+ )
+ mockCoreApi.createNamespacedConfigMap.mockImplementation(async (args: CreateArgs) => {
+ if (args.body.metadata.name === name) throw { code: 409 }
+ return storeCreate(args)
+ })
+ return name
+ }
+
+ it('raises a retryable error without attempting a PUT', async () => {
+ const r = recipe()
+ const name = await vanishAfterConflict(r)
+ clearServiceAndConfigMapCalls()
+
+ await expect(
+ (
+ reconciler as unknown as {
+ ensureConfigMap: (r: unknown, recipe: WorkflowRecipeCRD) => Promise<void>
+ }
+ ).ensureConfigMap(res, r)
+ ).rejects.toMatchObject({
+ name: 'RetryableReconcileError',
+ message: expect.stringContaining(
+ 'disappeared after create conflict; a fresh reconciliation is required'
+ ),
+ })
+
+ // Witness: gate read, POST, conflict re-read, in that order.
+ const reads = mockCoreApi.readNamespacedConfigMap.mock.invocationCallOrder
+ const post = mockCoreApi.createNamespacedConfigMap.mock.invocationCallOrder[0]
+ expect(mockCoreApi.readNamespacedConfigMap).toHaveBeenCalledTimes(2)
+ expect(reads[0]).toBeLessThan(post)
+ expect(post).toBeLessThan(reads[1])
+ expect(postsOf(mockCoreApi.createNamespacedConfigMap, name)).toBe(1)
+ expect(putsOf(mockCoreApi.replaceNamespacedConfigMap, name)).toBe(0)
+ })
+
+ it('degrades the recipe with a requeue instead of failing it', async () => {
+ const r = recipe()
+ const name = await vanishAfterConflict(r)
+
+ const result = await reconciler.reconcile(r)
+
+ expect(postsOf(mockCoreApi.createNamespacedConfigMap, name)).toBe(1)
+ expect(putsOf(mockCoreApi.replaceNamespacedConfigMap, name)).toBe(0)
+ expect(result.phase).toBe('degraded')
+ expect(result.message).toContain('disappeared after create conflict')
+ expect(result.requeueAfterMs).toBe(TRANSIENT_REQUEUE_BASE_MS)
+ })
+ })
+
+ it('refuses to replace a changed resource ConfigMap owned by another recipe', async () => {
+ const res = { id: 'cfg', type: 'configmap' as const, data: { k: 'v' } }
+ const recipe = makeRecipe({
+ spec: {
+ workloads: [
+ { id: 'app', type: 'deployment', image: 'nginx:1.30.1-alpine', port: 8080 },
+ ],
+ resources: [res],
+ },
+ })
+ const ensureConfigMap = () =>
+ (
+ reconciler as unknown as {
+ ensureConfigMap: (r: unknown, recipe: WorkflowRecipeCRD) => Promise<void>
+ }
+ ).ensureConfigMap(res, recipe)
+ await ensureConfigMap()
+ const created = onlyPost(mockCoreApi.createNamespacedConfigMap)
+ const name = created.body.metadata.name
+ clearServiceAndConfigMapCalls()
+ // A ConfigMap under the same physical name, labelled for another recipe
+ // and without this manifest's hash, so the gate takes the changed path.
+ mockCoreApi.readNamespacedConfigMap.mockResolvedValue({
+ metadata: {
+ name,
+ namespace: created.namespace,
+ resourceVersion: '4',
+ labels: { 'clerum.io/recipe': 'other-recipe' },
+ },
+ data: { k: 'foreign' },
+ })
+
+ await expect(ensureConfigMap()).rejects.toThrow('not owned by WorkflowRecipe')
+
+ // Witness: the gate read the foreign object and refused it before the
+ // replace path could read it again.
+ expect(readsOf(mockCoreApi.readNamespacedConfigMap, name, created.namespace)).toBe(1)
+ expect(postsOf(mockCoreApi.createNamespacedConfigMap, name)).toBe(0)
+ expect(putsOf(mockCoreApi.replaceNamespacedConfigMap, name)).toBe(0)
+ })
+
+ it('refuses a hash-matching ConfigMap labelled for another recipe instead of treating it as unchanged', async () => {
+ const res = { id: 'cfg', type: 'configmap' as const, data: { k: 'v' } }
+ const recipe = makeRecipe({
+ spec: {
+ workloads: [
+ { id: 'app', type: 'deployment', image: 'nginx:1.30.1-alpine', port: 8080 },
+ ],
+ resources: [res],
+ },
+ })
+ const ensureConfigMap = () =>
+ (
+ reconciler as unknown as {
+ ensureConfigMap: (r: unknown, recipe: WorkflowRecipeCRD) => Promise<void>
+ }
+ ).ensureConfigMap(res, recipe)
+ await ensureConfigMap()
+ const created = onlyPost(mockCoreApi.createNamespacedConfigMap)
+ const name = created.body.metadata.name
+ clearServiceAndConfigMapCalls()
+ // The object WRC wrote (spec-hash and controller ownerReference intact),
+ // relabelled for another recipe: the hash alone must not stand in for
+ // ownership.
+ mockCoreApi.readNamespacedConfigMap.mockResolvedValue({
+ ...structuredClone(created.body),
+ metadata: {
+ ...structuredClone(created.body.metadata),
+ resourceVersion: '4',
+ labels: { 'clerum.io/recipe': 'other-recipe' },
+ },
+ })
+
+ await expect(ensureConfigMap()).rejects.toThrow('not owned by WorkflowRecipe')
+
+ // Witness: the gate read the foreign object before refusing it.
+ expect(readsOf(mockCoreApi.readNamespacedConfigMap, name, created.namespace)).toBe(1)
+ expect(postsOf(mockCoreApi.createNamespacedConfigMap, name)).toBe(0)
+ expect(putsOf(mockCoreApi.replaceNamespacedConfigMap, name)).toBe(0)
+ })
})
describe('read-first apply of resource Secrets', () => {
@@ -2972,6 +3170,37 @@ describe('WorkflowRecipeReconciler', () => {
expect(putsOf(mockCoreApi.replaceNamespacedSecret, name)).toBe(0)
})
+ it('keeps a generated-key Secret created by a racing writer without claiming an update', async () => {
+ const res: SecretRes = { id: 'creds', type: 'secret', generateKeys: ['password'] }
+ const recipe = recipeWith(res)
+ await ensureSecret(res, recipe)
+ const created = onlyPost()
+ const name = created.body.metadata.name
+ const before = await readLive(name, created.namespace)
+ clearSecretCalls()
+ // The read misses; the POST then finds the Secret another writer created.
+ mockCoreApi.readNamespacedSecret.mockRejectedValueOnce({ code: 404 })
+ const infoLog = captureLogger('info')
+ try {
+ await ensureSecret(res, recipe)
+
+ // Witness: the missed read, the POST and the conflict re-read all ran.
+ expect(readsOf(mockCoreApi.readNamespacedSecret, name, created.namespace)).toBe(2)
+ expect(postsOf(mockCoreApi.createNamespacedSecret, name)).toBe(1)
+ expect(putsOf(mockCoreApi.replaceNamespacedSecret, name)).toBe(0)
+ const label = `Secret "creds" in ${created.namespace}`
+ expect(infoLog).toHaveBeenCalledWith(
+ 'Secret with generated keys exists; keeping its keys',
+ { label }
+ )
+ expect(infoLog).not.toHaveBeenCalledWith('Updated resource', { label })
+ const after = await readLive(name, created.namespace)
+ expect(after.data).toEqual(before.data)
+ } finally {
+ infoLog.mockRestore()
+ }
+ })
+
it('sends neither POST nor PUT for an unchanged user-data Secret', async () => {
const res: SecretRes = { id: 'api', type: 'secret', data: { token: 'v1' } }
const recipe = recipeWith(res)
@@ -3438,8 +3667,9 @@ describe('WorkflowRecipeReconciler', () => {
expect(createdBody!.metadata.annotations[SPEC_HASH]).toBeDefined()
// Second apply: the read-first gate finds the object with the SAME hash.
+ // The apiserver returns the metadata WRC wrote, controller ownerReference included.
mockBatchApi.readNamespacedCronJob.mockClear().mockResolvedValue({
- metadata: { resourceVersion: '9', annotations: createdBody!.metadata.annotations },
+ metadata: { ...createdBody!.metadata, resourceVersion: '9' },
spec: createdBody!.spec,
})
mockBatchApi.createNamespacedCronJob.mockClear()
@@ -3475,8 +3705,9 @@ describe('WorkflowRecipeReconciler', () => {
expect(createdBody!.metadata.annotations[SPEC_HASH]).toBeDefined()
// Second apply: the read-first gate finds the object with the SAME hash.
+ // The apiserver returns the metadata WRC wrote, controller ownerReference included.
mockBatchApi.readNamespacedJob.mockClear().mockResolvedValue({
- metadata: { resourceVersion: '9', annotations: createdBody!.metadata.annotations },
+ metadata: { ...createdBody!.metadata, resourceVersion: '9' },
spec: createdBody!.spec,
})
mockBatchApi.createNamespacedJob.mockClear()
@@ -3512,8 +3743,9 @@ describe('WorkflowRecipeReconciler', () => {
expect(createdBody!.metadata.annotations[SPEC_HASH]).toBeDefined()
// Second apply: the read-first gate finds the object with the SAME hash.
+ // The apiserver returns the metadata WRC wrote, controller ownerReference included.
mockAppsApi.readNamespacedDaemonSet.mockClear().mockResolvedValue({
- metadata: { resourceVersion: '9', annotations: createdBody!.metadata.annotations },
+ metadata: { ...createdBody!.metadata, resourceVersion: '9' },
spec: createdBody!.spec,
})
mockAppsApi.createNamespacedDaemonSet.mockClear()
@@ -8875,7 +9107,7 @@ describe('WorkflowRecipeReconciler', () => {
})
)
expect(result.requeueAfterMs).toBe(WORKFLOW_PROGRESS_REQUEUE_BASE_MS)
- expect(result.requeueFixedInterval).not.toBe(true)
+ expect(result.requeueFixedInterval).toBe(false)
})
it('degrades (retryable) workflow transport workloads when child McpServer pre-deploy fails', async () => {
@@ -11699,7 +11931,7 @@ describe('WorkflowRecipeReconciler', () => {
it('refuses to replace a homonymous policy not owned by the exact recipe', async () => {
stubSteadyWorkflowRuntime()
- mockNetworkingApi.createNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 409 })
+ // The read-first gate finds the homonymous policy; no create is attempted.
mockNetworkingApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
metadata: {
name: 'gfs-policy-workflow-coordinator-to-gfs',
@@ -11712,13 +11944,24 @@ describe('WorkflowRecipeReconciler', () => {
await expect(
reconciler.reconcile(activeWorkflow([{ drive: 'main', target: 'published-results' }]))
).rejects.toThrow('existing policy is not owned by WRC')
+ // Witness: the gate read the policy by name before refusing it.
+ expect(mockNetworkingApi.readNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'gfs-policy-workflow-coordinator-to-gfs',
+ namespace: 'sandbox-recipes',
+ })
+ expect(
+ postsOf(
+ mockNetworkingApi.createNamespacedNetworkPolicy,
+ 'gfs-policy-workflow-coordinator-to-gfs'
+ )
+ ).toBe(0)
expect(mockNetworkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
it('replaces the exact owned coordinator GFS policy with its live resourceVersion', async () => {
stubSteadyWorkflowRuntime()
- mockNetworkingApi.createNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 409 })
+ // The read-first gate finds an owned policy without the desired spec.
mockNetworkingApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
metadata: {
name: 'gfs-policy-workflow-coordinator-to-gfs',
@@ -11740,28 +11983,12 @@ describe('WorkflowRecipeReconciler', () => {
}),
}),
})
- })
-
- it('does not replace an already-converged owned policy', async () => {
- stubSteadyWorkflowRuntime()
- const existing = buildCoordinatorGfsNetworkPolicy({
- recipeName: 'gfs-policy-workflow',
- sandboxNamespace: 'sandbox-recipes',
- })
- existing.metadata = {
- ...existing.metadata,
- uid: 'uid-owned-policy',
- resourceVersion: '7',
- }
- mockNetworkingApi.createNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 409 })
- mockNetworkingApi.readNamespacedNetworkPolicy.mockResolvedValueOnce(existing)
-
- const result = await reconciler.reconcile(
- activeWorkflow([{ drive: 'main', target: 'published-results' }])
- )
-
- expect(result).toMatchObject({ phase: 'active', message: 'Workflow running' })
- expect(mockNetworkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(
+ postsOf(
+ mockNetworkingApi.createNamespacedNetworkPolicy,
+ 'gfs-policy-workflow-coordinator-to-gfs'
+ )
+ ).toBe(0)
})
describe('read-first apply of the coordinator GFS policy', () => {
@@ -11822,6 +12049,120 @@ describe('WorkflowRecipeReconciler', () => {
fn.mockClear()
}
}
+ // The gate read misses the policy another writer is about to create, so
+ // the pass takes the POST, gets a 409 and re-reads the race winner.
+ const missFirstGfsPolicyRead = () => {
+ const storeRead = mockNetworkingApi.readNamespacedNetworkPolicy.getMockImplementation()!
+ let missed = false
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockImplementation(
+ async (args: { name: string; namespace: string }) => {
+ if (args.name === gfsPolicyName && !missed) {
+ missed = true
+ throw { code: 404 }
+ }
+ return storeRead(args)
+ }
+ )
+ }
+
+ it('skips the PUT when the live spec matches in apiserver key order', async () => {
+ const infoLog = captureLogger('info')
+ try {
+ stubSteadyWorkflowRuntime()
+ const desired = buildCoordinatorGfsNetworkPolicy({
+ recipeName: 'gfs-policy-workflow',
+ sandboxNamespace: 'sandbox-recipes',
+ })
+ // A real read is deserialized by client-node, which rebuilds every
+ // object in its attributeTypeMap key order, not the builder's order.
+ const read = ObjectSerializer.deserialize(
+ JSON.parse(JSON.stringify(desired)),
+ 'V1NetworkPolicy',
+ ''
+ ) as k8s.V1NetworkPolicy
+ read.metadata = { ...read.metadata, uid: 'uid-owned-policy', resourceVersion: '7' }
+ expect(JSON.stringify(read.spec)).not.toBe(JSON.stringify(desired.spec))
+ installGfsPolicyStore(read)
+ clearPolicyCalls()
+
+ await reconciler.reconcile(activeWorkflow(publishTargets))
+
+ // Witness: the gate read the policy and chose the skip branch.
+ expect(
+ readsOf(mockNetworkingApi.readNamespacedNetworkPolicy, gfsPolicyName, 'sandbox-recipes')
+ ).toBe(1)
+ expect(infoLog).toHaveBeenCalledWith(
+ 'NetworkPolicy matches desired state; skipping update',
+ { label: `NetworkPolicy "${gfsPolicyName}" in sandbox-recipes` }
+ )
+ expect(postsOf(mockNetworkingApi.createNamespacedNetworkPolicy, gfsPolicyName)).toBe(0)
+ expect(putsOf(mockNetworkingApi.replaceNamespacedNetworkPolicy, gfsPolicyName)).toBe(0)
+ } finally {
+ infoLog.mockRestore()
+ }
+ })
+
+ it('refuses a race winner owned elsewhere without writing it', async () => {
+ stubSteadyWorkflowRuntime()
+ installGfsPolicyStore({
+ metadata: {
+ name: gfsPolicyName,
+ uid: 'uid-foreign-policy',
+ resourceVersion: '7',
+ labels: { 'clerum.io/managed-by': 'operator', 'clerum.io/recipe': 'other-recipe' },
+ },
+ })
+ missFirstGfsPolicyRead()
+ clearPolicyCalls()
+
+ await expect(reconciler.reconcile(activeWorkflow(publishTargets))).rejects.toThrow(
+ 'existing policy is not owned by WRC'
+ )
+
+ // Witness: the gate read, the POST and the conflict re-read all ran.
+ expect(
+ readsOf(mockNetworkingApi.readNamespacedNetworkPolicy, gfsPolicyName, 'sandbox-recipes')
+ ).toBe(2)
+ expect(postsOf(mockNetworkingApi.createNamespacedNetworkPolicy, gfsPolicyName)).toBe(1)
+ expect(putsOf(mockNetworkingApi.replaceNamespacedNetworkPolicy, gfsPolicyName)).toBe(0)
+ })
+
+ it('sends no PUT when the race winner is the converged owned policy', async () => {
+ stubSteadyWorkflowRuntime()
+ const converged = buildCoordinatorGfsNetworkPolicy({
+ recipeName: 'gfs-policy-workflow',
+ sandboxNamespace: 'sandbox-recipes',
+ })
+ converged.metadata = {
+ ...converged.metadata,
+ uid: 'uid-owned-policy',
+ resourceVersion: '7',
+ }
+ installGfsPolicyStore(converged)
+ missFirstGfsPolicyRead()
+ clearPolicyCalls()
+ const infoLog = captureLogger('info')
+ try {
+ const result = await reconciler.reconcile(activeWorkflow(publishTargets))
+
+ expect(result).toMatchObject({ phase: 'active', message: 'Workflow running' })
+ // Witness: the gate read, the POST and the conflict re-read all ran.
+ expect(
+ readsOf(mockNetworkingApi.readNamespacedNetworkPolicy, gfsPolicyName, 'sandbox-recipes')
+ ).toBe(2)
+ expect(postsOf(mockNetworkingApi.createNamespacedNetworkPolicy, gfsPolicyName)).toBe(1)
+ expect(putsOf(mockNetworkingApi.replaceNamespacedNetworkPolicy, gfsPolicyName)).toBe(0)
+ // The skip log is the witness that the conflict path ran; no update is claimed.
+ const label = `NetworkPolicy "${gfsPolicyName}" in sandbox-recipes`
+ expect(infoLog).toHaveBeenCalledWith(
+ 'NetworkPolicy matches desired state; skipping update',
+ { label }
+ )
+ expect(infoLog).not.toHaveBeenCalledWith('Updated resource', { label })
+ } finally {
+ infoLog.mockRestore()
+ }
+ })
it('sends neither POST nor PUT for a converged policy on the next pass', async () => {
stubSteadyWorkflowRuntime()
@@ -13054,6 +13395,53 @@ describe('WorkflowRecipeReconciler', () => {
expect(postsOf(api.create, gateway)).toBe(0)
expect(putsOf(api.replace, gateway)).toBe(0)
})
+
+ // The gateway Service is the object whose name and spec do not depend on
+ // the recipe uid (the handler names and the gateway Deployment do), so a
+ // recreated recipe leaves its spec hash equal and only the owner uid moves.
+ it('rewrites a hash-unchanged gateway Service whose controller ownerReference uid no longer matches the recipe', async () => {
+ const api = {
+ read: mockCoreApi.readNamespacedService,
+ create: mockCoreApi.createNamespacedService,
+ replace: mockCoreApi.replaceNamespacedService,
+ }
+ const clearCalls = () => {
+ api.read.mockClear()
+ api.create.mockClear()
+ api.replace.mockClear()
+ }
+ const controllerUid = (body: k8s.V1Service) =>
+ body.metadata?.ownerReferences?.find(ref => ref.controller)?.uid
+
+ // recipeWithWebhook() reinstalls the Deployment store, so it is called once.
+ const previous = recipeWithWebhook()
+ const recreated = structuredClone(previous)
+ previous.metadata.uid = 'uid-old'
+ recreated.metadata.uid = 'uid-new'
+ await reconciler.reconcile(previous)
+ expect(postsOf(api.create, gateway)).toBe(1)
+ clearCalls()
+
+ await reconciler.reconcile(recreated)
+
+ const puts = api.replace.mock.calls.filter(
+ ([arg]) => (arg as { name: string }).name === gateway
+ )
+ expect(puts).toHaveLength(1)
+ const body = (puts[0][0] as { body: k8s.V1Service }).body
+ expect(controllerUid(body)).toBe('uid-new')
+ expect(body.spec?.clusterIP).toBe(LIVE_CLUSTER_IP)
+ // The gate read, then the replace read for resourceVersion and clusterIP.
+ expect(readsOf(api.read, gateway, ns)).toBe(2)
+ expect(postsOf(api.create, gateway)).toBe(0)
+ clearCalls()
+
+ await reconciler.reconcile(recreated)
+
+ expect(readsOf(api.read, gateway, ns)).toBe(1)
+ expect(postsOf(api.create, gateway)).toBe(0)
+ expect(putsOf(api.replace, gateway)).toBe(0)
+ })
})
it('T6 (#575) converges the 3 gateway NetworkPolicies through live reads', async () => {
diff --git a/workflow-recipes/src/reconciler/specHash.test.ts b/workflow-recipes/src/reconciler/specHash.test.ts
index a767adf7f..53d7bc627 100644
--- a/workflow-recipes/src/reconciler/specHash.test.ts
+++ b/workflow-recipes/src/reconciler/specHash.test.ts
@@ -4,6 +4,7 @@ import {
HASH_EXCLUDED_ANNOTATIONS,
SPEC_HASH_ANNOTATION,
computeSpecHash,
+ controllerOwnerUidMatches,
specHashUnchanged,
stampSpecHash,
} from './specHash'
@@ -132,3 +133,27 @@ describe('specHashUnchanged', () => {
expect(specHashUnchanged(desired, null)).toBe(false)
})
})
+
+describe('controllerOwnerUidMatches', () => {
+ const owned = (uid: string, controller = true) => ({
+ metadata: { ownerReferences: [{ controller, uid }] },
+ })
+
+ it('matches when both sides name the same controller owner uid', () => {
+ expect(controllerOwnerUidMatches(owned('uid-a'), owned('uid-a'))).toBe(true)
+ })
+
+ it('does not match when the controller owner uid differs', () => {
+ expect(controllerOwnerUidMatches(owned('uid-new'), owned('uid-old'))).toBe(false)
+ })
+
+ it('does not match when only one side has a controller owner', () => {
+ expect(controllerOwnerUidMatches(owned('uid-a'), { metadata: {} })).toBe(false)
+ expect(controllerOwnerUidMatches({ metadata: {} }, owned('uid-a'))).toBe(false)
+ })
+
+ it('matches when neither side has a controller owner', () => {
+ expect(controllerOwnerUidMatches({ metadata: {} }, { metadata: {} })).toBe(true)
+ expect(controllerOwnerUidMatches(owned('uid-a', false), owned('uid-b', false))).toBe(true)
+ })
+})
diff --git a/workflow-recipes/src/reconciler/specHash.ts b/workflow-recipes/src/reconciler/specHash.ts
index 40df77839..bc8943d2f 100644
--- a/workflow-recipes/src/reconciler/specHash.ts
+++ b/workflow-recipes/src/reconciler/specHash.ts
@@ -133,3 +133,38 @@ export function specHashUnchanged(
const existingHash = existing?.metadata?.annotations?.[SPEC_HASH_ANNOTATION]
return Boolean(existingHash && desiredHash === existingHash)
}
+
+type ControllerOwnedManifest = {
+ metadata?: { ownerReferences?: Array<{ controller?: boolean; uid?: string }> }
+}
+
+/**
+ * The metadata a read-first apply gate reads: the spec hash, the controller
+ * owner, and the labels an ownership check inspects.
+ */
+export type GatedManifest = {
+ metadata?: {
+ annotations?: { [key: string]: string }
+ labels?: { [key: string]: string }
+ ownerReferences?: Array<{ controller?: boolean; uid?: string }>
+ }
+}
+
+/**
+ * True when `desired` and `existing` name the same controller owner uid, or
+ * neither has a controller owner. ownerReferences stay out of the spec hash
+ * (the apiserver assigns the uid, and a cross-namespace manifest drops them),
+ * so a recipe deleted and recreated under the same name leaves the hash equal
+ * while the live object still points at the old uid. Garbage collection would
+ * then delete that object once the old owner is gone; comparing the uid makes
+ * the gate write the new ownerReference instead. Same criterion as the
+ * Secret comparison in the reconciler.
+ */
+export function controllerOwnerUidMatches(
+ desired: ControllerOwnedManifest,
+ existing: ControllerOwnedManifest | null | undefined
+): boolean {
+ const controllerUid = (manifest: ControllerOwnedManifest | null | undefined) =>
+ manifest?.metadata?.ownerReferences?.find(ref => ref.controller)?.uid
+ return controllerUid(desired) === controllerUid(existing)
+}
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index 4b3c90294..38aa7dbfe 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -90,7 +90,12 @@ import {
buildInternalDependencyEgressNetworkPolicy,
buildInternalDependencyIngressNetworkPolicy,
} from './internalDependencyNetworkPolicies'
-import { getErrorCode, isRetryableInfraError } from './k8sErrors'
+import {
+ ResourceVanishedAfterConflictError,
+ RetryableReconcileError,
+ getErrorCode,
+ isRetryableInfraError,
+} from './k8sErrors'
import {
DelegationDeps,
cleanupDelegation,
@@ -133,7 +138,13 @@ import {
parseSecretOwnership,
} from './secretOwnership'
import { SecretReverseIndex } from './secretReverseIndex'
-import { SPEC_HASH_ANNOTATION, specHashUnchanged, stampSpecHash } from './specHash'
+import {
+ type GatedManifest,
+ SPEC_HASH_ANNOTATION,
+ controllerOwnerUidMatches,
+ specHashUnchanged,
+ stampSpecHash,
+} from './specHash'
import { isTerminal, transition } from './stateMachine'
import {
buildWebhookGatewayResources,
@@ -152,6 +163,11 @@ const PARENT_RECIPE_LABEL = 'clerum.io/parent-recipe'
const WORKFLOW_RUN_ID_LABEL = 'clerum.io/workflow-run-id'
const WORKFLOW_ACTOR_ID_LABEL = 'clerum.io/workflow-actor-id'
const WORKFLOW_ACTOR_TYPE_LABEL = 'clerum.io/workflow-actor-type'
+/**
+ * Returned by a replaceFn that re-read the live object after a 409 and chose not
+ * to write it; `replaceResource` then skips its "Updated resource" log.
+ */
+const NO_WRITE = Symbol('no-write')
export const TRANSPORT_NETWORK_CONDITION_TYPE = 'TransportExternalEgressReady'
const TRANSPORT_NETWORK_CONDITION_TYPES = new Set([TRANSPORT_NETWORK_CONDITION_TYPE])
@@ -499,28 +515,9 @@ function validateWorkloadBindings(
})
}
-/**
- * Thrown by a reconcile step that failed for a transient reason (e.g. a DNS
- * SERVFAIL/timeout while resolving egress FQDNs) rather than a permanent
- * misconfiguration. The top-level reconcile catch maps this to the non-terminal
- * `degraded` phase so the periodic reconcile retries and the recipe self-heals
- * once the underlying dependency recovers — instead of bricking it at the
- * terminal `failed` phase, which is never retried.
- */
-export class RetryableReconcileError extends Error {
- constructor(message: string, options?: { cause?: unknown }) {
- super(message)
- this.name = 'RetryableReconcileError'
- // Preserve the underlying error so logs (and any `.cause`-walking
- // classifier such as isRetryableInfraError's collectSocketCodes) can still
- // see the original transport/HTTP signal even though we re-message it for
- // the recipe status. Re-wrapping with `: ${String(error)}` alone would
- // flatten the chain and discard `.code`/`.cause`.
- if (options && 'cause' in options) {
- ;(this as { cause?: unknown }).cause = options.cause
- }
- }
-}
+// Defined in k8sErrors so mcpDelegation can raise it too; re-exported here for
+// the callers that import it from the reconciler.
+export { RetryableReconcileError }
class NetworkPolicyOwnershipConflictError extends Error {
constructor(message: string) {
@@ -4081,8 +4078,10 @@ export class WorkflowRecipeReconciler {
replaceFn: () => Promise<unknown>,
label: string,
idempotency?: {
- manifest: { metadata?: { annotations?: { [key: string]: string } } }
- readExisting: () => Promise<{ metadata?: { annotations?: { [key: string]: string } } } | null>
+ manifest: GatedManifest
+ readExisting: () => Promise<GatedManifest | null>
+ /** Throws when the live object belongs to someone else; runs before the hash compare. */
+ assertOwned?: (existing: GatedManifest) => void
}
): Promise<void> {
if (idempotency) {
@@ -4113,12 +4112,17 @@ export class WorkflowRecipeReconciler {
}
// Without a gate this is the create-first probe. With one, another writer
// created the object between our read and this POST: re-enter the gate.
- if (idempotency && (await this.applyGate(idempotency)) === 'unchanged') {
- createLogger('wrc', 'workflow-recipes').info(
- 'Resource spec hash unchanged; skipping update',
- { label }
- )
- return
+ if (idempotency) {
+ const raced = await this.applyGate(idempotency)
+ if (raced === 'unchanged') {
+ createLogger('wrc', 'workflow-recipes').info(
+ 'Resource spec hash unchanged; skipping update',
+ { label }
+ )
+ return
+ }
+ if (raced === 'absent')
+ throw new ResourceVanishedAfterConflictError(label, { cause: error })
}
await this.replaceResource(replaceFn, label)
}
@@ -4126,7 +4130,7 @@ export class WorkflowRecipeReconciler {
private async replaceResource(replaceFn: () => Promise<unknown>, label: string): Promise<void> {
try {
- await replaceFn()
+ if ((await replaceFn()) === NO_WRITE) return
createLogger('wrc', 'workflow-recipes').info('Updated resource', { label })
} catch (updateError) {
createLogger('wrc', 'workflow-recipes').error('Failed to update resource', {
@@ -4139,7 +4143,10 @@ export class WorkflowRecipeReconciler {
/**
* Read the live object and decide the write: `absent` (404) → create,
- * `unchanged` (it carries the desired spec-hash) → no write, `changed` → replace.
+ * `unchanged` (it carries the desired spec-hash and the same controller owner
+ * uid) → no write, `changed` → replace. When the caller passes `assertOwned`,
+ * it runs on the live object before the hash compare, so a matching hash never
+ * stands in for ownership.
*
* A read failure that carries an apiserver status or a transport signature
* returns `changed` — never skip an update we cannot prove is unnecessary.
@@ -4147,10 +4154,11 @@ export class WorkflowRecipeReconciler {
* and it propagates instead of turning into a silent overwrite.
*/
private async applyGate(idempotency: {
- manifest: { metadata?: { annotations?: { [key: string]: string } } }
- readExisting: () => Promise<{ metadata?: { annotations?: { [key: string]: string } } } | null>
+ manifest: GatedManifest
+ readExisting: () => Promise<GatedManifest | null>
+ assertOwned?: (existing: GatedManifest) => void
}): Promise<'absent' | 'unchanged' | 'changed'> {
- let existing: { metadata?: { annotations?: { [key: string]: string } } } | null
+ let existing: GatedManifest | null
try {
existing = await idempotency.readExisting()
} catch (error) {
@@ -4159,7 +4167,11 @@ export class WorkflowRecipeReconciler {
throw error
}
if (existing == null) return 'absent'
- return specHashUnchanged(idempotency.manifest, existing) ? 'unchanged' : 'changed'
+ idempotency.assertOwned?.(existing)
+ return specHashUnchanged(idempotency.manifest, existing) &&
+ controllerOwnerUidMatches(idempotency.manifest, existing)
+ ? 'unchanged'
+ : 'changed'
}
private stableComparableString(value: unknown): string {
@@ -4687,7 +4699,7 @@ export class WorkflowRecipeReconciler {
ns,
})
} else {
- await this.applyOwnedRecipeNetworkPolicy(policy, ns, recipe.metadata.name, existing)
+ await this.applyOwnedRecipeNetworkPolicy(policy, ns, recipe.metadata.name, existing !== null)
// #299: the policy has landed — record the set it actually enforces.
this.logResolvedEgressSet(
recipe.metadata.name,
@@ -5487,17 +5499,17 @@ export class WorkflowRecipeReconciler {
}
/**
- * `existing` is the live policy the caller already read this pass (or null
- * when there is none). When one exists the create probe is skipped and the
- * replace runs directly; the replace still re-reads and fences on that fresh
- * resourceVersion, because a contraction earlier in the same pass may have
- * written the policy after the caller's snapshot.
+ * `liveExists` says whether the caller's read this pass found the policy.
+ * When it did, the create probe is skipped and the replace runs directly; the
+ * replace still re-reads and fences on that fresh resourceVersion, because a
+ * contraction earlier in the same pass may have written the policy after the
+ * caller's snapshot.
*/
private async applyOwnedRecipeNetworkPolicy(
policy: k8s.V1NetworkPolicy,
namespace: string,
recipeName: string,
- existing: k8s.V1NetworkPolicy | null
+ liveExists: boolean
): Promise<void> {
const policyName = policy.metadata?.name
if (!policyName) throw new Error('Recipe NetworkPolicy requires a name')
@@ -5537,7 +5549,7 @@ export class WorkflowRecipeReconciler {
throwNetworkPolicyMutationError(error, policyName, namespace)
}
}
- if (existing) {
+ if (liveExists) {
await this.replaceResource(replaceLive, label)
return
}
@@ -5970,7 +5982,9 @@ export class WorkflowRecipeReconciler {
const labelsMatch = Object.entries(desiredLabels).every(
([key, value]) => existingLabels[key] === value
)
- return labelsMatch && JSON.stringify(existing.spec) === JSON.stringify(policy.spec)
+ // client-node rebuilds a read object in its own key order, so the spec
+ // comparison must not depend on key order.
+ return labelsMatch && this.equalComparable(existing.spec, policy.spec)
}
const replaceWith = (existing: k8s.V1NetworkPolicy) => {
policy.metadata!.resourceVersion = existing.metadata?.resourceVersion
@@ -6013,7 +6027,13 @@ export class WorkflowRecipeReconciler {
namespace,
})
this.assertCoordinatorGfsNetworkPolicyOwnership(raced, recipe.metadata.name, namespace)
- if (matchesDesired(raced)) return raced
+ if (matchesDesired(raced)) {
+ createLogger('wrc', recipe.metadata.name).info(
+ 'NetworkPolicy matches desired state; skipping update',
+ { label }
+ )
+ return NO_WRITE
+ }
return replaceWith(raced)
},
label
@@ -7184,6 +7204,11 @@ export class WorkflowRecipeReconciler {
// Secret; issue #571), then skip replace to preserve the generated keys.
const existing = await this.coreApi.readNamespacedSecret({ name, namespace: ns })
this.assertExistingResourceOwnedByRecipe(existing, name, res.id, recipe, ns, 'Secret')
+ createLogger('wrc', 'workflow-recipes').info(
+ 'Secret with generated keys exists; keeping its keys',
+ { label }
+ )
+ return NO_WRITE
},
label
)
@@ -7376,13 +7401,13 @@ export class WorkflowRecipeReconciler {
})
},
`ConfigMap "${res.id}" in ${ns}`,
- // An unchanged hash skips the ownership assert along with the write. Only
- // an object carrying this manifest's hash can match, and that hash covers
- // the `clerum.io/recipe` label the assert reads; forging the annotation
- // takes the same access as forging that label.
+ // The gate checks ownership before the hash, so a ConfigMap labelled for
+ // another recipe is refused even when it carries this manifest's hash.
{
manifest,
readExisting: () => this.coreApi.readNamespacedConfigMap({ name, namespace: ns }),
+ assertOwned: existing =>
+ this.assertExistingResourceOwnedByRecipe(existing, name, res.id, recipe, ns, 'ConfigMap'),
}
)
}
diff --git a/workflow-recipes/tests/unit/workflow/workflowReconcilerBifurcation.test.ts b/workflow-recipes/tests/unit/workflow/workflowReconcilerBifurcation.test.ts
index d249886d2..b9b1c7b0f 100644
--- a/workflow-recipes/tests/unit/workflow/workflowReconcilerBifurcation.test.ts
+++ b/workflow-recipes/tests/unit/workflow/workflowReconcilerBifurcation.test.ts
@@ -111,7 +111,8 @@ describe('Workflow Reconciler Bifurcation', () => {
// By default no Secret exists, the state of a freshly approved recipe.
mockCoreApi.createNamespacedSecret.mockReset().mockResolvedValue({})
mockCoreApi.readNamespacedSecret.mockReset().mockRejectedValue({ code: 404 })
- mockAppsApi.readNamespacedDeployment.mockResolvedValue({
+ // Reset so a 404-once queued by a test that failed early cannot leak.
+ mockAppsApi.readNamespacedDeployment.mockReset().mockResolvedValue({
metadata: { resourceVersion: '1', generation: 1 },
spec: { replicas: 1 },
status: { observedGeneration: 1, updatedReplicas: 1, readyReplicas: 1, availableReplicas: 1 },
@@ -245,7 +246,10 @@ describe('Workflow Reconciler Bifurcation', () => {
expect(result.message).toMatch(/Existing PVC "normal-recipe-data-[a-f0-9]{12}"/)
expect(result.message).toContain('is deleting')
expect(result.message).toContain('refusing to mount it')
+ // Read-first apply turns a write of an existing Deployment into a PUT, so
+ // both verbs must stay silent.
expect(mockAppsApi.createNamespacedDeployment).not.toHaveBeenCalled()
+ expect(mockAppsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()
})
it('rejects a pre-existing recipe PVC without matching WRC ownership labels', async () => {
@@ -273,7 +277,10 @@ describe('Workflow Reconciler Bifurcation', () => {
expect(result.phase).toBe('failed')
expect(result.message).toMatch(/Existing PVC "normal-recipe-data-[a-f0-9]{12}"/)
expect(result.message).toContain('refusing to mount a possibly external claim')
+ // Read-first apply turns a write of an existing Deployment into a PUT, so
+ // both verbs must stay silent.
expect(mockAppsApi.createNamespacedDeployment).not.toHaveBeenCalled()
+ expect(mockAppsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()
})
it('adopts a pre-existing raw PVC owned by this recipe into status.resourceInstances (issue #571 F1)', async () => {
@@ -422,7 +429,10 @@ describe('Workflow Reconciler Bifurcation', () => {
expect(result.phase).toBe('failed')
expect(result.message).toContain('security.prepareVolumeOwnership requires security.runAsUser')
+ // Read-first apply turns a write of an existing Deployment into a PUT, so
+ // both verbs must stay silent.
expect(mockAppsApi.createNamespacedDeployment).not.toHaveBeenCalled()
+ expect(mockAppsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()
})
it('rejects prepareVolumeOwnership without a writable volume mount', async () => {
@@ -450,7 +460,10 @@ describe('Workflow Reconciler Bifurcation', () => {
expect(result.message).toContain(
'security.prepareVolumeOwnership requires at least one writable volumeMount'
)
+ // Read-first apply turns a write of an existing Deployment into a PUT, so
+ // both verbs must stay silent.
expect(mockAppsApi.createNamespacedDeployment).not.toHaveBeenCalled()
+ expect(mockAppsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()
})
it('accepts recipes with steps but no workloads (workflow-only)', async () => {
@@ -876,9 +889,15 @@ describe('Workflow Reconciler Bifurcation', () => {
}),
expect.anything()
)
+ // Read-first apply turns a write of an existing object into a PUT, so
+ // every write verb must stay silent.
expect(mockCoreApi.createNamespacedSecret).not.toHaveBeenCalled()
+ expect(mockCoreApi.replaceNamespacedSecret).not.toHaveBeenCalled()
expect(mockAppsApi.createNamespacedStatefulSet).not.toHaveBeenCalled()
+ expect(mockAppsApi.replaceNamespacedStatefulSet).not.toHaveBeenCalled()
expect(mockCoreApi.createNamespacedService).not.toHaveBeenCalled()
+ expect(mockCoreApi.replaceNamespacedService).not.toHaveBeenCalled()
expect(mockCoreApi.createNamespacedConfigMap).not.toHaveBeenCalled()
+ expect(mockCoreApi.replaceNamespacedConfigMap).not.toHaveBeenCalled()
})
})