Skip to content

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

TypeScript

fix(hcc): stop scoped Context deltas certifying over a failed safety pass

Alfredo Lopez57e7d286ba41
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 4b38710f3..470a40b17 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.185",
+ "version": "0.1.186",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.185",
+ "version": "0.1.186",
"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 5bb9fbdac..9895007c7 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.185",
+ "version": "0.1.186",
"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/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index 717e9c73c..061537e26 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -4692,4 +4692,301 @@ describe('NetworkPolicyReconciler', () => {
expect(onDeleted).not.toHaveBeenCalled()
})
})
+
+ describe('scoped delta certification vs. a stuck safety inventory', () => {
+ const ambiguousReservedPolicy: k8s.V1NetworkPolicy = {
+ metadata: { name: 'ctx-reserved-context-server', labels: {} },
+ spec: { podSelector: {}, policyTypes: ['Ingress'] },
+ }
+ const deltaContext: ContextCRD = {
+ name: 'default',
+ namespace: 'mcp-server',
+ spec: { contextId: 'default', mcpServers: [] },
+ }
+
+ function stickSafetyInventory(): void {
+ // Only the namespace-wide safety inventory sees the foreign policy. The
+ // label-scoped LISTs the delta lane uses stay clean, which is exactly why
+ // the delta cannot vouch for the namespace.
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(
+ async ({ namespace, labelSelector }: { namespace?: string; labelSelector?: string }) => ({
+ items: !labelSelector && namespace === 'mcp-server' ? [ambiguousReservedPolicy] : [],
+ })
+ )
+ }
+
+ it('refuses to certify a scoped delta while the safety pass is stuck on its inventory', async () => {
+ stickSafetyInventory()
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ await expect(
+ reconciler.fullReconcile([], [], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+ ).rejects.toThrow(/Ambiguous NetworkPolicy ownership/)
+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()
+
+ expect(await reconciler.reconcileContext(deltaContext)).toBe(false)
+ })
+
+ it('certifies a scoped delta again once a later safety pass completes', async () => {
+ stickSafetyInventory()
+ await expect(
+ reconciler.fullReconcile([], [], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete: vi.fn(),
+ })
+ ).rejects.toThrow(/Ambiguous NetworkPolicy ownership/)
+
+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({ items: [] })
+ const onAuthoritativeRevocationComplete = vi.fn()
+ await reconciler.fullReconcile([], [], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+
+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
+ expect(await reconciler.reconcileContext(deltaContext)).toBe(true)
+ })
+
+ it('certifies a scoped delta when no safety pass has failed', async () => {
+ expect(await reconciler.reconcileContext(deltaContext)).toBe(true)
+ })
+ })
+
+ describe('lost delete fence during stale-allow revocation', () => {
+ const staleContext: ContextCRD = {
+ name: 'default',
+ namespace: 'mcp-server',
+ spec: { contextId: 'default', mcpServers: [] },
+ }
+ const stalePolicy: k8s.V1NetworkPolicy = {
+ metadata: {
+ name: 'ctx-default-alpha',
+ namespace: 'mcp-server',
+ labels: {
+ 'clerum.io/managed-by': 'host-context-controller',
+ 'clerum.io/policy-type': 'context-allow',
+ 'clerum.io/context': 'default',
+ 'clerum.io/mcpserver': 'alpha',
+ },
+ },
+ spec: { podSelector: {}, policyTypes: ['Ingress'] },
+ }
+ const lostFence = Object.assign(new Error('the UID in the precondition does not match'), {
+ code: 409,
+ })
+
+ function listOnlyTheStalePolicy(): void {
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(
+ async ({ namespace }: { namespace?: string }) => ({
+ items: namespace === 'mcp-server' ? [stalePolicy] : [],
+ })
+ )
+ }
+
+ it('refuses to certify a scoped delta instead of throwing the lost fence', async () => {
+ listOnlyTheStalePolicy()
+ mockApi.deleteNamespacedNetworkPolicy.mockRejectedValueOnce(lostFence)
+
+ // 409 is what Kubernetes returns when the uid/resourceVersion
+ // preconditions no longer match: the object live under that name is not
+ // the one this pass classified. Nothing was revoked, so the delta must
+ // decline to certify — and it must not blow up the caller, which would
+ // only force a spurious full re-convergence.
+ expect(await reconciler.reconcileContext(staleContext)).toBe(false)
+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'ctx-default-alpha', namespace: 'mcp-server' })
+ )
+ })
+
+ it('refuses to certify the safety pass instead of throwing the lost fence', async () => {
+ listOnlyTheStalePolicy()
+ mockApi.deleteNamespacedNetworkPolicy.mockRejectedValueOnce(lostFence)
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ await expect(
+ reconciler.fullReconcile([staleContext], [], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+ ).rejects.toThrow(/Desired NetworkPolicy inventory changed/)
+
+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()
+ })
+
+ it('still fails loud when the delete fails for any other reason', async () => {
+ listOnlyTheStalePolicy()
+ const forbidden = Object.assign(new Error('forbidden'), { code: 403 })
+ mockApi.deleteNamespacedNetworkPolicy.mockRejectedValueOnce(forbidden)
+
+ await expect(reconciler.reconcileContext(staleContext)).rejects.toBe(forbidden)
+ })
+
+ it('still certifies when the stale policy was already gone', async () => {
+ listOnlyTheStalePolicy()
+ mockApi.deleteNamespacedNetworkPolicy.mockRejectedValueOnce(
+ Object.assign(new Error('not found'), { code: 404 })
+ )
+
+ expect(await reconciler.reconcileContext(staleContext)).toBe(true)
+ })
+ })
+
+ describe('same-name conflict creating a safety external-egress policy', () => {
+ const server: McpServerCRD = {
+ name: 'renamed-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'renamed:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ egressBindings: [{ cidr: '104.18.0.0/16', port: 443 }],
+ },
+ }
+ const desiredName = 'ext-egress-renamed-server-104-18-0-0-16-443'
+ const stalePredecessor: k8s.V1NetworkPolicy = {
+ metadata: {
+ name: 'ext-egress-renamed-server-stale',
+ namespace: 'mcp-server',
+ uid: 'stale-uid',
+ resourceVersion: '3',
+ },
+ }
+
+ function reconcileExternalEgressSafety(): Promise<boolean> {
+ return (
+ reconciler as unknown as {
+ reconcileExternalEgressSafety: (
+ server: McpServerCRD,
+ existingPolicies: k8s.V1NetworkPolicy[],
+ isCurrent: () => boolean
+ ) => Promise<boolean>
+ }
+ ).reconcileExternalEgressSafety(server, [stalePredecessor], () => true)
+ }
+
+ it('converges an HCC-owned same-name policy instead of aborting the pass', async () => {
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(
+ Object.assign(new Error('already exists'), { code: 409 })
+ )
+ mockApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: desiredName,
+ namespace: server.namespace,
+ uid: 'own-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'host-context-controller',
+ 'clerum.io/policy-type': 'external-egress',
+ 'clerum.io/mcpserver': server.name,
+ },
+ },
+ })
+
+ // This is the only creation route that bypasses applyNetworkPolicy. A
+ // same-name object HCC already owns is an idempotent re-run, not a
+ // reason to fail the pass and hold readiness down.
+ expect(await reconcileExternalEgressSafety()).toBe(true)
+ expect(mockApi.replaceNamespacedNetworkPolicy).toHaveBeenCalledWith(
+ expect.objectContaining({ name: desiredName, namespace: server.namespace })
+ )
+ })
+
+ it('still fails closed when the same-name policy is foreign', async () => {
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(
+ Object.assign(new Error('already exists'), { code: 409 })
+ )
+ mockApi.readNamespacedNetworkPolicy.mockResolvedValueOnce({
+ metadata: {
+ name: desiredName,
+ namespace: server.namespace,
+ uid: 'foreign-uid',
+ resourceVersion: '7',
+ labels: {
+ 'clerum.io/managed-by': 'foreign-controller',
+ 'clerum.io/policy-type': 'external-egress',
+ 'clerum.io/mcpserver': server.name,
+ },
+ },
+ })
+
+ await expect(reconcileExternalEgressSafety()).rejects.toThrow(/ownership/i)
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('still fails loud when the create fails for any other reason', async () => {
+ const forbidden = Object.assign(new Error('forbidden'), { code: 403 })
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValueOnce(forbidden)
+
+ await expect(reconcileExternalEgressSafety()).rejects.toBe(forbidden)
+ })
+ })
+
+ describe('safety-pass duration on the uncertified return path', () => {
+ it('samples a failed outcome when the pass returns without certifying', async () => {
+ const onAuthoritativeRevocationComplete = vi.fn()
+
+ // Losing inventory authority ends the pass without an exception and
+ // without certifying. Operators alert on "the pass never completed", so
+ // this path has to produce a `failed` sample — absence is not a signal.
+ await expect(
+ reconciler.fullReconcile([], [], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => false,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+ ).resolves.toBeUndefined()
+
+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()
+ expect(networkPolicySafetyPassDurationSeconds.observe).toHaveBeenCalledWith(
+ { outcome: 'failed' },
+ expect.any(Number)
+ )
+ expect(networkPolicySafetyPassDurationSeconds.observe).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps the completed sample when a certified pass fails an additive effect afterwards', async () => {
+ const context: ContextCRD = {
+ name: 'default',
+ namespace: 'mcp-server',
+ spec: { contextId: 'default', mcpServers: [] },
+ }
+ const additiveFailure = new Error('additive list unavailable')
+ let certified = false
+ const onAuthoritativeRevocationComplete = vi.fn(() => {
+ certified = true
+ })
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(async () => {
+ if (certified) throw additiveFailure
+ return { items: [] }
+ })
+
+ await expect(
+ reconciler.fullReconcile([context], [], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ onAuthoritativeRevocationComplete,
+ })
+ ).rejects.toThrow(/additive Context NetworkPolicy reconciliations failed/)
+
+ expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()
+ expect(networkPolicySafetyPassDurationSeconds.observe).toHaveBeenCalledWith(
+ { outcome: 'completed' },
+ expect.any(Number)
+ )
+ expect(networkPolicySafetyPassDurationSeconds.observe).toHaveBeenCalledTimes(1)
+ })
+ })
})
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index d2d02006d..788183942 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -41,7 +41,7 @@ import {
McpServerCrdStatus,
McpServerResolvedEgressIP,
} from './types'
-import { applyNetworkPolicy, getErrorCode } from './utils'
+import { applyNetworkPolicy, getErrorCode, replaceWithConflictRetry } from './utils'
type JsonPatchOperation = {
op: 'add' | 'replace' | 'remove' | 'test'
@@ -350,6 +350,16 @@ export class NetworkPolicyReconciler {
/** Reference to the MCP server cache so we can look up ports. */
private serverCache: Map<string, McpServerCRD>
+ /**
+ * Set whenever an authoritative safety pass ends without certifying, cleared
+ * as soon as one certifies again. Only that pass enumerates the bounded
+ * namespaces and classifies every object it finds; the scoped delta lane sees
+ * nothing but its own label selectors. A delta therefore cannot vouch for a
+ * namespace whose classified inventory is still stuck on an unresolved
+ * policy, and must not certify readiness on its behalf.
+ */
+ private safetyPassLeftUncertified = false
+
constructor(kc: k8s.KubeConfig, serverCache: Map<string, McpServerCRD>) {
this.networkingApi = kc.makeApiClient(k8s.NetworkingV1Api)
this.customApi = kc.makeApiClient(k8s.CustomObjectsApi)
@@ -814,7 +824,14 @@ 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.
- return await this.revokeStaleContextAllows(context, isCurrent)
+ 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
}
private async revokeStaleContextAllows(
@@ -829,6 +846,10 @@ export class NetworkPolicyReconciler {
): Promise<boolean> {
if (!isCurrent()) return false
const safetySnapshotProvided = listedPolicies !== undefined
+ // A delete whose uid/resourceVersion preconditions were rejected revoked
+ // nothing. The scoped lane has no second source of truth to reclassify
+ // from, so it finishes its remaining work and then declines to certify.
+ let lostDeleteFence = false
const contextId = context.spec.contextId
const allowedServers = context.spec.mcpServers || []
const desiredIngress = new Map<string, k8s.V1NetworkPolicy>()
@@ -853,11 +874,27 @@ export class NetworkPolicyReconciler {
if (!desired) {
console.log(`[NetPol] Deleting orphaned policy "${existingName}"`)
if (safetySnapshotProvided) {
- if (!(await this.deleteSafetyPolicySnapshot(config.namespace, existing, isCurrent))) {
+ if (
+ !(await this.deleteSafetyPolicySnapshot(
+ config.namespace,
+ existing,
+ isCurrent,
+ undefined,
+ 'report'
+ ))
+ ) {
return false
}
- } else {
- await this.deleteSafetyPolicySnapshot(config.namespace, existing, isCurrent)
+ } else if (
+ !(await this.deleteSafetyPolicySnapshot(
+ config.namespace,
+ existing,
+ isCurrent,
+ undefined,
+ 'report'
+ ))
+ ) {
+ lostDeleteFence = true
}
onRevoked?.()
} else if (
@@ -900,11 +937,27 @@ export class NetworkPolicyReconciler {
if (!desired) {
console.log(`[NetPol] Deleting orphaned L2 egress policy "${existingName}"`)
if (safetySnapshotProvided) {
- if (!(await this.deleteSafetyPolicySnapshot(config.hostNamespace, existing, isCurrent))) {
+ if (
+ !(await this.deleteSafetyPolicySnapshot(
+ config.hostNamespace,
+ existing,
+ isCurrent,
+ undefined,
+ 'report'
+ ))
+ ) {
return false
}
- } else {
- await this.deleteSafetyPolicySnapshot(config.hostNamespace, existing, isCurrent)
+ } else if (
+ !(await this.deleteSafetyPolicySnapshot(
+ config.hostNamespace,
+ existing,
+ isCurrent,
+ undefined,
+ 'report'
+ ))
+ ) {
+ lostDeleteFence = true
}
onRevoked?.()
} else if (
@@ -948,12 +1001,26 @@ export class NetworkPolicyReconciler {
console.log(`[NetPol] Deleting orphaned rpc-proxy egress policy "${existingName}"`)
if (safetySnapshotProvided) {
if (
- !(await this.deleteSafetyPolicySnapshot(config.rpcProxyNamespace, existing, isCurrent))
+ !(await this.deleteSafetyPolicySnapshot(
+ config.rpcProxyNamespace,
+ existing,
+ isCurrent,
+ undefined,
+ 'report'
+ ))
) {
return false
}
- } else {
- await this.deleteSafetyPolicySnapshot(config.rpcProxyNamespace, existing, isCurrent)
+ } else if (
+ !(await this.deleteSafetyPolicySnapshot(
+ config.rpcProxyNamespace,
+ existing,
+ isCurrent,
+ undefined,
+ 'report'
+ ))
+ ) {
+ lostDeleteFence = true
}
onRevoked?.()
} else if (
@@ -986,7 +1053,7 @@ export class NetworkPolicyReconciler {
}
}
- return isCurrent()
+ return isCurrent() && !lostDeleteFence
}
/**
@@ -1034,6 +1101,10 @@ export class NetworkPolicyReconciler {
const recordSafetyPassDuration = (outcome: 'completed' | 'failed'): void => {
if (safetyPassDurationRecorded) return
safetyPassDurationRecorded = true
+ // First outcome wins for both the sample and the delta fence: a pass that
+ // certified and only then failed an additive effect still revoked every
+ // stale allow its inventory implied.
+ this.safetyPassLeftUncertified = outcome === 'failed'
networkPolicySafetyPassDurationSeconds.observe(
{ outcome },
(performance.now() - safetyPassStartedAt) / 1_000
@@ -1048,6 +1119,9 @@ export class NetworkPolicyReconciler {
recordSafetyPassDuration('completed')
},
})
+ // The pass returned without certifying: no exception, no certificate.
+ // Operators alert on this exact condition, so it must produce a sample
+ // rather than the absence of one.
recordSafetyPassDuration('failed')
} catch (error) {
recordSafetyPassDuration('failed')
@@ -1643,11 +1717,19 @@ export class NetworkPolicyReconciler {
// Preserve traffic only with deterministic CIDR/public-web policies. A
// renamed deterministic binding is created before its stale predecessor is
- // removed; a conflict aborts safety rather than adopting the live object.
+ // removed; a same-name conflict is converged only under the ownership
+ // guard, which still refuses to adopt a foreign live object.
if (stale.length > 0) {
for (const selected of desired.values()) {
if (!selected.policy) continue
- if (!(await this.createSafetyPolicy(server.namespace, selected.policy, isCurrent))) {
+ if (
+ !(await this.createSafetyPolicy(
+ server.namespace,
+ selected.policy,
+ 'external-egress',
+ isCurrent
+ ))
+ ) {
return false
}
}
@@ -2377,7 +2459,8 @@ export class NetworkPolicyReconciler {
namespace: string,
policy: k8s.V1NetworkPolicy,
isCurrent?: () => boolean,
- onDeleted?: () => void
+ onDeleted?: () => void,
+ lostFenceOutcome: 'throw' | 'report' = 'throw'
): Promise<boolean> {
if (isCurrent && !isCurrent()) return false
const { name, uid, resourceVersion } = this.safetyPolicyIdentity(policy)
@@ -2395,6 +2478,18 @@ export class NetworkPolicyReconciler {
console.log(`[NetPol] Safety-inventory policy "${name}" already gone`)
return true
}
+ if (getErrorCode(error) === 409 && lostFenceOutcome === 'report') {
+ // Kubernetes rejected the uid/resourceVersion preconditions, so the
+ // object live under this name is not the one the authoritative
+ // inventory classified. Nothing was revoked, and nothing may be
+ // adopted. Callers that opt in act on this outcome by declining to
+ // certify, which is the expected racy result rather than a failure.
+ // Callers that cannot act on it keep the loud default.
+ console.warn(
+ `[NetPol] Lost the delete fence on safety-inventory policy "${name}" in ${namespace}; it changed identity after the authoritative inventory and was not revoked`
+ )
+ return false
+ }
console.error(
`[NetPol] Failed identity-bound delete of safety-inventory policy "${name}" in ${namespace}:`,
error
@@ -2448,13 +2543,42 @@ export class NetworkPolicyReconciler {
private async createSafetyPolicy(
namespace: string,
desired: k8s.V1NetworkPolicy,
+ lane: SafetyInventoryLane,
isCurrent: () => boolean
): Promise<boolean> {
if (!isCurrent()) return false
- const created = await this.networkingApi.createNamespacedNetworkPolicy({
- namespace,
- body: desired,
- })
+ let created: k8s.V1NetworkPolicy
+ try {
+ created = await this.networkingApi.createNamespacedNetworkPolicy({
+ namespace,
+ body: desired,
+ })
+ } catch (error: unknown) {
+ if (getErrorCode(error) !== 409) throw error
+ // This is the only creation route that does not go through
+ // applyNetworkPolicy, so a same-name object used to abort the whole
+ // safety pass and hold readiness down. Converge it exactly like every
+ // other lane does: adopt it only under the ownership guard, which still
+ // refuses a foreign or ambiguous object.
+ const name = desired.metadata?.name
+ if (!name) {
+ throw new Error(`Cannot converge a conflicting ${lane} policy without a desired name`)
+ }
+ console.log(
+ `[NetPol] Safety policy "${name}" in ${namespace} already exists — converging it to the desired spec`
+ )
+ await replaceWithConflictRetry<k8s.V1NetworkPolicy>({
+ description: `policy "${name}" in ${namespace}`,
+ logPrefix: '[NetPol]',
+ body: desired,
+ read: () => this.networkingApi.readNamespacedNetworkPolicy({ name, namespace }),
+ replace: body =>
+ this.networkingApi.replaceNamespacedNetworkPolicy({ name, namespace, body }),
+ mutationAllowed: isCurrent,
+ validateExisting: existing => this.assertPolicyOwnership(name, existing, desired, lane),
+ })
+ return isCurrent()
+ }
if (isCurrent()) return true
// The mutation crossed its desired-state fence. Remove exactly the object