Skip to content

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

TypeScript

refactor(hcc): move the readiness certification policy to the readiness lane

Alfredo Lopez54382ff089e5
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 5b698d951..5f0eec783 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.188",
+ "version": "0.1.189",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.188",
+ "version": "0.1.189",
"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 3664f50a5..59a0864f5 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.188",
+ "version": "0.1.189",
"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 95e8af758..f47ec22c5 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -1,6 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as http from 'http'
-import { config } from './config'
import { HostFleetReconcileError } from './hostReconciler'
import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'
import {
@@ -121,6 +120,7 @@ const mocks = vi.hoisted(() => {
.fn()
.mockRejectedValue(Object.assign(new Error('not found'), { code: 404 }))
const ensureDefaultPolicies = vi.fn().mockResolvedValue(undefined)
+ const hasCertifiedSafetyInventory = vi.fn().mockReturnValue(true)
const netPolFullReconcile = vi.fn().mockImplementation(async (...args: unknown[]) => {
const options = args[2] as { onAuthoritativeRevocationComplete?: () => void } | undefined
options?.onAuthoritativeRevocationComplete?.()
@@ -133,6 +133,7 @@ const mocks = vi.hoisted(() => {
const hostListCallOptions = vi.fn()
const createAdministrativeOutcomeReporter = vi.fn().mockReturnValue(undefined)
return {
+ hasCertifiedSafetyInventory,
listNamespacedCustomObject,
getNamespacedCustomObject,
ensureDefaultPolicies,
@@ -305,6 +306,7 @@ vi.mock('./networkPolicyReconciler', () => ({
reconcileContext = vi.fn()
reconcileDeleteContext = vi.fn()
cleanupExternalEgress = vi.fn()
+ hasCertifiedSafetyInventory = mocks.hasCertifiedSafetyInventory
},
}))
@@ -1343,6 +1345,86 @@ describe('McpServerWatcher startup', () => {
}
})
+ it('does not certify a Context delta while the namespace-wide inventory is uncertified', async () => {
+ const olderAdditivePass = deferred()
+ const uncertifiedDelta = deferred<boolean>()
+ let contextWatchCallback:
+ | ((
+ type: string,
+ apiObj: {
+ metadata: { name: string; namespace: string; uid: string }
+ spec: { contextId: string; mcpServers: string[] }
+ }
+ ) => Promise<void>)
+ | undefined
+ let networkPolicyPasses = 0
+ mocks.watch.mockImplementationOnce(async (path, _options, callback) => {
+ if (path.endsWith('/contexts')) contextWatchCallback = callback
+ return { abort: vi.fn() }
+ })
+ mocks.netPolFullReconcile.mockImplementation(async (...args: unknown[]) => {
+ networkPolicyPasses += 1
+ const options = args[2] as { onAuthoritativeRevocationComplete?: () => void } | undefined
+ options?.onAuthoritativeRevocationComplete?.()
+ if (networkPolicyPasses === 1) await olderAdditivePass.promise
+ })
+
+ const watcher = new McpServerWatcher()
+ await (watcher as any).startContextWatch('uncertified-inventory-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('delta-context', {
+ name: 'delta-context',
+ namespace: 'mcp-server',
+ uid: 'delta-context-uid',
+ spec: { contextId: 'delta-context', mcpServers: [] },
+ })
+ const server = new ContextMapperServer(watcher, 0, undefined, undefined, () =>
+ watcher.isReadinessInventoryAuthoritative()
+ )
+ await server.start()
+ server.setReady(true)
+ const initialPass = (watcher as any).runInitialNetworkPolicyConvergence() as Promise<void>
+ ;(watcher as any).netPolReconciler.reconcileContext.mockImplementationOnce(
+ () => uncertifiedDelta.promise
+ )
+ // The delta's own revocation completes, but the last authoritative pass left
+ // the namespace-wide inventory uncertified. A label-scoped delta cannot
+ // vouch for that namespace, so readiness must stay withheld.
+ mocks.hasCertifiedSafetyInventory.mockReturnValue(false)
+
+ try {
+ await vi.waitFor(() => expect(mocks.netPolFullReconcile).toHaveBeenCalledOnce())
+ expect((await requestReadyOverHttp(server)).statusCode).toBe(200)
+
+ const delta = contextWatchCallback!('MODIFIED', {
+ metadata: {
+ name: 'delta-context',
+ namespace: 'mcp-server',
+ uid: 'delta-context-uid',
+ },
+ spec: { contextId: 'delta-context', mcpServers: ['delta-server'] },
+ })
+
+ await vi.waitFor(() =>
+ expect((watcher as any).netPolReconciler.reconcileContext).toHaveBeenCalledOnce()
+ )
+ expect((await requestReadyOverHttp(server)).statusCode).toBe(503)
+ uncertifiedDelta.resolve(true)
+ await delta
+
+ expect((await requestReadyOverHttp(server)).statusCode).toBe(503)
+ } finally {
+ mocks.hasCertifiedSafetyInventory.mockReturnValue(true)
+ olderAdditivePass.resolve(undefined)
+ await initialPass
+ await server.stop()
+ await watcher.stop()
+ }
+ })
+
it('does not issue a Context delta certificate before any authoritative safety certificate', async () => {
const pendingFullSafetyPass = deferred()
let contextWatchCallback:
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index 18fca3e8e..448e894b0 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -3718,14 +3718,16 @@ export class McpServerWatcher implements McpServerProvider {
} else if (current?.spec.contextId !== context.spec.contextId) {
return
}
- // A scoped delta may only certify readiness when its own stale-allow
- // revocation ran to completion. `reconcileContext` aborts mid-pass
- // whenever its authority fence breaks, so treating "it returned" as
- // "it revoked" would certify a Context whose stale allows are live.
- let scopedRevocationCompleted = false
if (type === 'ADDED' || type === 'MODIFIED') {
const selectedContext = current!
- scopedRevocationCompleted = await this.netPolReconciler.reconcileContext(
+ // A scoped delta may only replace the safety certificate when its
+ // own stale-allow revocation ran to completion — `reconcileContext`
+ // aborts mid-pass whenever its authority fence breaks — and when
+ // the last authoritative pass certified its namespace-wide
+ // inventory, which a label-scoped delta cannot vouch for.
+ // `deltaSafetyCertificate` is only ever built for MODIFIED, so this
+ // is the one branch where it can be recorded.
+ const scopedRevocationCompleted = await this.netPolReconciler.reconcileContext(
selectedContext,
{
isCurrent: () =>
@@ -3734,6 +3736,15 @@ export class McpServerWatcher implements McpServerProvider {
this.contexts.get(selectedContext.name) === selectedContext,
}
)
+ if (deltaSafetyCertificate && scopedRevocationCompleted) {
+ if (this.netPolReconciler.hasCertifiedSafetyInventory()) {
+ this.recordNetworkPolicySafetyCertificate(deltaSafetyCertificate)
+ } else {
+ console.warn(
+ `[K8s] Not certifying the scoped delta for context "${context.spec.contextId}": the last authoritative safety pass ended without certifying its namespace-wide inventory`
+ )
+ }
+ }
} else if (type === 'DELETED') {
const deleteAllowed = () =>
this.contextAbsentForDelete(context.name, context.namespace, watchGeneration)
@@ -3743,10 +3754,6 @@ export class McpServerWatcher implements McpServerProvider {
deleteAllowed
)
}
-
- if (deltaSafetyCertificate && scopedRevocationCompleted) {
- this.recordNetworkPolicySafetyCertificate(deltaSafetyCertificate)
- }
} catch (error) {
console.error(
`[K8s] NetworkPolicy reconciliation failed for context ${context.name}:`,
diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index 061537e26..dbf2533a0 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -4729,7 +4729,11 @@ describe('NetworkPolicyReconciler', () => {
).rejects.toThrow(/Ambiguous NetworkPolicy ownership/)
expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()
- expect(await reconciler.reconcileContext(deltaContext)).toBe(false)
+ // The delta's own revocation still completes — its label-scoped LISTs are
+ // clean. What it may not do is vouch for the namespace-wide inventory,
+ // which the readiness lane checks separately.
+ expect(await reconciler.reconcileContext(deltaContext)).toBe(true)
+ expect(reconciler.hasCertifiedSafetyInventory()).toBe(false)
})
it('certifies a scoped delta again once a later safety pass completes', async () => {
@@ -4754,10 +4758,12 @@ describe('NetworkPolicyReconciler', () => {
expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
expect(await reconciler.reconcileContext(deltaContext)).toBe(true)
+ expect(reconciler.hasCertifiedSafetyInventory()).toBe(true)
})
it('certifies a scoped delta when no safety pass has failed', async () => {
expect(await reconciler.reconcileContext(deltaContext)).toBe(true)
+ expect(reconciler.hasCertifiedSafetyInventory()).toBe(true)
})
})
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index 1dfe2b5aa..211d511d8 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -823,14 +823,19 @@ export class NetworkPolicyReconciler {
// Re-LIST every lane after writes so a same-name policy that was just
// replaced is compared in its new form and cannot delete itself.
- const revoked = await this.revokeStaleContextAllows(context, isCurrent)
- if (revoked && this.safetyPassLeftUncertified) {
- console.warn(
- `[NetPol] Not certifying the scoped delta for context "${contextId}": the last authoritative safety pass ended without certifying its namespace-wide inventory`
- )
- return false
- }
- return revoked
+ return await this.revokeStaleContextAllows(context, isCurrent)
+ }
+
+ /**
+ * Whether the last authoritative safety pass certified its namespace-wide
+ * inventory. Only that pass enumerates the bounded namespaces and classifies
+ * every object it finds; a scoped delta sees nothing but its own label
+ * selectors, so it cannot vouch for a namespace whose classified inventory is
+ * still stuck. The readiness lane consults this before letting a delta
+ * replace the safety certificate.
+ */
+ hasCertifiedSafetyInventory(): boolean {
+ return !this.safetyPassLeftUncertified
}
private async revokeStaleContextAllows(
@@ -2525,6 +2530,12 @@ export class NetworkPolicyReconciler {
console.log(
`[NetPol] Safety policy "${name}" in ${namespace} already exists — converging it to the desired spec`
)
+ // Deliberately not delegating to applyOwnedPolicy here: that helper owns
+ // the create-then-conflict flow, so calling it from inside our own
+ // create's catch would issue a second create. Delegating from the top is
+ // not an option either — the desired-state fence below needs the object
+ // this request created, which applyNetworkPolicy does not return. The
+ // wiring below is kept identical to it on purpose.
await replaceWithConflictRetry<k8s.V1NetworkPolicy>({
description: `policy "${name}" in ${namespace}`,
logPrefix: '[NetPol]',
diff --git a/scripts/tests/test-hcc-watch-recovery-gate.sh b/scripts/tests/test-hcc-watch-recovery-gate.sh
index 33aa920f4..8bc7d7a63 100755
--- a/scripts/tests/test-hcc-watch-recovery-gate.sh
+++ b/scripts/tests/test-hcc-watch-recovery-gate.sh
@@ -393,27 +393,6 @@ else
fail "the DNS fixture can mistake a resolver retransmit for a dedicated retry"
fi
-# Keep the runtime log contract consumed above tied to its producer. Template
-# literals are checked as their fixed text plus the variable that supplies the
-# dynamic identity, avoiding a rendered-string grep that would produce false
-# drift reports.
-if grep -Fq 'Initial external egress reconciliation failed for ${key};' \
- "$HCC_EGRESS_COORDINATOR" &&
- grep -Fq 'Scheduling external egress retry ${attempt}/${EXTERNAL_EGRESS_RETRY_DELAYS_MS.length}' \
- "$HCC_EGRESS_COORDINATOR" &&
- grep -Fq 'for McpServer "${this.retryIntents.get(key)!.server.name}"' \
- "$HCC_EGRESS_COORDINATOR" &&
- grep -Fq 'Context watch event: ${type} for ${context.name}' \
- "$HCC_K8S_CLIENT" &&
- grep -Fq 'Running initial NetworkPolicy background reconciliation...' \
- "$HCC_K8S_CLIENT" &&
- grep -Fq 'Reconciling context "${contextId}" — allowed servers: [${allowedServers.join(' \
- "$HCC_NETWORK_POLICY_RECONCILER"; then
- pass "MCP readiness log predicates remain bound to their runtime producers"
-else
- fail "an MCP readiness log predicate drifted from its runtime producer"
-fi
-
# Full marker inventory: every runtime log marker any HCC gate consumes, paired
# with the producer statement that emits it. Both sides are matched as fixed
# source text, never as a rendered string: a template literal is pinned by its