Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): certify runtime convergence against policy safety
Alfredo Lopez1abcfb1b2b0a
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 1bc92d7a2..dc160d1d5 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.174",+ "version": "0.1.175","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.174",+ "version": "0.1.175","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.jsonindex 3a77c0db1..e3c5e1512 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.174",+ "version": "0.1.175","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.tsindex a7b92327c..39309f519 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -102,6 +102,10 @@ function markNetworkPolicyRevocationAuthoritative(watcher: McpServerWatcher): vowatcher as any).contextWatchGeneration;(watcher as any).networkPolicyRevocationServerGeneration = (watcher as any).mcpWatchGeneration+ ;(watcher as any).networkPolicyRevocationContextRevision = (watcher as any).contextDesiredRevision+ ;(watcher as any).networkPolicyRevocationServerRevision = (+ watcher as any+ ).mcpServerDesiredRevision}function newContextAuthoritativeWatcher(): McpServerWatcher {@@ -1030,12 +1034,12 @@ describe('McpServerWatcher startup', () => {try {await vi.waitFor(() => {- expect(mocks.serverFullReconcile).toHaveBeenCalledOnce()expect(mocks.netPolFullReconcile).toHaveBeenCalledOnce()expect(mocks.hostFullReconcile).toHaveBeenCalledOnce()expect(mocks.sfsFullReconcile).toHaveBeenCalledOnce()expect(gfsFullReconcile).toHaveBeenCalledOnce()})+ expect(mocks.serverFullReconcile).not.toHaveBeenCalled()await expect(bootstrap).resolves.toBeUndefined()server.setReady(true)@@ -1044,6 +1048,7 @@ describe('McpServerWatcher startup', () => {expect(completeAuthoritativeRevocation).toBeTypeOf('function')completeAuthoritativeRevocation?.()+ await vi.waitFor(() => expect(mocks.serverFullReconcile).toHaveBeenCalledOnce())const ready = await requestReadyOverHttp(server)expect(ready.statusCode).toBe(200)expect(JSON.parse(ready.body)).toEqual({ status: 'ready', ready: true })@@ -1053,9 +1058,10 @@ describe('McpServerWatcher startup', () => {expect(startGlobalFileSystemWatch).toHaveBeenCalledOnce()expect(watcher.isCommunicationChannelCacheSynced()).toBe(true)- // McpServer and NetworkPolicy convergence are independent background- // lanes: neither a slow runtime fleet nor policy fleet may delay safe- // bootstrap or prevent the other lane from starting.+ // Runtime convergence starts at the safety-certification boundary, not+ // after the NetworkPolicy additive fleet completes. This prevents the+ // startup egress lane from racing the policy safety pass while retaining+ // readiness decoupling from both additive fleets.expect(mocks.serverFullReconcile).toHaveBeenCalledOnce()expect(mocks.netPolFullReconcile).toHaveBeenCalledOnce()} finally {@@ -1391,6 +1397,8 @@ describe('McpServerWatcher startup', () => {const reconciliationOrder: string[] = []const watcher = new McpServerWatcher();(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextCacheSynced = true+ markNetworkPolicyRevocationAuthoritative(watcher);(watcher as any).servers.set(staleServer.name, staleServer)const netPol = (watcher as any).netPolReconcilernetPol.reconcileExternalEgress.mockImplementationOnce(async () => {@@ -1424,7 +1432,7 @@ describe('McpServerWatcher startup', () => {releaseEgress.resolve(undefined)await Promise.all([convergence, watchConvergence])- expect(reconciliationOrder).toEqual(['watch', 'initial'])+ expect(reconciliationOrder).toEqual(['watch'])expect(reconciler.reconcile).toHaveBeenLastCalledWith(expect.objectContaining({ name: 'current-server' }),{ isCurrent: expect.any(Function) }@@ -1678,6 +1686,8 @@ describe('McpServerWatcher startup', () => {const releaseEgress = deferred()const watcher = new McpServerWatcher();(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextCacheSynced = true+ markNetworkPolicyRevocationAuthoritative(watcher);(watcher as any).servers.set(dnsBlockedServer.name, dnsBlockedServer);(watcher as any).servers.set(independentServer.name, independentServer)const netPol = (watcher as any).netPolReconciler@@ -2413,6 +2423,8 @@ describe('McpServerWatcher startup', () => {const releaseEgress = deferred()const watcher = new McpServerWatcher();(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextCacheSynced = true+ markNetworkPolicyRevocationAuthoritative(watcher);(watcher as any).servers.set(initialServer.name, initialServer)const netPol = (watcher as any).netPolReconcilernetPol.reconcileExternalEgress.mockImplementationOnce(async () => {@@ -2446,6 +2458,8 @@ describe('McpServerWatcher startup', () => {const snapshots: string[][] = []const watcher = new McpServerWatcher();(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextCacheSynced = true+ markNetworkPolicyRevocationAuthoritative(watcher);(watcher as any).servers.set('first-server', {name: 'first-server',namespace: 'mcp-server',@@ -2622,7 +2636,9 @@ describe('McpServerWatcher startup', () => {const releaseEgress = deferred()const watcher = new McpServerWatcher();(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextCacheSynced = true;(watcher as any).mcpWatchGeneration = 7+ markNetworkPolicyRevocationAuthoritative(watcher);(watcher as any).initialConvergenceRetryAttempts.set('McpServer', 3);(watcher as any).servers.set('stale-server', {name: 'stale-server',@@ -2671,6 +2687,7 @@ describe('McpServerWatcher startup', () => {},});(watcher as any).mcpServerCacheSynced = true+ markNetworkPolicyRevocationAuthoritative(watcher)await (watcher as any).runInitialMcpServerConvergence()expect(reconciler.reconcile).toHaveBeenCalledOnce()@@ -2789,6 +2806,136 @@ describe('McpServerWatcher startup', () => {await watcher.stop()})+ it('does not start runtime fleet convergence without a current NetworkPolicy safety certificate', async () => {+ const watcher = new McpServerWatcher()+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextWatchGeneration = 4+ ;(watcher as any).mcpWatchGeneration = 7++ await (watcher as any).runInitialMcpServerConvergence()+ expect(mocks.serverFullReconcile).not.toHaveBeenCalled()++ await (watcher as any).runInitialNetworkPolicyConvergence()+ await vi.waitFor(() => expect(mocks.serverFullReconcile).toHaveBeenCalledOnce())++ await watcher.stop()+ })++ it('invalidates readiness when either desired policy revision advances', async () => {+ const watcher = new McpServerWatcher()+ ;(watcher as any).hostCacheSynced = true+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextWatchGeneration = 4+ ;(watcher as any).mcpWatchGeneration = 7+ markNetworkPolicyRevocationAuthoritative(watcher)+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(true)+ ;(watcher as any).mcpServerDesiredRevision += 1+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(false)++ markNetworkPolicyRevocationAuthoritative(watcher)+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(true)+ ;(watcher as any).contextDesiredRevision += 1+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(false)++ await watcher.stop()+ })++ it('retires readiness and requests a safety pass before a changed McpServer effect settles', async () => {+ const previous = {+ metadata: {+ name: 'restrictive-change',+ namespace: 'mcp-server',+ uid: 'restrictive-change-uid',+ generation: 1,+ },+ spec: {+ contextRef: 'default',+ image: 'clerum/restrictive-change:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'TCP' as const }],+ },+ }+ const current = {+ ...previous,+ metadata: { ...previous.metadata, generation: 2 },+ spec: {+ ...previous.spec,+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'UDP' as const }],+ },+ }+ const watcher = new McpServerWatcher()+ ;(watcher as any).hostCacheSynced = true+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextWatchGeneration = 4+ ;(watcher as any).mcpWatchGeneration = 7+ ;(watcher as any).servers.set(previous.metadata.name, {+ name: previous.metadata.name,+ namespace: previous.metadata.namespace,+ uid: previous.metadata.uid,+ generation: previous.metadata.generation,+ spec: previous.spec,+ })+ markNetworkPolicyRevocationAuthoritative(watcher)+ const safetyPass = vi+ .spyOn(watcher as any, 'runInitialNetworkPolicyConvergence')+ .mockResolvedValue(undefined)+ ;(watcher as any).netPolReconciler.reconcileExternalEgress.mockRejectedValueOnce(+ new Error('replacement policy unavailable')+ )+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})++ await (watcher as any).getMcpServerWatchCallback(7)('MODIFIED', current)++ expect(watcher.isReadinessInventoryAuthoritative()).toBe(false)+ expect(safetyPass).toHaveBeenCalled()+ await watcher.stop()+ errorSpy.mockRestore()+ })++ it('fences runtime effects when either generation retires the safety certificate', async () => {+ const selected = {+ name: 'certificate-fenced-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'clerum/certificate-fenced:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ egressBindings: [{ dns: 'certificate-fenced.example', port: 443 }],+ },+ }+ const egressStarted = deferred()+ const releaseEgress = deferred()+ const runtimeEffect = vi.fn()+ const watcher = new McpServerWatcher()+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextWatchGeneration = 11+ ;(watcher as any).mcpWatchGeneration = 13+ markNetworkPolicyRevocationAuthoritative(watcher)+ ;(watcher as any).servers.set(selected.name, selected)+ ;(watcher as any).netPolReconciler.reconcileExternalEgress.mockImplementationOnce(async () => {+ egressStarted.resolve(undefined)+ await releaseEgress.promise+ })+ mocks.serverFullReconcile.mockImplementationOnce(async (servers, options) => {+ await Promise.all(+ servers.map((server: { name: string }) => options.runEffect(server.name, runtimeEffect))+ )+ })++ const convergence = (watcher as any).runInitialMcpServerConvergence()+ await egressStarted.promise+ ;(watcher as any).contextWatchGeneration = 12+ releaseEgress.resolve(undefined)+ await convergence++ expect(runtimeEffect).not.toHaveBeenCalled()+ await watcher.stop()+ })+it.each([['SharedFileSystem', 'enqueueSharedFileSystemReconciliation'],['GlobalFileSystem', 'enqueueGlobalFileSystemReconciliation'],@@ -2953,6 +3100,8 @@ describe('McpServerWatcher startup', () => {vi.useFakeTimers()const watcher = new McpServerWatcher();(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).contextCacheSynced = true+ markNetworkPolicyRevocationAuthoritative(watcher)mocks.serverFullReconcile.mockRejectedValueOnce(new Error('initial runtime reconciliation unavailable'))diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex 29838c759..f08a26503 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -141,6 +141,13 @@ type HostInventoryRecoveryCause = 'cold-start' | 'watch-recovery'type HostWatchEventType = 'ADDED' | 'MODIFIED' | 'DELETED'type InitialConvergenceLane = 'McpServer' | 'NetworkPolicy'+type NetworkPolicySafetyCertificate = {+ contextGeneration: number+ serverGeneration: number+ contextRevision: number+ serverRevision: number+}+type ActiveInitialConvergenceRun = {trailingRequested: booleanpromise: Promise<void>@@ -631,6 +638,8 @@ export class McpServerWatcher implements McpServerProvider {// this marker until the new inventory's orphan-allow sweep completes.private networkPolicyRevocationContextGeneration = 0private networkPolicyRevocationServerGeneration = 0+ private networkPolicyRevocationContextRevision = 0+ private networkPolicyRevocationServerRevision = 0private mcpServerCacheSynced = falseprivate contextCacheSynced = falseprivate mcpServerCacheRecoveryTimer: ReturnType<typeof setTimeout> | null = null@@ -855,7 +864,9 @@ export class McpServerWatcher implements McpServerProvider {this.contextCacheSynced &&this.hostCacheSynced &&this.networkPolicyRevocationContextGeneration === this.contextWatchGeneration &&- this.networkPolicyRevocationServerGeneration === this.mcpWatchGeneration+ this.networkPolicyRevocationServerGeneration === this.mcpWatchGeneration &&+ this.networkPolicyRevocationContextRevision === this.contextDesiredRevision &&+ this.networkPolicyRevocationServerRevision === this.mcpServerDesiredRevision)}@@ -1173,7 +1184,6 @@ export class McpServerWatcher implements McpServerProvider {await this.restartMcpServerWatch(snapshot)if (this.stopped) return falsethis.changeCallback?.()- void this.runInitialMcpServerConvergence()if (this.contextCacheSynced) {void this.runInitialNetworkPolicyConvergence()}@@ -2385,11 +2395,11 @@ export class McpServerWatcher implements McpServerProvider {this.externalEgressCoordinator.startPeriodicResync(externalEgressResyncSec)// Full convergence is observable and retains each lane's existing retry or- // periodic-resync contract, but it no longer extends provider.start() or- // the readiness probe. Each lane snapshots its cache only after cache/watch- // bootstrap above, so a watch event accepted during startup is not undone by- // a pre-watch inventory snapshot.- void this.runInitialMcpServerConvergence()+ // periodic-resync contract, but it no longer extends provider.start().+ // NetworkPolicy safety starts first and launches McpServer convergence from+ // its certification callback, before additive policy convergence completes.+ // This prevents the startup egress refresh from racing or undoing the safety+ // pass while keeping readiness independent from both additive fleets.void this.runInitialNetworkPolicyConvergence()if (sfsInventoryComplete) {void this.runInitialSharedFileSystemConvergence()@@ -2403,10 +2413,46 @@ export class McpServerWatcher implements McpServerProvider {return this.runInitialConvergence('McpServer')}+ private currentNetworkPolicySafetyCertificate(): NetworkPolicySafetyCertificate | null {+ if (+ this.stopped ||+ !this.contextCacheSynced ||+ !this.mcpServerCacheSynced ||+ this.networkPolicyRevocationContextGeneration !== this.contextWatchGeneration ||+ this.networkPolicyRevocationServerGeneration !== this.mcpWatchGeneration ||+ this.networkPolicyRevocationContextRevision !== this.contextDesiredRevision ||+ this.networkPolicyRevocationServerRevision !== this.mcpServerDesiredRevision+ ) {+ return null+ }+ return {+ contextGeneration: this.contextWatchGeneration,+ serverGeneration: this.mcpWatchGeneration,+ contextRevision: this.contextDesiredRevision,+ serverRevision: this.mcpServerDesiredRevision,+ }+ }++ private isNetworkPolicySafetyCertificateCurrent(+ certificate: NetworkPolicySafetyCertificate+ ): boolean {+ const current = this.currentNetworkPolicySafetyCertificate()+ return (+ current !== null &&+ current.contextGeneration === certificate.contextGeneration &&+ current.serverGeneration === certificate.serverGeneration &&+ current.contextRevision === certificate.contextRevision &&+ current.serverRevision === certificate.serverRevision+ )+ }+private async runInitialMcpServerConvergenceCore(): Promise<void> {- if (!this.mcpServerCacheSynced) return+ const safetyCertificate = this.currentNetworkPolicySafetyCertificate()+ if (safetyCertificate === null) returnconst inventoryGeneration = this.mcpWatchGeneration- const inventoryAuthoritative = () => this.hasMcpServerInventoryAuthority(inventoryGeneration)+ const inventoryAuthoritative = () =>+ this.hasMcpServerInventoryAuthority(inventoryGeneration) &&+ this.isNetworkPolicySafetyCertificateCurrent(safetyCertificate)try {const initialServers = [...this.servers.values()]const initialExternalEgressGates = this.externalEgressCoordinator.prepareStartupGates(@@ -2528,6 +2574,13 @@ export class McpServerWatcher implements McpServerProvider {if (!contextInventoryAuthoritative() || !serverInventoryAuthoritative()) returnthis.networkPolicyRevocationContextGeneration = contextInventoryGenerationthis.networkPolicyRevocationServerGeneration = serverInventoryGeneration+ this.networkPolicyRevocationContextRevision = this.contextDesiredRevision+ this.networkPolicyRevocationServerRevision = this.mcpServerDesiredRevision+ // Start runtime convergence at the safety boundary, before this full+ // pass enters additive Context and DNS refresh work. Startup egress+ // gates may now preserve only policies certified by this exact+ // authoritative inventory generation.+ void this.runInitialMcpServerConvergence()},})if (!contextInventoryAuthoritative() || !serverInventoryAuthoritative()) return@@ -3064,7 +3117,10 @@ export class McpServerWatcher implements McpServerProvider {desiredStateChanged = this.servers.delete(server.name)}}- if (desiredStateChanged) this.mcpServerDesiredRevision += 1+ if (desiredStateChanged) {+ this.mcpServerDesiredRevision += 1+ void this.runInitialNetworkPolicyConvergence()+ }// HCC writes McpServer status during reconciliation. Those writes emit// MODIFIED events but do not change the desired runtime or policy state.@@ -3374,7 +3430,10 @@ export class McpServerWatcher implements McpServerProvider {} else if (type === 'DELETED') {desiredStateChanged = this.contexts.delete(context.name)}- if (desiredStateChanged) this.contextDesiredRevision += 1+ if (desiredStateChanged) {+ this.contextDesiredRevision += 1+ void this.runInitialNetworkPolicyConvergence()+ }// Re-reconcile every SFS this Context referenced before or after the// change so SharedFileSystem.status.mountedByContexts stays in syncdiff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.tsindex 1650cd3ef..f517a5dc6 100644--- a/host-context-controller/src/networkPolicyReconciler.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.test.ts@@ -2322,6 +2322,56 @@ describe('NetworkPolicyReconciler', () => {expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()})+ it('revokes a divergent same-name DNS policy when its safe replacement cannot resolve', async () => {+ const oldServer: McpServerCRD = {+ name: 'live-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'live:latest',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'TCP' }],+ },+ }+ const currentServer: McpServerCRD = {+ ...oldServer,+ spec: {+ ...oldServer.spec,+ egressBindings: [{ dns: 'api.example.com', port: 443, protocol: 'UDP' }],+ },+ }+ const rec = makeReconciler(mockApi, new Map([[oldServer.name, oldServer]]), mockCustomApi)++ await rec.reconcileExternalEgress(oldServer)+ const oldPolicy = 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(oldPolicy).toBeDefined()++ vi.clearAllMocks()+ vi.mocked(dns.resolve4).mockRejectedValue(new Error('dns unavailable'))+ mockApi.listNamespacedNetworkPolicy.mockImplementation(+ async ({ labelSelector }: { labelSelector?: string }) =>+ labelSelector?.includes('external-egress') ? { items: [oldPolicy!] } : { items: [] }+ )+ const onAuthoritativeRevocationComplete = vi.fn()++ await expect(+ rec.fullReconcile([], [currentServer], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete,+ })+ ).rejects.toThrow('dns unavailable')++ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({+ name: oldPolicy!.metadata!.name!,+ namespace: oldServer.namespace,+ })+ expect(onAuthoritativeRevocationComplete).not.toHaveBeenCalled()+ })+it('retains a valid same-intent DNS policy so readiness does not await fleet DNS refresh', async () => {const server: McpServerCRD = {name: 'stable-dns-server',@@ -2370,7 +2420,7 @@ describe('NetworkPolicyReconciler', () => {}})- it('preserves a safety-certified DNS policy when the post-ready refresh fails', async () => {+ it('preserves a safety-certified DNS policy on every default refresh failure', async () => {const server: McpServerCRD = {name: 'stable-dns-server',namespace: 'mcp-server',@@ -2394,19 +2444,10 @@ describe('NetworkPolicyReconciler', () => {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')+ await expect(rec.reconcileExternalEgress(server)).rejects.toThrow('dns unavailable')- expect(onAuthoritativeRevocationComplete).toHaveBeenCalledOnce()expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()})it('does not certify revocation when an earlier Context changes while a later owner is paused', async () => {diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.tsindex 2ec29b061..accc491ee 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -52,7 +52,6 @@ type JsonPatchOperation = {type NetworkPolicyMutationOptions = {isCurrent?: () => booleanexistingPolicies?: k8s.V1NetworkPolicy[]- preserveCertifiedDnsPolicyOnRefreshFailure?: boolean}export function sameContextDesiredRevision(expected: ContextCRD, current: ContextCRD): boolean {@@ -1147,7 +1146,6 @@ export class NetworkPolicyReconciler {}await this.reconcileExternalEgress(current, {isCurrent: serverEffectIsCurrent,- preserveCertifiedDnsPolicyOnRefreshFailure: true,})})}@@ -1536,10 +1534,7 @@ export class NetworkPolicyReconciler {policy.metadata?.name === name &&this.canRetainDnsEgressPolicy(policy, server, binding))- if (- options.preserveCertifiedDnsPolicyOnRefreshFailure &&- certifiedExisting !== undefined- ) {+ if (certifiedExisting !== undefined) {desiredPolicyNames.add(name)}failures.push(`failed to resolve hostname "${binding.dns}": ${this.errorMessage(err)}`)diff --git a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh b/scripts/e2e/e2e-hcc-mcp-context-readiness.shindex fc1dbc6ca..d68ab1719 100755--- a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh+++ b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh@@ -5,14 +5,13 @@# The gate runs only on an exact-HEAD, branch-owned Minikube profile. It routes# HCC DNS through an isolated in-cluster proxy that forwards every query except# one fixture hostname. The gate first lets HCC create a real external-egress-# policy, then changes that same DNS binding's protocol while HCC is stopped.-# Holding the next A query proves HCC removes the now-unprovable old allow-# before it reports Ready. While the query is held, the gate also applies a-# real Context watch update and requires that Context's three NetworkPolicies-# converge independently. It then releases DNS and proves eventual McpServer-# runtime convergence. It also creates a fleet wider than the controller's-# bounded worker width, so the branch-owned runtime proof covers the original-# large-fleet symptom rather than a single delayed object only.+# policy. A same-intent restart then holds DNS through a real retry and proves+# the certified policy keeps the same UID/spec while HCC remains Ready. A+# second phase changes that binding's protocol while HCC is stopped; holding+# DNS now proves the divergent allow is revoked and HCC remains unready until+# the UDP replacement exists. A real Context watch update must still converge+# its three NetworkPolicies during that hold. The fleet is wider than the+# bounded worker width, covering the original large-fleet symptom.set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"@@ -77,11 +76,13 @@ ORIGINAL_DNS_POLICY=""ORIGINAL_DNS_CONFIG=""DNS_BLOCKER_IP=""DNS_RELEASE_COUNT_AT_HOLD=0+DNS_HOLD_COUNT_AT_ARM=0UPSTREAM_DNS_IP=""NEW_HCC_POD=""HCC_UID=""HCC_RESTARTS=""HCC_PORT=""+CERTIFIED_POLICY_IDENTITY=""HCC_MUTATED=0DNS_BLOCKER_CREATED=0MCP_CREATED=0@@ -162,6 +163,11 @@ running_hcc_pod() {awk -F '\t' '$1 != "" && $4 == "" { print $1; exit }' <<<"$rows"}+capture_hcc() {+ NEW_HCC_POD="$(running_hcc_pod)"+ [ -n "$NEW_HCC_POD" ]+}+hcc_pods_absent() {local podspods="$(kctl get pods -n "$HCC_NS" -l "app=${HCC_DEPLOY}" -o name 2>/dev/null)" ||@@ -191,22 +197,32 @@ dns_release_count() {grep -Fc "$marker" <<<"$logs" || true}+dns_hold_count() {+ local marker="holding DNS A ${TARGET_DNS}" logs+ logs="$(kctl logs "deployment/${DNS_BLOCKER_NAME}" -n "$HCC_NS" 2>/dev/null)" ||+ return 1+ grep -Fc "$marker" <<<"$logs" || true+}++dns_hold_observed_since_arm() {+ [ "$(dns_hold_count)" -gt "$DNS_HOLD_COUNT_AT_ARM" ]+}+dns_has_not_released_since_hold() {[ "$(dns_release_count)" = "$DNS_RELEASE_COUNT_AT_HOLD" ]}-startup_convergence_window_is_clean() {+dns_released_since_hold() {+ [ "$(dns_release_count)" -gt "$DNS_RELEASE_COUNT_AT_HOLD" ]+}++initial_network_policy_retry_progress_is_observed() {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. Read one authoritative snapshot first so a kubectl- # logs failure cannot make the negative assertions pass vacuously.[ -n "$NEW_HCC_POD" ] || return 1logs="$(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"+ grep -Fq "Initial NetworkPolicy background reconciliation failed:" <<<"$logs" &&+ grep -Fq "Scheduling initial NetworkPolicy background convergence retry" <<<"$logs"}external_egress_retry_progress_is_observed() {@@ -220,6 +236,14 @@ external_egress_retry_progress_is_observed() {grep -Fq "for McpServer \"${MCP_NAME}\"" <<<"$logs"}+external_egress_retry_rearmed_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 "Scheduling external egress retry 2/3 for McpServer \"${MCP_NAME}\"" <<<"$logs"+}+hcc_identity_is_stable() {local row uid restartsrow="$(kctl get pod "$NEW_HCC_POD" -n "$HCC_NS" \@@ -274,8 +298,8 @@ fixture_runtime_absent() {resource_absent service "$MCP_NAME" "$MCP_NS"}-fixture_mcp_convergence_absent() {- fixture_mcp_runtime_absent &&+fixture_runtime_and_ready_absent() {+ fixture_runtime_absent &&kctl get mcpserver "$MCP_NAME" -n "$MCP_NS" -o json 2>/dev/null |jq -e 'any(@@ -412,6 +436,45 @@ external_egress_policy_converged() {external_egress_policy_converged_with_protocol "$EXTERNAL_EGRESS_PROTOCOL"}+external_egress_policy_absent() {+ local policies+ policies="$(+ kctl get networkpolicy -n "$MCP_NS" \+ -l "${MCP_SERVER_LABEL}=${MCP_NAME},${POLICY_TYPE_LABEL}=external-egress" \+ -o name 2>/dev/null+ )" || return 1+ [ -z "$policies" ]+}++external_egress_policy_identity() {+ kctl get networkpolicy -n "$MCP_NS" \+ -l "${MCP_SERVER_LABEL}=${MCP_NAME},${POLICY_TYPE_LABEL}=external-egress" \+ -o json |+ jq -ceS '+ select((.items | length) == 1) |+ {uid: .items[0].metadata.uid, spec: .items[0].spec}+ '+}++certified_external_egress_policy_is_unchanged() {+ [ -n "$CERTIFIED_POLICY_IDENTITY" ] &&+ [ "$(external_egress_policy_identity)" = "$CERTIFIED_POLICY_IDENTITY" ]+}++fixture_runtime_converged_with_protocol() {+ local protocol=$1 desired available+ desired="$(kctl get deployment "$MCP_NAME" -n "$MCP_NS" \+ -o jsonpath='{.spec.replicas}' 2>/dev/null)" || return 1+ available="$(kctl get deployment "$MCP_NAME" -n "$MCP_NS" \+ -o jsonpath='{.status.availableReplicas}' 2>/dev/null)" || return 1+ [ "${desired:-0}" -ge 1 ] && [ "${available:-0}" -ge 1 ] || return 1+ kctl get service "$MCP_NAME" -n "$MCP_NS" >/dev/null 2>&1 || return 1+ kctl get mcpserver "$MCP_NAME" -n "$MCP_NS" -o json |+ jq -e 'any(.status.conditions[]?; .type == "Ready" and .status == "True")' >/dev/null ||+ return 1+ external_egress_policy_converged_with_protocol "$protocol"+}+fixture_resources_absent() {fixture_mcp_runtime_absent && context_policies_absent && peer_fleet_runtime_absent}@@ -438,38 +501,6 @@ peer_fleet_runtime_absent() {done}-peer_fleet_has_background_progress() {- local index server context namespace policy_type policy_count ready_peers=0- for ((index = 1; index < ${#MCP_FLEET_NAMES[@]}; index++)); do- server="${MCP_FLEET_NAMES[index]}"- context="${CONTEXT_FLEET_NAMES[index]}"- kctl get context "$context" -n "$MCP_NS" -o json | jq -e --arg server "$server" '- .spec.mcpServers == [$server]- ' >/dev/null || return 1- for namespace_policy in \- "${MCP_NS}:context-allow" \- "${HOST_NS}:context-allow" \- "${RPC_PROXY_NS}:rpc-proxy-egress"; do- namespace="${namespace_policy%%:*}"- policy_type="${namespace_policy#*:}"- policy_count="$(kctl get networkpolicy -n "$namespace" \- -l "${CONTEXT_LABEL}=${context},${MCP_SERVER_LABEL}=${server},${POLICY_TYPE_LABEL}=${policy_type}" \- -o json 2>/dev/null | jq '.items | length')" || return 1- [ "$policy_count" = 1 ] || return 1- done- if kctl get mcpserver "$server" -n "$MCP_NS" -o json | jq -e '- any(.status.conditions[]?; .type == "Ready" and .status == "True")- ' >/dev/null; then- ready_peers=$((ready_peers + 1))- fi- done- # At least one independent peer must finish a real runtime reconcile while- # the primary remains held. Requiring every peer here would contradict the- # deliberately bounded startup worker pool: a held item is allowed to leave- # later peers queued, but it must never keep HCC readiness unavailable.- [ "$ready_peers" -ge 1 ]-}-peer_fleet_converged() {local index server desired availablefor ((index = 1; index < ${#MCP_FLEET_NAMES[@]}; index++)); do@@ -564,52 +595,6 @@ fixture_converged() {context_policies_converged}-probe_hcc_during_block() {- local probe_script- probe_script="$(cat <<'NODE'-const http = require('http');-const expected = process.argv[1];-function get(path) {- return new Promise((resolve, reject) => {- const request = http.get({- host: '127.0.0.1',- port: Number(process.env.HCC_E2E_PORT),- path- }, response => {- let body = '';- response.setEncoding('utf8');- response.on('data', chunk => { body += chunk; });- response.on('end', () => resolve({status: response.statusCode, body}));- });- request.setTimeout(5000, () => request.destroy(new Error('timeout')));- request.once('error', reject);- });-}-(async () => {- const ready = await get('/ready');- const readyBody = JSON.parse(ready.body);- if (ready.status !== 200 || readyBody.ready !== true) {- throw new Error('readiness unavailable: ' + ready.status + ' ' + ready.body);- }- const discovery = await get('/api/v1/mcpservers');- const discoveryBody = JSON.parse(discovery.body);- const fixture = discoveryBody.servers?.find(server => server.name === expected);- if (discovery.status !== 200 || !fixture) {- throw new Error('fixture missing from discovery: ' + discovery.status + ' ' + discovery.body);- }- console.log(JSON.stringify({- readyStatus: ready.status,- discoveryStatus: discovery.status,- fixture: fixture.name,- fixtureReady: fixture.status?.ready ?? null- }));-})().catch(error => { console.error(error.message); process.exit(1); });-NODE-)"- kctl exec "pod/${NEW_HCC_POD}" -n "$HCC_NS" -c host-context-controller -- \- env "HCC_E2E_PORT=${HCC_PORT}" node -e "$probe_script" "$MCP_NAME"-}-probe_hcc_final_context() {local probe_scriptprobe_script="$(cat <<'NODE'@@ -707,10 +692,38 @@ probe_new_hcc_ready_endpoint() {' >/dev/null 2>&1}-hcc_ready_only_after_stale_policy_revoked() {+probe_new_hcc_unready_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 === 503 && parsed?.ready === false ? 0 : 3);+ });+ }+ );+ request.setTimeout(2000, () => request.destroy(new Error("timeout")));+ request.once("error", () => process.exit(4));+ ' >/dev/null 2>&1+}++hcc_unready_after_stale_policy_revoked() {+ probe_new_hcc_unready_endpoint && external_egress_policy_absent+}++hcc_ready_only_after_current_policy_applied() {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"+ external_egress_policy_converged ||+ die "HCC served /ready=200 before the safe replacement external-egress policy existed"}hcc_restore_is_verified() {@@ -750,6 +763,8 @@ NODEhold_dns_blocker() {local hold_script+ DNS_HOLD_COUNT_AT_ARM="$(dns_hold_count)" ||+ return 1hold_script="$(cat <<'NODE'const http = require('http');const request = http.request(@@ -952,8 +967,6 @@ cleanup() {fiif [ "$status" = 0 ] && [ "$cleanup_failed" = 0 ] && [ "$restore_ok" = 1 ]; thenheader "HCC McpServer/Context readiness gate passed"- echo "$blocked_probe"- echo "$post_context_probe"echo "$final_probe"fiexit "$status"@@ -1267,19 +1280,81 @@ EOFwait_until 180 "HCC to create the real initial TCP external-egress policy" \external_egress_policy_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||die "HCC never created the initial external-egress policy for the stale-policy fixture"-ok "HCC created a real TCP external-egress policy before the revision"+CERTIFIED_POLICY_IDENTITY="$(external_egress_policy_identity)" ||+ die "could not capture the certified TCP policy UID and spec"+ok "HCC created and certified a real TCP external-egress policy"+# Availability phase: restart with the exact same desired binding. Safety may+# certify the existing policy without DNS, and every later refresh/retry must+# preserve that same object while DNS is unavailable.kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=0 >/dev/nullwait_until 120 "existing HCC pods to stop" hcc_pods_absent ||die "existing HCC pod did not stop"delete_fixture_runtime_preserving_external_policy ||die "could not remove the initial MCP runtime while retaining its external-egress policy"-external_egress_policy_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||- die "the actual initial external-egress policy disappeared before the revision"+certified_external_egress_policy_is_unchanged ||+ die "the certified TCP policy changed before the same-intent restart"+create_peer_fleet || die "could not create the gate-owned MCP/Context peer fleet"+ok "created ${#MCP_FLEET_NAMES[@]} gate-owned MCP/Context fixtures before fleet bootstrap"hold_dns_blocker || die "could not hold the next fixture DNS query"DNS_RELEASE_COUNT_AT_HOLD="$(dns_release_count)" ||- die "could not capture the DNS release baseline before the held revision"+ die "could not capture the DNS release baseline before the same-intent restart"+kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=1 >/dev/null+wait_until 120 "same-intent HCC pod to enter Running" capture_hcc ||+ die "same-intent HCC pod did not start"+identity="$(kctl get pod "$NEW_HCC_POD" -n "$HCC_NS" \+ -o jsonpath='{.metadata.uid}{" "}{.status.containerStatuses[?(@.name=="host-context-controller")].restartCount}')"+read -r HCC_UID HCC_RESTARTS <<<"$identity"+[ -n "$HCC_UID" ] && [ -n "$HCC_RESTARTS" ] ||+ die "could not capture same-intent HCC pod identity"+wait_until 120 "same-intent external-egress refresh to reach the DNS hold" \+ dns_hold_observed_since_arm ||+ die "same-intent external-egress refresh never reached the DNS hold"+wait_until_fast 60 "HCC /ready with a certified policy while DNS refresh is held" \+ probe_new_hcc_ready_endpoint ||+ die "HCC readiness incorrectly waited for same-intent DNS refresh"+fixture_runtime_absent ||+ die "HCC became ready only after the held fleet runtime resources had already converged"+wait_until 30 "Kubernetes to corroborate same-intent HCC readiness" \+ hcc_kubernetes_readiness_is_exact ||+ die "Kubernetes did not corroborate same-intent HCC readiness"+certified_external_egress_policy_is_unchanged ||+ die "the certified policy was deleted or rewritten before the first retry"+wait_until 120 "a real same-intent external-egress retry to be scheduled" \+ external_egress_retry_progress_is_observed ||+ die "the held same-intent refresh did not schedule a real retry"+wait_until 180 "the scheduled same-intent external-egress retry to execute" \+ external_egress_retry_rearmed_is_observed ||+ die "the scheduled same-intent external-egress retry did not execute"+probe_new_hcc_ready_endpoint ||+ die "HCC lost readiness after a same-intent DNS retry"+certified_external_egress_policy_is_unchanged ||+ die "a same-intent retry deleted or rewrote the certified policy"+dns_has_not_released_since_hold ||+ die "the DNS blocker released before the retry preservation assertion"+ok "same-intent DNS failure and retry preserved the policy UID/spec while HCC stayed Ready"++release_dns_blocker || die "could not release the same-intent DNS query"+wait_until 30 "DNS blocker to answer the same-intent query" \+ dns_released_since_hold ||+ die "DNS blocker did not answer the same-intent query"+wait_until 180 "same-intent runtime convergence after DNS release" \+ fixture_runtime_converged_with_protocol "$INITIAL_EXTERNAL_EGRESS_PROTOCOL" ||+ die "same-intent runtime did not converge after DNS release"++# Security phase: a protocol change invalidates the certified policy. The old+# TCP allow must be revoked even when DNS prevents constructing the UDP policy.+kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=0 >/dev/null+wait_until 120 "same-intent HCC pod to stop" hcc_pods_absent ||+ die "same-intent HCC pod did not stop"+delete_fixture_runtime_preserving_external_policy ||+ die "could not remove the same-intent runtime before the divergent revision"+certified_external_egress_policy_is_unchanged ||+ die "the certified TCP policy changed before the divergent revision"+hold_dns_blocker || die "could not hold the divergent fixture DNS query"+DNS_RELEASE_COUNT_AT_HOLD="$(dns_release_count)" ||+ die "could not capture the DNS release baseline before the divergent revision"egress_patch="$(jq -cn --arg dns "$TARGET_DNS" \'{spec:{egressBindings:[{dns:$dns,port:443,protocol:"UDP"}]}}')"kctl patch mcpserver "$MCP_NAME" -n "$MCP_NS" --type=merge \@@ -1288,15 +1363,7 @@ wait_until 60 "McpServer API to expose the revised UDP external-egress binding"mcp_egress_binding_is_udp ||die "McpServer external-egress revision did not persist"-create_peer_fleet || die "could not create the gate-owned MCP/Context peer fleet"-ok "created ${#MCP_FLEET_NAMES[@]} gate-owned MCP/Context fixtures for bounded-worker coverage"-kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=1 >/dev/null--capture_hcc() {- NEW_HCC_POD="$(running_hcc_pod)"- [ -n "$NEW_HCC_POD" ]-}wait_until 120 "replacement HCC pod to enter Running" capture_hcc ||die "replacement HCC pod did not start"identity="$(kctl get pod "$NEW_HCC_POD" -n "$HCC_NS" \@@ -1306,52 +1373,35 @@ read -r HCC_UID HCC_RESTARTS <<<"$identity"die "could not capture replacement HCC pod identity"wait_until 120 "fixture external-egress DNS query to reach the hold proxy" \- dns_log_contains "holding DNS A ${TARGET_DNS}" ||- die "initial McpServer external-egress convergence never reached the DNS hold boundary"-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_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 "Kubernetes did not corroborate HCC readiness after the direct ordering assertion"+ dns_hold_observed_since_arm ||+ die "NetworkPolicy safety convergence never reached the divergent DNS hold"+wait_until_fast 120 "HCC to stay unready after revoking the divergent stale policy" \+ hcc_unready_after_stale_policy_revoked ||+ die "HCC did not revoke the divergent stale policy before readiness"dns_log_contains "holding DNS A ${TARGET_DNS}" ||- die "DNS hold ended before Kubernetes reported HCC Ready"+ die "DNS hold ended before the fail-closed revocation assertion"if ! dns_has_not_released_since_hold; then- die "DNS blocker released the McpServer query before Kubernetes reported HCC Ready"+ die "DNS blocker released before the fail-closed revocation assertion"fi-fixture_mcp_runtime_absent ||- die "the stale same-name external-egress policy or fixture runtime survived before HCC reported Ready"-fixture_mcp_convergence_absent ||- die "fixture runtime, policy, or Ready status appeared before Kubernetes reported HCC Ready"-blocked_probe="$(probe_hcc_during_block)" ||- die "HCC readiness/discovery was unavailable while MCP convergence was blocked"-echo "$blocked_probe" | jq -e \- --arg fixture "$MCP_NAME" \- '.readyStatus == 200 and .discoveryStatus == 200 and- .fixture == $fixture and .fixtureReady != true' >/dev/null ||- die "HCC blocked-state probe returned an invalid result: ${blocked_probe}"-fixture_mcp_convergence_absent ||- die "fixture runtime or external-egress policy converged before the held DNS query was released"+fixture_runtime_and_ready_absent ||+ die "fixture runtime or Ready status appeared before safe egress replacement"+external_egress_policy_absent ||+ die "a divergent external-egress policy survived before safe replacement"context_policies_absent ||die "Context policy existed before the Context watch update"baseline_policies_exist ||- die "baseline safety NetworkPolicies are absent while HCC reports Ready"+ die "baseline safety NetworkPolicies are absent during safety convergence"hcc_identity_is_stable ||die "HCC restarted while the MCP external-egress query was held"-ok "/ready is 200 and discovery contains the exact McpServer while its real initial convergence is blocked"-ok "baseline NetworkPolicies exist and the stale same-name external-egress policy was revoked before Ready"+ok "/ready is 503 and the divergent stale policy is absent while replacement is blocked"+ok "baseline NetworkPolicies remain present throughout fail-closed safety convergence"initial_empty_context_log="[NetPol] Reconciling context \"${CONTEXT_ID}\" — allowed servers: []"wait_until 120 "initial NetworkPolicy pass to reconcile the fixture's empty Context snapshot" \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 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"+initial_network_policy_retry_progress_is_observed ||+ die "the safety lane did not expose observable NetworkPolicy retry progress"context_policies_absent ||die "Context policy appeared before the isolated MODIFIED event"@@ -1370,38 +1420,36 @@ wait_until 60 "MODIFIED handler to reconcile the fixture's latest Context snapshwait_until 120 "all three latest-Context NetworkPolicies to converge during the MCP hold" \context_policies_converged ||die "Context policies remained blocked behind the held McpServer convergence"-startup_convergence_window_is_clean ||- 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"+fixture_runtime_and_ready_absent ||+ die "McpServer runtime or Ready status escaped the deterministic DNS hold boundary"+external_egress_policy_absent ||+ die "a divergent external-egress policy reappeared before safe replacement"dns_log_contains "holding DNS A ${TARGET_DNS}" ||die "DNS hold evidence disappeared before Context policy convergence"if ! dns_has_not_released_since_hold; thendie "DNS blocker released the McpServer query before the Context isolation assertion"fi-post_context_probe="$(probe_hcc_during_block)" ||- die "HCC readiness/discovery regressed after Context policy convergence during the MCP hold"-echo "$post_context_probe" | jq -e \- --arg fixture "$MCP_NAME" \- '.readyStatus == 200 and .discoveryStatus == 200 and- .fixture == $fixture and .fixtureReady != true' >/dev/null ||- die "HCC post-Context blocked-state probe returned an invalid result: ${post_context_probe}"-hcc_kubernetes_readiness_is_exact ||- die "HCC lost Kubernetes readiness while Context policies converged during the MCP hold"+probe_new_hcc_unready_endpoint ||+ die "HCC became ready before the safe replacement policy existed"+if hcc_kubernetes_readiness_is_exact; then+ die "Kubernetes reported HCC Ready before the safe replacement policy existed"+fihcc_identity_is_stable ||die "HCC restarted while Context policies converged around the held MCP entity"-wait_until 300 "peer MCP/Context fleet to make safe background progress during held primary egress" \- peer_fleet_has_background_progress ||- die "peer MCP/Context fleet made no safe background progress while the primary egress remained held"ok "the MODIFIED handler, not the initial empty-Context pass, converged all three policies"-ok "McpServer runtime and external-egress remained absent until release; readiness stayed 200"-ok "the worker-width-crossing peer fleet made safe background progress while the primary egress remained held"+ok "McpServer runtime and divergent policy stayed absent until safe replacement"release_dns_blocker ||die "could not release the fixture DNS query"wait_until 30 "DNS blocker to answer the held query" \- dns_log_contains "released DNS A ${TARGET_DNS}" ||+ dns_released_since_hold ||die "DNS blocker did not answer the held query"+wait_until_fast 120 "HCC /ready only after the current replacement policy is applied" \+ hcc_ready_only_after_current_policy_applied ||+ die "HCC did not become ready after the safe replacement policy was applied"+wait_until 30 "replacement HCC pod and Deployment to corroborate readiness" \+ hcc_kubernetes_readiness_is_exact ||+ die "Kubernetes did not corroborate HCC readiness after the direct ordering assertion"wait_until 300 "McpServer runtime, status, and latest Context NetworkPolicies to converge" \fixture_converged ||die "McpServer/Context/NetworkPolicy convergence did not complete after DNS release"@@ -1411,8 +1459,9 @@ wait_until 300 "all peer MCP/Context runtimes to converge after releasing the hewait_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 HCC logs were unavailable before final convergence"+wait_until 60 "initial NetworkPolicy retry to complete after DNS release" \+ hcc_log_contains "[NetPol] Full reconciliation complete" ||+ die "initial NetworkPolicy convergence did not recover after DNS release"hcc_identity_is_stable ||die "HCC restarted instead of completing the released background convergence"final_probe="$(probe_hcc_final_context)" ||@@ -1423,9 +1472,9 @@ echo "$final_probe" | jq -e \.fixture == $fixture and .fixtureReady == true and .contextRef == $context' >/dev/null ||die "HCC final probe returned an invalid result: ${final_probe}"-ok "released MCP convergence created the real runtime and external-egress policy"+ok "DNS release replaced the old policy before readiness and then created the real runtime"ok "the full worker-width-crossing peer fleet converged after releasing the held primary egress"ok "Context ingress, mcp-host egress, and rpc-proxy egress policies reflect the latest watch state"-ok "HCC stayed Ready on the same pod throughout blocked and released convergence"+ok "HCC stayed unready through divergent revocation and became Ready only after replacement"header "HCC McpServer/Context assertions complete; restoring branch-owned runtime"diff --git a/scripts/tests/test-hcc-watch-recovery-gate.sh b/scripts/tests/test-hcc-watch-recovery-gate.shindex 9c640a706..1c77d37c4 100755--- a/scripts/tests/test-hcc-watch-recovery-gate.sh+++ b/scripts/tests/test-hcc-watch-recovery-gate.sh@@ -231,12 +231,15 @@ for case_name in detached minikube-profile-missing minikube-profile profile-namefidone-startup_window_function="$(- sed -n '/^startup_convergence_window_is_clean() {$/,/^}$/p' "$MCP_READINESS_GATE"+network_policy_retry_function="$(+ sed -n '/^initial_network_policy_retry_progress_is_observed() {$/,/^}$/p' "$MCP_READINESS_GATE")"retry_progress_function="$(sed -n '/^external_egress_retry_progress_is_observed() {$/,/^}$/p' "$MCP_READINESS_GATE")"+retry_rearmed_function="$(+ sed -n '/^external_egress_retry_rearmed_is_observed() {$/,/^}$/p' "$MCP_READINESS_GATE"+)"if (NEW_HCC_POD=hcc-podHCC_NS=control-plane@@ -246,13 +249,19 @@ if (MOCK_HCC_LOG='[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+[K8s] Scheduling external egress retry 2/3 for McpServer "e2e-held-server" in 15000ms+[K8s] Initial NetworkPolicy background reconciliation failed: dns timeout+[K8s] Scheduling initial NetworkPolicy background convergence retry 1 in 5000ms'kctl() { printf '%s\n' "$MOCK_HCC_LOG"; }- eval "$startup_window_function"+ eval "$network_policy_retry_function"eval "$retry_progress_function"- startup_convergence_window_is_clean && external_egress_retry_progress_is_observed+ eval "$retry_rearmed_function"+ initial_network_policy_retry_progress_is_observed &&+ external_egress_retry_progress_is_observed &&+ external_egress_retry_rearmed_is_observed); then- pass "the injected DNS hold requires observable live retry progress without treating it as fatal"+ pass "the two DNS phases require observable runtime-refresh and safety-pass retries"elsefail "the injected DNS hold cannot distinguish expected live retry progress"fi@@ -264,12 +273,12 @@ if (CONTEXT_NAME=e2e-contextMOCK_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+ eval "$network_policy_retry_function"+ ! initial_network_policy_retry_progress_is_observed); then- pass "the convergence window rejects a real NetworkPolicy failure marker"+ pass "the safety retry predicate rejects a failure without scheduled recovery"else- fail "the convergence window accepts a real NetworkPolicy failure marker"+ fail "the safety retry predicate accepts a failure without scheduled recovery"fiif (NEW_HCC_POD=hcc-pod@@ -278,12 +287,12 @@ if (MCP_NAME=e2e-held-serverCONTEXT_NAME=e2e-contextkctl() { return 1; }- eval "$startup_window_function"- ! startup_convergence_window_is_clean+ eval "$network_policy_retry_function"+ ! initial_network_policy_retry_progress_is_observed); then- pass "the convergence window fails closed when HCC logs are unavailable"+ pass "the safety retry predicate fails closed when HCC logs are unavailable"else- fail "the convergence window passes vacuously when HCC logs are unavailable"+ fail "the safety retry predicate passes vacuously when HCC logs are unavailable"fi# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-logs.sh@@ -375,10 +384,10 @@ elsefireadiness_boundary_function="$(- sed -n '/^hcc_ready_only_after_stale_policy_revoked() {$/,/^}$/p' "$MCP_READINESS_GATE"+ sed -n '/^hcc_ready_only_after_current_policy_applied() {$/,/^}$/p' "$MCP_READINESS_GATE")"direct_ready_line="$(- grep -nF 'wait_until_fast 120 "HCC /ready to become available only after stale policy revocation"' \+ grep -nF 'wait_until_fast 120 "HCC /ready only after the current replacement policy is applied"' \"$MCP_READINESS_GATE" | cut -d: -f1)"kubernetes_ready_line="$(@@ -387,14 +396,57 @@ kubernetes_ready_line="$()"# shellcheck disable=SC2016if [[ "$readiness_boundary_function" == *'probe_new_hcc_ready_endpoint || return 1'* ]] &&- [[ "$readiness_boundary_function" == *'fixture_mcp_runtime_absent ||'* ]] &&+ [[ "$readiness_boundary_function" == *'external_egress_policy_converged ||'* ]] &&[ -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"+ pass "direct /ready ordering is asserted against current policy materialization before Kubernetes corroboration"elsefail "readiness ordering still relies on the delayed Kubernetes Pod Ready signal"fi+same_intent_capture_line="$(+ grep -nF 'CERTIFIED_POLICY_IDENTITY="$(external_egress_policy_identity)"' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+same_intent_retry_line="$(+ grep -nF 'wait_until 120 "a real same-intent external-egress retry to be scheduled"' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+same_intent_ready_line="$(+ grep -nF 'wait_until_fast 60 "HCC /ready with a certified policy while DNS refresh is held"' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+same_intent_incomplete_line="$(+ grep -nF 'HCC became ready only after the held fleet runtime resources had already converged' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+same_intent_retry_execution_line="$(+ grep -nF 'wait_until 180 "the scheduled same-intent external-egress retry to execute"' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+same_intent_recheck_line="$(+ grep -nF 'a same-intent retry deleted or rewrote the certified policy' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+divergent_revoke_line="$(+ grep -nF 'wait_until_fast 120 "HCC to stay unready after revoking the divergent stale policy"' \+ "$MCP_READINESS_GATE" | cut -d: -f1+)"+if [ -n "$same_intent_capture_line" ] && [ -n "$same_intent_retry_line" ] &&+ [ -n "$same_intent_ready_line" ] && [ -n "$same_intent_incomplete_line" ] &&+ [ -n "$same_intent_retry_execution_line" ] &&+ [ -n "$same_intent_recheck_line" ] && [ -n "$divergent_revoke_line" ] &&+ [ "$same_intent_capture_line" -lt "$same_intent_ready_line" ] &&+ [ "$same_intent_ready_line" -lt "$same_intent_incomplete_line" ] &&+ [ "$same_intent_incomplete_line" -lt "$same_intent_retry_line" ] &&+ [ "$same_intent_retry_line" -lt "$same_intent_retry_execution_line" ] &&+ [ "$same_intent_retry_execution_line" -lt "$same_intent_recheck_line" ] &&+ [ "$same_intent_recheck_line" -lt "$divergent_revoke_line" ]; then+ pass "same-intent UID/spec preservation through retry precedes divergent fail-closed revocation"+else+ fail "the MCP readiness gate does not cover both DNS availability and revocation contracts"+fi+printf '%s\n' \'[K8s] CommunicationChannel watch ended; holding stateless lifecycle active until snapshot recovery' \'[K8s] Listing all Hosts in namespace mcp-host' \@@ -630,7 +682,7 @@ if grep -Fq 'source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-fixture.sh"' \! grep -Fq -- '--for=delete' "$MCP_READINESS_GATE" &&! grep -Fq 'port: 8081' "$MCP_READINESS_GATE" &&[ "$mcp_port_probe_count" = 4 ] &&- [ "$mcp_pod_absence_count" = 3 ]; then+ [ "$mcp_pod_absence_count" = 4 ]; thenpass "MCP readiness gate shares exact-head ownership and uses bounded portable runtime probes"elsefail "MCP readiness gate duplicates ownership or retains a deadline, pod-absence, or port edge"@@ -646,9 +698,7 @@ mcp_restart_line="$(grep -nF 'kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" -if grep -Fq 'MCP_FLEET_SIZE="${E2E_HCC_MCP_FLEET_SIZE:-11}"' "$MCP_READINESS_GATE" &&grep -Fq '[ "$MCP_FLEET_SIZE" -gt 10 ]' "$MCP_READINESS_GATE" &&grep -Fq 'create_peer_fleet' "$MCP_READINESS_GATE" &&- grep -Fq 'peer_fleet_has_background_progress' "$MCP_READINESS_GATE" &&grep -Fq 'peer_fleet_converged' "$MCP_READINESS_GATE" &&- grep -Fq 'peer MCP/Context fleet to make safe background progress during held primary egress' "$MCP_READINESS_GATE" &&grep -Fq 'all peer MCP/Context runtimes to converge after releasing the held primary egress' "$MCP_READINESS_GATE" &&[ -n "$mcp_peer_create_line" ] && [ -n "$mcp_restart_line" ] &&[ "$mcp_peer_create_line" -lt "$mcp_restart_line" ]; then