Skip to content

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

TypeScript

fix(wrc,hcc): close the #568 review — brand, notify, and the vacuous assertion

Alfredo Lopezd8f112419137
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 677db12b5..aa4238fa6 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.286",
+ "version": "0.1.287",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.286",
+ "version": "0.1.287",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index 2bc819451..53fc757ae 100644
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.286",
+ "version": "0.1.287",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.ts
index b48e67bc5..65eea1818 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -38,6 +38,19 @@ async function flushMicrotasks(turns = 8): Promise<void> {
}
}
+/**
+ * How many Context MODIFIED events HCC has absorbed as metadata-only. Read from
+ * the real registry rather than a spy, because this is also the signal an
+ * operator watches for the #460 storm returning — a test that asserted on a mock
+ * would not tell us the metric is actually registered and named.
+ */
+async function metadataOnlyEventCount(): Promise<number> {
+ const metric = registry.getSingleMetric('clerum_hcc_context_metadata_only_events_total')
+ if (!metric) throw new Error('clerum_hcc_context_metadata_only_events_total is not registered')
+ const snapshot = await metric.get()
+ return snapshot.values[0]?.value ?? 0
+}
+
async function readInitialConvergenceMetric(
name:
| 'clerum_hcc_initial_convergence_retries_total'
@@ -2152,6 +2165,22 @@ describe('McpServerWatcher startup', () => {
expect.objectContaining({ name: 'steady-context' }),
expect.objectContaining({ honorsLostFence: false })
)
+ // Which of the two negative assertions below actually pins the gate, by
+ // mutation rather than by reading (#568 review, jozer-rami #3):
+ //
+ // remove ONLY the `if (metadataOnlyModified) return` -> this test STAYS GREEN
+ // remove ONLY the `if (!metadataOnlyModified)` SFS skip -> this test DIES
+ //
+ // So `sfsPropagate` is the load-bearing one, and it is load-bearing because
+ // the SFS skip happens earlier, outside the try. `hostReconcile` is NOT
+ // pinning the gate on this input: the 409 is caught, the catch calls
+ // runInitialNetworkPolicyConvergence and RETURNS, and both the gate's early
+ // return and reconcileHostsReferencingContext are downstream of that return.
+ // The two are redundant here and no assertion in this test can tell them
+ // apart. Kept as a cheap regression guard on the catch's ordering — if the
+ // catch stopped returning, the gate would still have to hold the line — but
+ // the Host-skip itself is pinned by the two non-rejecting tests (T4 and the
+ // #460 Phase 2 test), which are the ones the first mutation kills.
expect(hostReconcile).not.toHaveBeenCalled()
expect(sfsPropagate).not.toHaveBeenCalled()
await vi.waitFor(() =>
@@ -2783,6 +2812,10 @@ describe('McpServerWatcher startup', () => {
hostReconcile.mockClear()
sfsPropagate.mockClear()
+ const changeSpy = vi.fn()
+ watcher.onChange(changeSpy)
+ const metadataOnlyBefore = await metadataOnlyEventCount()
+
const revisionBefore = (watcher as any).contextDesiredRevision
const cachedBefore = (watcher as any).contexts.get('shared-context')
await contextWatchCallback!('MODIFIED', added)
@@ -2804,6 +2837,22 @@ describe('McpServerWatcher startup', () => {
expect(hostReconcile).not.toHaveBeenCalled()
expect(sfsPropagate).not.toHaveBeenCalled()
+ // The quiet path notifies nobody. An earlier revision called changeCallback
+ // here — the one event where nothing changed, and where this same commit
+ // deliberately does not even replace the cache entry — while a real
+ // desired-state change on this watch still did not call it. The only
+ // subscriber is a console.log in main.ts reporting the MCPSERVER cache, so
+ // for a Context event the line was wrong, and the getAllServers() behind it
+ // is an O(n) rebuild on the hot path this PR removes work from
+ // (#568 review: jozer-rami #2 / zach88 R1-M1, both independently).
+ expect(changeSpy).not.toHaveBeenCalled()
+
+ // …but the absorption is not invisible. The counter is the witness that this
+ // branch ran, which is also what makes the negative assertions above mean
+ // "correctly skipped" rather than "never executed", and it is what an
+ // operator watches to see the Loop A storm return.
+ expect(await metadataOnlyEventCount()).toBe(metadataOnlyBefore + 1)
+
await watcher.stop()
})
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index dc1cb34c5..374113ff0 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -55,6 +55,7 @@ import {
sameMcpServerDesiredRevision,
} from './mcpServerSafety'
import {
+ contextMetadataOnlyEventsTotal,
hostDeleteCleanupTotal,
hostFleetLifecycleCatchTotal,
hostFleetRequestsTotal,
@@ -4372,10 +4373,21 @@ export class McpServerWatcher implements McpServerProvider {
// NetworkPolicy revoke: without a delta certificate honorsLostFence is
// false, so a lost delete fence still throws into full convergence.
// Periodic resync (default 0 / #478) is not the healer for this path.
+ // No changeCallback here. The Context watch never notified before this PR,
+ // and adding the notification on THIS path would have fired it exactly
+ // where nothing changed — the label ping-pong this gate exists to silence —
+ // while a real desired-state change on the same watch still would not fire
+ // it. The only subscriber is a `console.log` in main.ts that reports the
+ // McpServer cache, so for a Context event the line is wrong, and the
+ // `getAllServers()` behind it is an O(n) rebuild on the hot path this PR
+ // removes work from (#568 review: jozer-rami #2 / zach88 R1-M1, converged).
const metadataOnlyModified = type === 'MODIFIED' && !desiredStateChanged
- if (metadataOnlyModified) {
- this.changeCallback?.()
- }
+ // The absorption must not be invisible: if the Loop A storm ever returns,
+ // HCC now silently eats it. A COUNTER rather than a log line, because this
+ // fires on exactly the churn that made the logs unreadable in the first
+ // place (#492) — a per-event line would reproduce the problem it is meant
+ // to make observable (claude[bot] audit, finding 1).
+ if (metadataOnlyModified) contextMetadataOnlyEventsTotal.inc()
// Re-reconcile every SFS this Context referenced before or after the
// change so SharedFileSystem.status.mountedByContexts stays in sync
diff --git a/host-context-controller/src/metrics.ts b/host-context-controller/src/metrics.ts
index 76e35cb21..c7af445f3 100644
--- a/host-context-controller/src/metrics.ts
+++ b/host-context-controller/src/metrics.ts
@@ -155,6 +155,11 @@ export const netPolResyncTicksSkippedTotal = counter({
labelNames: ['reason'] as const,
})
+export const contextMetadataOnlyEventsTotal = counter({
+ name: 'clerum_hcc_context_metadata_only_events_total',
+ help: 'Context MODIFIED watch events that did not move the desired revision, so Host and SharedFileSystem fan-out were skipped (#460 Loop A label churn absorbed by HCC). A rising rate here is the storm returning; it is deliberately a counter and not a log line, because the event fires on exactly the churn that made the logs unreadable (#492).',
+})
+
export const netPolDefaultsOnlyTicksTotal = counter({
name: 'clerum_hcc_netpol_defaults_only_ticks_total',
help: 'NetworkPolicy defaults-only ticks by named result (success/error).',
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 8549a3f01..6f0ac98c7 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.341",
+ "version": "0.1.342",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.341",
+ "version": "0.1.342",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
@@ -31,6 +31,7 @@
"@types/js-yaml": "^4.0.9",
"@types/node": "^20.10.0",
"@types/pg": "^8.20.0",
+ "fast-check": "^4.9.0",
"js-yaml": "^4.1.1",
"ts-node": "^10.9.2",
"vitest": "^3.0.0"
@@ -2700,6 +2701,29 @@
"express": ">= 4.11"
}
},
+ "node_modules/fast-check": {
+ "version": "4.9.0",
+ "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.9.0.tgz",
+ "integrity": "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/dubzzz"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fast-check"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "pure-rand": "^8.0.0"
+ },
+ "engines": {
+ "node": ">=12.17.0"
+ }
+ },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -3728,6 +3752,23 @@
"node": ">=6"
}
},
+ "node_modules/pure-rand": {
+ "version": "8.4.2",
+ "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-8.4.2.tgz",
+ "integrity": "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/dubzzz"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fast-check"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/qs": {
"version": "6.15.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index 0e09abecd..c105fced2 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.341",
+ "version": "0.1.342",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
@@ -29,8 +29,8 @@
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
- "@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract",
"@clerum/image-policy": "file:../packages/image-policy",
+ "@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/network-policy-core": "file:../packages/network-policy-core",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
@@ -49,6 +49,7 @@
"@types/js-yaml": "^4.0.9",
"@types/node": "^20.10.0",
"@types/pg": "^8.20.0",
+ "fast-check": "^4.9.0",
"js-yaml": "^4.1.1",
"ts-node": "^10.9.2",
"vitest": "^3.0.0"
diff --git a/workflow-recipes/src/reconciler/mcpDelegation.test.ts b/workflow-recipes/src/reconciler/mcpDelegation.test.ts
index 8903ef100..3f2152c65 100644
--- a/workflow-recipes/src/reconciler/mcpDelegation.test.ts
+++ b/workflow-recipes/src/reconciler/mcpDelegation.test.ts
@@ -989,6 +989,91 @@ describe('ensureRecipeContext', () => {
)
})
+ it('H04c — does NOT brand a shared Context with clerum.io/recipe at CREATE', async () => {
+ // Review of #568, jozer-rami #1. The replace path already omits the recipe
+ // label for an explicit Context — `authoredContextLabels(explicit=true, …)`
+ // returns `managed-by` only, and `authoredLabelsMatch` never checks it. The
+ // create path hardcoded it for every Context.
+ //
+ // Nothing rewrites it afterwards, so recipe A's name stayed on an object
+ // whose only remaining users were B and C, and it survived A's deletion. The
+ // PR body states the invariant as "shared Contexts do not stamp
+ // clerum.io/recipe", which was true on update and false on create.
+ //
+ // It is not purely cosmetic either: `scripts/e2e/e2e-snippet-runtime.sh`
+ // reaps with `kubectl delete mcpserver,context -l clerum.io/recipe=<name>`,
+ // so the brand puts a SHARED Context inside a delete-by-label blast radius.
+ const recipe = makeRecipe({ spec: { ...makeRecipe().spec, contextRef: 'context1' } })
+ const mockCustomApi = {
+ createNamespacedCustomObject: vi.fn().mockResolvedValue({}),
+ }
+ const deps: DelegationDeps = {
+ customApi: mockCustomApi as unknown as DelegationDeps['customApi'],
+ coreApi: {} as DelegationDeps['coreApi'],
+ }
+
+ const contextName = await ensureRecipeContext(
+ deps,
+ recipe,
+ ['test-recipe-redis-mcp'],
+ 'mcp-server',
+ ownerRef,
+ 'sandbox-recipes'
+ )
+
+ // Liveness witness: the create path really ran and really wrote this object.
+ // Without it, "no recipe label" is satisfied by a call that never happened.
+ expect(contextName).toBe('context1')
+ expect(mockCustomApi.createNamespacedCustomObject).toHaveBeenCalledTimes(1)
+ const body = mockCustomApi.createNamespacedCustomObject.mock.calls[0][0].body
+ expect(body.metadata.name).toBe('context1')
+ // Ownership is still claimed, so this is a narrowing and not a removal …
+ expect(body.metadata.labels).toEqual({ 'clerum.io/managed-by': 'wrc' })
+ // … and cross-namespace/explicit still means no ownerReference, as before.
+ expect(body.metadata.ownerReferences).toBeUndefined()
+ // H04a is the other half: a PRIVATE wf-* Context must still be branded, so a
+ // fix that simply dropped the label everywhere fails there rather than here.
+ })
+
+ it('heals a duplicated live mcpServers entry instead of skipping forever', async () => {
+ // Review of #568, jozer-rami minors. `sameMcpServerSet` collapsed both sides
+ // to a Set, so `['a','a']` and `['a']` compared equal: a duplicate that had
+ // reached spec.mcpServers was reported unchanged on every pass and could
+ // never be repaired. The length check makes exactly that case a write.
+ const recipe = makeRecipe({ spec: { ...makeRecipe().spec, contextRef: 'context1' } })
+ const mockCustomApi = {
+ createNamespacedCustomObject: vi.fn().mockRejectedValueOnce({ code: 409 }),
+ getNamespacedCustomObject: vi.fn().mockResolvedValue({
+ metadata: { resourceVersion: '7', labels: { 'clerum.io/managed-by': 'wrc' } },
+ spec: {
+ contextId: 'context1',
+ mcpServers: ['existing-server', 'existing-server', 'test-recipe-redis-mcp'],
+ },
+ }),
+ replaceNamespacedCustomObject: vi.fn().mockResolvedValue({}),
+ }
+ const deps: DelegationDeps = {
+ customApi: mockCustomApi as unknown as DelegationDeps['customApi'],
+ coreApi: {} as DelegationDeps['coreApi'],
+ }
+
+ await ensureRecipeContext(
+ deps,
+ recipe,
+ ['test-recipe-redis-mcp'],
+ 'mcp-server',
+ ownerRef,
+ 'sandbox-recipes'
+ )
+
+ // The pre-read happened (witness), and the pass did not skip.
+ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledTimes(1)
+ expect(mockCustomApi.replaceNamespacedCustomObject).toHaveBeenCalledTimes(1)
+ const written =
+ mockCustomApi.replaceNamespacedCustomObject.mock.calls[0][0].body.spec.mcpServers
+ expect(written).toEqual(['existing-server', 'test-recipe-redis-mcp'])
+ })
+
it('H04b — writes on 409 when live Context has no mcpServers (empty→filled is not a skip)', async () => {
const mockCustomApi = {
createNamespacedCustomObject: vi.fn().mockRejectedValueOnce({ code: 409 }),
diff --git a/workflow-recipes/src/reconciler/mcpDelegation.ts b/workflow-recipes/src/reconciler/mcpDelegation.ts
index 852ce28e4..498d337e3 100644
--- a/workflow-recipes/src/reconciler/mcpDelegation.ts
+++ b/workflow-recipes/src/reconciler/mcpDelegation.ts
@@ -118,7 +118,20 @@ const CONTEXT_RECIPE_LABEL = 'clerum.io/recipe'
const CONTEXT_MANAGED_BY_LABEL = 'clerum.io/managed-by'
const CONTEXT_MANAGED_BY_WRC = 'wrc'
+/**
+ * Set equality, plus a length check so a DUPLICATED live entry can heal.
+ *
+ * Collapsing both sides to a Set made `['a','a']` and `['a']` compare equal, so
+ * a `spec.mcpServers` that had acquired a duplicate — out-of-band, or from the
+ * pre-dedupe private path — was reported unchanged on every pass and could never
+ * be repaired. Comparing lengths first makes exactly that case a write, and the
+ * write is idempotent because both branches of `mergedServers` now dedupe
+ * (#568 review, jozer-rami minors).
+ *
+ * Order stays irrelevant: `mcpServers` is an allowlist, not a sequence.
+ */
function sameMcpServerSet(left: readonly string[], right: readonly string[]): boolean {
+ if (left.length !== right.length) return false
const leftSet = new Set(left)
const rightSet = new Set(right)
if (leftSet.size !== rightSet.size) return false
@@ -158,6 +171,22 @@ type ExistingContextSnapshot = {
spec?: { contextId?: string; mcpServers?: string[]; [key: string]: unknown }
}
+/**
+ * Identity of "an ownerRef this recipe planted", matched by kind + name only.
+ *
+ * `uid` is deliberately excluded: a STALE ref carries a stale uid, and matching
+ * on uid would stop the repair from ever recognising the thing it exists to
+ * strip. `apiVersion` is excluded for a subtler reason — including it would make
+ * a CRD version bump produce a ref we no longer recognise as ours, so
+ * `desiredOwnerReferences` would KEEP the old one and APPEND a new one, leaving
+ * the Context owned twice by the same recipe. Stricter here is worse.
+ *
+ * Correctness rests on one assumption, pinned here rather than left implicit:
+ * ownerReferences are namespace-local, and under canonical namespacing no
+ * WorkflowRecipe lives in the Context's namespace (`mcp-server`), so no
+ * same-named foreign recipe ref can exist to be stripped by mistake
+ * (#568 review: jozer-rami minors, claude[bot] finding 2).
+ */
function isThisRecipeOwner(
ref: ContextOwnerReference,
recipeOwner: ContextOwnerReference
@@ -178,6 +207,16 @@ function desiredOwnerReferences(
return kept
}
+/**
+ * Order-INSENSITIVE ownerRef comparison, which is why it is not `stableJson`.
+ *
+ * `stableJson` (`:66`) sorts object keys but preserves array order, so using it
+ * here would report a merely REORDERED ownerReferences list as changed and turn
+ * a no-op into a write — the churn this PR exists to remove. Order carries no
+ * meaning in `ownerReferences`, so set semantics over a 6-field key is the
+ * correct comparison, not a hand-rolled duplicate of an existing helper
+ * (#568 review, jozer-rami minors).
+ */
function ownerReferenceKey(ref: ContextOwnerReference): string {
return [
ref.apiVersion,
@@ -217,7 +256,7 @@ function observedContextId(value: unknown): string {
* labels, normalized contextId, and the recipe-owned ownerRef relation already
* match the body this reconcile would write.
*/
-function planContextReplacement(
+export function planContextReplacement(
existing: ExistingContextSnapshot,
args: {
contextName: string
@@ -235,9 +274,13 @@ function planContextReplacement(
nextOwnerReferences: ContextOwnerReference[]
} | null {
const existingServers = Array.isArray(existing.spec?.mcpServers) ? existing.spec.mcpServers : []
+ // Both paths dedupe. The private path used to pass `serverNames` through
+ // verbatim, so a duplicated entry would be written into `spec.mcpServers` and
+ // then hidden by `sameMcpServerSet`, which collapses both sides to a Set and
+ // would never see the difference again (#568 review, R1-L4).
const mergedServers = args.explicitContext
? Array.from(new Set([...existingServers, ...args.serverNames]))
- : [...args.serverNames]
+ : Array.from(new Set(args.serverNames))
const existingLabels = existing.metadata?.labels ?? {}
const authoredLabels = authoredContextLabels(args.explicitContext, args.recipeName)
const observedId = observedContextId(existing.spec?.contextId)
@@ -835,10 +878,14 @@ export async function ensureRecipeContext(
name: contextName,
namespace,
...(!explicitContext && sameNsAsRecipe && { ownerReferences: [ownerReference] }),
- labels: {
- [CONTEXT_RECIPE_LABEL]: recipeName,
- [CONTEXT_MANAGED_BY_LABEL]: CONTEXT_MANAGED_BY_WRC,
- },
+ // Same projection as the replace path. Branding a SHARED Context with
+ // `clerum.io/recipe` at birth outlives the recipe that happened to create
+ // it: the label is never rewritten (authoredLabelsMatch does not check it
+ // for an explicit Context), so recipe A's name stays on an object whose
+ // only remaining users are B and C. The ownerReferences line above already
+ // gates on `explicitContext`; the labels were the one field in this
+ // literal that ignored it (#568 review, jozer-rami).
+ labels: authoredContextLabels(explicitContext, recipeName),
},
spec: {
contextId: contextName,
@@ -924,6 +971,12 @@ export async function ensureRecipeContext(
throw new Error(`failed to update Context "${contextName}" after conflict retries`)
}
+ // One mechanism for all three outcomes of this one decision. The skip branch
+ // introduced `createLogger` while its siblings stayed on `console.log`, which
+ // left the same event reported two ways (#568 review, R1-L5). Scoped to this
+ // function: the file-wide console -> logger migration is #569.
+ const log = createLogger('wrc', recipeName)
+
try {
await deps.customApi.createNamespacedCustomObject({
group: CRD_GROUP,
@@ -932,18 +985,18 @@ export async function ensureRecipeContext(
plural: CONTEXT_PLURAL,
body: contextBody,
})
- console.log(
- `[MCP-Delegation] Created per-recipe Context "${contextName}" with ${serverNames.length} server(s)`
- )
+ log.info('Created per-recipe Context', { contextName, servers: serverNames.length })
} catch (error) {
if (getErrorCode(error) === 409) {
const { wrote } = await replaceExistingContext()
if (wrote) {
- console.log(
- `[MCP-Delegation] Updated per-recipe Context "${contextName}" with ${serverNames.length} server(s)`
- )
+ log.info('Updated per-recipe Context', { contextName, servers: serverNames.length })
} else {
- createLogger('wrc', recipeName).info('Context unchanged; skipping update', { contextName })
+ // DEBUG, not INFO. This is the steady state: it fires on every reconcile
+ // pass for every recipe, which at the current cadence is the log volume
+ // #492 exists about. The writes above are the events worth an INFO line;
+ // "nothing happened" is not (#568 review, jozer-rami minors).
+ log.debug('Context unchanged; skipping update', { contextName })
}
} else {
throw error
diff --git a/workflow-recipes/src/reconciler/planContextReplacement.property.test.ts b/workflow-recipes/src/reconciler/planContextReplacement.property.test.ts
new file mode 100644
index 000000000..1dd02d8ed
--- /dev/null
+++ b/workflow-recipes/src/reconciler/planContextReplacement.property.test.ts
@@ -0,0 +1,133 @@
+// Property coverage for the Context replace planner (#568 review, zach88 R1-M2).
+//
+// `planContextReplacement` is the single source of truth for both the skip
+// decision and the PUT body, so a defect in it is either a lost repair or a
+// write storm. The example tests in mcpDelegation.test.ts pin named scenarios;
+// these pin the INVARIANTS over random inputs, which is what "never shrinks the
+// allowlist" and "converges" actually mean.
+//
+// The three that matter, and why:
+//
+// no-shrink a shared Context is multi-writer. If recipe A's pass could
+// drop a server B declared, A would silently de-authorize B.
+// no-duplicates a duplicate in spec.mcpServers used to be permanent: the old
+// sameMcpServerSet collapsed both sides to a Set and could
+// never see it again (jozer-rami minors).
+// convergence the planner must reach a fixed point. A plan that always
+// reports "changed" is a write on every reconcile pass, for
+// every recipe, forever — the #460 storm this PR closes.
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import { planContextReplacement } from './mcpDelegation'
+
+const ownerReference = {
+ apiVersion: 'clerum.io/v1alpha1',
+ kind: 'WorkflowRecipe',
+ name: 'test-recipe',
+ uid: 'uid-abc-123',
+ controller: true,
+ blockOwnerDeletion: true,
+}
+
+/** Server names are DNS-ish labels; a small alphabet makes collisions frequent,
+ * which is the point — random unique strings would never exercise the dedupe. */
+const serverName = fc.constantFrom('a-mcp', 'b-mcp', 'c-mcp', 'd-mcp')
+const serverList = fc.array(serverName, { maxLength: 8 })
+
+function planArgs(explicitContext: boolean, serverNames: readonly string[]) {
+ return {
+ contextName: 'context1',
+ explicitContext,
+ // Cross-namespace, so ownerReferences stay empty and the properties below
+ // isolate the mcpServers merge rather than the ownership repair.
+ sameNsAsRecipe: false,
+ recipeName: 'test-recipe',
+ serverNames,
+ ownerReference,
+ }
+}
+
+function liveContext(mcpServers: readonly string[], contextId = 'context1') {
+ return {
+ metadata: { resourceVersion: '1', labels: { 'clerum.io/managed-by': 'wrc' } },
+ spec: { contextId, mcpServers: [...mcpServers] },
+ }
+}
+
+describe('planContextReplacement invariants', () => {
+ it('shared Context: the merged allowlist never loses a server that was live', () => {
+ fc.assert(
+ fc.property(serverList, serverList, (existing, desired) => {
+ const plan = planContextReplacement(liveContext(existing), planArgs(true, desired))
+ // A null plan is a skip, which by definition writes nothing and so
+ // cannot shrink anything. Only a planned write can drop an entry.
+ if (plan === null) return
+ for (const name of existing) expect(plan.mergedServers).toContain(name)
+ for (const name of desired) expect(plan.mergedServers).toContain(name)
+ })
+ )
+ })
+
+ it('never plans a body containing duplicates, on either path', () => {
+ fc.assert(
+ fc.property(fc.boolean(), serverList, serverList, (explicit, existing, desired) => {
+ const plan = planContextReplacement(liveContext(existing), planArgs(explicit, desired))
+ if (plan === null) return
+ expect(new Set(plan.mergedServers).size).toBe(plan.mergedServers.length)
+ })
+ )
+ })
+
+ it('converges: applying a plan makes the next pass a skip', () => {
+ fc.assert(
+ fc.property(fc.boolean(), serverList, serverList, (explicit, existing, desired) => {
+ const args = planArgs(explicit, desired)
+ const first = planContextReplacement(liveContext(existing), args)
+ if (first === null) return
+
+ // Apply the plan the way replaceExistingContext does, then re-plan
+ // against the resulting object. A planner that cannot reach a fixed
+ // point writes on every pass forever.
+ const applied = {
+ metadata: {
+ resourceVersion: '2',
+ labels: { ...first.existingLabels, ...first.authoredLabels },
+ ...(first.nextOwnerReferences.length > 0
+ ? { ownerReferences: first.nextOwnerReferences }
+ : {}),
+ },
+ spec: { contextId: first.nextContextId, mcpServers: first.mergedServers },
+ }
+ expect(planContextReplacement(applied, args)).toBeNull()
+ })
+ )
+ })
+
+ it('a private Context is authoritative: the merged set is exactly what was asked for', () => {
+ // The counterpart to no-shrink. `wf-*` is single-writer, so removing a
+ // server from the recipe MUST remove it from the Context — a property that
+ // would be destroyed by "fixing" the shared no-shrink rule globally.
+ fc.assert(
+ fc.property(serverList, serverList, (existing, desired) => {
+ const plan = planContextReplacement(liveContext(existing), planArgs(false, desired))
+ if (plan === null) return
+ expect([...plan.mergedServers].sort()).toEqual([...new Set(desired)].sort())
+ })
+ )
+ })
+
+ it('a non-empty legacy contextId is preserved verbatim; an empty one is repaired once', () => {
+ fc.assert(
+ fc.property(
+ fc.oneof(fc.constant(''), fc.constantFrom('legacy-id', 'context1', 'other-id')),
+ serverList,
+ (contextId, desired) => {
+ const args = planArgs(true, desired)
+ const plan = planContextReplacement(liveContext(desired, contextId), args)
+ if (plan === null) return
+ expect(plan.nextContextId).toBe(contextId === '' ? 'context1' : contextId)
+ }
+ )
+ )
+ })
+})