Skip to content

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

TypeScript

fix(workflow-recipes): one marker writer union and one pass translation (R4-L3)

Alfredo Lopeza54c705c0ac7
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index b0c54174e..029c0e5ff 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.441",
+ "version": "0.1.442",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.441",
+ "version": "0.1.442",
"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 07d28ab83..8115445e9 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.441",
+ "version": "0.1.442",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.ts
index de13328f7..a6c585a54 100644
--- a/workflow-recipes/src/reconciler/reconciler.test.ts
+++ b/workflow-recipes/src/reconciler/reconciler.test.ts
@@ -22,7 +22,7 @@ import { deriveWorkflowRuntimePlan } from '../workflow/runtimePlan'
import {
WorkflowReconciler,
buildNetworkPolicyConvergedCondition,
- translateNetworkPolicyApplySummary,
+ translateNetworkPolicyPassSummary,
} from '../workflow/workflowReconciler'
import { captureLogger, captureLoggerLevels } from './__tests__/captureLogger'
import { defaultFqdnLookup } from './fqdnResolver'
@@ -1326,7 +1326,12 @@ describe('WorkflowRecipeReconciler', () => {
policyReady: true,
verifiedAt: '2026-08-04T00:00:00.000Z',
},
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
const workflowReconcile = vi.fn()
const setCodexReconcileContext = vi.fn()
@@ -1385,7 +1390,12 @@ describe('WorkflowRecipeReconciler', () => {
const reconcilePluginWorkloadSdkOnly = vi.fn().mockResolvedValue({
phase: 'active',
message: 'Plugin Workload SDK mcp-host registered',
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
;(
reconciler as unknown as {
@@ -1425,7 +1435,12 @@ describe('WorkflowRecipeReconciler', () => {
const reconcilePluginWorkloadSdkOnly = vi.fn().mockResolvedValue({
phase: 'deploying',
message: 'Plugin Workload SDK mcp-host starting',
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
;(
reconciler as unknown as {
@@ -1516,6 +1531,8 @@ describe('WorkflowRecipeReconciler', () => {
},
],
retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
},
})
@@ -1540,7 +1557,12 @@ describe('WorkflowRecipeReconciler', () => {
phase: 'active',
message: 'Plugin Workload SDK mcp-host registered',
pluginWorkloadSdkBootstrapProof: bootstrapProof,
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
const result = await reconciler.reconcile(sdkOnlyRecipe([ownershipCondition]))
@@ -1581,6 +1603,8 @@ describe('WorkflowRecipeReconciler', () => {
},
],
retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
},
})
@@ -1602,7 +1626,12 @@ describe('WorkflowRecipeReconciler', () => {
const converged = stubSdkOnly({
phase: 'failed',
message: 'Plugin Workload SDK mcp-host could not start',
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
const failedConverged = await reconciler.reconcile(sdkOnlyRecipe([ownershipCondition]))
@@ -1620,7 +1649,12 @@ describe('WorkflowRecipeReconciler', () => {
phase: 'active',
message: 'Plugin Workload SDK mcp-host registered',
pluginWorkloadSdkBootstrapProof: bootstrapProof,
- networkPolicies: { conflicts: [], retryPending: true },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: true,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
const retrying = await reconciler.reconcile(sdkOnlyRecipe())
@@ -1643,7 +1677,12 @@ describe('WorkflowRecipeReconciler', () => {
phase: 'active',
message: 'Plugin Workload SDK mcp-host registered',
pluginWorkloadSdkBootstrapProof: bootstrapProof,
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
const steady = await reconciler.reconcile(sdkOnlyRecipe())
@@ -1663,7 +1702,12 @@ describe('WorkflowRecipeReconciler', () => {
const pending = stubSdkOnly({
phase: 'failed',
message: 'Plugin Workload SDK mcp-host could not start',
- networkPolicies: { conflicts: [], retryPending: true },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: true,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
const retrying = await reconciler.reconcile(sdkOnlyRecipe())
@@ -1684,7 +1728,12 @@ describe('WorkflowRecipeReconciler', () => {
const settled = stubSdkOnly({
phase: 'failed',
message: 'Plugin Workload SDK mcp-host could not start',
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
const terminal = await reconciler.reconcile(sdkOnlyRecipe())
@@ -1821,7 +1870,12 @@ describe('WorkflowRecipeReconciler', () => {
const reconcilePluginWorkloadSdkOnly = vi.fn().mockResolvedValue({
phase: 'awaiting_policy',
message: 'operator policy pending (policy_not_ready)',
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
;(
reconciler as unknown as {
@@ -16496,7 +16550,7 @@ describe('WorkflowRecipeReconciler', () => {
phase: 'active',
message: 'Workflow running',
workflowPhase: 'running',
- ...translateNetworkPolicyApplySummary(
+ ...translateNetworkPolicyPassSummary(
summary,
currentStatus?.conditions,
new Date().toISOString()
@@ -17437,7 +17491,12 @@ describe('WorkflowRecipeReconciler', () => {
policyReady: true,
verifiedAt: '2026-08-04T00:00:00.000Z',
},
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
;(
reconciler as unknown as { config: { pluginWorkloadSdkEnabled: boolean } }
@@ -17482,7 +17541,12 @@ describe('WorkflowRecipeReconciler', () => {
policyReady: true,
verifiedAt: new Date().toISOString(),
},
- networkPolicies: { conflicts: [], retryPending: false },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
;(
reconciler as unknown as { config: { pluginWorkloadSdkEnabled: boolean } }
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index cff738087..2bca25ed1 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -57,22 +57,22 @@ import { ModelConfigHandler } from '../workflow/modelConfigHandler'
import { buildCoordinatorGfsNetworkPolicy } from '../workflow/networkPolicyFactory'
import type {
EagerSdkBootstrapProof,
+ NetworkPolicyPassSummary,
WorkflowNetworkPolicyApplySummary,
} from '../workflow/pluginWorkloadSdkProvisioner'
import { HttpPluginWorkloadSdkRevocationClient } from '../workflow/pluginWorkloadSdkRevocationClient'
import { deriveWorkflowRuntimePlan } from '../workflow/runtimePlan'
import { validateWorkflowRecipeLimits } from '../workflow/workflowLimits'
import {
- NETWORK_POLICIES_CONVERGED_CONDITION_TYPE,
NETWORK_POLICY_OWNERSHIP_CONDITION_TYPES,
+ type NetworkPolicyMarkerWriter,
WORKFLOW_OUTPUT_CONDITION_TYPES,
WorkflowReconciler,
WorkflowReconcilerDeps,
- buildNetworkPolicyConvergedCondition,
hasNetworkPolicyRetryPendingMarker,
networkPolicyConditionsChanged,
- networkPolicyMarkerFacts,
- translateNetworkPolicyApplySummary,
+ networkPolicyMarkerConditions,
+ translateNetworkPolicyPassSummary,
} from '../workflow/workflowReconciler'
import { evaluateComputedValues } from './computedValuesEvaluator'
import { CRD_GROUP, CRD_VERSION, WORKFLOWRECIPE_PLURAL } from './crdConstants'
@@ -1521,20 +1521,8 @@ export class WorkflowRecipeReconciler {
)
return TRANSIENT_REQUEUE_BASE_MS
}
- const existing = recipe.status?.conditions
- const translated = translateNetworkPolicyApplySummary(
- summary,
- existing,
- new Date().toISOString()
- )
- const fresh = translated.networkPolicyOwnershipConditions ?? []
- if (networkPolicyConditionsChanged(existing, fresh)) {
- await this.publishNetworkPolicyConditions(
- recipe,
- mergeOwnedConditions(existing, fresh, NETWORK_POLICY_OWNERSHIP_CONDITION_TYPES) ?? []
- )
- }
- return translated.networkPolicyRetryPending ? WORKFLOW_PROGRESS_REQUEUE_BASE_MS : undefined
+ await this.publishNetworkPolicyMarkerWriter(recipe, { kind: 'apply-retry', summary })
+ return summary.retryPending ? WORKFLOW_PROGRESS_REQUEUE_BASE_MS : undefined
}
/**
@@ -1547,19 +1535,25 @@ export class WorkflowRecipeReconciler {
* changes.
*/
private async settleNetworkPolicyMarkerForTerminalRun(recipe: WorkflowRecipeCRD): Promise<void> {
+ await this.publishNetworkPolicyMarkerWriter(recipe, { kind: 'terminal' })
+ }
+
+ /**
+ * Publishes the NetworkPolicy condition group `writer` produces, outside
+ * `patchStatus`, for the paths that return before it. Opens a patch only
+ * when the group changes; every other condition is kept.
+ */
+ private async publishNetworkPolicyMarkerWriter(
+ recipe: WorkflowRecipeCRD,
+ writer: NetworkPolicyMarkerWriter
+ ): Promise<void> {
const existing = recipe.status?.conditions
- const { prune } = networkPolicyMarkerFacts(existing)
- const marker = buildNetworkPolicyConvergedCondition(
- { apply: 'converged', prune },
- new Date().toISOString(),
- existing
+ const fresh = networkPolicyMarkerConditions(writer, existing, new Date().toISOString())
+ if (!networkPolicyConditionsChanged(existing, fresh)) return
+ await this.publishNetworkPolicyConditions(
+ recipe,
+ mergeOwnedConditions(existing, fresh, NETWORK_POLICY_OWNERSHIP_CONDITION_TYPES) ?? []
)
- const settled = [
- ...(existing ?? []).filter(c => c.type !== NETWORK_POLICIES_CONVERGED_CONDITION_TYPE),
- ...(marker ? [marker] : []),
- ]
- if (!networkPolicyConditionsChanged(existing, settled)) return
- await this.publishNetworkPolicyConditions(recipe, settled)
}
/**
@@ -1825,9 +1819,13 @@ export class WorkflowRecipeReconciler {
phase: currentPhase,
message: 'Plugin Workload SDK disabled after confirmed teardown',
workloadStatuses: [],
- // The SDK runtime is gone and this return skips the SDK-only lane, so
- // no policy is managed and a published ownership conflict is stale.
- networkPolicyOwnershipConditions: [],
+ // The confirmed teardown deleted every SDK policy (the legacy one by
+ // name included), so no policy is managed: the unmanaged writer.
+ networkPolicyOwnershipConditions: networkPolicyMarkerConditions(
+ { kind: 'unmanaged' },
+ recipe.status?.conditions,
+ new Date().toISOString()
+ ),
pluginWorkloadSdkTeardownConfirmed: true,
}
}
@@ -1856,6 +1854,13 @@ export class WorkflowRecipeReconciler {
requeueAfterMs: TRANSIENT_REQUEUE_BASE_MS,
}
}
+ // A stepless recipe managed policies only through the SDK, and the
+ // teardown above deleted them all, so the group is cleared here: the
+ // terminal and validation returns below never reach the SDK-only lane.
+ // A workflow recipe keeps its run lane, which still manages policies.
+ if (!isWorkflow) {
+ await this.publishNetworkPolicyMarkerWriter(recipe, { kind: 'unmanaged' })
+ }
}
const limitError = validateWorkflowRecipeLimits(recipe.spec, this.config)
@@ -3084,19 +3089,29 @@ export class WorkflowRecipeReconciler {
sdkOnlyRuntime?.phase === 'active' &&
recipe.spec.pluginWorkloadSdk !== undefined &&
sdkOnlyRuntime.pluginWorkloadSdkBootstrapProof?.ready !== true
- // Without an SDK runtime this lane manages no policies: nothing conflicts
- // and nothing is pending, so a condition published by an earlier pass is
- // stale and `[]` removes it. A runtime without a summary did not evaluate
- // the policies (the host returned before the apply), so the ownership
- // field stays absent and patchStatus keeps what was published.
+ // Without an SDK runtime this lane reaches no policy: the spec has no
+ // SDK block, and the capability-removal teardown deleted every SDK
+ // policy, the legacy one by name included. That is the unmanaged
+ // writer, which clears the whole group. A runtime without a summary did
+ // not evaluate the policies (the host returned before the apply), so
+ // the field stays absent and patchStatus keeps what was published.
+ const now = new Date().toISOString()
const {
networkPolicyRetryPending: sdkOnlyNetworkPolicyRetryPending,
...sdkOnlyNetworkPolicyOwnership
- } = translateNetworkPolicyApplySummary(
- sdkOnlyRuntime ? sdkOnlyRuntime.networkPolicies : { conflicts: [], retryPending: false },
- recipe.status?.conditions,
- new Date().toISOString()
- )
+ } = sdkOnlyRuntime
+ ? translateNetworkPolicyPassSummary(
+ sdkOnlyRuntime.networkPolicies,
+ recipe.status?.conditions,
+ now
+ )
+ : {
+ networkPolicyOwnershipConditions: networkPolicyMarkerConditions(
+ { kind: 'unmanaged' },
+ recipe.status?.conditions,
+ now
+ ),
+ }
if (sdkOnlyRuntime?.phase === 'failed') {
return {
phase: 'failed',
@@ -3279,7 +3294,7 @@ export class WorkflowRecipeReconciler {
message: string
pluginWorkloadSdkBootstrapProof?: EagerSdkBootstrapProof
/** Undefined when the pass returned before applying the policies. */
- networkPolicies?: WorkflowNetworkPolicyApplySummary
+ networkPolicies?: NetworkPolicyPassSummary
}> {
if (!this.workflowReconciler) {
return {
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
index 8c21f8ce2..f8e481eda 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
@@ -50,37 +50,50 @@ export type EagerSdkMcpHostStatus =
| 'provider_unavailable'
/**
- * What one `applyWorkflowNetworkPolicies` pass could not converge. A conflict
- * names a live policy another controller owns; WRC leaves it untouched. A
- * pending retry means a policy was left unwritten for a later pass: it was
- * terminating, or still contended after the bounded apply rounds.
- *
- * `prune` is set only by a pass that pruned (see `NetworkPolicyPruneFact`).
- * A pass that did not prune leaves it undefined, and the published prune
- * fact is carried over unchanged.
+ * What one policy apply could not converge. A conflict names a live policy
+ * another controller owns; WRC leaves it untouched. A pending retry means a
+ * policy was left unwritten for a later pass: it was terminating, or still
+ * contended after the bounded apply rounds. An apply prunes nothing, so it
+ * says nothing about the prune or the legacy policy.
*/
export type WorkflowNetworkPolicyApplySummary = {
conflicts: { policy: string; reason: NetworkPolicyConflictReason }[]
retryPending: boolean
- prune?: NetworkPolicyPruneFact
}
/**
* What a prune pass established about the run-lane policies the spec no
* longer wants: `converged` when every DELETE it owed landed (2xx or 404),
- * `pending` when one did not (a non-404 prune or legacy DELETE), and
- * `unevaluated` when its LIST failed, so it could not tell which policies
- * were owed a DELETE at all.
+ * `pending` when one did not (a non-404 DELETE), and `unevaluated` when its
+ * LIST failed, so it could not tell which policies were owed a DELETE at all.
*/
export type NetworkPolicyPruneFact = 'converged' | 'pending' | 'unevaluated'
+/**
+ * What a pass established about the legacy
+ * `<recipe>-mcp-servers-egress-internet` policy, deleted by name because it
+ * may carry no labels: `removed` when its DELETE landed (2xx or 404) or an
+ * earlier DELETE already did, `pending` when it did not.
+ */
+export type NetworkPolicyLegacyFact = 'removed' | 'pending'
+
+/**
+ * What one full `applyWorkflowNetworkPolicies` pass (apply, prune and legacy
+ * delete) established. Every field is required: an absent fact is never
+ * read as "carry the published one".
+ */
+export type NetworkPolicyPassSummary = WorkflowNetworkPolicyApplySummary & {
+ prune: NetworkPolicyPruneFact
+ legacy: NetworkPolicyLegacyFact
+}
+
export type EagerSdkMcpHostResult = {
status: EagerSdkMcpHostStatus
/**
* Undefined when the pass returned before applying the policies. An empty
* summary would claim every policy converged and clear a published conflict.
*/
- networkPolicies?: WorkflowNetworkPolicyApplySummary
+ networkPolicies?: NetworkPolicyPassSummary
}
/** Why the mcp-host runtime JWT Secret was reminted. */
@@ -174,7 +187,7 @@ export type PluginWorkloadSdkProvisionerDeps = {
codexProjection: CodexRecipeVerdict['projection'],
eagerSdkMcpHost: boolean,
grokProjection?: CodexRecipeVerdict['grokProjection']
- ) => Promise<WorkflowNetworkPolicyApplySummary>
+ ) => Promise<NetworkPolicyPassSummary>
ensureMcpHostHeadlessService: (recipeName: string) => Promise<void>
createIfNotExists: (createFn: () => Promise<unknown>, label: string) => Promise<boolean>
safeDelete: (deleteFn: () => Promise<unknown>) => Promise<void>
diff --git a/workflow-recipes/src/workflow/workflowReconciler.test.ts b/workflow-recipes/src/workflow/workflowReconciler.test.ts
index 7e7e99708..b45b79f23 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.test.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.test.ts
@@ -1430,6 +1430,9 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
mockCoreApi.readNamespacedEndpoints.mockRejectedValue({ code: 404 })
mockNetworkingApi.readNamespacedNetworkPolicy.mockRejectedValue({ code: 404 })
mockNetworkingApi.listNamespacedNetworkPolicy.mockResolvedValue({ items: [] })
+ // clearAllMocks keeps implementations, so a DELETE failure one test
+ // injects must not leak into the next teardown.
+ mockNetworkingApi.deleteNamespacedNetworkPolicy.mockResolvedValue({})
mockModelConfigHandler.configurePluginWorkloadSdkBootstrap.mockResolvedValue({
status: 202,
body: sdkBootstrapProof(),
@@ -1727,11 +1730,12 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
// The conflict did not stop the rest of the pass.
expect(createdNames()).toContain('sdk-only-workload-to-mcp-host-sdk-egress')
expect(result.phase).toBe('active')
- // The eager apply prunes too, so its summary carries the prune fact.
+ // The eager apply prunes too, so its summary carries the prune and legacy facts.
expect(result.networkPolicies).toEqual({
conflicts: [{ policy: foreignName, reason: 'owner-reference-mismatch' }],
retryPending: false,
prune: 'converged',
+ legacy: 'removed',
})
expect(writesTo(foreignName)).toHaveLength(0)
})
@@ -1761,6 +1765,8 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
networkPolicies: {
conflicts: [{ policy: foreignName, reason: 'owner-reference-mismatch' }],
retryPending: true,
+ prune: 'converged',
+ legacy: 'removed',
},
})
@@ -1777,6 +1783,8 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
expect(result.networkPolicies).toEqual({
conflicts: [{ policy: foreignName, reason: 'owner-reference-mismatch' }],
retryPending: true,
+ prune: 'converged',
+ legacy: 'removed',
})
}
)
@@ -1890,6 +1898,8 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
networkPolicies: {
conflicts: [{ policy: foreignName, reason: 'owner-reference-mismatch' }],
retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
},
})
@@ -1927,7 +1937,12 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
).pluginWorkloadSdkProvisioner
const ensure = vi.spyOn(provisioner, 'ensureEagerSdkMcpHost').mockResolvedValue({
status: 'failed',
- networkPolicies: { conflicts: [], retryPending: true },
+ networkPolicies: {
+ conflicts: [],
+ retryPending: true,
+ prune: 'converged',
+ legacy: 'removed',
+ },
})
const result = await reconciler.reconcile(
@@ -1968,6 +1983,8 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
networkPolicies: {
conflicts: [{ policy: foreignName, reason: 'owner-reference-mismatch' }],
retryPending: true,
+ prune: 'converged',
+ legacy: 'removed',
},
})
@@ -2021,6 +2038,8 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
networkPolicies: {
conflicts: [{ policy: foreignName, reason: 'owner-reference-mismatch' }],
retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
},
})
@@ -2216,9 +2235,12 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
expect(legacyDeletes()).toHaveLength(1)
await reconciler.cleanupPluginWorkloadSdk('sdk-only', { recipeUid: 'uid-sdk-only' })
+ // The teardown deletes the legacy policy by name (R4-L3).
+ expect(legacyDeletes()).toHaveLength(2)
await reconcileSdkOnly()
- expect(legacyDeletes()).toHaveLength(2)
+ // The ledger entry was forgotten, so the next pass deletes it again.
+ expect(legacyDeletes()).toHaveLength(3)
})
it('defers absence reads until pod deletion completes so 404s cannot become unhandled rejections', async () => {
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 5a84c15ac..28c8ae5b1 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -107,6 +107,8 @@ import {
type McpHostRuntimeTokenRefreshReason,
type McpHostRuntimeTokenRefreshResult,
NO_MCP_HOST_RUNTIME_TOKEN_REFRESH,
+ type NetworkPolicyLegacyFact,
+ type NetworkPolicyPassSummary,
type NetworkPolicyPruneFact,
PluginWorkloadSdkProvisioner,
type WorkflowNetworkPolicyApplySummary,
@@ -285,8 +287,9 @@ export const NETWORK_POLICY_OWNERSHIP_CONDITION_TYPE = 'WorkflowNetworkPolicyOwn
* - prune (`converged | pending | unevaluated`, see `NetworkPolicyPruneFact`):
* `pending` when a DELETE the prune owed did not land, `unevaluated` when
* its LIST failed. No requeue for either, since nothing but `reconcile()`
- * prunes. Only a later `reconcile()` prune that lands, or the finalizer,
- * clears it; every other path carries it over.
+ * prunes. Only a later `reconcile()` prune that lands, the `unmanaged`
+ * writer after a full SDK teardown, or the finalizer clears it; every other
+ * path carries it over (see `networkPolicyMarkerConditions`).
*
* Each combination with a fact that is not converged has its own reason
* (`RetryPending`, `PrunePending`, `PruneUnevaluated`, `RetryAndPrunePending`,
@@ -364,6 +367,30 @@ function networkPolicyMarkerReason(
}
}
+/**
+ * Published only as `False`/`DeletePending` while the legacy
+ * `<recipe>-mcp-servers-egress-internet` policy is pending a delete (see
+ * `NetworkPolicyLegacyFact`), and removed once it is gone. The fact is read
+ * back from the reason alone.
+ */
+export const LEGACY_NETWORK_POLICY_REMOVED_CONDITION_TYPE = 'WorkflowLegacyNetworkPolicyRemoved'
+
+const LEGACY_NETWORK_POLICY_REASONS = {
+ DeletePending: {
+ fact: 'pending',
+ message:
+ 'The legacy mcp-servers internet egress NetworkPolicy is pending a delete; a later pass or the finalizer removes it',
+ },
+} as const satisfies Record<string, { fact: NetworkPolicyLegacyFact; message: string }>
+
+type LegacyNetworkPolicyReason = keyof typeof LEGACY_NETWORK_POLICY_REASONS
+
+function isLegacyNetworkPolicyReason(
+ reason: string | undefined
+): reason is LegacyNetworkPolicyReason {
+ return reason !== undefined && Object.hasOwn(LEGACY_NETWORK_POLICY_REASONS, reason)
+}
+
/**
* Merged by its own group in `patchStatus`, apart from the workflow-output
* group: a pass that never reached the policy apply leaves the field
@@ -372,6 +399,7 @@ function networkPolicyMarkerReason(
export const NETWORK_POLICY_OWNERSHIP_CONDITION_TYPES = new Set([
NETWORK_POLICY_OWNERSHIP_CONDITION_TYPE,
NETWORK_POLICIES_CONVERGED_CONDITION_TYPE,
+ LEGACY_NETWORK_POLICY_REMOVED_CONDITION_TYPE,
])
/**
@@ -488,33 +516,212 @@ export function buildNetworkPolicyOwnershipConditions(
}
/**
- * The status fields one policy apply pass contributes, shared by the run lane
- * and the SDK-only lane so both translate a summary the same way. No summary
- * (the pass returned before the apply) yields neither field, which keeps the
- * published conditions. A summary always yields the group's conditions, `[]`
- * included: the ownership condition when a policy conflicts, and the
- * converged marker while a policy is pending a retry, or the prune is pending
- * or unevaluated. Only a pending retry sets the retry flag (and with it a
- * requeue). A summary without a prune fact (a path that did not prune) carries
- * the published prune fact over, so only a pass that pruned can clear it.
+ * The legacy marker for `fact`, or `undefined` once the policy is removed.
+ * `lastTransitionTime` is kept while the marker stays `False`.
+ */
+function buildLegacyNetworkPolicyCondition(
+ fact: NetworkPolicyLegacyFact,
+ now: string,
+ existingConditions?: StatusCondition[]
+): StatusCondition | undefined {
+ switch (fact) {
+ case 'removed':
+ return undefined
+ case 'pending': {
+ const existing = existingConditions?.find(
+ c => c.type === LEGACY_NETWORK_POLICY_REMOVED_CONDITION_TYPE && c.status === 'False'
+ )
+ return {
+ type: LEGACY_NETWORK_POLICY_REMOVED_CONDITION_TYPE,
+ status: 'False',
+ reason: 'DeletePending',
+ message: LEGACY_NETWORK_POLICY_REASONS.DeletePending.message,
+ lastTransitionTime: existing?.lastTransitionTime ?? now,
+ }
+ }
+ default: {
+ const unreachable: never = fact
+ throw new Error(`Unknown legacy NetworkPolicy fact: ${String(unreachable)}`)
+ }
+ }
+}
+
+/**
+ * Who writes the NetworkPolicy condition group, and so which facts it
+ * observed (Table A on `retryRunLaneNetworkPolicies`):
+ *
+ * - `reconcile`: a full pass (run lane, eager lane, SDK-only lane with a
+ * summary). Observes the apply, the prune and the legacy delete.
+ * - `apply-retry`: the mid-run retry. Observes the apply; carries the prune
+ * and legacy facts.
+ * - `terminal`: the run ended, so a pending apply is dropped; carries the
+ * prune and legacy facts and the ownership condition.
+ * - `unmanaged`: the kill switch, the SDK-only lane without a runtime and
+ * the capability removal. Written only after a teardown that deleted every
+ * SDK policy, the legacy one by name included, so it clears the group.
*/
-export function translateNetworkPolicyApplySummary(
- summary: WorkflowNetworkPolicyApplySummary | undefined,
+export type NetworkPolicyMarkerWriter =
+ | { kind: 'reconcile'; summary: NetworkPolicyPassSummary }
+ | { kind: 'apply-retry'; summary: WorkflowNetworkPolicyApplySummary }
+ | { kind: 'terminal' }
+ | { kind: 'unmanaged' }
+
+/**
+ * A marker a carrying writer found published. `unknown` is a condition of a
+ * marker type whose status or reason this controller did not write: it is
+ * never interpreted, only kept as it is.
+ */
+type PublishedMarker =
+ | { kind: 'absent' }
+ | { kind: 'known'; condition: StatusCondition }
+ | { kind: 'unknown'; condition: StatusCondition }
+
+function publishedMarker(
+ existingConditions: StatusCondition[] | undefined,
+ type: string,
+ isKnownReason: (reason: string | undefined) => boolean
+): PublishedMarker {
+ const condition = (existingConditions ?? []).find(c => c.type === type)
+ if (condition === undefined) return { kind: 'absent' }
+ if (condition.status === 'False' && isKnownReason(condition.reason)) {
+ return { kind: 'known', condition }
+ }
+ return { kind: 'unknown', condition }
+}
+
+function warnUnknownNetworkPolicyMarker(
+ writer: NetworkPolicyMarkerWriter['kind'],
+ condition: StatusCondition
+): void {
+ createLogger('wrc', 'network-policy-marker').warn(
+ 'Keeping a NetworkPolicy marker with a reason this controller did not write',
+ { writer, type: condition.type, status: condition.status, reason: condition.reason }
+ )
+}
+
+/** The converged marker a carrying writer publishes for its observed apply. */
+function carriedConvergedMarker(
+ writer: NetworkPolicyMarkerWriter['kind'],
+ apply: NetworkPolicyMarkerFacts['apply'],
+ existingConditions: StatusCondition[] | undefined,
+ now: string
+): StatusCondition | undefined {
+ const published = publishedMarker(
+ existingConditions,
+ NETWORK_POLICIES_CONVERGED_CONDITION_TYPE,
+ isNetworkPolicyMarkerReason
+ )
+ if (published.kind === 'unknown') {
+ warnUnknownNetworkPolicyMarker(writer, published.condition)
+ return published.condition
+ }
+ const { prune } = networkPolicyMarkerFacts(existingConditions)
+ return buildNetworkPolicyConvergedCondition({ apply, prune }, now, existingConditions)
+}
+
+/** The legacy marker a carrying writer publishes: the published one, as is. */
+function carriedLegacyMarker(
+ writer: NetworkPolicyMarkerWriter['kind'],
+ existingConditions: StatusCondition[] | undefined
+): StatusCondition | undefined {
+ const published = publishedMarker(
+ existingConditions,
+ LEGACY_NETWORK_POLICY_REMOVED_CONDITION_TYPE,
+ isLegacyNetworkPolicyReason
+ )
+ switch (published.kind) {
+ case 'absent':
+ return undefined
+ case 'known':
+ return published.condition
+ case 'unknown':
+ warnUnknownNetworkPolicyMarker(writer, published.condition)
+ return published.condition
+ default: {
+ const unreachable: never = published
+ throw new Error(`Unknown published marker: ${String(unreachable)}`)
+ }
+ }
+}
+
+function presentConditions(conditions: (StatusCondition | undefined)[]): StatusCondition[] {
+ return conditions.filter((c): c is StatusCondition => c !== undefined)
+}
+
+/**
+ * The whole NetworkPolicy condition group `writer` publishes: the ownership
+ * condition, the converged marker and the legacy marker, each only while it
+ * is `False`. `[]` removes the group. Every writer goes through here, so each
+ * fact is observed, carried or cleared exactly as Table A says.
+ */
+export function networkPolicyMarkerConditions(
+ writer: NetworkPolicyMarkerWriter,
+ existingConditions: StatusCondition[] | undefined,
+ now: string
+): StatusCondition[] {
+ switch (writer.kind) {
+ case 'reconcile': {
+ const { summary } = writer
+ return presentConditions([
+ ...buildNetworkPolicyOwnershipConditions(summary, now, existingConditions),
+ buildNetworkPolicyConvergedCondition(
+ { apply: summary.retryPending ? 'pending' : 'converged', prune: summary.prune },
+ now,
+ existingConditions
+ ),
+ buildLegacyNetworkPolicyCondition(summary.legacy, now, existingConditions),
+ ])
+ }
+ case 'apply-retry': {
+ const { summary } = writer
+ return presentConditions([
+ ...buildNetworkPolicyOwnershipConditions(summary, now, existingConditions),
+ carriedConvergedMarker(
+ writer.kind,
+ summary.retryPending ? 'pending' : 'converged',
+ existingConditions,
+ now
+ ),
+ carriedLegacyMarker(writer.kind, existingConditions),
+ ])
+ }
+ case 'terminal':
+ return presentConditions([
+ ...(existingConditions ?? []).filter(
+ c => c.type === NETWORK_POLICY_OWNERSHIP_CONDITION_TYPE
+ ),
+ carriedConvergedMarker(writer.kind, 'converged', existingConditions, now),
+ carriedLegacyMarker(writer.kind, existingConditions),
+ ])
+ case 'unmanaged':
+ return []
+ default: {
+ const unreachable: never = writer
+ throw new Error(`Unknown NetworkPolicy marker writer: ${String(unreachable)}`)
+ }
+ }
+}
+
+/**
+ * The status fields one full pass contributes, shared by the run lane, the
+ * eager lane and the SDK-only lane so all three translate a summary the same
+ * way (the `reconcile` writer). No summary (the pass returned before the
+ * apply) yields neither field, which keeps the published conditions. A
+ * summary always yields the whole group, `[]` included. Only a pending retry
+ * sets the retry flag (and with it a requeue).
+ */
+export function translateNetworkPolicyPassSummary(
+ summary: NetworkPolicyPassSummary | undefined,
existingConditions: StatusCondition[] | undefined,
now: string
): Pick<WorkflowReconcileResult, 'networkPolicyOwnershipConditions' | 'networkPolicyRetryPending'> {
if (summary === undefined) return {}
- const prune = summary.prune ?? networkPolicyMarkerFacts(existingConditions).prune
- const marker = buildNetworkPolicyConvergedCondition(
- { apply: summary.retryPending ? 'pending' : 'converged', prune },
- now,
- existingConditions
- )
return {
- networkPolicyOwnershipConditions: [
- ...buildNetworkPolicyOwnershipConditions(summary, now, existingConditions),
- ...(marker ? [marker] : []),
- ],
+ networkPolicyOwnershipConditions: networkPolicyMarkerConditions(
+ { kind: 'reconcile', summary },
+ existingConditions,
+ now
+ ),
...(summary.retryPending ? { networkPolicyRetryPending: true } : {}),
}
}
@@ -1037,10 +1244,11 @@ export interface WorkflowReconcileResult {
clearWorkflowExecution?: boolean
workflowConditions?: StatusCondition[]
/**
- * The `WorkflowNetworkPolicyOwnership` condition from this pass's policy
- * apply. Undefined when the pass returned before the apply, which keeps the
- * published condition; `[]` when no policy is owned by another controller (a
- * pending retry does not count as a conflict), which removes it.
+ * The NetworkPolicy condition group this pass's policy apply produced
+ * (`networkPolicyMarkerConditions`): the ownership condition and the
+ * converged and legacy markers. Undefined when the pass returned before the
+ * apply, which keeps the published group; `[]` when every fact converged
+ * and no policy is owned by another controller, which removes it.
*/
networkPolicyOwnershipConditions?: StatusCondition[]
/**
@@ -1500,7 +1708,7 @@ export class WorkflowReconciler {
message: string
pluginWorkloadSdkBootstrapProof?: EagerSdkBootstrapProof
/** Undefined when the eager host returned before applying the policies. */
- networkPolicies?: WorkflowNetworkPolicyApplySummary
+ networkPolicies?: NetworkPolicyPassSummary
}> {
if (!this.deps.config.pluginWorkloadSdkEnabled || !spec.pluginWorkloadSdk) {
// Nothing is applied here, so no summary: an empty one would read as
@@ -1682,6 +1890,16 @@ export class WorkflowReconciler {
`clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`
)
),
+ // The legacy internet policy may carry no labels, so the sweep
+ // above cannot be trusted to remove it. Deleting it by name is
+ // what lets the caller publish the unmanaged marker writer after
+ // this teardown: any non-404 failure rejects the teardown.
+ this.teardownDelete(() =>
+ this.deps.networkingApi.deleteNamespacedNetworkPolicy({
+ name: `${recipeName}-mcp-servers-egress-internet`,
+ namespace: this.deps.config.mcpServerNamespace,
+ })
+ ),
]),
])
if (!preserveWorkflowRuntime) {
@@ -1898,7 +2116,7 @@ export class WorkflowReconciler {
// Empty until this pass applies the policies, then what the apply found.
// A return before the apply leaves it empty, and patchStatus keeps the
// published condition.
- let networkPolicyStatus: ReturnType<typeof translateNetworkPolicyApplySummary> = {}
+ let networkPolicyStatus: ReturnType<typeof translateNetworkPolicyPassSummary> = {}
const withWorkflowConditions = (result: WorkflowReconcileResult): WorkflowReconcileResult => ({
...result,
workflowConditions,
@@ -2063,7 +2281,7 @@ export class WorkflowReconciler {
// No summary means the host returned before the apply, so the pass
// cannot say whether a conflict is gone. A `failed` pod after the
// apply still carries a real summary and publishes it.
- networkPolicyStatus = translateNetworkPolicyApplySummary(
+ networkPolicyStatus = translateNetworkPolicyPassSummary(
eagerNetworkPolicies,
currentStatus?.conditions,
new Date().toISOString()
@@ -2528,7 +2746,7 @@ export class WorkflowReconciler {
false,
codexVerdict.grokProjection
)
- networkPolicyStatus = translateNetworkPolicyApplySummary(
+ networkPolicyStatus = translateNetworkPolicyPassSummary(
runLaneNetworkPolicies,
currentStatus?.conditions,
new Date().toISOString()
@@ -3117,11 +3335,9 @@ export class WorkflowReconciler {
* applies it, but deletes nothing: the run's pods are live and may still use
* any lane the spec wanted when they were created, so a revoke here cuts
* their traffic. That includes the legacy mcp-servers internet policy, which
- * only a reconcile() pass deletes. retryPending reflects the applies alone
- * and the summary carries no prune fact, so a pending prune a reconcile()
- * pass published survives this path: a run-lane leftover waits for the next
- * reconcile() pass or the finalizer's label sweep, the legacy policy for the
- * next reconcile() pass.
+ * only a reconcile() pass deletes. The summary is apply-only, so this path
+ * is the `apply-retry` writer of Table A below: it observes the apply and
+ * carries the published prune and legacy facts.
*
* What each path does to a run-lane policy (verdict = Codex/Grok
* eligibility; it governs only the proxy lanes, every other catalog lane
@@ -3133,13 +3349,40 @@ export class WorkflowReconciler {
* | terminal teardown | kept | kept | kept | kept | kept |
* | finalizer | deleted | deleted | deleted | deleted | only if labeled |
*
- * What a failed write leaves behind, per path:
+ * Table A, what each writer publishes (`networkPolicyMarkerConditions`).
+ * The facts are A (apply: `converged | pending`), P (prune: `converged |
+ * pending | unevaluated`, `unevaluated` being a failed LIST) and L (legacy:
+ * `removed | pending`), read back from the condition reasons alone:
+ *
+ * | A | P | `WorkflowNetworkPoliciesConverged` | requeue |
+ * | converged | converged | absent | none |
+ * | pending | converged | False/`RetryPending` | the retry's |
+ * | converged | pending | False/`PrunePending` | none |
+ * | converged | unevaluated | False/`PruneUnevaluated` | none |
+ * | pending | pending | False/`RetryAndPrunePending` | as RetryPending |
+ * | pending | unevaluated | False/`RetryAndPruneUnevaluated` | as RetryPending |
*
- * | path | on failure |
- * | reconcile() pass | apply terminating/contended: `RetryPending`, requeue. Non-404 DELETE (prune or legacy) or a failed LIST: `PrunePending`, no requeue |
- * | mid-run retry (this) | apply still pending: marker kept, progress requeue. Apply threw: marker kept, transient requeue. A pending prune is carried over |
- * | terminal teardown | a pending apply is dropped; a pending prune is kept (`PrunePending`) |
- * | finalizer | a non-404 DELETE is logged by `safeDelete` and not rethrown, so the finalizer completes |
+ * | L | `WorkflowLegacyNetworkPolicyRemoved` |
+ * | removed | absent |
+ * | pending | False/`DeletePending` |
+ *
+ * | writer | A | P | L | clears |
+ * | `reconcile` (run lane, eager, SDK with a summary) | observed | observed | observed | what converged |
+ * | SDK with a runtime and no summary | not written | not written | not written | nothing |
+ * | `apply-retry` (this, in-progress and active) | observed | carried | carried | A only |
+ * | `terminal` | forced converged | carried | carried | A |
+ * | `unmanaged` (kill switch, SDK lane without a runtime, capability removal) | converged | converged | removed | everything |
+ * | finalizer | the object is deleted | | | |
+ *
+ * A carrying writer keeps a marker whose reason it did not write as it is
+ * and warns; `reconcile` overwrites it. `unmanaged` is written only after
+ * `cleanupPluginWorkloadSdk` without `preserveWorkflowRuntime` succeeded:
+ * it sweeps the recipe labels and deletes the legacy policy by name, and a
+ * failure there fails the pass before the writer runs. A pending or
+ * unevaluated prune is not retried outside reconcile(): only reconcile()
+ * can compute the desired set, and the finalizer's label sweep removes
+ * every run-lane leftover. On the finalizer, a non-404 DELETE is logged by
+ * `safeDelete` and not rethrown, so the finalizer completes.
*
* A desired lane is applied on both apply paths; an uncertain verdict never
* creates a proxy. Terminal teardown deletes a run-scoped run's compute pods
@@ -3389,13 +3632,13 @@ export class WorkflowReconciler {
private async pruneLegacyMcpServersInternetEgressPolicy(
recipeName: string,
recipeUid?: string
- ): Promise<{ deletePending: boolean }> {
+ ): Promise<NetworkPolicyLegacyFact> {
const key = this.legacyMcpServersInternetEgressKey(recipeName, recipeUid)
if (this.prunedLegacyMcpServersInternetEgress.has(key)) {
this.log.debug('Skipping legacy mcp-servers internet NP delete; already observed gone', {
recipe: recipeName,
})
- return { deletePending: false }
+ return 'removed'
}
const outcome = await observeNamespacedDelete(() =>
this.deps.networkingApi.deleteNamespacedNetworkPolicy({
@@ -3409,7 +3652,7 @@ export class WorkflowReconciler {
...deleteOutcomeFields(outcome),
err: outcome.error,
})
- return { deletePending: true }
+ return 'pending'
}
this.log.info('Legacy mcp-servers internet NP delete', {
recipe: recipeName,
@@ -3418,7 +3661,7 @@ export class WorkflowReconciler {
if (shouldRecordDelete(outcome)) {
this.prunedLegacyMcpServersInternetEgress.add(key)
}
- return { deletePending: false }
+ return 'removed'
}
private needsRuntimeHttpEgressRefresh(spec: WorkflowRecipeSpec): boolean {
@@ -3584,7 +3827,7 @@ export class WorkflowReconciler {
codexProjection: CodexExecutionProjection,
eagerSdkMcpHost = false,
grokProjection?: CodexExecutionProjection & { requiresGrokProxyEgress?: boolean }
- ): Promise<WorkflowNetworkPolicyApplySummary> {
+ ): Promise<NetworkPolicyPassSummary> {
const { policies, catalog } = await this.buildWorkflowNetworkPoliciesForSpec(
recipeName,
recipeUid,
@@ -3607,8 +3850,8 @@ export class WorkflowReconciler {
policies: k8s.V1NetworkPolicy[],
catalog: Set<string>,
keepProxies: RunLaneProxyKeepReasons
- ): Promise<WorkflowNetworkPolicyApplySummary> {
- const summary = await this.applyNetworkPolicyList(policies)
+ ): Promise<NetworkPolicyPassSummary> {
+ const applied = await this.applyNetworkPolicyList(policies)
const policyNames = new Set(policies.map(policy => policy.metadata?.name))
const prune = await this.pruneUndesiredRunLaneNetworkPolicies(
recipeName,
@@ -3617,10 +3860,7 @@ export class WorkflowReconciler {
keepProxies
)
const legacy = await this.pruneLegacyMcpServersInternetEgressPolicy(recipeName, recipeUid)
- // An unevaluated prune does not know which policies it owed a DELETE, so
- // it outranks a legacy DELETE that did not land.
- summary.prune = prune === 'converged' && legacy.deletePending ? 'pending' : prune
- return summary
+ return { ...applied, prune, legacy }
}
/**
diff --git a/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts b/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
index c29fed1e4..218b62ac6 100644
--- a/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
+++ b/workflow-recipes/tests/unit/workflow/workflowReconciler.test.ts
@@ -21,6 +21,7 @@ import {
issueMcpHostWorkflowControlToken,
} from '../../../src/workflow/mcpHostRuntimeTokenIssuerClient'
import { buildWorkflowNetworkPolicies } from '../../../src/workflow/networkPolicyFactory'
+import type { NetworkPolicyPassSummary } from '../../../src/workflow/pluginWorkloadSdkProvisioner'
import {
buildArtifactReaderHeadlessService,
buildMcpHostHeadlessService,
@@ -41,8 +42,9 @@ import {
buildNetworkPolicyConvergedCondition,
buildNetworkPolicyOwnershipConditions,
networkPolicyConditionsChanged,
+ networkPolicyMarkerConditions,
networkPolicyMarkerFacts,
- translateNetworkPolicyApplySummary,
+ translateNetworkPolicyPassSummary,
} from '../../../src/workflow/workflowReconciler'
import { asApiserverNetworkPolicy } from './asApiserverNetworkPolicy'
@@ -3657,7 +3659,7 @@ describe('WorkflowReconciler — reconcile loop', () => {
}
})
- it('marks the prune pending, not a retry, when the legacy internet NP DELETE fails', async () => {
+ it('marks the legacy policy pending, apart from the prune, when the legacy internet NP DELETE fails', async () => {
const apiserver = makeApiserverNetworkingApi()
apiserver.api.deleteNamespacedNetworkPolicy.mockImplementation(
async ({ name, namespace }: { name: string; namespace: string }) => {
@@ -3677,7 +3679,9 @@ describe('WorkflowReconciler — reconcile loop', () => {
([arg]: [{ name: string }]) => arg.name === `${RECIPE}-mcp-servers-egress-internet`
)
).toHaveLength(1)
- expect(summary.prune).toBe('pending')
+ // R4-L3: the legacy delete is its own fact; the catalog prune converged.
+ expect(summary.legacy).toBe('pending')
+ expect(summary.prune).toBe('converged')
expect(summary.retryPending).toBe(false)
})
@@ -5534,16 +5538,18 @@ describe('WorkflowReconciler — reconcile loop', () => {
).toMatchObject([{ status: 'False', reason: 'PrunePending' }])
})
- // The legacy mcp-servers internet policy is a prune like any other:
- // only reconcile() deletes it. A failed delete is PrunePending, with
- // no retry flag, and the next reconcile() pass deletes it again.
+ // The legacy mcp-servers internet policy is deleted by name, apart
+ // from the catalog prune: only reconcile() deletes it. A failed delete
+ // is its own fact (R4-L3), DeletePending on its own condition, with no
+ // retry flag and the catalog prune converged, and the next reconcile()
+ // pass deletes it again.
const LEGACY = 'test-wf-mcp-servers-egress-internet'
const legacyDeletes = (apiserver: Converged) =>
apiserver.api.deleteNamespacedNetworkPolicy.mock.calls.filter(
([arg]) => arg.name === LEGACY
)
- it('reports a failed legacy internet policy delete from reconcile() as PrunePending, and deletes it on the next reconcile()', async () => {
+ it('reports a failed legacy internet policy delete from reconcile() as DeletePending, and deletes it on the next reconcile()', async () => {
const apiserver = makeApiserverNetworkingApi()
const reconciler = new WorkflowReconciler(
makeDeps({ networkingApi: apiserver.api as never })
@@ -5562,9 +5568,10 @@ describe('WorkflowReconciler — reconcile loop', () => {
expect(legacyDeletes(apiserver)).toHaveLength(1)
expect(failed.networkPolicyRetryPending).toBeFalsy()
const published = failed.networkPolicyOwnershipConditions ?? []
+ expect(published.filter(c => c.type === 'WorkflowNetworkPoliciesConverged')).toEqual([])
expect(
- published.filter(c => c.type === 'WorkflowNetworkPoliciesConverged')
- ).toMatchObject([{ status: 'False', reason: 'PrunePending' }])
+ published.filter(c => c.type === 'WorkflowLegacyNetworkPolicyRemoved')
+ ).toMatchObject([{ status: 'False', reason: 'DeletePending' }])
const pruned = await reconciler.reconcile(
'test-wf',
@@ -5577,12 +5584,7 @@ describe('WorkflowReconciler — reconcile loop', () => {
)
expect(legacyDeletes(apiserver)).toHaveLength(2)
expect(pruned.networkPolicyRetryPending).toBeFalsy()
- expect(pruned.networkPolicyOwnershipConditions).toBeDefined()
- expect(
- (pruned.networkPolicyOwnershipConditions ?? []).filter(
- c => c.type === 'WorkflowNetworkPoliciesConverged'
- )
- ).toEqual([])
+ expect(pruned.networkPolicyOwnershipConditions).toEqual([])
})
it('sends no legacy internet policy DELETE from the retry, even one no pass has seen gone', async () => {
@@ -9074,17 +9076,24 @@ describe('buildNetworkPolicyOwnershipConditions', () => {
})
})
-// The one translation of an apply summary into status fields, shared by the
-// run lane and the SDK-only lane. `toStrictEqual` pins which keys are present:
-// an absent ownership key keeps the published condition, so it must not be
-// emitted as an explicit `undefined`.
-describe('translateNetworkPolicyApplySummary', () => {
+// The one translation of a full pass summary into status fields, shared by
+// the run lane, the eager lane and the SDK-only lane (the `reconcile` writer
+// of Table A). `toStrictEqual` pins which keys are present: an absent
+// ownership key keeps the published condition, so it must not be emitted as
+// an explicit `undefined`.
+describe('translateNetworkPolicyPassSummary', () => {
const now = '2026-09-23T12:00:00.000Z'
const earlier = '2026-09-20T08:00:00.000Z'
- const conflictSummary = {
- conflicts: [{ policy: 'test-wf-coord-to-wrc', reason: 'owner-reference-mismatch' as const }],
+ const pass = (overrides: Partial<NetworkPolicyPassSummary> = {}): NetworkPolicyPassSummary => ({
+ conflicts: [],
retryPending: false,
- }
+ prune: 'converged',
+ legacy: 'removed',
+ ...overrides,
+ })
+ const conflictSummary = pass({
+ conflicts: [{ policy: 'test-wf-coord-to-wrc', reason: 'owner-reference-mismatch' as const }],
+ })
const publishedConflict = {
type: 'WorkflowNetworkPolicyOwnership',
status: 'False' as const,
@@ -9101,23 +9110,19 @@ describe('translateNetworkPolicyApplySummary', () => {
}
it('emits neither field when the pass produced no summary, so the published condition is kept', () => {
- const result = translateNetworkPolicyApplySummary(undefined, [publishedConflict], now)
+ const result = translateNetworkPolicyPassSummary(undefined, [publishedConflict], now)
expect(result).toStrictEqual({})
// Witness: the same existing conditions with a summary do produce the
// field, so the empty result above is caused by the missing summary.
expect(
- translateNetworkPolicyApplySummary(conflictSummary, [publishedConflict], now)
+ translateNetworkPolicyPassSummary(conflictSummary, [publishedConflict], now)
.networkPolicyOwnershipConditions
).toEqual([publishedConflict])
})
it('clears the condition with [] and sets no retry flag when nothing conflicts or is pending', () => {
- const result = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: false },
- [publishedConflict],
- now
- )
+ const result = translateNetworkPolicyPassSummary(pass(), [publishedConflict], now)
expect(result.networkPolicyOwnershipConditions).toEqual([])
expect(result).not.toHaveProperty('networkPolicyRetryPending')
@@ -9125,8 +9130,8 @@ describe('translateNetworkPolicyApplySummary', () => {
})
it('replaces the conflict with the retry marker and sets the retry flag when a retry is pending without a conflict', () => {
- const result = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: true },
+ const result = translateNetworkPolicyPassSummary(
+ pass({ retryPending: true }),
[publishedConflict],
now
)
@@ -9138,8 +9143,8 @@ describe('translateNetworkPolicyApplySummary', () => {
})
it('keeps the lastTransitionTime of a published retry marker while the retry stays pending', () => {
- const result = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: true },
+ const result = translateNetworkPolicyPassSummary(
+ pass({ retryPending: true }),
[publishedRetryMarker],
now
)
@@ -9151,24 +9156,19 @@ describe('translateNetworkPolicyApplySummary', () => {
})
it('clears a published retry marker with [] once no retry is pending', () => {
- const result = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: false },
- [publishedRetryMarker],
- now
- )
+ const result = translateNetworkPolicyPassSummary(pass(), [publishedRetryMarker], now)
expect(result).toStrictEqual({ networkPolicyOwnershipConditions: [] })
})
it('replaces the condition with one False condition naming every conflicting policy', () => {
- const result = translateNetworkPolicyApplySummary(
- {
+ const result = translateNetworkPolicyPassSummary(
+ pass({
conflicts: [
{ policy: 'test-wf-wrc-to-artifact-reader', reason: 'identity-label-mismatch' },
{ policy: 'test-wf-coord-to-wrc', reason: 'owner-reference-mismatch' },
],
- retryPending: false,
- },
+ }),
undefined,
now
)
@@ -9187,14 +9187,14 @@ describe('translateNetworkPolicyApplySummary', () => {
})
it('keeps the lastTransitionTime of an identical published condition', () => {
- const result = translateNetworkPolicyApplySummary(conflictSummary, [publishedConflict], now)
+ const result = translateNetworkPolicyPassSummary(conflictSummary, [publishedConflict], now)
expect(result).toStrictEqual({ networkPolicyOwnershipConditions: [publishedConflict] })
expect(result.networkPolicyOwnershipConditions?.[0]?.lastTransitionTime).toBe(earlier)
})
it('reports a conflict and a pending retry from the same pass together', () => {
- const result = translateNetworkPolicyApplySummary(
+ const result = translateNetworkPolicyPassSummary(
{ ...conflictSummary, retryPending: true },
undefined,
now
@@ -9209,8 +9209,8 @@ describe('translateNetworkPolicyApplySummary', () => {
})
})
- // R3-L3: a prune that could not delete (a non-404 DELETE or a failed legacy
- // delete) is its own fact; a failed LIST is `unevaluated` (R4-L6). It is published as PrunePending
+ // R3-L3: a prune that could not delete (a non-404 DELETE) is its own fact;
+ // a failed LIST is `unevaluated` (R4-L6). It is published as PrunePending
// and never sets the retry flag: nothing in the run's short-circuits can
// prune, so a requeue would only repeat the failed DELETE.
describe('prune-pending', () => {
@@ -9224,8 +9224,8 @@ describe('translateNetworkPolicyApplySummary', () => {
}
it('publishes PrunePending without the retry flag when only the prune is pending', () => {
- const result = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: false, prune: 'pending' },
+ const result = translateNetworkPolicyPassSummary(
+ pass({ prune: 'pending' }),
[publishedConflict],
now
)
@@ -9235,35 +9235,15 @@ describe('translateNetworkPolicyApplySummary', () => {
})
})
- it('keeps a published PrunePending marker when a summary without a prune fact converges', () => {
- // The mid-run retry prunes nothing, so its summary says nothing about the
- // prune and must not clear the fact a reconcile() pass published.
- const result = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: false },
- [publishedPruneMarker],
- now
- )
+ it('clears a published PrunePending marker once a pass pruned', () => {
+ const result = translateNetworkPolicyPassSummary(pass(), [publishedPruneMarker], now)
- expect(result).toStrictEqual({ networkPolicyOwnershipConditions: [publishedPruneMarker] })
- expect(
- networkPolicyConditionsChanged(
- [publishedPruneMarker],
- result.networkPolicyOwnershipConditions!
- )
- ).toBe(false)
- // Witness: a summary that did prune is authoritative and clears it.
- expect(
- translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: false, prune: 'converged' },
- [publishedPruneMarker],
- now
- )
- ).toStrictEqual({ networkPolicyOwnershipConditions: [] })
+ expect(result).toStrictEqual({ networkPolicyOwnershipConditions: [] })
})
- it('reports a pending retry and a carried prune in one RetryAndPrunePending marker', () => {
- const result = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: true },
+ it('reports a pending retry and a pending prune in one RetryAndPrunePending marker', () => {
+ const result = translateNetworkPolicyPassSummary(
+ pass({ retryPending: true, prune: 'pending' }),
[publishedPruneMarker],
now
)
@@ -9285,17 +9265,17 @@ describe('translateNetworkPolicyApplySummary', () => {
})
// R4-L6: a failed prune LIST evaluated nothing, so the prune fact is
- // `unevaluated`, never `pending`. It has its own reasons, carries over like
- // `pending`, and sets no retry flag of its own.
+ // `unevaluated`, never `pending`. It has its own reasons and sets no retry
+ // flag of its own.
describe('prune-unevaluated', () => {
- const convergedMarkers = (result: ReturnType<typeof translateNetworkPolicyApplySummary>) =>
+ const convergedMarkers = (result: ReturnType<typeof translateNetworkPolicyPassSummary>) =>
(result.networkPolicyOwnershipConditions ?? []).filter(
c => c.type === 'WorkflowNetworkPoliciesConverged'
)
it('R4-L6: publishes PruneUnevaluated without the retry flag when the prune LIST failed', () => {
- const result = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: false, prune: 'unevaluated' },
+ const result = translateNetworkPolicyPassSummary(
+ pass({ prune: 'unevaluated' }),
[publishedConflict],
now
)
@@ -9307,8 +9287,8 @@ describe('translateNetworkPolicyApplySummary', () => {
})
it('R4-L6: publishes RetryAndPruneUnevaluated for a pending retry and an unevaluated prune', () => {
- const result = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: true, prune: 'unevaluated' },
+ const result = translateNetworkPolicyPassSummary(
+ pass({ retryPending: true, prune: 'unevaluated' }),
[],
now
)
@@ -9318,34 +9298,218 @@ describe('translateNetworkPolicyApplySummary', () => {
])
expect(result.networkPolicyRetryPending).toBe(true)
})
+ })
+
+ // R4-L3: the legacy policy is its own fact, on its own condition.
+ describe('legacy', () => {
+ const legacyMarkers = (result: ReturnType<typeof translateNetworkPolicyPassSummary>) =>
+ (result.networkPolicyOwnershipConditions ?? []).filter(
+ c => c.type === 'WorkflowLegacyNetworkPolicyRemoved'
+ )
+
+ it('R4-L3: publishes DeletePending on its own condition, apart from the prune marker', () => {
+ const result = translateNetworkPolicyPassSummary(pass({ legacy: 'pending' }), [], now)
+
+ expect(result).toStrictEqual({
+ networkPolicyOwnershipConditions: [
+ {
+ type: 'WorkflowLegacyNetworkPolicyRemoved',
+ status: 'False',
+ reason: 'DeletePending',
+ message:
+ 'The legacy mcp-servers internet egress NetworkPolicy is pending a delete; a later pass or the finalizer removes it',
+ lastTransitionTime: now,
+ },
+ ],
+ })
+ })
- it('R4-L6: carries a published PruneUnevaluated marker through a summary without a prune fact', () => {
- const published = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: false, prune: 'unevaluated' },
+ it('R4-L3: keeps the first transition time while the delete stays pending, and clears it once removed', () => {
+ const published = translateNetworkPolicyPassSummary(
+ pass({ legacy: 'pending' }),
[],
earlier
).networkPolicyOwnershipConditions!
- // Liveness witness: the pass that failed its LIST published the marker.
- expect(convergedMarkers({ networkPolicyOwnershipConditions: published })).toMatchObject([
- { reason: 'PruneUnevaluated' },
+ // Liveness witness: the failing pass published the marker.
+ expect(legacyMarkers({ networkPolicyOwnershipConditions: published })).toHaveLength(1)
+
+ const still = translateNetworkPolicyPassSummary(pass({ legacy: 'pending' }), published, now)
+ expect(legacyMarkers(still)).toMatchObject([{ lastTransitionTime: earlier }])
+
+ expect(translateNetworkPolicyPassSummary(pass(), published, now)).toStrictEqual({
+ networkPolicyOwnershipConditions: [],
+ })
+ })
+ })
+})
+
+// R4-L3: every writer goes through `networkPolicyMarkerConditions`, and each
+// fact is observed, carried or cleared as Table A says.
+describe('networkPolicyMarkerConditions', () => {
+ const now = '2026-09-23T12:00:00.000Z'
+ const earlier = '2026-09-20T08:00:00.000Z'
+ const pass = (overrides: Partial<NetworkPolicyPassSummary> = {}): NetworkPolicyPassSummary => ({
+ conflicts: [],
+ retryPending: false,
+ prune: 'converged',
+ legacy: 'removed',
+ ...overrides,
+ })
+ const conflict = { policy: 'test-wf-coord-to-wrc', reason: 'owner-reference-mismatch' as const }
+ const published = (overrides: Partial<NetworkPolicyPassSummary>) =>
+ networkPolicyMarkerConditions({ kind: 'reconcile', summary: pass(overrides) }, [], earlier)
+ const reasons = (conditions: { type: string; reason?: string }[]) =>
+ conditions.map(c => `${c.type}/${c.reason}`)
+
+ describe('apply-retry', () => {
+ it('R4-L3: observes the apply and carries the prune and legacy facts', () => {
+ const existing = published({ retryPending: true, prune: 'pending', legacy: 'pending' })
+ // Liveness witness: all three facts were published.
+ expect(reasons(existing)).toEqual([
+ 'WorkflowNetworkPoliciesConverged/RetryAndPrunePending',
+ 'WorkflowLegacyNetworkPolicyRemoved/DeletePending',
])
- const carried = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: false },
- published,
+ const settled = networkPolicyMarkerConditions(
+ { kind: 'apply-retry', summary: { conflicts: [], retryPending: false } },
+ existing,
now
)
- expect(carried).toStrictEqual({ networkPolicyOwnershipConditions: published })
- const retried = translateNetworkPolicyApplySummary(
- { conflicts: [], retryPending: true },
- published,
+ expect(reasons(settled)).toEqual([
+ 'WorkflowNetworkPoliciesConverged/PrunePending',
+ 'WorkflowLegacyNetworkPolicyRemoved/DeletePending',
+ ])
+ expect(settled.every(c => c.lastTransitionTime === earlier)).toBe(true)
+ })
+
+ it('R4-L3: carries an unevaluated prune through a pending retry', () => {
+ const existing = published({ prune: 'unevaluated' })
+
+ const retried = networkPolicyMarkerConditions(
+ { kind: 'apply-retry', summary: { conflicts: [], retryPending: true } },
+ existing,
now
)
- expect(convergedMarkers(retried)).toMatchObject([
- { reason: 'RetryAndPruneUnevaluated', lastTransitionTime: earlier },
+
+ expect(reasons(retried)).toEqual([
+ 'WorkflowNetworkPoliciesConverged/RetryAndPruneUnevaluated',
+ ])
+ })
+
+ it('R4-L3: publishes the conflicts the retry observed', () => {
+ const retried = networkPolicyMarkerConditions(
+ { kind: 'apply-retry', summary: { conflicts: [conflict], retryPending: false } },
+ [],
+ now
+ )
+
+ expect(reasons(retried)).toEqual(['WorkflowNetworkPolicyOwnership/OwnershipConflict'])
+ })
+ })
+
+ describe('terminal', () => {
+ it('R4-L3: drops a pending apply and carries the prune, the legacy fact and the ownership condition', () => {
+ const existing = published({
+ conflicts: [conflict],
+ retryPending: true,
+ prune: 'pending',
+ legacy: 'pending',
+ })
+ // Liveness witness: all three conditions were published.
+ expect(existing).toHaveLength(3)
+
+ const settled = networkPolicyMarkerConditions({ kind: 'terminal' }, existing, now)
+
+ expect(reasons(settled)).toEqual([
+ 'WorkflowNetworkPolicyOwnership/OwnershipConflict',
+ 'WorkflowNetworkPoliciesConverged/PrunePending',
+ 'WorkflowLegacyNetworkPolicyRemoved/DeletePending',
])
})
+
+ it('R4-L3: removes a marker that only named a pending apply', () => {
+ const existing = published({ retryPending: true })
+ expect(reasons(existing)).toEqual(['WorkflowNetworkPoliciesConverged/RetryPending'])
+
+ expect(networkPolicyMarkerConditions({ kind: 'terminal' }, existing, now)).toEqual([])
+ })
+ })
+
+ describe('unmanaged', () => {
+ it('R4-L3: clears every fact after a full SDK teardown', () => {
+ const existing = published({
+ conflicts: [conflict],
+ retryPending: true,
+ prune: 'unevaluated',
+ legacy: 'pending',
+ })
+ // Liveness witness: the group was published.
+ expect(existing).toHaveLength(3)
+
+ expect(networkPolicyMarkerConditions({ kind: 'unmanaged' }, existing, now)).toEqual([])
+ })
+ })
+
+ describe('a reason this controller did not write', () => {
+ const foreignMarker = {
+ type: 'WorkflowNetworkPoliciesConverged',
+ status: 'False' as const,
+ reason: 'SomethingElse',
+ message: 'written by another head',
+ lastTransitionTime: earlier,
+ }
+ const foreignLegacy = {
+ type: 'WorkflowLegacyNetworkPolicyRemoved',
+ status: 'False' as const,
+ reason: 'SomethingElse',
+ message: 'written by another head',
+ lastTransitionTime: earlier,
+ }
+
+ it('R4-L3: is kept as it is by a carrying writer, which warns', () => {
+ const warnLog = captureLogger('warn')
+ try {
+ const carried = networkPolicyMarkerConditions(
+ { kind: 'terminal' },
+ [foreignMarker, foreignLegacy],
+ now
+ )
+
+ expect(carried).toEqual([foreignMarker, foreignLegacy])
+ expect(warnLog).toHaveBeenCalledTimes(2)
+ expect(warnLog).toHaveBeenCalledWith(
+ 'Keeping a NetworkPolicy marker with a reason this controller did not write',
+ {
+ writer: 'terminal',
+ type: 'WorkflowNetworkPoliciesConverged',
+ status: 'False',
+ reason: 'SomethingElse',
+ }
+ )
+ } finally {
+ warnLog.mockRestore()
+ }
+ })
+
+ it('R4-L3: is overwritten by reconcile()', () => {
+ const warnLog = captureLogger('warn')
+ try {
+ const overwritten = networkPolicyMarkerConditions(
+ { kind: 'reconcile', summary: pass({ prune: 'pending' }) },
+ [foreignMarker, foreignLegacy],
+ now
+ )
+
+ expect(reasons(overwritten)).toEqual(['WorkflowNetworkPoliciesConverged/PrunePending'])
+ expect(warnLog).not.toHaveBeenCalled()
+ // Liveness witness: the same input through a carrying writer warns.
+ networkPolicyMarkerConditions({ kind: 'terminal' }, [foreignMarker], now)
+ expect(warnLog).toHaveBeenCalledTimes(1)
+ } finally {
+ warnLog.mockRestore()
+ }
+ })
})
})