Skip to content

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

TypeScript

fix(wrc,hcc): skip no-op Context replaces and metadata-only fan-out

Alfredo Lopezf08cba62aac6
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index e09d87ca2..c76d3e955 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.284",
+ "version": "0.1.285",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.284",
+ "version": "0.1.285",
"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 a0eb362b8..31e93dd0b 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.284",
+ "version": "0.1.285",
"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 945658d20..ccfd97f06 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -2031,12 +2031,13 @@ describe('McpServerWatcher startup', () => {
}
})
- it('recovers when a Context delta loses the delete fence with no certificate to withhold', async () => {
+ it('does not fan out on a Context MODIFIED that does not move desired revision (#460 Phase 2)', async () => {
// A MODIFIED that does not move the desired revision — a status or label
- // write by another controller — still runs a scoped revocation, but builds
- // no delta certificate. Nothing reads the returned boolean there, so a lost
- // delete fence must stay loud and reach the convergence retry instead of
- // leaving a stale allow live with no NetworkPolicy resync to recover it.
+ // write by another controller — used to run scoped revocation so a lost
+ // delete fence could reach the convergence retry. That path was also the
+ // #460 Loop A Host fan-out. Phase 2 returns after the cache update;
+ // subtractive-drift recovery is the periodic netPol resync (#478 / infra
+ // gcp-dev enable), not metadata-only Context events.
let contextWatchCallback:
| ((
type: string,
@@ -2066,9 +2067,54 @@ describe('McpServerWatcher startup', () => {
})
markNetworkPolicyRevocationAuthoritative(watcher)
const passesBefore = mocks.netPolFullReconcile.mock.calls.length
- // With honorsLostFence false the real reconciler throws the 409 rather than
- // reporting it, which is the whole point: the throw is what reaches the
- // convergence retry below.
+
+ try {
+ await contextWatchCallback!('MODIFIED', {
+ metadata: {
+ name: 'steady-context',
+ namespace: 'mcp-server',
+ uid: 'steady-context-uid',
+ generation: 4,
+ },
+ spec: { contextId: 'steady-context', mcpServers: [] },
+ })
+
+ expect((watcher as any).netPolReconciler.reconcileContext).not.toHaveBeenCalled()
+ expect(mocks.netPolFullReconcile.mock.calls.length).toBe(passesBefore)
+ } finally {
+ await watcher.stop()
+ }
+ })
+
+ it('still retries convergence when a desired-state Context MODIFIED loses the delete fence', async () => {
+ let contextWatchCallback:
+ | ((
+ type: string,
+ apiObj: {
+ metadata: { name: string; namespace: string; uid: string; generation?: number }
+ spec: { contextId: string; mcpServers: string[] }
+ }
+ ) => Promise<void>)
+ | undefined
+ mocks.watch.mockImplementationOnce(async (path, _options, callback) => {
+ if (path.endsWith('/contexts')) contextWatchCallback = callback
+ return { abort: vi.fn() }
+ })
+
+ const watcher = new McpServerWatcher()
+ await (watcher as any).startContextWatch('lost-fence-desired-state-rv')
+ ;(watcher as any).contextCacheSynced = true
+ ;(watcher as any).mcpServerCacheSynced = true
+ ;(watcher as any).hostCacheSynced = true
+ ;(watcher as any).mcpWatchGeneration = 1
+ ;(watcher as any).contexts.set('steady-context', {
+ name: 'steady-context',
+ namespace: 'mcp-server',
+ uid: 'steady-context-uid',
+ generation: 4,
+ spec: { contextId: 'steady-context', mcpServers: [] },
+ })
+ const passesBefore = mocks.netPolFullReconcile.mock.calls.length
;(watcher as any).netPolReconciler.reconcileContext.mockRejectedValueOnce(
Object.assign(new Error('the UID in the precondition does not match'), { code: 409 })
)
@@ -2079,15 +2125,13 @@ describe('McpServerWatcher startup', () => {
name: 'steady-context',
namespace: 'mcp-server',
uid: 'steady-context-uid',
- generation: 4,
+ generation: 5,
},
- spec: { contextId: 'steady-context', mcpServers: [] },
+ spec: { contextId: 'steady-context', mcpServers: ['new-server'] },
})
- // This lane cannot act on the boolean, so it must not have opted into the
- // reported outcome.
expect((watcher as any).netPolReconciler.reconcileContext).toHaveBeenCalledWith(
- expect.objectContaining({ name: 'steady-context' }),
+ expect.objectContaining({ name: 'steady-context', generation: 5 }),
expect.objectContaining({ honorsLostFence: false })
)
await vi.waitFor(() =>
@@ -2619,6 +2663,139 @@ describe('McpServerWatcher startup', () => {
await watcher.stop()
})
+ it('T4 — skips Context fan-out on metadata-only MODIFIED (same uid/generation/spec)', async () => {
+ const watcher = new McpServerWatcher()
+ let contextWatchCallback:
+ | ((
+ type: string,
+ apiObj: {
+ metadata: { name: string; namespace: string; uid?: string; generation?: number }
+ spec: { contextId: string; mcpServers: string[] }
+ }
+ ) => Promise<void>)
+ | undefined
+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {
+ contextWatchCallback = callback
+ return { abort: vi.fn() }
+ })
+ await (watcher as any).startContextWatch('context-t4-rv')
+ ;(watcher as any).contextCacheSynced = true
+ ;(watcher as any).mcpServerCacheSynced = true
+ ;(watcher as any).hostCacheSynced = true
+ ;(watcher as any).hosts.set('bound-host', {
+ name: 'bound-host',
+ namespace: 'mcp-host',
+ spec: { host: 'bound-host', contextRef: 'shared-context', secretRef: 'host-secret' },
+ })
+
+ const added = {
+ metadata: {
+ name: 'shared-context',
+ namespace: 'mcp-server',
+ uid: 'ctx-uid-1',
+ generation: 1011,
+ },
+ spec: { contextId: 'shared-context', mcpServers: ['server-a'] },
+ }
+ await contextWatchCallback!('ADDED', added)
+ await flushMicrotasks()
+
+ const netPol = (watcher as any).netPolReconciler
+ const hostReconcile = vi.spyOn(watcher.getHostReconciler(), 'reconcile')
+ const sfsPropagate = vi.spyOn(watcher as any, 'reconcileSharedFileSystemsReferencedByContext')
+ netPol.reconcileContext.mockClear()
+ hostReconcile.mockClear()
+ sfsPropagate.mockClear()
+
+ const revisionBefore = (watcher as any).contextDesiredRevision
+ await contextWatchCallback!('MODIFIED', {
+ ...added,
+ metadata: { ...added.metadata, labels: { 'clerum.io/recipe': 'other-recipe' } },
+ })
+ await flushMicrotasks()
+
+ expect((watcher as any).contexts.get('shared-context')).toEqual(
+ expect.objectContaining({
+ name: 'shared-context',
+ generation: 1011,
+ spec: added.spec,
+ })
+ )
+ expect((watcher as any).contextDesiredRevision).toBe(revisionBefore)
+ expect(netPol.reconcileContext).not.toHaveBeenCalled()
+ expect(hostReconcile).not.toHaveBeenCalled()
+ expect(sfsPropagate).not.toHaveBeenCalled()
+
+ await watcher.stop()
+ })
+
+ it('T5 — still fans out on Context MODIFIED when spec or generation changes', async () => {
+ const watcher = new McpServerWatcher()
+ let contextWatchCallback:
+ | ((
+ type: string,
+ apiObj: {
+ metadata: { name: string; namespace: string; uid?: string; generation?: number }
+ spec: { contextId: string; mcpServers: string[] }
+ }
+ ) => Promise<void>)
+ | undefined
+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {
+ contextWatchCallback = callback
+ return { abort: vi.fn() }
+ })
+ await (watcher as any).startContextWatch('context-t5-rv')
+ ;(watcher as any).contextCacheSynced = true
+ ;(watcher as any).mcpServerCacheSynced = true
+ ;(watcher as any).hostCacheSynced = true
+ ;(watcher as any).hosts.set('bound-host', {
+ name: 'bound-host',
+ namespace: 'mcp-host',
+ spec: { host: 'bound-host', contextRef: 'shared-context', secretRef: 'host-secret' },
+ })
+
+ const added = {
+ metadata: {
+ name: 'shared-context',
+ namespace: 'mcp-server',
+ uid: 'ctx-uid-1',
+ generation: 1011,
+ },
+ spec: { contextId: 'shared-context', mcpServers: ['server-a'] },
+ }
+ await contextWatchCallback!('ADDED', added)
+ await flushMicrotasks()
+
+ const netPol = (watcher as any).netPolReconciler
+ const hostReconcile = vi.spyOn(watcher.getHostReconciler(), 'reconcile')
+ const sfsPropagate = vi.spyOn(watcher as any, 'reconcileSharedFileSystemsReferencedByContext')
+ netPol.reconcileContext.mockClear()
+ hostReconcile.mockClear()
+ sfsPropagate.mockClear()
+
+ const revisionBefore = (watcher as any).contextDesiredRevision
+ await contextWatchCallback!('MODIFIED', {
+ ...added,
+ metadata: { ...added.metadata, generation: 1012 },
+ spec: { ...added.spec, mcpServers: ['server-a', 'server-b'] },
+ })
+ await flushMicrotasks()
+
+ expect((watcher as any).contextDesiredRevision).toBe(revisionBefore + 1)
+ expect(sfsPropagate).toHaveBeenCalled()
+ expect(hostReconcile).toHaveBeenCalledWith(expect.objectContaining({ name: 'bound-host' }))
+ expect(netPol.reconcileContext).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'shared-context',
+ generation: 1012,
+ spec: expect.objectContaining({ mcpServers: ['server-a', 'server-b'] }),
+ }),
+ expect.objectContaining({ isCurrent: expect.any(Function) })
+ )
+
+ await watcher.stop()
+ })
+
it('uses only the bounded fleet pass for the cold-start Host snapshot', async () => {
const initialHosts = Array.from({ length: 50 }, (_, index) => ({
metadata: {
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index 754e621d5..b3d7556af 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -4361,6 +4361,15 @@ export class McpServerWatcher implements McpServerProvider {
void this.runInitialNetworkPolicyConvergence()
}
+ // Metadata-only Context MODIFIED (label ping-pong, annotation churn)
+ // does not change desired revision. Skip SFS propagate and Host fan-out
+ // — that accidental resync is the #460 Loop A storm. Mirrors the
+ // McpServer status-only early return above.
+ if (type === 'MODIFIED' && !desiredStateChanged) {
+ this.changeCallback?.()
+ return
+ }
+
// Re-reconcile every SFS this Context referenced before or after the
// change so SharedFileSystem.status.mountedByContexts stays in sync
// without waiting for an SFS-level event.
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 386b77e65..523c9265d 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.322",
+ "version": "0.1.323",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.322",
+ "version": "0.1.323",
"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 a8b8f3a4a..b26da66da 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.322",
+ "version": "0.1.323",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/reconciler/mcpDelegation.test.ts b/workflow-recipes/src/reconciler/mcpDelegation.test.ts
index 929ff5419..f778fde72 100644
--- a/workflow-recipes/src/reconciler/mcpDelegation.test.ts
+++ b/workflow-recipes/src/reconciler/mcpDelegation.test.ts
@@ -989,7 +989,7 @@ describe('ensureRecipeContext', () => {
)
})
- it('H04b — updates existing Context on 409 conflict (re-reconcile path)', async () => {
+ 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 }),
getNamespacedCustomObject: vi.fn().mockResolvedValue({ metadata: { resourceVersion: '5' } }),
@@ -1025,7 +1025,11 @@ describe('ensureRecipeContext', () => {
const mockCustomApi = {
createNamespacedCustomObject: vi.fn().mockRejectedValueOnce({ code: 409 }),
getNamespacedCustomObject: vi.fn().mockResolvedValue({
- metadata: { resourceVersion: '5', labels: { 'clerum.io/context-owner': 'admin' } },
+ metadata: {
+ resourceVersion: '5',
+ labels: { 'clerum.io/context-owner': 'admin', 'clerum.io/recipe': 'other-recipe' },
+ annotations: { 'operator.io/note': 'keep' },
+ },
spec: {
contextId: 'context1',
description: 'shared operator context',
@@ -1056,7 +1060,12 @@ describe('ensureRecipeContext', () => {
name: 'context1',
body: expect.objectContaining({
metadata: expect.objectContaining({
- labels: expect.objectContaining({ 'clerum.io/context-owner': 'admin' }),
+ labels: expect.objectContaining({
+ 'clerum.io/context-owner': 'admin',
+ 'clerum.io/managed-by': 'wrc',
+ 'clerum.io/recipe': 'other-recipe',
+ }),
+ annotations: { 'operator.io/note': 'keep' },
}),
spec: {
contextId: 'context1',
@@ -1067,6 +1076,11 @@ describe('ensureRecipeContext', () => {
}),
})
)
+ expect(
+ (replaceCall.body as { metadata?: { labels?: Record<string, string> } }).metadata?.labels?.[
+ 'clerum.io/recipe'
+ ]
+ ).not.toBe('test-recipe')
expect(
(replaceCall.body as { metadata?: Record<string, unknown> }).metadata
).not.toHaveProperty('ownerReferences')
@@ -1169,6 +1183,162 @@ describe('ensureRecipeContext', () => {
expect(mockCustomApi.replaceNamespacedCustomObject).toHaveBeenCalledTimes(3)
})
+ it('skips shared Context replace when the union and WRC-authored labels already match', async () => {
+ const recipe = makeRecipe({ spec: { ...makeRecipe().spec, contextRef: 'context1' } })
+ const mockCustomApi = {
+ createNamespacedCustomObject: vi.fn().mockRejectedValueOnce({ code: 409 }),
+ getNamespacedCustomObject: vi.fn().mockResolvedValue({
+ metadata: {
+ resourceVersion: '9',
+ labels: {
+ 'clerum.io/recipe': 'other-recipe',
+ 'clerum.io/managed-by': 'wrc',
+ 'clerum.io/context-owner': 'admin',
+ },
+ },
+ spec: {
+ contextId: 'context1',
+ mcpServers: ['existing-server', 'test-recipe-redis-mcp'],
+ },
+ }),
+ replaceNamespacedCustomObject: 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'
+ )
+
+ expect(contextName).toBe('context1')
+ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledTimes(1)
+ expect(mockCustomApi.replaceNamespacedCustomObject).not.toHaveBeenCalled()
+ })
+
+ it('writes a shared Context when managed-by is missing even if the server union already matches', async () => {
+ const recipe = makeRecipe({ spec: { ...makeRecipe().spec, contextRef: 'context1' } })
+ const mockCustomApi = {
+ createNamespacedCustomObject: vi.fn().mockRejectedValueOnce({ code: 409 }),
+ getNamespacedCustomObject: vi.fn().mockResolvedValue({
+ metadata: {
+ resourceVersion: '9',
+ labels: { 'clerum.io/recipe': 'other-recipe' },
+ },
+ spec: {
+ contextId: 'context1',
+ mcpServers: ['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'
+ )
+
+ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledTimes(1)
+ const replaceCall = mockCustomApi.replaceNamespacedCustomObject.mock.calls[0]?.[0]
+ expect(replaceCall).toEqual(
+ expect.objectContaining({
+ name: 'context1',
+ body: expect.objectContaining({
+ metadata: expect.objectContaining({
+ labels: expect.objectContaining({
+ 'clerum.io/managed-by': 'wrc',
+ 'clerum.io/recipe': 'other-recipe',
+ }),
+ }),
+ }),
+ })
+ )
+ expect(
+ (replaceCall.body as { metadata?: { labels?: Record<string, string> } }).metadata?.labels?.[
+ 'clerum.io/recipe'
+ ]
+ ).not.toBe('test-recipe')
+ })
+
+ it('skips shared Context replace even when a leftover spec-hash annotation is present', async () => {
+ const recipe = makeRecipe({ spec: { ...makeRecipe().spec, contextRef: 'context1' } })
+ const mockCustomApi = {
+ createNamespacedCustomObject: vi.fn().mockRejectedValueOnce({ code: 409 }),
+ getNamespacedCustomObject: vi.fn().mockResolvedValue({
+ metadata: {
+ resourceVersion: '9',
+ labels: { 'clerum.io/managed-by': 'wrc', 'clerum.io/recipe': 'other-recipe' },
+ annotations: { 'clerum.io/spec-hash': 'deadbeefdeadbeefdeadbeefdeadbeef' },
+ },
+ spec: {
+ contextId: 'context1',
+ mcpServers: ['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'
+ )
+
+ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledTimes(1)
+ expect(mockCustomApi.replaceNamespacedCustomObject).not.toHaveBeenCalled()
+ })
+
+ it('skips private Context replace when mcpServers and WRC labels already match', async () => {
+ const mockCustomApi = {
+ createNamespacedCustomObject: vi.fn().mockRejectedValueOnce({ code: 409 }),
+ getNamespacedCustomObject: vi.fn().mockResolvedValue({
+ metadata: {
+ resourceVersion: '3',
+ labels: { 'clerum.io/recipe': 'test-recipe', 'clerum.io/managed-by': 'wrc' },
+ },
+ spec: { contextId: 'wf-test-recipe', mcpServers: ['server-a', 'server-b'] },
+ }),
+ replaceNamespacedCustomObject: vi.fn().mockResolvedValue({}),
+ }
+ const deps: DelegationDeps = {
+ customApi: mockCustomApi as unknown as DelegationDeps['customApi'],
+ coreApi: {} as DelegationDeps['coreApi'],
+ }
+
+ const contextName = await ensureRecipeContext(
+ deps,
+ 'test-recipe',
+ ['server-a', 'server-b'],
+ 'mcp-server',
+ ownerRef
+ )
+
+ expect(contextName).toBe('wf-test-recipe')
+ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledTimes(1)
+ expect(mockCustomApi.replaceNamespacedCustomObject).not.toHaveBeenCalled()
+ })
+
it('H04c — re-throws non-409 errors', async () => {
const mockCustomApi = {
createNamespacedCustomObject: vi.fn().mockRejectedValue(new Error('API error')),
@@ -1300,6 +1470,82 @@ describe('delegateTransportWorkloads', () => {
expect(mcpServerReplaceCalls).toHaveLength(0)
})
+ it('does NOT replace an explicit Context on the second reconcile when the union is already live', async () => {
+ const CONTEXT_PLURAL = 'contexts'
+ const MCPSERVER_PLURAL = 'mcpservers'
+ const recipe = makeRecipe({ spec: { ...makeRecipe().spec, contextRef: 'context1' } })
+ let storedMcpServer: { metadata?: unknown; spec?: Record<string, unknown> } | undefined
+ let storedContext:
+ | {
+ metadata?: { labels?: Record<string, string>; annotations?: Record<string, string> }
+ spec?: { mcpServers?: string[] }
+ }
+ | undefined
+
+ const mockCustomApi = {
+ getNamespacedCustomObject: vi.fn().mockImplementation((args: { plural: string }) => {
+ if (args.plural === MCPSERVER_PLURAL && storedMcpServer) {
+ return Promise.resolve(storedMcpServer)
+ }
+ if (args.plural === CONTEXT_PLURAL && storedContext) {
+ return Promise.resolve(storedContext)
+ }
+ return Promise.reject({ code: 404 })
+ }),
+ createNamespacedCustomObject: vi.fn().mockImplementation(
+ (args: {
+ plural: string
+ body: {
+ metadata?: { labels?: Record<string, string> }
+ spec?: { mcpServers?: string[] }
+ }
+ }) => {
+ if (args.plural === MCPSERVER_PLURAL) {
+ storedMcpServer = args.body as typeof storedMcpServer
+ return Promise.resolve({})
+ }
+ if (args.plural === CONTEXT_PLURAL) {
+ if (storedContext) {
+ return Promise.reject({ code: 409 })
+ }
+ storedContext = {
+ ...args.body,
+ metadata: {
+ ...args.body.metadata,
+ labels: {
+ ...(args.body.metadata?.labels ?? {}),
+ 'clerum.io/managed-by': 'wrc',
+ },
+ },
+ }
+ return Promise.resolve({})
+ }
+ return Promise.resolve({})
+ }
+ ),
+ replaceNamespacedCustomObject: vi.fn().mockResolvedValue({}),
+ }
+ const mockCoreApi = { createNamespacedService: vi.fn().mockResolvedValue({}) }
+ const deps: DelegationDeps = {
+ customApi: mockCustomApi as unknown as DelegationDeps['customApi'],
+ coreApi: mockCoreApi as unknown as DelegationDeps['coreApi'],
+ }
+
+ await delegateTransportWorkloads(deps, recipe, 'mcp-server', new Map())
+ expect(storedContext).toBeDefined()
+
+ mockCustomApi.replaceNamespacedCustomObject.mockClear()
+ await delegateTransportWorkloads(deps, recipe, 'mcp-server', new Map())
+
+ const contextReplaceCalls = mockCustomApi.replaceNamespacedCustomObject.mock.calls.filter(
+ (call: unknown[]) => (call[0] as { plural?: string } | undefined)?.plural === CONTEXT_PLURAL
+ )
+ expect(contextReplaceCalls).toHaveLength(0)
+ expect(mockCustomApi.getNamespacedCustomObject).toHaveBeenCalledWith(
+ expect.objectContaining({ plural: CONTEXT_PLURAL, name: 'context1' })
+ )
+ })
+
it('DOES replace an McpServer when the desired spec-hash differs (changed recipe / pre-upgrade object)', async () => {
const MCPSERVER_PLURAL = 'mcpservers'
const SPEC_HASH = 'clerum.io/spec-hash'
diff --git a/workflow-recipes/src/reconciler/mcpDelegation.ts b/workflow-recipes/src/reconciler/mcpDelegation.ts
index 21b5f8168..43c438de5 100644
--- a/workflow-recipes/src/reconciler/mcpDelegation.ts
+++ b/workflow-recipes/src/reconciler/mcpDelegation.ts
@@ -113,6 +113,33 @@ function hasExplicitWorkflowContextRef(recipe: WorkflowRecipeCRD): boolean {
return Boolean(recipe.spec.contextRef?.trim())
}
+const CONTEXT_RECIPE_LABEL = 'clerum.io/recipe'
+const CONTEXT_MANAGED_BY_LABEL = 'clerum.io/managed-by'
+const CONTEXT_MANAGED_BY_WRC = 'wrc'
+
+function sameMcpServerSet(left: readonly string[], right: readonly string[]): boolean {
+ const leftSet = new Set(left)
+ const rightSet = new Set(right)
+ if (leftSet.size !== rightSet.size) return false
+ for (const name of leftSet) {
+ if (!rightSet.has(name)) return false
+ }
+ return true
+}
+
+function contextReplaceIsNoOp(
+ explicitContext: boolean,
+ existingLabels: Record<string, string> | undefined,
+ existingServers: readonly string[],
+ mergedServers: readonly string[],
+ recipeName: string
+): boolean {
+ if (!sameMcpServerSet(existingServers, mergedServers)) return false
+ if ((existingLabels ?? {})[CONTEXT_MANAGED_BY_LABEL] !== CONTEXT_MANAGED_BY_WRC) return false
+ if (!explicitContext && (existingLabels ?? {})[CONTEXT_RECIPE_LABEL] !== recipeName) return false
+ return true
+}
+
/**
* Compute McpServer CRD name.
*
@@ -693,7 +720,7 @@ export async function ensureRecipeContext(
},
}
- const replaceExistingContext = async (): Promise<void> => {
+ const replaceExistingContext = async (): Promise<{ wrote: boolean }> => {
for (let attempt = 1; attempt <= CONTEXT_REPLACE_CONFLICT_RETRIES; attempt += 1) {
const existing = (await deps.customApi.getNamespacedCustomObject({
group: CRD_GROUP,
@@ -702,7 +729,11 @@ export async function ensureRecipeContext(
plural: CONTEXT_PLURAL,
name: contextName,
})) as {
- metadata?: { resourceVersion?: string; labels?: Record<string, string> }
+ metadata?: {
+ resourceVersion?: string
+ labels?: Record<string, string>
+ annotations?: Record<string, string>
+ }
spec?: { contextId?: string; mcpServers?: string[]; [key: string]: unknown }
}
const existingServers = Array.isArray(existing.spec?.mcpServers)
@@ -711,6 +742,27 @@ export async function ensureRecipeContext(
const mergedServers = explicitContext
? Array.from(new Set([...existingServers, ...serverNames]))
: serverNames
+ const existingLabels = existing.metadata?.labels ?? {}
+
+ // Semantic post-merge equality. Do not stamp clerum.io/spec-hash on a
+ // shared Context: N recipe writers would flap the annotation the same
+ // way clerum.io/recipe already flaps resourceVersion (#460 Phase 1).
+ if (
+ contextReplaceIsNoOp(
+ explicitContext,
+ existingLabels,
+ existingServers,
+ mergedServers,
+ recipeName
+ )
+ ) {
+ return { wrote: false }
+ }
+
+ const authoredLabels: Record<string, string> = {
+ [CONTEXT_MANAGED_BY_LABEL]: CONTEXT_MANAGED_BY_WRC,
+ ...(!explicitContext ? { [CONTEXT_RECIPE_LABEL]: recipeName } : {}),
+ }
try {
await deps.customApi.replaceNamespacedCustomObject({
@@ -724,9 +776,12 @@ export async function ensureRecipeContext(
metadata: {
...contextBody.metadata,
labels: {
- ...(existing.metadata?.labels ?? {}),
- ...contextBody.metadata.labels,
+ ...existingLabels,
+ ...authoredLabels,
},
+ ...(existing.metadata?.annotations
+ ? { annotations: { ...existing.metadata.annotations } }
+ : {}),
resourceVersion: existing.metadata?.resourceVersion,
},
spec: {
@@ -736,7 +791,7 @@ export async function ensureRecipeContext(
},
},
})
- return
+ return { wrote: true }
} catch (replaceError) {
if (getErrorCode(replaceError) === 409) {
if (attempt < CONTEXT_REPLACE_CONFLICT_RETRIES) {
@@ -747,6 +802,7 @@ export async function ensureRecipeContext(
throw replaceError
}
}
+ throw new Error(`failed to update Context "${contextName}" after conflict retries`)
}
try {
@@ -762,10 +818,14 @@ export async function ensureRecipeContext(
)
} catch (error) {
if (getErrorCode(error) === 409) {
- await replaceExistingContext()
- console.log(
- `[MCP-Delegation] Updated per-recipe Context "${contextName}" with ${serverNames.length} server(s)`
- )
+ const { wrote } = await replaceExistingContext()
+ if (wrote) {
+ console.log(
+ `[MCP-Delegation] Updated per-recipe Context "${contextName}" with ${serverNames.length} server(s)`
+ )
+ } else {
+ console.log(`[MCP-Delegation] Context "${contextName}" unchanged; skipping update`)
+ }
} else {
throw error
}