Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(wrc): normalize policy defaults and strengthen convergence contracts
Alfredo Lopezf37ce9b311f7
diff --git a/docs/deploy/workflow-recipes-guide.md b/docs/deploy/workflow-recipes-guide.mdindex 0cd5e2559..1467ed345 100644--- a/docs/deploy/workflow-recipes-guide.md+++ b/docs/deploy/workflow-recipes-guide.md@@ -345,8 +345,11 @@ it cannot hide later drift.not emit a WorkflowRecipe event. The following reconcile is read-only.- **Retryable races schedule their own recovery.** A terminating object, create conflictwhose winner disappears, missing live `resourceVersion`, replace 404/409 or transient- API failure re-enqueues the parent with bounded backoff. A status-only update is not- treated as the retry trigger.+ API failure re-enqueues the parent with exponential backoff (5 seconds initially,+ capped at 60 seconds for consecutive transient results). The cap limits the delay,+ not the total number of attempts: a policy waiting on a finalizer can recover when+ deletion eventually completes without another parent event. A status-only update+ is not treated as the retry trigger.- **Metadata ownership applies to writes too.** Replacing a policy preserves externallabels, annotations and finalizers from the validated snapshot. Desired WRC keys win;retired egress state and the legacy spec-hash are removed. Additional foreign lifecyclediff --git a/scripts/tests/test-wrc-fixtures.sh b/scripts/tests/test-wrc-fixtures.shindex 5e89c9a89..857b9f3a2 100755--- a/scripts/tests/test-wrc-fixtures.sh+++ b/scripts/tests/test-wrc-fixtures.sh@@ -74,6 +74,25 @@ must_reject() {fi}+assert_no_delete_calls() {+ local status=0+ grep -q '^delete ' "$1" || status=$?+ # Only grep's no-match result proves absence. A missing binary or unreadable+ # call log must fail, rather than becoming a successful negative assertion.+ [[ "$status" -eq 1 ]]+}++printf 'delete fixture\n' > "$TEST_ROOT/calls"+must_reject assert_no_delete_calls "$TEST_ROOT/calls"+: > "$TEST_ROOT/calls"+assert_no_delete_calls "$TEST_ROOT/calls"+must_reject assert_no_delete_calls "$TEST_ROOT/missing-calls"+(+ grep() { return 127; }+ must_reject assert_no_delete_calls "$TEST_ROOT/calls"+)+echo 'PASS: no-delete assertion rejects writes, unreadable logs, and unavailable search dependency'+reset_fixturecreate_fixturejq -e '.metadata.uid=="created-uid" and .metadata.labels["e2e.clerum.io/run"]=="contract123" and (has("data")|not)' \@@ -85,12 +104,12 @@ echo 'PASS: collision preserves prior object and does not enroll it twice'MODE=read-errormust_reject wrc_delete_owned sandbox-recipes ConfigMap fixture-[[ "$(rg -c '^delete ' "$TEST_ROOT/calls" || true)" == '' ]]+assert_no_delete_calls "$TEST_ROOT/calls"MODE=normaljq '.metadata.uid="replacement-uid"' "$TEST_ROOT/live.json" > "$TEST_ROOT/replacement.json"mv "$TEST_ROOT/replacement.json" "$TEST_ROOT/live.json"must_reject wrc_delete_owned sandbox-recipes ConfigMap fixture-[[ "$(rg -c '^delete ' "$TEST_ROOT/calls" || true)" == '' ]]+assert_no_delete_calls "$TEST_ROOT/calls"echo 'PASS: read errors and changed UID refuse deletion'reset_fixturediff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex 3ba32f781..dfadc90db 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.350",+ "version": "0.1.351","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.350",+ "version": "0.1.351","license": "SEE LICENSE IN LICENSE","dependencies": {"@aws-sdk/client-s3": "^3.1009.0",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex 602cd213c..833f27248 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.350",+ "version": "0.1.351","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/src/reconciler/networkPolicyConvergence.property.test.ts b/workflow-recipes/src/reconciler/networkPolicyConvergence.property.test.tsnew file mode 100644index 000000000..c511ffe9d--- /dev/null+++ b/workflow-recipes/src/reconciler/networkPolicyConvergence.property.test.ts@@ -0,0 +1,193 @@+import { describe, expect, it } from 'vitest'+import * as k8s from '@kubernetes/client-node'+import { ObjectSerializer } from '@kubernetes/client-node/dist/gen/models/ObjectSerializer'+import fc from 'fast-check'+import type { WorkflowRecipeCRD } from '../types'+import {+ buildNetworkPolicyReplacement,+ classifyOwnerlessNetworkPolicyOwnership,+ decideNetworkPolicyConvergence,+ networkPolicyMatchesDesired,+} from './networkPolicyConvergence'+import {+ buildUiEgressNetworkPolicy,+ buildUiIngressNetworkPolicy,+ buildWorkloadIngressNetworkPolicy,+} from './resourceBuilder'++// Exercise the installed Kubernetes model/wire conversion. The few server+// defaults below are explicit: ObjectSerializer itself is not an API server.+function apiRoundTrip(policy: k8s.V1NetworkPolicy): k8s.V1NetworkPolicy {+ const wire = ObjectSerializer.serialize(policy, 'V1NetworkPolicy', '')+ if (!wire.spec.policyTypes?.length) {+ wire.spec.policyTypes = wire.spec.egress?.length ? ['Ingress', 'Egress'] : ['Ingress']+ }+ for (const rule of [...(wire.spec.ingress ?? []), ...(wire.spec.egress ?? [])]) {+ for (const port of rule.ports ?? []) port.protocol ??= 'TCP'+ }+ return ObjectSerializer.deserialize(JSON.parse(JSON.stringify(wire)), 'V1NetworkPolicy', '')+}++const scenario = fc.record({+ id: fc.integer({ min: 1, max: 1_000_000 }),+ ports: fc.uniqueArray(fc.integer({ min: 1, max: 65535 }), { minLength: 1, maxLength: 6 }),+ revision: fc.integer({ min: 1, max: 1_000_000 }),+ protocol: fc.constantFrom('TCP' as const, 'UDP' as const),+ reverse: fc.boolean(),+})++function generatedPolicies(input: fc.ArbitraryValue<typeof scenario>) {+ const ports = input.reverse ? [...input.ports].reverse() : input.ports+ const recipe: WorkflowRecipeCRD = {+ apiVersion: 'clerum.io/v1alpha1',+ kind: 'WorkflowRecipe',+ metadata: { name: `recipe-${input.id}`, namespace: 'sandbox-recipes', uid: `uid-${input.id}` },+ spec: {+ workloads: [{ id: 'backend', type: 'deployment', image: 'nginx:1.30.1-alpine' }],+ ui: {+ workloadRef: 'backend',+ port: ports[0],+ egress: { internal: ports.map(port => ({ workloadRef: 'backend', port })) },+ },+ },+ }+ return [+ buildUiEgressNetworkPolicy(recipe, 'sandbox-ui', 'sandbox-recipes', [])!,+ buildUiIngressNetworkPolicy(recipe, 'backend', ports, 'sandbox-recipes', 'sandbox-ui')!,+ buildWorkloadIngressNetworkPolicy(+ recipe.spec.workloads[0],+ recipe,+ 'sandbox-recipes',+ ports.map(port => ({+ fromWorkloadId: 'caller',+ fromNamespace: 'sandbox-recipes',+ port,+ protocol: input.protocol,+ }))+ )!,+ ]+}++describe('generated NetworkPolicy serialization and replacement properties', () => {+ it('preserves real producer enforcement through model and wire round trips', () => {+ fc.assert(+ fc.property(scenario, input => {+ for (const desired of generatedPolicies(input)) {+ if (input.reverse) {+ for (const rule of [+ ...(desired.spec!.ingress ?? []),+ ...(desired.spec!.egress ?? []),+ ]) {+ for (const port of rule.ports ?? []) {+ if (port.protocol === 'TCP') delete port.protocol+ }+ }+ if (desired.spec!.policyTypes?.[0] === 'Ingress') {+ delete desired.spec!.policyTypes+ desired.spec!.egress = []+ } else {+ desired.spec!.ingress = []+ }+ }+ const before = structuredClone(desired)+ const wire = ObjectSerializer.serialize(desired, 'V1NetworkPolicy', '')+ if (desired.spec!.ingress?.length) {+ expect(wire.spec.ingress[0].from).toEqual(desired.spec!.ingress[0]._from)+ expect(wire.spec.ingress[0]._from).toBeUndefined()+ }+ expect(networkPolicyMatchesDesired(desired, wire)).toBe(true)+ const live = apiRoundTrip(desired)+ expect(networkPolicyMatchesDesired(desired, live)).toBe(true)+ expect(networkPolicyMatchesDesired(desired, apiRoundTrip(live))).toBe(true)+ // Comparison must retain the generated security boundary, not just+ // accept all API responses as equivalent.+ const drifted = apiRoundTrip(desired)+ drifted.spec!.podSelector = {}+ expect(networkPolicyMatchesDesired(desired, drifted)).toBe(false)+ expect(desired).toEqual(before)+ }+ }),+ { numRuns: 100 }+ )+ })++ it('makes replacement idempotent and composes desired updates across both writer families', () => {+ fc.assert(+ fc.property(scenario, scenario, (first, second) => {+ const initial = generatedPolicies(first)+ const updates = generatedPolicies({ ...second, id: first.id })+ for (let index = 0; index < initial.length; index++) {+ const family = index === 1 ? 'ui-ingress' : index === 2 ? 'workload-ingress' : undefined+ const desired = initial[index]+ const live = apiRoundTrip(desired)+ live.metadata!.resourceVersion = String(first.revision)+ live.metadata!.labels!['admission.example/revision'] = String(first.id)+ live.metadata!.annotations = {+ 'clerum.io/external-controller-note': String(first.id),+ 'clerum.io/egress-fqdn-state': 'retired-state',+ 'clerum.io/spec-hash': 'legacy-hash',+ }+ live.metadata!.finalizers = ['admission.example/hold']+ live.spec!.podSelector = {}+ const snapshot = structuredClone(live)+ const replacement = buildNetworkPolicyReplacement(desired, live)+ expect(replacement.metadata!.resourceVersion).toBe(String(first.revision))+ expect(networkPolicyMatchesDesired(desired, apiRoundTrip(replacement))).toBe(true)+ if (family) {+ expect(+ decideNetworkPolicyConvergence(family, desired, apiRoundTrip(replacement))+ ).toEqual({+ action: 'unchanged',+ })+ }+ expect(buildNetworkPolicyReplacement(desired, apiRoundTrip(replacement))).toEqual(+ replacement+ )++ const update = updates[index]+ // Updating the same identity with a new port set must compose just as+ // applying the newest desired state directly to the original snapshot.+ const composed = buildNetworkPolicyReplacement(update, apiRoundTrip(replacement))+ expect(composed).toEqual(buildNetworkPolicyReplacement(update, live))+ expect(composed.spec).toEqual(update.spec)+ expect(composed.metadata!.annotations).toEqual({+ 'clerum.io/external-controller-note': String(first.id),+ })+ expect(composed.metadata!.labels!['admission.example/revision']).toBe(String(first.id))+ expect(composed.metadata!.finalizers).toEqual(['admission.example/hold'])+ expect(networkPolicyMatchesDesired(update, apiRoundTrip(composed))).toBe(true)+ if (family) {+ expect(decideNetworkPolicyConvergence(family, update, apiRoundTrip(composed))).toEqual({+ action: 'unchanged',+ })+ }+ expect(live).toEqual(snapshot)+ // Replacement is only legal after ownership checks. An unexpected+ // lifecycle owner must still be vetoed even for matching enforcement.+ const foreign = apiRoundTrip(composed)+ foreign.metadata!.ownerReferences = [+ {+ apiVersion: 'apps/v1',+ kind: 'Deployment',+ name: 'foreign',+ uid: `foreign-${first.id}`,+ controller: true,+ },+ ]+ if (family) {+ expect(decideNetworkPolicyConvergence(family, update, foreign)).toEqual({+ action: 'conflict',+ reason: 'owner-reference-mismatch',+ })+ } else {+ expect(classifyOwnerlessNetworkPolicyOwnership(foreign)).toEqual({+ kind: 'conflict',+ reason: 'owner-reference-mismatch',+ })+ }+ }+ }),+ { numRuns: 100 }+ )+ })+})diff --git a/workflow-recipes/src/reconciler/networkPolicyConvergence.test.ts b/workflow-recipes/src/reconciler/networkPolicyConvergence.test.tsindex c42e1cfb6..c69694851 100644--- a/workflow-recipes/src/reconciler/networkPolicyConvergence.test.ts+++ b/workflow-recipes/src/reconciler/networkPolicyConvergence.test.ts@@ -9,6 +9,8 @@ import {const SPEC_HASH = 'clerum.io/spec-hash'+// These minimal fixtures isolate comparison and ownership edge cases. Real+// producer output and Kubernetes serialization are covered by the property suite.function policy(): k8s.V1NetworkPolicy {return {apiVersion: 'networking.k8s.io/v1',@@ -84,6 +86,20 @@ describe('NetworkPolicy live convergence', () => {expect(networkPolicyMatchesDesired(desired, live)).toBe(true)})+ it('compares inferred mixed policyTypes with API defaults in either order', () => {+ const desired = policy()+ delete desired.spec!.policyTypes+ desired.spec!.egress = [{ ports: [{ port: 443 }] }]+ for (const policyTypes of [+ ['Ingress', 'Egress'],+ ['Egress', 'Ingress'],+ ]) {+ const live = structuredClone(desired)+ live.spec!.policyTypes = policyTypes+ expect(networkPolicyMatchesDesired(desired, live)).toBe(true)+ }+ })+it('normalizes the client model _from field and the Kubernetes wire from field', () => {const desired = policy()desired.spec!.ingress = [diff --git a/workflow-recipes/src/reconciler/networkPolicyConvergence.ts b/workflow-recipes/src/reconciler/networkPolicyConvergence.tsindex ee6b4079a..b59c27fc3 100644--- a/workflow-recipes/src/reconciler/networkPolicyConvergence.ts+++ b/workflow-recipes/src/reconciler/networkPolicyConvergence.ts@@ -165,9 +165,8 @@ function normalizeProjectedNetworkPolicy(normalized: k8s.V1NetworkPolicy): unknoconst hasEgressRules = (spec.egress?.length ?? 0) > 0if (!spec.policyTypes?.length) {spec.policyTypes = hasEgressRules ? ['Ingress', 'Egress'] : ['Ingress']- } else {- spec.policyTypes = [...spec.policyTypes].sort()}+ spec.policyTypes = [...spec.policyTypes].sort()for (const rule of spec.ingress ?? []) normalizeIngressFrom(rule)for (const rule of [...(spec.ingress ?? []), ...(spec.egress ?? [])]) {for (const port of rule.ports ?? []) {@@ -181,10 +180,6 @@ function normalizeProjectedNetworkPolicy(normalized: k8s.V1NetworkPolicy): unknoreturn canonicalizeValue(normalized)}-export function normalizeNetworkPolicyForComparison(policy: k8s.V1NetworkPolicy): unknown {- return normalizeProjectedNetworkPolicy(projectNetworkPolicyForComparison(policy, policy))-}-export function networkPolicyMatchesDesired(desired: k8s.V1NetworkPolicy | undefined,existing: k8s.V1NetworkPolicy | undefineddiff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.tsindex 0cc3f51f9..28e36557a 100644--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts@@ -5691,6 +5691,8 @@ export class WorkflowRecipeReconciler {)}if (decision.action === 'retry') {+ // The early deletion guard currently handles this before ownership checks.+ // Keep the pure decision's retry outcome fail-closed at this consumer too.throw new RetryableReconcileError(`NetworkPolicy "${policyName}" in ${namespace} is terminating; retrying after deletion`)