Skip to content

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

TypeScript

fix(hcc): close readiness review gaps

Alfredo Lopez1f90ad90b3ed
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index 17988f896..404216748 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -331,6 +331,12 @@ jobs:
- name: Test host-storm metric adjudication
run: bash scripts/tests/test-host-storm-metric-gate.sh
+ - name: Test WRC-to-HCC contracts
+ run: bash scripts/tests/test-wrc-hcc-contracts-gate.sh
+
+ - name: Test WRC internal dependency NetworkPolicy contracts
+ run: bash scripts/tests/test-wrc-internal-dependency-networkpolicy-gate.sh
+
- name: Test Plugin Workload SDK auth bootstrap policy
run: bash scripts/tests/test-plugin-workload-sdk-auth-bootstrap.sh
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index c1bd6fa81..0607476da 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.172",
+ "version": "0.1.173",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.172",
+ "version": "0.1.173",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index 705941267..72a920567 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.172",
+ "version": "0.1.173",
"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/__tests__/reconciler.remote.test.ts b/host-context-controller/src/__tests__/reconciler.remote.test.ts
index 642ae4d7a..6da92a177 100644
--- a/host-context-controller/src/__tests__/reconciler.remote.test.ts
+++ b/host-context-controller/src/__tests__/reconciler.remote.test.ts
@@ -676,7 +676,7 @@ describe('McpServerReconciler remote egress proxy', () => {
})
describe('canonicalizeRemoteEgressProxyImage', () => {
- it('patches stale remote McpServer spec.image to the platform egress proxy image', async () => {
+ it('patches stale remote spec.image without mutating the observed cache object', async () => {
const staleRemote = cloneServer(REMOTE_SERVER, {
image: LEGACY_REMOTE_EGRESS_IMAGE,
})
@@ -700,7 +700,7 @@ describe('McpServerReconciler remote egress proxy', () => {
middleware: expect.any(Array),
})
)
- expect(staleRemote.spec.image).toBe('clerum/nginx-egress-proxy:0.1.0')
+ expect(staleRemote.spec.image).toBe(LEGACY_REMOTE_EGRESS_IMAGE)
expect(lastPatchedStatusConditions(customApi)).toEqual(
expect.arrayContaining([
expect.objectContaining({
@@ -873,7 +873,7 @@ describe('McpServerReconciler remote egress proxy', () => {
'createService',
'createDeployment',
])
- expect(staleRemote.spec.image).toBe('clerum/nginx-egress-proxy:0.1.0')
+ expect(staleRemote.spec.image).toBe(LEGACY_REMOTE_EGRESS_IMAGE)
expect(customApi.patchNamespacedCustomObject).toHaveBeenCalledWith(
expect.objectContaining({
body: {
diff --git a/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts b/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
index 0e38b4c6d..8521b148d 100644
--- a/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
+++ b/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
@@ -132,9 +132,17 @@ describe('ExternalEgressConvergenceCoordinator', () => {
}).instance
instance.scheduleRetry('ADDED', selected)
- for (const delay of [5000, 15000, 30000, 30000, 30000]) {
- await vi.advanceTimersByTimeAsync(delay)
- }
+ await vi.advanceTimersByTimeAsync(5000)
+ await vi.advanceTimersByTimeAsync(15000)
+ await vi.advanceTimersByTimeAsync(30000)
+ expect(attempts).toBe(3)
+ await vi.advanceTimersByTimeAsync(29999)
+ expect(attempts).toBe(3)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(attempts).toBe(4)
+ await vi.advanceTimersByTimeAsync(29999)
+ expect(attempts).toBe(4)
+ await vi.advanceTimersByTimeAsync(1)
expect(attempts).toBe(5)
await vi.advanceTimersByTimeAsync(30000)
diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.ts
index 06eb0b336..5c8e6eeaa 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -655,6 +655,59 @@ describe('McpServerWatcher startup', () => {
watcher.stop()
})
+ it.each([
+ ['Context', 'startContextWatch', 'contextWatchGeneration'],
+ ['Host', 'startHostWatch', 'hostWatchGeneration'],
+ ] as const)(
+ 'assigns a fresh generation to every replacement %s watch',
+ async (_kind, method, generationField) => {
+ const watcher = new McpServerWatcher()
+ const before = (watcher as any)[generationField] as number
+
+ const first = await (watcher as any)[method]('first-rv')
+ const second = await (watcher as any)[method]('second-rv')
+
+ expect(first).toBe(before + 1)
+ expect(second).toBe(before + 2)
+ expect((watcher as any)[generationField]).toBe(before + 2)
+ await watcher.stop()
+ }
+ )
+
+ it.each([
+ [
+ 'McpServer',
+ 'restartMcpServerWatch',
+ 'startMcpServerWatch',
+ 'mcpWatchGeneration',
+ 'mcpServerCacheSynced',
+ { resourceVersion: 'mcp-rv', servers: [] },
+ ],
+ [
+ 'Context',
+ 'restartContextWatch',
+ 'startContextWatch',
+ 'contextWatchGeneration',
+ 'contextCacheSynced',
+ { resourceVersion: 'context-rv', contexts: [] },
+ ],
+ ] as const)(
+ 'rejects a %s LIST snapshot that is not paired with a live watch request',
+ async (_kind, restartMethod, startMethod, generationField, cacheField, snapshot) => {
+ const watcher = new McpServerWatcher()
+ vi.spyOn(watcher as any, startMethod).mockImplementation(async () => {
+ ;(watcher as any)[generationField] += 1
+ return (watcher as any)[generationField]
+ })
+
+ await expect((watcher as any)[restartMethod](snapshot)).rejects.toThrow(
+ 'snapshot could not be paired with an active watch'
+ )
+ expect((watcher as any)[cacheField]).toBe(false)
+ await watcher.stop()
+ }
+ )
+
it.each([
['McpServer', 'mcpservers'],
['Context', 'contexts'],
@@ -2476,6 +2529,93 @@ describe('McpServerWatcher startup', () => {
await watcher.stop()
})
+ it('does not lose an initial convergence request queued in the settlement microtask', async () => {
+ const watcher = new McpServerWatcher()
+ let trailing: Promise<void> | undefined
+ const convergenceCore = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ ({
+ then: (resolve: () => void) => {
+ resolve()
+ queueMicrotask(() => {
+ trailing = (watcher as any).runInitialMcpServerConvergence()
+ })
+ },
+ }) as PromiseLike<void>
+ )
+ .mockResolvedValueOnce(undefined)
+ ;(watcher as any).runInitialMcpServerConvergenceCore = convergenceCore
+
+ const first = (watcher as any).runInitialMcpServerConvergence()
+ await first
+ await vi.waitFor(() => expect(trailing).toBeDefined())
+ await trailing
+
+ expect(convergenceCore).toHaveBeenCalledTimes(2)
+ await watcher.stop()
+ })
+
+ it('retains one keyed queue until every same-key waiter has drained', async () => {
+ const watcher = new McpServerWatcher()
+ const firstStarted = deferred()
+ const releaseFirst = deferred()
+ const effects: string[] = []
+ const queues = (watcher as any).contextReconciliationQueues as Map<
+ string,
+ { references: number }
+ >
+
+ const first = (watcher as any).enqueueContextReconciliation('shared', async () => {
+ effects.push('first')
+ firstStarted.resolve(undefined)
+ await releaseFirst.promise
+ })
+ await firstStarted.promise
+ const second = (watcher as any).enqueueContextReconciliation('shared', async () => {
+ effects.push('second')
+ })
+
+ expect(queues.get('shared')?.references).toBe(2)
+ expect(effects).toEqual(['first'])
+ releaseFirst.resolve(undefined)
+ await Promise.all([first, second])
+ expect(effects).toEqual(['first', 'second'])
+ expect(queues.size).toBe(0)
+ await watcher.stop()
+ })
+
+ it('does not execute newly enqueued keyed work after stop', async () => {
+ const watcher = new McpServerWatcher()
+ const work = vi.fn()
+ ;(watcher as any).stopped = true
+
+ await (watcher as any).enqueueContextReconciliation('stopped', work)
+
+ expect(work).not.toHaveBeenCalled()
+ expect((watcher as any).contextReconciliationQueues.size).toBe(0)
+ })
+
+ it('acquires multi-context identity keys in one deterministic sorted order', async () => {
+ const watcher = new McpServerWatcher()
+ const acquired: string[] = []
+ vi.spyOn(watcher as any, 'enqueueContextReconciliation').mockImplementation(
+ async (key: string, work: () => Promise<void>) => {
+ acquired.push(key)
+ await work()
+ }
+ )
+
+ await (watcher as any).enqueueContextIdentityReconciliation(
+ ['z-context', 'a-context', 'm-context', 'z-context'],
+ async () => undefined
+ )
+
+ expect(acquired).toEqual(['a-context', 'm-context', 'z-context'])
+ await watcher.stop()
+ })
+
it('fences an McpServer fleet pass when its LIST-to-WATCH authority is retired', async () => {
const egressStarted = deferred()
const releaseEgress = deferred()
@@ -2630,6 +2770,24 @@ describe('McpServerWatcher startup', () => {
await watcher.stop()
})
+ it('does not certify NetworkPolicy revocation after authority is lost at the callback boundary', async () => {
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).contextCacheSynced = true
+ ;(watcher as any).mcpServerCacheSynced = true
+ ;(watcher as any).contextWatchGeneration = 21
+ ;(watcher as any).mcpWatchGeneration = 34
+ mocks.netPolFullReconcile.mockImplementationOnce(async (_contexts, _servers, options) => {
+ ;(watcher as any).contextCacheSynced = false
+ options.onAuthoritativeRevocationComplete()
+ })
+
+ await (watcher as any).runInitialNetworkPolicyConvergence()
+
+ expect((watcher as any).networkPolicyRevocationContextGeneration).not.toBe(21)
+ expect((watcher as any).networkPolicyRevocationServerGeneration).not.toBe(34)
+ await watcher.stop()
+ })
+
it.each([
['SharedFileSystem', 'enqueueSharedFileSystemReconciliation'],
['GlobalFileSystem', 'enqueueGlobalFileSystemReconciliation'],
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index b4f6c06b5..29838c759 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -2465,8 +2465,15 @@ export class McpServerWatcher implements McpServerProvider {
await this.runInitialNetworkPolicyConvergenceCore()
}
} while (!this.stopped && run.trailingRequested)
+ // Retire the active slot synchronously before this promise settles.
+ // A request arriving in the following settlement microtask must start
+ // a new run instead of attaching to a pass whose loop already exited.
+ if (this.initialConvergenceRuns.get(lane) === run) {
+ this.initialConvergenceRuns.delete(lane)
+ }
})
.finally(() => {
+ // Errors bypass the normal retirement above.
if (this.initialConvergenceRuns.get(lane) === run) {
this.initialConvergenceRuns.delete(lane)
}
diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index 261a80d09..1650cd3ef 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -504,6 +504,69 @@ describe('NetworkPolicyReconciler', () => {
)
})
+ it('retains the ingress policy it just replaced when the authoritative server port changes', async () => {
+ const oldServer: McpServerCRD = {
+ name: 'mongo',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'dev',
+ image: 'mongo:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ }
+ const cache = new Map([[oldServer.name, oldServer]])
+ const rec = makeReconciler(mockApi, cache)
+ const context: ContextCRD = {
+ name: 'dev',
+ namespace: 'mcp-server',
+ spec: { contextId: 'dev', mcpServers: [oldServer.name] },
+ }
+
+ await rec.reconcileContext(context)
+ const livePolicies = new Map(
+ mockApi.createNamespacedNetworkPolicy.mock.calls.map(call => {
+ const policy = (call[0] as { body: k8s.V1NetworkPolicy }).body
+ return [`${policy.metadata?.namespace}/${policy.metadata?.name}`, policy]
+ })
+ )
+
+ vi.clearAllMocks()
+ cache.set(oldServer.name, {
+ ...oldServer,
+ generation: 2,
+ spec: {
+ ...oldServer.spec,
+ transport: { type: 'streamableHttp', port: 4000 },
+ },
+ })
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(
+ async ({ namespace }: { namespace?: string }) => ({
+ items: [...livePolicies.values()].filter(
+ policy => policy.metadata?.namespace === namespace
+ ),
+ })
+ )
+ mockApi.createNamespacedNetworkPolicy.mockImplementation(async ({ namespace, body }) => {
+ livePolicies.set(`${namespace}/${body.metadata?.name}`, body)
+ return {}
+ })
+ mockApi.replaceNamespacedNetworkPolicy.mockImplementation(
+ async ({ namespace, name, body }) => {
+ livePolicies.set(`${namespace}/${name}`, body)
+ return {}
+ }
+ )
+
+ await rec.reconcileContext(context)
+
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({
+ name: 'ctx-dev-mongo',
+ namespace: 'mcp-server',
+ })
+ const ingress = livePolicies.get('mcp-server/ctx-dev-mongo')
+ expect(ingress?.spec?.ingress?.[0]?.ports).toEqual([expect.objectContaining({ port: 4000 })])
+ })
+
it('does not mutate policies after its combined inventory authority lease is retired', async () => {
const cache = new Map<string, McpServerCRD>()
cache.set('mongo', {
@@ -2030,7 +2093,7 @@ describe('NetworkPolicyReconciler', () => {
}
})
- it('revokes stale external egress for a live McpServer before additive convergence', async () => {
+ it('revokes stale external egress for a live McpServer before readiness certification', async () => {
const liveServer: McpServerCRD = {
name: 'live-server',
namespace: 'mcp-server',
@@ -2041,12 +2104,7 @@ describe('NetworkPolicyReconciler', () => {
egressBindings: [],
},
}
- const additiveStarted = deferred()
- const releaseAdditive = deferred()
- vi.spyOn(reconciler, 'reconcileExternalEgress').mockImplementationOnce(async () => {
- additiveStarted.resolve(undefined)
- await releaseAdditive.promise
- })
+ const ordering: string[] = []
mockApi.listNamespacedNetworkPolicy.mockImplementation(
async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {
if (namespace === 'mcp-server' && labelSelector?.includes('external-egress')) {
@@ -2064,26 +2122,27 @@ describe('NetworkPolicyReconciler', () => {
return { items: [] }
}
)
- const onAuthoritativeRevocationComplete = vi.fn()
+ mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async () => {
+ ordering.push('delete')
+ return {}
+ })
+ const onAuthoritativeRevocationComplete = vi.fn(() => {
+ ordering.push('certify')
+ })
- const fullPass = reconciler.fullReconcile([], [liveServer], {
+ await reconciler.fullReconcile([], [liveServer], {
ensureDefaults: false,
contextInventoryAuthoritative: () => true,
serverInventoryAuthoritative: () => true,
onAuthoritativeRevocationComplete,
})
- await additiveStarted.promise
- try {
- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
- name: 'ext-egress-live-server-old.example-443',
- namespace: 'mcp-server',
- })
- expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
- } finally {
- releaseAdditive.resolve(undefined)
- await fullPass
- }
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'ext-egress-live-server-old.example-443',
+ namespace: 'mcp-server',
+ })
+ expect(ordering.slice(0, 2)).toEqual(['delete', 'certify'])
+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
})
it('revokes same-name Context allow policies whose authoritative server port changed', async () => {
@@ -2205,7 +2264,7 @@ describe('NetworkPolicyReconciler', () => {
expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
- it('revokes same-name DNS egress whose protocol or resolved IP cannot be proven current', async () => {
+ it('replaces same-name DNS egress before certifying readiness without an allow gap', async () => {
const oldServer: McpServerCRD = {
name: 'live-server',
namespace: 'mcp-server',
@@ -2232,12 +2291,25 @@ describe('NetworkPolicyReconciler', () => {
expect(oldPolicy).toBeDefined()
vi.clearAllMocks()
+ const ordering: string[] = []
mockApi.listNamespacedNetworkPolicy.mockImplementation(
async ({ labelSelector }: { labelSelector?: string }) =>
labelSelector?.includes('external-egress') ? { items: [oldPolicy!] } : { items: [] }
)
- vi.spyOn(rec, 'reconcileExternalEgress').mockResolvedValue(undefined)
- const onAuthoritativeRevocationComplete = vi.fn()
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValue(
+ Object.assign(new Error('already exists'), { code: 409 })
+ )
+ mockApi.replaceNamespacedNetworkPolicy.mockImplementation(async () => {
+ ordering.push('replace')
+ return {}
+ })
+ mockApi.deleteNamespacedNetworkPolicy.mockImplementation(async () => {
+ ordering.push('delete')
+ return {}
+ })
+ const onAuthoritativeRevocationComplete = vi.fn(() => {
+ ordering.push('certify')
+ })
await rec.fullReconcile([], [currentServer], {
ensureDefaults: false,
@@ -2246,11 +2318,95 @@ describe('NetworkPolicyReconciler', () => {
onAuthoritativeRevocationComplete,
})
- expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
- name: oldPolicy!.metadata!.name!,
+ expect(ordering.slice(0, 2)).toEqual(['replace', 'certify'])
+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
+ })
+
+ it('retains a valid same-intent DNS policy so readiness does not await fleet DNS refresh', async () => {
+ const server: McpServerCRD = {
+ name: 'stable-dns-server',
namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'stable:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'TCP' }],
+ },
+ }
+ const rec = makeReconciler(mockApi, new Map([[server.name, server]]), mockCustomApi)
+ await rec.reconcileExternalEgress(server)
+ const existing = mockApi.createNamespacedNetworkPolicy.mock.calls
+ .map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)
+ .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')
+ expect(existing).toBeDefined()
+
+ vi.clearAllMocks()
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(
+ async ({ labelSelector }: { labelSelector?: string }) =>
+ labelSelector?.includes('external-egress') ? { items: [existing!] } : { items: [] }
+ )
+ const additiveStarted = deferred()
+ const releaseAdditive = deferred()
+ vi.spyOn(rec, 'reconcileExternalEgress').mockImplementationOnce(async () => {
+ additiveStarted.resolve(undefined)
+ await releaseAdditive.promise
})
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ const fullPass = rec.fullReconcile([], [server], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+ await additiveStarted.promise
+ try {
+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(dns.resolve4).not.toHaveBeenCalled()
+ } finally {
+ releaseAdditive.resolve(undefined)
+ await fullPass
+ }
+ })
+
+ it('preserves a safety-certified DNS policy when the post-ready refresh fails', async () => {
+ const server: McpServerCRD = {
+ name: 'stable-dns-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'stable:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'TCP' }],
+ },
+ }
+ const rec = makeReconciler(mockApi, new Map([[server.name, server]]), mockCustomApi)
+ await rec.reconcileExternalEgress(server)
+ const existing = mockApi.createNamespacedNetworkPolicy.mock.calls
+ .map(call => (call[0] as { body: k8s.V1NetworkPolicy }).body)
+ .find(policy => policy.metadata?.labels?.['clerum.io/policy-type'] === 'external-egress')
+ expect(existing).toBeDefined()
+
+ vi.clearAllMocks()
+ vi.mocked(dns.resolve4).mockRejectedValue(new Error('dns unavailable'))
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(
+ async ({ labelSelector }: { labelSelector?: string }) =>
+ labelSelector?.includes('external-egress') ? { items: [existing!] } : { items: [] }
+ )
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ await expect(
+ rec.fullReconcile([], [server], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+ ).rejects.toThrow('dns unavailable')
+
expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
it('does not certify revocation when an earlier Context changes while a later owner is paused', async () => {
@@ -2625,6 +2781,77 @@ describe('NetworkPolicyReconciler', () => {
})
})
+ it('fails closed by deleting HCC-managed policies with missing owner labels', async () => {
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(
+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => {
+ const managedLabels = { 'clerum.io/managed-by': 'host-context-controller' }
+ if (labelSelector?.includes('policy-type=context-allow')) {
+ return {
+ items: [
+ {
+ metadata: {
+ name:
+ namespace === 'mcp-host'
+ ? 'malformed-host-egress'
+ : 'malformed-context-ingress',
+ labels: managedLabels,
+ },
+ },
+ ],
+ }
+ }
+ if (labelSelector?.includes('rpc-proxy-egress')) {
+ return {
+ items: [
+ {
+ metadata: {
+ name: 'malformed-rpc-proxy-egress',
+ labels: managedLabels,
+ },
+ },
+ ],
+ }
+ }
+ if (labelSelector?.includes('external-egress')) {
+ return {
+ items: [
+ {
+ metadata: {
+ name: 'malformed-external-egress',
+ labels: managedLabels,
+ },
+ },
+ ],
+ }
+ }
+ return { items: [] }
+ }
+ )
+
+ await reconciler.fullReconcile([], [], {
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ serverInventoryComplete: true,
+ })
+
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'malformed-context-ingress',
+ namespace: 'mcp-server',
+ })
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'malformed-host-egress',
+ namespace: 'mcp-host',
+ })
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'malformed-rpc-proxy-egress',
+ namespace: 'rpc-proxy',
+ })
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'malformed-external-egress',
+ namespace: 'mcp-server',
+ })
+ })
+
it('skips external egress orphan cleanup when startup server discovery is incomplete', async () => {
mockApi.listNamespacedNetworkPolicy.mockImplementation(
async ({ labelSelector }: { labelSelector?: string }) => {
@@ -2750,9 +2977,12 @@ describe('NetworkPolicyReconciler', () => {
serverInventoryAuthoritative,
})
- expect(reconcileExternalEgress).toHaveBeenCalledWith(desiredServer, {
- isCurrent: expect.any(Function),
- })
+ expect(reconcileExternalEgress).toHaveBeenCalledWith(
+ desiredServer,
+ expect.objectContaining({
+ isCurrent: expect.any(Function),
+ })
+ )
expect(serverInventoryAuthoritative).toHaveBeenCalled()
expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({
name: 'ext-egress-deleted-server-api-example-com-443',
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index e3cf6065a..2ec29b061 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -51,6 +51,8 @@ type JsonPatchOperation = {
type NetworkPolicyMutationOptions = {
isCurrent?: () => boolean
+ existingPolicies?: k8s.V1NetworkPolicy[]
+ preserveCertifiedDnsPolicyOnRefreshFailure?: boolean
}
export function sameContextDesiredRevision(expected: ContextCRD, current: ContextCRD): boolean {
@@ -655,7 +657,7 @@ export class NetworkPolicyReconciler {
`[NetPol] Reconciling context "${contextId}" — allowed servers: [${allowedServers.join(', ')}]`
)
- const existingPolicies = await this.listPoliciesForContext(contextId)
+ await this.listPoliciesForContext(contextId)
if (!isCurrent()) return
// Create or update policies for each allowed server.
@@ -696,7 +698,10 @@ export class NetworkPolicyReconciler {
)
}
- await this.revokeStaleContextAllows(context, isCurrent, { context: existingPolicies })
+ // The pre-apply LIST above is an authority fence, not a post-apply cleanup
+ // snapshot. Re-LIST every lane after the writes so a same-name policy that
+ // was just replaced is compared in its new form and cannot delete itself.
+ await this.revokeStaleContextAllows(context, isCurrent)
}
private async revokeStaleContextAllows(
@@ -885,7 +890,20 @@ export class NetworkPolicyReconciler {
if (!contextCleanupAuthoritative()) return
for (const policy of policies) {
const contextId = policy.metadata?.labels?.[CONTEXT_LABEL]
- if (contextId && !desiredContextIds.has(contextId)) {
+ if (!contextId) {
+ if (!contextCleanupAuthoritative()) return
+ const name = policy.metadata?.name
+ if (!name) {
+ throw new Error('HCC-managed Context NetworkPolicy is missing its name and owner label')
+ }
+ console.warn(
+ `[NetPol] Deleting malformed HCC-managed policy "${name}" without ${CONTEXT_LABEL}`
+ )
+ await deletePolicy(name)
+ recordSafetyPassRevocation()
+ continue
+ }
+ if (!desiredContextIds.has(contextId)) {
const name = policy.metadata?.name || ''
await runContextEffect(contextId, async () => {
if (
@@ -980,7 +998,22 @@ export class NetworkPolicyReconciler {
safetyPassListedPolicies += allExternalPolicies.length
for (const policy of allExternalPolicies) {
const serverName = policy.metadata?.labels?.[MCPSERVER_LABEL]
- if (serverName && !desiredServerNames.has(serverName)) {
+ if (!serverName) {
+ if (!serverCleanupAuthoritative()) break
+ const name = policy.metadata?.name
+ if (!name) {
+ throw new Error(
+ 'HCC-managed external egress NetworkPolicy is missing its name and owner label'
+ )
+ }
+ console.warn(
+ `[NetPol] Deleting malformed HCC-managed policy "${name}" without ${MCPSERVER_LABEL}`
+ )
+ await this.deletePolicyInNamespace(config.namespace, name)
+ recordSafetyPassRevocation()
+ continue
+ }
+ if (!desiredServerNames.has(serverName)) {
const name = policy.metadata?.name || ''
await runServerEffect(serverName, async () => {
if (
@@ -1027,12 +1060,12 @@ export class NetworkPolicyReconciler {
const latest = options.resolveCurrentServer(current.name)
return latest !== undefined && sameMcpServerDesiredRevision(current, latest)
}
- const completed = await this.revokeStaleExternalEgress(
+ const completed = await this.reconcileExternalEgressSafety(
current,
- serverEffectIsCurrent,
allExternalPolicies.filter(
policy => policy.metadata?.labels?.[MCPSERVER_LABEL] === server.name
),
+ serverEffectIsCurrent,
recordSafetyPassRevocation
)
if (!completed && serverCleanupAuthoritative()) {
@@ -1095,8 +1128,11 @@ export class NetworkPolicyReconciler {
})
}
- // Reconcile external egress for all existing servers on startup so a
- // controller restart converges pre-existing McpServer CRDs too.
+ // Refresh and create external egress policies after certification. The
+ // safety phase above retains structurally valid same-intent DNS policies
+ // across restart, while changed bindings use make-before-break before
+ // readiness. This background refresh therefore cannot create a restart-
+ // induced deny window or preserve a stale allow.
for (const server of servers) {
await runServerEffect(server.name, async () => {
const current = options.resolveCurrentServer
@@ -1109,7 +1145,10 @@ export class NetworkPolicyReconciler {
const latest = options.resolveCurrentServer(current.name)
return latest !== undefined && sameMcpServerDesiredRevision(current, latest)
}
- await this.reconcileExternalEgress(current, { isCurrent: serverEffectIsCurrent })
+ await this.reconcileExternalEgress(current, {
+ isCurrent: serverEffectIsCurrent,
+ preserveCertifiedDnsPolicyOnRefreshFailure: true,
+ })
})
}
@@ -1207,10 +1246,47 @@ export class NetworkPolicyReconciler {
}
}
- private desiredProvableExternalEgressPolicies(
- server: McpServerCRD
- ): Map<string, k8s.V1NetworkPolicy> {
- const desired = new Map<string, k8s.V1NetworkPolicy>()
+ private canRetainDnsEgressPolicy(
+ policy: k8s.V1NetworkPolicy,
+ server: McpServerCRD,
+ binding: EgressBinding
+ ): boolean {
+ const expectedProtocol = binding.protocol ?? 'TCP'
+ return (
+ policy.metadata?.labels?.[MANAGED_BY_LABEL] === MANAGED_BY_VALUE &&
+ policy.metadata?.labels?.[POLICY_TYPE_LABEL] === EXTERNAL_EGRESS_POLICY_TYPE &&
+ policy.metadata?.labels?.[MCPSERVER_LABEL] === server.name &&
+ policy.metadata?.labels?.[EGRESS_CLASS_LABEL] === 'exact-host' &&
+ policy.spec?.podSelector?.matchLabels?.[MCPSERVER_LABEL] === server.name &&
+ policy.spec?.policyTypes?.length === 1 &&
+ policy.spec.policyTypes[0] === 'Egress' &&
+ (policy.spec.egress?.length ?? 0) > 0 &&
+ policy.spec.egress!.every(rule => {
+ const port = rule.ports?.[0]
+ const cidr = rule.to?.[0]?.ipBlock?.cidr
+ return (
+ rule.ports?.length === 1 &&
+ port !== undefined &&
+ port.port === binding.port &&
+ port.protocol === expectedProtocol &&
+ rule.to?.length === 1 &&
+ typeof cidr === 'string' &&
+ cidr.endsWith('/32') &&
+ isAllowedExternalEgressCidr(cidr) &&
+ (rule.to[0].ipBlock?.except?.length ?? 0) === 0
+ )
+ })
+ )
+ }
+
+ private async reconcileExternalEgressSafety(
+ server: McpServerCRD,
+ existingPolicies: k8s.V1NetworkPolicy[],
+ isCurrent: () => boolean,
+ onRevoked?: () => void
+ ): Promise<boolean> {
+ if (!isCurrent()) return false
+ const desired = new Map<string, { binding: EgressBinding; policy?: k8s.V1NetworkPolicy }>()
for (const binding of server.spec.egressBindings ?? []) {
const name = this.externalEgressPolicyName(server.name, binding)
if (!name) continue
@@ -1222,10 +1298,8 @@ export class NetworkPolicyReconciler {
binding.port === undefined &&
binding.protocol === undefined
) {
- desired.set(name, this.buildPublicWebEgressPolicy(server, name))
- continue
- }
- if (
+ desired.set(name, { binding, policy: this.buildPublicWebEgressPolicy(server, name) })
+ } else if (
egressClass === 'exact-host' &&
binding.cidr &&
isAllowedExternalEgressCidr(binding.cidr) &&
@@ -1234,37 +1308,55 @@ export class NetworkPolicyReconciler {
binding.port >= 1 &&
binding.port <= 65535
) {
- desired.set(name, this.buildExactHostEgressPolicy(server, name, binding, [binding.cidr]))
+ desired.set(name, {
+ binding,
+ policy: this.buildExactHostEgressPolicy(server, name, binding, [binding.cidr]),
+ })
+ } else if (
+ egressClass === 'exact-host' &&
+ binding.dns &&
+ isPublicDnsHostname(binding.dns) &&
+ binding.port !== undefined &&
+ Number.isInteger(binding.port) &&
+ binding.port >= 1 &&
+ binding.port <= 65535
+ ) {
+ desired.set(name, { binding })
}
- // DNS-derived IPs are intentionally not retained in the safety phase:
- // their currentness cannot be proven without the slow external lookup.
- // The additive phase resolves DNS and recreates the policy after stale
- // allows have been revoked and readiness can become available.
}
- return desired
- }
- private async revokeStaleExternalEgress(
- server: McpServerCRD,
- isCurrent: () => boolean,
- listedPolicies?: k8s.V1NetworkPolicy[],
- onRevoked?: () => void
- ): Promise<boolean> {
- if (!isCurrent()) return false
- const existingPolicies =
- listedPolicies ??
- (await this.listExternalEgressPoliciesForServer(server.name, server.namespace))
- if (!isCurrent()) return false
- const desiredPolicies = this.desiredProvableExternalEgressPolicies(server)
+ const stale: k8s.V1NetworkPolicy[] = []
+ let needsMakeBeforeBreak = false
+ for (const existing of existingPolicies) {
+ const name = existing.metadata?.name
+ const selected = name ? desired.get(name) : undefined
+ if (!selected) {
+ stale.push(existing)
+ continue
+ }
+ desired.delete(name!)
+ const retainable = selected.policy
+ ? sameNetworkPolicySpec(existing, selected.policy)
+ : this.canRetainDnsEgressPolicy(existing, server, selected.binding)
+ if (!retainable) {
+ needsMakeBeforeBreak = true
+ }
+ }
+ // A desired replacement with a different name must be created before its
+ // stale predecessor is removed. A purely missing allow has no stale
+ // permission to revoke and remains additive work after readiness.
+ if (stale.length > 0 && desired.size > 0) {
+ needsMakeBeforeBreak = true
+ }
+
+ if (needsMakeBeforeBreak) {
+ await this.reconcileExternalEgress(server, { isCurrent, existingPolicies })
+ return isCurrent()
+ }
await this.cleanupExternalEgress(
server.name,
server.namespace,
- existingPolicies.filter(policy => {
- const name = policy.metadata?.name
- if (!name) return false
- const desired = desiredPolicies.get(name)
- return !desired || !sameNetworkPolicySpec(policy, desired)
- }),
+ stale,
async () => isCurrent(),
onRevoked
)
@@ -1282,23 +1374,25 @@ export class NetworkPolicyReconciler {
): Promise<void> {
const isCurrent = options.isCurrent ?? (() => true)
if (!isCurrent()) return
- let existingPolicies: k8s.V1NetworkPolicy[]
- try {
- existingPolicies = await this.listExternalEgressPoliciesForServer(
- server.name,
- server.namespace
- )
- } catch (error) {
- if (!isCurrent()) return
- await this.writeExternalEgressStatus(
- server,
- [],
- 'False',
- 'InventoryListFailed',
- `Failed to list existing external egress policies: ${this.errorMessage(error)}`,
- isCurrent
- )
- throw error
+ let existingPolicies = options.existingPolicies
+ if (!existingPolicies) {
+ try {
+ existingPolicies = await this.listExternalEgressPoliciesForServer(
+ server.name,
+ server.namespace
+ )
+ } catch (error) {
+ if (!isCurrent()) return
+ await this.writeExternalEgressStatus(
+ server,
+ [],
+ 'False',
+ 'InventoryListFailed',
+ `Failed to list existing external egress policies: ${this.errorMessage(error)}`,
+ isCurrent
+ )
+ throw error
+ }
}
if (!isCurrent()) return
@@ -1437,6 +1531,17 @@ export class NetworkPolicyReconciler {
resolvedEgressIPs.push({ dns: binding.dns, ips: uniqueIps, resolvedAt })
console.log(`[NetPol] Resolved ${binding.dns} → [${cidrs.join(', ')}]`)
} catch (err) {
+ const certifiedExisting = existingPolicies.find(
+ policy =>
+ policy.metadata?.name === name &&
+ this.canRetainDnsEgressPolicy(policy, server, binding)
+ )
+ if (
+ options.preserveCertifiedDnsPolicyOnRefreshFailure &&
+ certifiedExisting !== undefined
+ ) {
+ desiredPolicyNames.add(name)
+ }
failures.push(`failed to resolve hostname "${binding.dns}": ${this.errorMessage(err)}`)
continue
}
diff --git a/host-context-controller/src/reconciler.test.ts b/host-context-controller/src/reconciler.test.ts
index 4cc083410..52916065b 100644
--- a/host-context-controller/src/reconciler.test.ts
+++ b/host-context-controller/src/reconciler.test.ts
@@ -41,6 +41,7 @@ vi.mock('./config', () => ({
controlPlaneNamespace: 'control-plane',
hostNamespace: 'mcp-host',
rpcProxyNamespace: 'rpc-proxy',
+ egressProxyImage: 'clerum/nginx-egress-proxy:test',
devMcpServers: [],
devContexts: [],
devAuthTokens: new Map(),
@@ -166,6 +167,26 @@ describe('Reconciler managed:false guard (Risk 1.7)', () => {
expect(appsApi.createNamespacedDeployment).toHaveBeenCalled()
})
+ it('canonicalizes a remote proxy image without mutating the authoritative cache object', async () => {
+ const server = makeServer({
+ name: 'remote-api',
+ image: 'vendor/original-image:1',
+ remote: { baseUrl: 'https://api.example.com' },
+ })
+ const originalSpec = structuredClone(server.spec)
+
+ await reconciler.reconcile(server)
+
+ expect(server.spec).toEqual(originalSpec)
+ expect(customApi.patchNamespacedCustomObject).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'remote-api',
+ body: { spec: { image: 'clerum/nginx-egress-proxy:test' } },
+ }),
+ expect.anything()
+ )
+ })
+
it('should log WRC-owned ownership when managed: false', async () => {
const consoleSpy = vi.spyOn(console, 'log')
const server = makeServer({ name: 'workflow-recipes', managed: false })
diff --git a/host-context-controller/src/reconciler.ts b/host-context-controller/src/reconciler.ts
index eae8da378..b1664c887 100644
--- a/host-context-controller/src/reconciler.ts
+++ b/host-context-controller/src/reconciler.ts
@@ -1532,7 +1532,6 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
}
)
if (!isCurrent()) return
- server.spec.image = config.egressProxyImage
console.log(
`[Reconciler] Canonicalized remote McpServer "${server.name}" image to ${config.egressProxyImage}`
)
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index a66c660a1..a003ab769 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.214",
+ "version": "0.1.215",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.214",
+ "version": "0.1.215",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index dfb6f2a56..fd8da4977 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.214",
+ "version": "0.1.215",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/main.mcpInitialization.test.ts b/mcp-host/src/__tests__/main.mcpInitialization.test.ts
index b6f711fa2..2aa2dde99 100644
--- a/mcp-host/src/__tests__/main.mcpInitialization.test.ts
+++ b/mcp-host/src/__tests__/main.mcpInitialization.test.ts
@@ -705,6 +705,7 @@ describe('replaceAuthoritativeMcpFleet', () => {
}
let installedState: Map<string, string> | undefined
const pollingStarted = vi.fn()
+ let initializationSettled = false
const initialization = replaceAuthoritativeMcpFleet({
servers: [slowServer, healthyServer],
previousManager: null,
@@ -716,11 +717,14 @@ describe('replaceAuthoritativeMcpFleet', () => {
coordinator,
onColdStartPublished: pollingStarted,
maxConcurrency: 2,
+ }).finally(() => {
+ initializationSettled = true
})
await slowStarted.promise
await vi.waitFor(() => expect(connected).toContain(healthyServer.name))
expect(pollingStarted).toHaveBeenCalledTimes(1)
+ await vi.waitFor(() => expect(initializationSettled).toBe(true))
await reconcileAuthoritativeMcpSnapshot({
servers: [slowServer, healthyServer],
@@ -809,6 +813,15 @@ describe('replaceAuthoritativeMcpFleet', () => {
releaseFirst.resolve()
await initialization
+ await vi.waitFor(() =>
+ expect(
+ (
+ coordinator as unknown as {
+ admissionTasks: Set<Promise<void>>
+ }
+ ).admissionTasks.size
+ ).toBe(0)
+ )
expect(state).toEqual(new Map())
await reconcileAuthoritativeMcpSnapshot({
@@ -1586,6 +1599,47 @@ describe('reconcileAuthoritativeMcpSnapshot', () => {
expect(serverState.get(previous.name)).toBe(JSON.stringify(notReady))
})
+ it.each([
+ [
+ 'disabled',
+ readyServer({
+ enabled: false,
+ status: { deployed: true, ready: true, authoritative: true },
+ }),
+ ],
+ [
+ 'authoritatively not-ready',
+ readyServer({
+ status: { deployed: true, ready: false, authoritative: true },
+ }),
+ ],
+ ])(
+ 'synchronously detaches a connected %s server before asynchronous reconciliation',
+ async (_reason, next) => {
+ const previous = readyServer()
+ const detachServer = vi.fn(() => vi.fn().mockResolvedValue(undefined))
+ const manager = {
+ addServer: appliedAdmission(),
+ replaceServer: appliedAdmission(),
+ removeServer: vi.fn().mockResolvedValue(undefined),
+ detachServer,
+ getConnectedServers: vi.fn(() => [previous.name]),
+ getKnownServers: vi.fn(() => [previous.name]),
+ recordAdmissionFailure: vi.fn(),
+ }
+
+ const reconciliation = reconcileAuthoritativeMcpSnapshot({
+ servers: [next],
+ manager,
+ serverState: new Map([[previous.name, JSON.stringify(previous)]]),
+ getAuthToken: vi.fn(),
+ })
+
+ expect(detachServer).toHaveBeenCalledWith(previous.name)
+ await reconciliation
+ }
+ )
+
it('retains legacy fail-closed teardown when status authority is undefined', async () => {
const previous = readyServer()
const legacyNotReady = readyServer({
diff --git a/mcp-host/src/mcp/authoritativeFleet.ts b/mcp-host/src/mcp/authoritativeFleet.ts
index e4ad9c185..9c3c5aa3d 100644
--- a/mcp-host/src/mcp/authoritativeFleet.ts
+++ b/mcp-host/src/mcp/authoritativeFleet.ts
@@ -569,11 +569,18 @@ export async function replaceAuthoritativeMcpFleet<
// them independently through a finite worker pool so one slow connection
// cannot head-of-line block a healthy peer and a large fleet cannot create
// an unbounded connection burst. Each failure remains retryable above.
- await runMcpFleetEffects(options.servers, maxConcurrency, server =>
+ const reconciliation = runMcpFleetEffects(options.servers, maxConcurrency, server =>
coordinator.runAdmission(nextManager, server.name, lease, isCurrent =>
admitServer(server, () => isCurrent() && options.isFleetLifecycleCurrent?.() !== false)
)
)
+ if (coldStart && coordinator.reconcilesInBackground) {
+ void reconciliation.catch(error => {
+ console.error('[Main] MCP background cold-start reconciliation failed:', error)
+ })
+ return
+ }
+ await reconciliation
// Cold start may publish healthy peers so HCC readiness is independent of
// full-fleet convergence. A live prior fleet is safer to preserve
diff --git a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
index f64d48e3c..fc1dbc6ca 100755
--- a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
+++ b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
@@ -138,6 +138,21 @@ wait_until() {
return 1
}
+wait_until_fast() {
+ local timeout=$1 description=$2
+ shift 2
+ local deadline now
+ deadline=$(( $(date +%s) + timeout ))
+ while :; do
+ "$@" && return 0
+ now="$(date +%s)"
+ [ "$now" -lt "$deadline" ] || break
+ sleep 0.5
+ done
+ echo "Timed out after ${timeout}s waiting for ${description}" >&2
+ return 1
+}
+
running_hcc_pod() {
local rows
rows="$(kctl get pods -n "$HCC_NS" -l "app=${HCC_DEPLOY}" \
@@ -181,15 +196,28 @@ dns_has_not_released_since_hold() {
}
startup_convergence_window_is_clean() {
+ local logs
# The fault injection deliberately withholds DNS answers. A resolver timeout
# may therefore schedule a bounded external-egress retry before the Context
- # assertion completes. That retry is expected while runtime and policy stay
- # absent; NetworkPolicy failures and terminal retry exhaustion are not.
- ! hcc_log_contains "Initial NetworkPolicy background reconciliation failed:" &&
- ! hcc_log_contains "Scheduling initial NetworkPolicy background convergence retry" &&
- ! hcc_log_contains "NetworkPolicy reconciliation failed for context ${CONTEXT_NAME}:" &&
- ! hcc_log_contains \
- "External egress retry exhausted for McpServer \"${MCP_NAME}\" in namespace \"${MCP_NS}\""
+ # assertion completes. Read one authoritative snapshot first so a kubectl
+ # logs failure cannot make the negative assertions pass vacuously.
+ [ -n "$NEW_HCC_POD" ] || return 1
+ logs="$(kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" \
+ -c host-context-controller 2>/dev/null)" || return 1
+ ! grep -Fq "Initial NetworkPolicy background reconciliation failed:" <<<"$logs" &&
+ ! grep -Fq "Scheduling initial NetworkPolicy background convergence retry" <<<"$logs" &&
+ ! grep -Fq "NetworkPolicy reconciliation failed for context ${CONTEXT_NAME}:" <<<"$logs"
+}
+
+external_egress_retry_progress_is_observed() {
+ local logs
+ [ -n "$NEW_HCC_POD" ] || return 1
+ logs="$(kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" \
+ -c host-context-controller 2>/dev/null)" || return 1
+ grep -Fq \
+ "Initial external egress reconciliation failed for ${MCP_NS}/${MCP_NAME};" <<<"$logs" &&
+ grep -Fq "Scheduling external egress retry " <<<"$logs" &&
+ grep -Fq "for McpServer \"${MCP_NAME}\"" <<<"$logs"
}
hcc_identity_is_stable() {
@@ -480,6 +508,9 @@ mcp_egress_binding_is_udp() {
create_peer_fleet() {
local index server context
+ # Arm cleanup before the first write so a partial apply cannot strand input
+ # CRDs or leave HCC deliberately scaled down during failure recovery.
+ PEER_FLEET_CREATED=1
for ((index = 1; index < ${#MCP_FLEET_NAMES[@]}; index++)); do
server="${MCP_FLEET_NAMES[index]}"
context="${CONTEXT_FLEET_NAMES[index]}"
@@ -516,7 +547,6 @@ spec:
port: 3000
EOF
done
- PEER_FLEET_CREATED=1
}
fixture_converged() {
@@ -653,6 +683,36 @@ probe_hcc_ready_pod() {
' >/dev/null 2>&1
}
+probe_new_hcc_ready_endpoint() {
+ [ -n "$NEW_HCC_POD" ] || return 1
+ kctl exec "pod/${NEW_HCC_POD}" -n "$HCC_NS" -c host-context-controller -- \
+ env "HCC_E2E_PORT=${HCC_PORT}" \
+ node -e '
+ const http = require("node:http");
+ const request = http.get(
+ {host: "127.0.0.1", port: Number(process.env.HCC_E2E_PORT), path: "/ready"},
+ response => {
+ let body = "";
+ response.setEncoding("utf8");
+ response.on("data", chunk => { body += chunk; });
+ response.on("end", () => {
+ let parsed;
+ try { parsed = JSON.parse(body); } catch { process.exit(2); }
+ process.exit(response.statusCode === 200 && parsed?.ready === true ? 0 : 3);
+ });
+ }
+ );
+ request.setTimeout(2000, () => request.destroy(new Error("timeout")));
+ request.once("error", () => process.exit(4));
+ ' >/dev/null 2>&1
+}
+
+hcc_ready_only_after_stale_policy_revoked() {
+ probe_new_hcc_ready_endpoint || return 1
+ fixture_mcp_runtime_absent ||
+ die "HCC served /ready=200 while the stale external-egress allow or fixture runtime was present"
+}
+
hcc_restore_is_verified() {
local deployment
deployment="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" -o json)" || return 1
@@ -1251,9 +1311,12 @@ wait_until 120 "fixture external-egress DNS query to reach the hold proxy" \
wait_until 60 "HCC to begin initial external-egress convergence" \
hcc_log_contains "Reconciling external egress before startup runtime reconciliation" ||
die "HCC did not log initial McpServer external-egress convergence"
-wait_until 120 "replacement HCC pod and Deployment to become Kubernetes Ready during the hold" \
+wait_until_fast 120 "HCC /ready to become available only after stale policy revocation" \
+ hcc_ready_only_after_stale_policy_revoked ||
+ die "HCC did not become ready after authoritative stale-policy revocation"
+wait_until 30 "replacement HCC pod and Deployment to corroborate readiness" \
hcc_kubernetes_readiness_is_exact ||
- die "HCC did not become Kubernetes Ready while initial McpServer convergence remained blocked"
+ die "Kubernetes did not corroborate HCC readiness after the direct ordering assertion"
dns_log_contains "holding DNS A ${TARGET_DNS}" ||
die "DNS hold ended before Kubernetes reported HCC Ready"
if ! dns_has_not_released_since_hold; then
@@ -1286,7 +1349,9 @@ wait_until 120 "initial NetworkPolicy pass to reconcile the fixture's empty Cont
hcc_log_contains "$initial_empty_context_log" ||
die "initial NetworkPolicy pass never reconciled the fixture's empty Context"
startup_convergence_window_is_clean ||
- die "startup NetworkPolicy failed or fixture external-egress retries exhausted before the Context update"
+ die "startup NetworkPolicy failed or HCC logs were unavailable before the Context update"
+external_egress_retry_progress_is_observed ||
+ die "the injected DNS failure did not produce observable external-egress retry progress"
context_policies_absent ||
die "Context policy appeared before the isolated MODIFIED event"
@@ -1306,7 +1371,7 @@ wait_until 120 "all three latest-Context NetworkPolicies to converge during the
context_policies_converged ||
die "Context policies remained blocked behind the held McpServer convergence"
startup_convergence_window_is_clean ||
- die "startup NetworkPolicy failed or fixture external-egress retries exhausted during the isolation window"
+ die "startup NetworkPolicy failed or HCC logs were unavailable during the isolation window"
fixture_mcp_convergence_absent ||
die "McpServer runtime or external-egress policy escaped the deterministic DNS hold boundary"
dns_log_contains "holding DNS A ${TARGET_DNS}" ||
@@ -1347,7 +1412,7 @@ wait_until 60 "initial NetworkPolicy full pass to run" \
hcc_log_contains "Running initial NetworkPolicy background reconciliation" ||
die "initial NetworkPolicy convergence was not observed after releasing MCP convergence"
startup_convergence_window_is_clean ||
- die "startup NetworkPolicy failed or fixture external-egress retries exhausted before final convergence"
+ die "startup NetworkPolicy failed or HCC logs were unavailable before final convergence"
hcc_identity_is_stable ||
die "HCC restarted instead of completing the released background convergence"
final_probe="$(probe_hcc_final_context)" ||
diff --git a/scripts/e2e/e2e-hcc-readiness-bootstrap.sh b/scripts/e2e/e2e-hcc-readiness-bootstrap.sh
index 4e5614886..e26ac3b4a 100755
--- a/scripts/e2e/e2e-hcc-readiness-bootstrap.sh
+++ b/scripts/e2e/e2e-hcc-readiness-bootstrap.sh
@@ -216,6 +216,7 @@ fixture_inputs_absent() {
fixture_runtime_absent() {
local host resources
+ [ "${#FIXTURE_HOST_NAMES[@]}" -eq 0 ] && return 0
for host in "${FIXTURE_HOST_NAMES[@]}"; do
resources="$(
kctl get deployment,service,serviceaccount,role,rolebinding,secret,persistentvolumeclaim,networkpolicy \
@@ -327,6 +328,7 @@ delete_host_fixtures() {
--ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
kctl delete secret -n "$HOST_NS" -l "e2e.clerum.io/suite=${SUITE_NAME}" \
--ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ [ "${#FIXTURE_HOST_NAMES[@]}" -eq 0 ] && return "$failed"
for host in "${FIXTURE_HOST_NAMES[@]}"; do
kctl delete \
deployment,service,serviceaccount,role,rolebinding,secret,persistentvolumeclaim,networkpolicy \
diff --git a/scripts/tests/test-hcc-watch-recovery-gate.sh b/scripts/tests/test-hcc-watch-recovery-gate.sh
index 300defab1..9c640a706 100755
--- a/scripts/tests/test-hcc-watch-recovery-gate.sh
+++ b/scripts/tests/test-hcc-watch-recovery-gate.sh
@@ -1,4 +1,7 @@
#!/usr/bin/env bash
+# Values in the eval-based fixture harness are consumed by extracted gate
+# functions, which static shell analysis cannot follow.
+# shellcheck disable=SC2034
set -u
FAIL=0
@@ -231,7 +234,12 @@ done
startup_window_function="$(
sed -n '/^startup_convergence_window_is_clean() {$/,/^}$/p' "$MCP_READINESS_GATE"
)"
+retry_progress_function="$(
+ sed -n '/^external_egress_retry_progress_is_observed() {$/,/^}$/p' "$MCP_READINESS_GATE"
+)"
if (
+ NEW_HCC_POD=hcc-pod
+ HCC_NS=control-plane
MCP_NS=mcp-server
MCP_NAME=e2e-held-server
CONTEXT_NAME=e2e-context
@@ -239,26 +247,43 @@ if (
[K8s] Initial external egress reconciliation failed for mcp-server/e2e-held-server; runtime reconciliation will stay blocked until retry succeeds: dns timeout
[K8s] Scheduling external egress retry 1/3 for McpServer "e2e-held-server" in 5000ms
'
- hcc_log_contains() { grep -Fq "$1" <<<"$MOCK_HCC_LOG"; }
+ kctl() { printf '%s\n' "$MOCK_HCC_LOG"; }
eval "$startup_window_function"
- startup_convergence_window_is_clean
+ eval "$retry_progress_function"
+ startup_convergence_window_is_clean && external_egress_retry_progress_is_observed
); then
- pass "the injected DNS hold permits transient external-egress failure and bounded retry"
+ pass "the injected DNS hold requires observable live retry progress without treating it as fatal"
else
- fail "the injected DNS hold incorrectly treats its expected transient retry as fatal"
+ fail "the injected DNS hold cannot distinguish expected live retry progress"
fi
if (
+ NEW_HCC_POD=hcc-pod
+ HCC_NS=control-plane
MCP_NS=mcp-server
MCP_NAME=e2e-held-server
CONTEXT_NAME=e2e-context
- MOCK_HCC_LOG='External egress retry exhausted for McpServer "e2e-held-server" in namespace "mcp-server"'
- hcc_log_contains() { grep -Fq "$1" <<<"$MOCK_HCC_LOG"; }
+ MOCK_HCC_LOG='[K8s] Initial NetworkPolicy background reconciliation failed: denied'
+ kctl() { printf '%s\n' "$MOCK_HCC_LOG"; }
eval "$startup_window_function"
! startup_convergence_window_is_clean
); then
- pass "the injected DNS hold still rejects terminal external-egress retry exhaustion"
+ pass "the convergence window rejects a real NetworkPolicy failure marker"
else
- fail "the injected DNS hold can accept terminal external-egress retry exhaustion"
+ fail "the convergence window accepts a real NetworkPolicy failure marker"
+fi
+if (
+ NEW_HCC_POD=hcc-pod
+ HCC_NS=control-plane
+ MCP_NS=mcp-server
+ MCP_NAME=e2e-held-server
+ CONTEXT_NAME=e2e-context
+ kctl() { return 1; }
+ eval "$startup_window_function"
+ ! startup_convergence_window_is_clean
+); then
+ pass "the convergence window fails closed when HCC logs are unavailable"
+else
+ fail "the convergence window passes vacuously when HCC logs are unavailable"
fi
# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-logs.sh
@@ -321,6 +346,55 @@ else
fail "fixture creation can continue or report success after an intermediate apply failure"
fi
+bootstrap_runtime_absent_function="$(
+ sed -n '/^fixture_runtime_absent() {$/,/^}$/p' "$READINESS_GATE"
+)"
+bootstrap_delete_fixtures_function="$(
+ sed -n '/^delete_host_fixtures() {$/,/^}$/p' "$READINESS_GATE"
+)"
+# Literal source-code assertions for macOS bash 3.2, where expanding an empty
+# array under set -u terminates the shell before cleanup can release its lock.
+# shellcheck disable=SC2016
+if [[ "$bootstrap_runtime_absent_function" == *'[ "${#FIXTURE_HOST_NAMES[@]}" -eq 0 ] && return 0'* ]] &&
+ [[ "$bootstrap_delete_fixtures_function" == *'[ "${#FIXTURE_HOST_NAMES[@]}" -eq 0 ] && return "$failed"'* ]]; then
+ pass "bootstrap cleanup guards empty fixture arrays before bash 3.2 expansion"
+else
+ fail "bootstrap cleanup can abort on an empty fixture array before lock finalization"
+fi
+
+create_peer_fleet_function="$(
+ sed -n '/^create_peer_fleet() {$/,/^}$/p' "$MCP_READINESS_GATE"
+)"
+peer_flag_line="$(grep -nF ' PEER_FLEET_CREATED=1' <<<"$create_peer_fleet_function" | head -1 | cut -d: -f1)"
+peer_loop_line="$(grep -nF ' for ((index = 1;' <<<"$create_peer_fleet_function" | head -1 | cut -d: -f1)"
+if [ -n "$peer_flag_line" ] && [ -n "$peer_loop_line" ] &&
+ [ "$peer_flag_line" -lt "$peer_loop_line" ]; then
+ pass "peer fleet cleanup is armed before the first partial apply can fail"
+else
+ fail "peer fleet cleanup is armed only after all applies complete"
+fi
+
+readiness_boundary_function="$(
+ sed -n '/^hcc_ready_only_after_stale_policy_revoked() {$/,/^}$/p' "$MCP_READINESS_GATE"
+)"
+direct_ready_line="$(
+ grep -nF 'wait_until_fast 120 "HCC /ready to become available only after stale policy revocation"' \
+ "$MCP_READINESS_GATE" | cut -d: -f1
+)"
+kubernetes_ready_line="$(
+ grep -nF 'wait_until 30 "replacement HCC pod and Deployment to corroborate readiness"' \
+ "$MCP_READINESS_GATE" | cut -d: -f1
+)"
+# shellcheck disable=SC2016
+if [[ "$readiness_boundary_function" == *'probe_new_hcc_ready_endpoint || return 1'* ]] &&
+ [[ "$readiness_boundary_function" == *'fixture_mcp_runtime_absent ||'* ]] &&
+ [ -n "$direct_ready_line" ] && [ -n "$kubernetes_ready_line" ] &&
+ [ "$direct_ready_line" -lt "$kubernetes_ready_line" ]; then
+ pass "direct /ready ordering is asserted against stale policy presence before Kubernetes corroboration"
+else
+ fail "readiness ordering still relies on the delayed Kubernetes Pod Ready signal"
+fi
+
printf '%s\n' \
'[K8s] CommunicationChannel watch ended; holding stateless lifecycle active until snapshot recovery' \
'[K8s] Listing all Hosts in namespace mcp-host' \
@@ -555,7 +629,7 @@ if grep -Fq 'source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-fixture.sh"' \
grep -Fq 'hcc_pods_absent' "$MCP_READINESS_GATE" &&
! grep -Fq -- '--for=delete' "$MCP_READINESS_GATE" &&
! grep -Fq 'port: 8081' "$MCP_READINESS_GATE" &&
- [ "$mcp_port_probe_count" = 3 ] &&
+ [ "$mcp_port_probe_count" = 4 ] &&
[ "$mcp_pod_absence_count" = 3 ]; then
pass "MCP readiness gate shares exact-head ownership and uses bounded portable runtime probes"
else
@@ -649,7 +723,7 @@ truncate_rfc1123() { printf '%.63s' "$1"; }
source "$LOCK_HELPER"
HCC_NS=control-plane
-HCC_DEPLOY=host-context-controller
+HCC_DEPLOY="host-context-controller"
E2E_KUBECONTEXT=clerum-codex-lock-test-1234abcd
RUN_ID=owner-1
HCC_GATE_LOCK_ACQUIRED=0