Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): fence readiness convergence mutations
Alfredo Lopez50921c953750
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 7ed85b211..30215a324 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.164",+ "version": "0.1.165","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.164",+ "version": "0.1.165","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 9bf751897..2b9bf2c0f 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.164",+ "version": "0.1.165","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/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.tsindex c6d258c89..042c539e3 100644--- a/host-context-controller/src/hostReconciler.test.ts+++ b/host-context-controller/src/hostReconciler.test.ts@@ -10,7 +10,11 @@ import {createMockNetworkingApi,createMockRbacApi,} from '../test/__fixtures__/testMocks'-import { HostFleetReconcileError, HostReconciler, destructiveCleanupAllowed } from './hostReconciler'+import {+ HostFleetReconcileError,+ HostReconciler,+ destructiveCleanupAllowed,+} from './hostReconciler'import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'import { registry } from './metrics'import { HostCRD } from './types'@@ -355,14 +359,20 @@ describe('HostReconciler fleet failure isolation', () => {metadata: {name: 'orphan-a',namespace: 'mcp-host',- labels: { 'clerum.io/managed-by': 'host-context-controller', 'clerum.io/host': 'orphan-a' },+ labels: {+ 'clerum.io/managed-by': 'host-context-controller',+ 'clerum.io/host': 'orphan-a',+ },},} as k8s.V1Deployment,{metadata: {name: 'orphan-b',namespace: 'mcp-host',- labels: { 'clerum.io/managed-by': 'host-context-controller', 'clerum.io/host': 'orphan-b' },+ labels: {+ 'clerum.io/managed-by': 'host-context-controller',+ 'clerum.io/host': 'orphan-b',+ },},} as k8s.V1Deployment,])@@ -417,7 +427,12 @@ describe('HostReconciler bounded fleet workers', () => {rbacApi: asRbacApi(createMockRbacApi()),})// Isolate reconcile concurrency from the cleanup phase.- vi.spyOn(reconciler as unknown as { collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]> }, 'collectHostCleanupFailures').mockResolvedValue([])+ vi.spyOn(+ reconciler as unknown as {+ collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]>+ },+ 'collectHostCleanupFailures'+ ).mockResolvedValue([])let active = 0let maxActive = 0const gates: Array<() => void> = []@@ -450,7 +465,12 @@ describe('HostReconciler bounded fleet workers', () => {networkingApi: asNetworkingApi(createMockNetworkingApi()),rbacApi: asRbacApi(createMockRbacApi()),})- vi.spyOn(reconciler as unknown as { collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]> }, 'collectHostCleanupFailures').mockResolvedValue([])+ vi.spyOn(+ reconciler as unknown as {+ collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]>+ },+ 'collectHostCleanupFailures'+ ).mockResolvedValue([])let active = 0let maxActive = 0const gates = new Map<string, () => void>()@@ -923,6 +943,42 @@ describe('HostReconciler cleanup authority gate', () => {expect(del).not.toHaveBeenCalled()})+ it('defers orphan deletion when authority changes before serializer admission', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ const authority = { known: true, generation: 3 }+ reconciler.setHostWatchAuthority(() => ({ ...authority }))+ reconciler.setResolveCurrentHost(() => undefined)+ const internals = reconciler as unknown as {+ lifecycle: {+ serializeByHost(name: string, task: () => Promise<void>): Promise<void>+ }+ listManagedHostDeployments(): Promise<k8s.V1Deployment[]>+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>+ }+ vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue([+ orphanDeployment('authority-race-host'),+ ])+ const del = vi.spyOn(internals, 'deleteHostRuntimeResources').mockResolvedValue(undefined)+ const blockerStarted = deferred()+ const releaseBlocker = deferred()+ const occupied = internals.lifecycle.serializeByHost('authority-race-host', async () => {+ blockerStarted.resolve(undefined)+ await releaseBlocker.promise+ })+ await blockerStarted.promise++ const cleanup = reconciler.fullReconcile([])+ await vi.waitFor(() => expect(getObj).toHaveBeenCalledOnce())+ authority.known = false+ authority.generation = 4+ releaseBlocker.resolve(undefined)+ await occupied+ await cleanup++ expect(del).not.toHaveBeenCalled()+ })+it('defers an orphan whose fresh authoritative read fails', async () => {const getObj = vi.fn().mockRejectedValue({ code: 503 })const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })@@ -976,3 +1032,389 @@ describe('HostReconciler cleanup authority gate', () => {expect(del).not.toHaveBeenCalled()})})++describe('HostReconciler Host inventory mutation authority', () => {+ function wireAuthoritativeHost(+ reconciler: HostReconciler,+ host: HostCRD,+ authorityRef: { current: { known: boolean; generation: number } }+ ): void {+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => authorityRef.current)+ }++ function stubPreDeploymentReconcileEffects(reconciler: HostReconciler): void {+ vi.spyOn(reconciler as any, 'validateHostSecret').mockResolvedValue({ ok: true })+ for (const method of [+ 'ensureHostServiceAccount',+ 'ensureHostRole',+ 'ensureHostRoleBinding',+ 'ensurePvc',+ 'ensureService',+ 'ensureMcpHostIngressNetworkPolicy',+ 'ensureMcpHostGfsEgressNetworkPolicy',+ 'ensureWorkflowApprovalReaderMcpHostIngressNetworkPolicy',+ 'ensureRpcProxyMcpHostIngressNetworkPolicy',+ 'ensureRpcProxyHostEgressNetworkPolicy',+ 'ensureDesktopNetworkPolicy',+ 'ensureChannelReaderEgressNetworkPolicy',+ 'ensureWorkflowApprovalReaderHostEgressNetworkPolicy',+ ]) {+ vi.spyOn(reconciler as any, method).mockResolvedValue(undefined)+ }+ }++ function runtimeTokenScopeWithoutChannels(host: HostCRD): string {+ return (+ HostReconciler as unknown as {+ runtimeTokenScopeHash(selected: HostCRD, hasChannelIngress: boolean): string+ }+ ).runtimeTokenScopeHash(host, false)+ }++ it('rejects a queued reconcile when Host authority changes before admission', async () => {+ const reconciler = makeBasicReconciler()+ const host = makeHost({ name: 'authority-race' })+ const authority = { current: { known: true, generation: 7 } }+ wireAuthoritativeHost(reconciler, host, authority)+ const reconcileCore = vi.spyOn(reconciler as any, 'reconcileCore').mockResolvedValue(undefined)+ const blockerStarted = deferred()+ const releaseBlocker = deferred()+ const occupied = (reconciler as any).lifecycle.serializeByHost(host.name, async () => {+ blockerStarted.resolve(undefined)+ await releaseBlocker.promise+ }) as Promise<void>+ await blockerStarted.promise++ const pending = reconciler.reconcile(host)+ authority.current = { known: false, generation: 8 }+ releaseBlocker.resolve(undefined)+ await occupied++ await expect(pending).rejects.toThrow(/Host inventory authority/)+ expect(reconcileCore).not.toHaveBeenCalled()+ })++ it('does not delete runtime after a Secret rejection when Host authority changes in flight', async () => {+ const reconciler = makeBasicReconciler()+ const host = { ...makeHost({ name: 'secret-authority-race' }), uid: 'host-uid', generation: 3 }+ const authority = { current: { known: true, generation: 7 } }+ wireAuthoritativeHost(reconciler, host, authority)+ const secretReadStarted = deferred()+ const releaseSecretRead = deferred()+ vi.spyOn(reconciler as any, 'validateHostSecret').mockImplementation(async () => {+ secretReadStarted.resolve(undefined)+ await releaseSecretRead.promise+ return {+ ok: false,+ reason: 'SecretNotFound',+ message: 'secret missing in stale spec',+ }+ })+ const deleteRuntime = vi+ .spyOn(reconciler as any, 'deleteHostRuntimeResources')+ .mockResolvedValue(undefined)++ const pending = reconciler.reconcile(host)+ await secretReadStarted.promise+ authority.current = { known: false, generation: 8 }+ releaseSecretRead.resolve(undefined)++ await expect(pending).rejects.toThrow(/Host inventory authority/)+ expect(deleteRuntime).not.toHaveBeenCalled()+ })++ it.each([+ [+ 'UID',+ (host: HostCRD) => ({ ...host, uid: 'replacement-host-uid', generation: 1 }),+ /Host identity/,+ ],+ [+ 'spec generation',+ (host: HostCRD) => ({+ ...host,+ generation: (host.generation ?? 0) + 1,+ spec: { ...host.spec, secretRef: 'replacement-secret' },+ }),+ /Host spec generation/,+ ],+ ] as const)(+ 'does not delete runtime after a Secret rejection when the Host %s changes in flight',+ async (_, replaceCurrent, expectedError) => {+ const reconciler = makeBasicReconciler()+ const host = {+ ...makeHost({ name: 'secret-identity-race' }),+ uid: 'host-uid',+ generation: 3,+ }+ let current = host+ const authority = { current: { known: true, generation: 7 } }+ reconciler.setResolveCurrentHost(name => (name === host.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => authority.current)+ const secretReadStarted = deferred()+ const releaseSecretRead = deferred()+ vi.spyOn(reconciler as any, 'validateHostSecret').mockImplementation(async () => {+ secretReadStarted.resolve(undefined)+ await releaseSecretRead.promise+ return {+ ok: false,+ reason: 'SecretNotFound',+ message: 'secret missing in stale spec',+ }+ })+ const deleteRuntime = vi+ .spyOn(reconciler as any, 'deleteHostRuntimeResources')+ .mockResolvedValue(undefined)++ const pending = reconciler.reconcile(host)+ await secretReadStarted.promise+ current = replaceCurrent(host)+ releaseSecretRead.resolve(undefined)++ await expect(pending).rejects.toThrow(expectedError)+ expect(deleteRuntime).not.toHaveBeenCalled()+ }+ )++ it('revalidates the Host spec after token provisioning and before Deployment mutation', async () => {+ const reconciler = makeBasicReconciler()+ const host = {+ ...makeHost({ name: 'deployment-generation-race' }),+ uid: 'host-uid',+ generation: 3,+ }+ let current = host+ const authority = { current: { known: true, generation: 11 } }+ reconciler.setResolveCurrentHost(name => (name === host.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => authority.current)+ stubPreDeploymentReconcileEffects(reconciler)+ const tokenProvisionStarted = deferred()+ const releaseTokenProvision = deferred()+ vi.spyOn(reconciler as any, 'provisionRuntimeTokenRevision').mockImplementation(async () => {+ tokenProvisionStarted.resolve(undefined)+ await releaseTokenProvision.promise+ return { revision: 'stale-revision', scopeHash: 'stale-scope' }+ })+ const ensureDeployment = vi+ .spyOn(reconciler as any, 'ensureDeployment')+ .mockResolvedValue(undefined)++ const pending = reconciler.reconcile(host)+ await tokenProvisionStarted.promise+ current = {+ ...host,+ generation: 4,+ spec: { ...host.spec, contextRef: 'replacement-context' },+ }+ releaseTokenProvision.resolve(undefined)++ await expect(pending).rejects.toThrow(/Host spec generation/)+ expect(ensureDeployment).not.toHaveBeenCalled()+ })++ it('revalidates the Host spec at the final Deployment create-state boundary', async () => {+ const appsApi = createMockAppsApi()+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })+ const host = {+ ...makeHost({ name: 'deployment-create-race' }),+ uid: 'host-uid',+ generation: 3,+ }+ let current = host+ reconciler.setResolveCurrentHost(name => (name === host.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 12 }))+ stubPreDeploymentReconcileEffects(reconciler)+ vi.spyOn(reconciler as any, 'provisionRuntimeTokenRevision').mockResolvedValue({+ revision: 'runtime-revision',+ scopeHash: runtimeTokenScopeWithoutChannels(host),+ })+ let channelIngressReads = 0+ vi.spyOn(reconciler as any, 'hasChannelIngress').mockImplementation(() => {+ channelIngressReads += 1+ if (channelIngressReads === 2) {+ current = {+ ...host,+ generation: 4,+ spec: { ...host.spec, contextRef: 'replacement-context' },+ }+ }+ return false+ })++ await expect(reconciler.reconcile(host)).rejects.toThrow(/Host spec generation/)++ expect(channelIngressReads).toBe(2)+ expect(appsApi.createNamespacedDeployment).not.toHaveBeenCalled()+ expect(appsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()+ })++ it('revalidates the Host spec after a Deployment create conflict and before replace', async () => {+ const appsApi = createMockAppsApi()+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })+ const host = {+ ...makeHost({ name: 'deployment-replace-race' }),+ uid: 'host-uid',+ generation: 3,+ }+ let current = host+ reconciler.setResolveCurrentHost(name => (name === host.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 13 }))+ stubPreDeploymentReconcileEffects(reconciler)+ vi.spyOn(reconciler as any, 'provisionRuntimeTokenRevision').mockResolvedValue({+ revision: 'runtime-revision',+ scopeHash: runtimeTokenScopeWithoutChannels(host),+ })+ vi.spyOn(reconciler as any, 'hasChannelIngress').mockReturnValue(false)+ appsApi.createNamespacedDeployment.mockRejectedValueOnce({ code: 409 })+ appsApi.readNamespacedDeployment.mockImplementationOnce(async () => {+ current = {+ ...host,+ generation: 4,+ spec: { ...host.spec, contextRef: 'replacement-context' },+ }+ return { metadata: { resourceVersion: 'rv-existing' } }+ })++ await expect(reconciler.reconcile(host)).rejects.toThrow(/Host spec generation/)++ expect(appsApi.createNamespacedDeployment).toHaveBeenCalledTimes(1)+ expect(appsApi.readNamespacedDeployment).toHaveBeenCalledTimes(1)+ expect(appsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()+ })++ it('revalidates the Host spec before retrying a conflicted Deployment replace', async () => {+ const appsApi = createMockAppsApi()+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })+ const host = {+ ...makeHost({ name: 'deployment-retry-race' }),+ uid: 'host-uid',+ generation: 3,+ }+ let current = host+ let deploymentReads = 0+ reconciler.setResolveCurrentHost(name => (name === host.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 14 }))+ stubPreDeploymentReconcileEffects(reconciler)+ vi.spyOn(reconciler as any, 'provisionRuntimeTokenRevision').mockResolvedValue({+ revision: 'runtime-revision',+ scopeHash: runtimeTokenScopeWithoutChannels(host),+ })+ vi.spyOn(reconciler as any, 'hasChannelIngress').mockReturnValue(false)+ appsApi.createNamespacedDeployment.mockRejectedValueOnce({ code: 409 })+ appsApi.readNamespacedDeployment.mockImplementation(async () => {+ deploymentReads += 1+ if (deploymentReads === 2) {+ current = {+ ...host,+ generation: 4,+ spec: { ...host.spec, contextRef: 'replacement-context' },+ }+ }+ return { metadata: { resourceVersion: `rv-existing-${deploymentReads}` } }+ })+ appsApi.replaceNamespacedDeployment.mockRejectedValueOnce({ code: 409 })+ const random = vi.spyOn(Math, 'random').mockReturnValue(0)++ try {+ await expect(reconciler.reconcile(host)).rejects.toThrow(/Host spec generation/)+ } finally {+ random.mockRestore()+ }++ expect(appsApi.createNamespacedDeployment).toHaveBeenCalledTimes(1)+ expect(appsApi.readNamespacedDeployment).toHaveBeenCalledTimes(2)+ expect(appsApi.replaceNamespacedDeployment).toHaveBeenCalledTimes(1)+ })++ it('resolves the latest authoritative Host object at reconcile admission', async () => {+ const reconciler = makeBasicReconciler()+ const stale = { ...makeHost({ name: 'latest-host' }), generation: 1 }+ const current = {+ ...stale,+ generation: 2,+ spec: { ...stale.spec, contextRef: 'current-context' },+ }+ const authority = { current: { known: true, generation: 7 } }+ wireAuthoritativeHost(reconciler, current, authority)+ const reconcileCore = vi.spyOn(reconciler as any, 'reconcileCore').mockResolvedValue(undefined)++ await reconciler.reconcile(stale)++ expect(reconcileCore).toHaveBeenCalledOnce()+ expect(reconcileCore).toHaveBeenCalledWith(+ expect.objectContaining({+ generation: 2,+ spec: expect.objectContaining({ contextRef: 'current-context' }),+ }),+ expect.any(Function)+ )+ })++ it('does not patch channel-reader after Host authority changes during revision resolution', async () => {+ const reconciler = makeBasicReconciler()+ const host = makeHost({ name: 'channel-authority-race' })+ const authority = { current: { known: true, generation: 9 } }+ wireAuthoritativeHost(reconciler, host, authority)+ const revisionStarted = deferred()+ const releaseRevision = deferred<string>()+ vi.spyOn(reconciler as any, 'computeChannelReaderRevisionForHost').mockImplementation(+ async () => {+ revisionStarted.resolve(undefined)+ return releaseRevision.promise+ }+ )+ const patchDeployment = vi+ .spyOn((reconciler as any).appsApi, 'patchNamespacedDeployment')+ .mockResolvedValue(undefined)++ const pending = reconciler.patchChannelReaderRevisionAnnotation(host.name)+ await revisionStarted.promise+ authority.current = { known: false, generation: 10 }+ releaseRevision.resolve('resolved-revision')+ await pending++ expect(patchDeployment).not.toHaveBeenCalled()+ })++ it('rejects a queued delete when Host authority changes before admission', async () => {+ const reconciler = makeBasicReconciler()+ const host = makeHost({ name: 'delete-authority-race' })+ const authority = { current: { known: true, generation: 11 } }+ reconciler.setResolveCurrentHost(() => undefined)+ reconciler.setHostWatchAuthority(() => authority.current)+ const deleteRuntime = vi+ .spyOn(reconciler as any, 'deleteHostRuntimeResources')+ .mockResolvedValue(undefined)+ const blockerStarted = deferred()+ const releaseBlocker = deferred()+ const occupied = (reconciler as any).lifecycle.serializeByHost(host.name, async () => {+ blockerStarted.resolve(undefined)+ await releaseBlocker.promise+ }) as Promise<void>+ await blockerStarted.promise++ const pending = reconciler.reconcileDelete(host.name, host.namespace)+ authority.current = { known: false, generation: 12 }+ releaseBlocker.resolve(undefined)+ await occupied++ await expect(pending).rejects.toThrow(/Host inventory authority/)+ expect(deleteRuntime).not.toHaveBeenCalled()+ })+})diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 5bf92cfa6..9484c1279 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -77,6 +77,35 @@ export type HostReconcileSource = 'urgent' | 'retry' | 'fleet'/** Immutable Host watch authority snapshot captured at a full-pass boundary. */export type HostWatchAuthoritySnapshot = { known: boolean; generation: number }+class HostInventoryAuthorityUnavailableError extends Error {+ constructor(+ action: string,+ captured: HostWatchAuthoritySnapshot,+ current: HostWatchAuthoritySnapshot+ ) {+ super(+ `Host inventory authority changed before ${action} admission ` ++ `(captured known=${captured.known} generation=${captured.generation}, ` ++ `current known=${current.known} generation=${current.generation})`+ )+ this.name = 'HostInventoryAuthorityUnavailableError'+ }+}++class HostMutationIdentityChangedError extends Error {+ constructor(action: string, hostName: string) {+ super(`Host identity changed before ${action} admission for "${hostName}"`)+ this.name = 'HostMutationIdentityChangedError'+ }+}++class HostMutationSpecRevisionChangedError extends Error {+ constructor(action: string, hostName: string) {+ super(`Host spec generation changed before ${action} admission for "${hostName}"`)+ this.name = 'HostMutationSpecRevisionChangedError'+ }+}+/*** The exact §13.2 destructive-cleanup predicate. Deletion of an orphan Host's* owned bundle is permitted ONLY when watch authority is known, the watch@@ -419,7 +448,9 @@ export class HostReconciler {now: this.now,countCommunicationChannels: hostName => this.countCommunicationChannels(hostName),isCommunicationChannelCacheSynced: () => this.ccCacheSyncedFn(),- reconcileCore: host => this.reconcileCore(host),+ reconcileCore: (host, revalidate) => this.reconcileCore(host, revalidate),+ prepareHostMutationAdmission: (action, host) =>+ this.prepareHostMutationAdmission(action, host),onLifecycleStatusCommitted: (host, lifecycle) => {const occurredAt = this.now().toISOString()this.infrastructureTelemetryReporter?.enqueueHealthTransition({@@ -494,6 +525,66 @@ export class HostReconciler {this.hostWatchAuthority = fn}+ /**+ * A standalone HostReconciler receives an explicit Host object and has no+ * watch-backed cache to fence. Once a live-cache resolver is wired (the+ * production McpServerWatcher path), every mutation captures and revalidates+ * Host LIST -> WATCH authority at its actual serializer admission boundary.+ */+ private captureHostMutationAuthority(): HostWatchAuthoritySnapshot | null {+ return this.resolveCurrentHost === null ? null : this.hostWatchAuthority()+ }++ private requireHostMutationAuthority(+ action: string,+ captured: HostWatchAuthoritySnapshot | null+ ): void {+ if (captured === null) return+ const current = this.hostWatchAuthority()+ if (!captured.known || !current.known || captured.generation !== current.generation) {+ throw new HostInventoryAuthorityUnavailableError(action, captured, current)+ }+ }++ /**+ * Heartbeat writers own their serializer inside StatelessLifecycleExecutor.+ * Capture authority here at dispatch, then let the returned closure re-check+ * it and resolve the current same-UID Host when that serializer admits the+ * work. This preserves one queue per Host without a nested-lock deadlock.+ */+ private prepareHostMutationAdmission(action: string, requested: HostCRD): () => HostCRD {+ const capturedAuthority = this.captureHostMutationAuthority()+ return this.makeHostMutationAdmission(action, requested, capturedAuthority)+ }++ private makeHostMutationAdmission(+ action: string,+ requested: HostCRD,+ capturedAuthority: HostWatchAuthoritySnapshot | null+ ): () => HostCRD {+ return () => {+ this.requireHostMutationAuthority(action, capturedAuthority)+ if (this.resolveCurrentHost === null) return requested+ const current = this.resolveCurrentHost(requested.name)+ if (+ current === undefined ||+ requested.uid === undefined ||+ current.uid === undefined ||+ requested.uid !== current.uid+ ) {+ throw new HostMutationIdentityChangedError(action, requested.name)+ }+ if (+ requested.generation === undefined ||+ current.generation === undefined ||+ requested.generation !== current.generation+ ) {+ throw new HostMutationSpecRevisionChangedError(action, requested.name)+ }+ return current+ }+ }+/*** Late-bound setter for the host-ref lookup used by* `patchChannelReaderRevisionAnnotation` to discover Secret(s) referenced@@ -2091,9 +2182,20 @@ export class HostReconciler {* Host CRD is present).*/async patchChannelReaderRevisionAnnotation(hostName: string): Promise<void> {+ const capturedAuthority = this.captureHostMutationAuthority()const depName = `channel-reader-${hostName}`try {+ this.requireHostMutationAuthority(+ `channel-reader "${hostName}" revision patch`,+ capturedAuthority+ )+ if (this.resolveCurrentHost && !this.resolveCurrentHost(hostName)) returnconst revision = await this.computeChannelReaderRevisionForHost(hostName)+ this.requireHostMutationAuthority(+ `channel-reader "${hostName}" revision patch`,+ capturedAuthority+ )+ if (this.resolveCurrentHost && !this.resolveCurrentHost(hostName)) returnconst patchBody = {spec: {template: {@@ -3548,16 +3650,25 @@ export class HostReconciler {async reconcile(host: HostCRD, source: HostReconcileSource = 'urgent'): Promise<void> {const dispatchedAt = Date.now()+ const capturedAuthority = this.captureHostMutationAuthority()return this.lifecycle.serializeByHost(host.name, async () => {+ this.requireHostMutationAuthority(`Host "${host.name}" reconcile`, capturedAuthority)+ const admittedHost = this.resolveCurrentHost ? this.resolveCurrentHost(host.name) : host+ if (!admittedHost) return+ const revalidate = this.makeHostMutationAdmission(+ `Host "${host.name}" reconcile`,+ admittedHost,+ capturedAuthority+ )const admittedAt = Date.now()hostReconcileInFlight.inc({ lane: source })try {- await this.reconcileCore(host)- this.enqueueReconcileOutcome(host)+ await this.reconcileCore(admittedHost, revalidate)+ this.enqueueReconcileOutcome(admittedHost)this.observeReconcileLatency(source, 'success', dispatchedAt, admittedAt)} catch (error) {- this.enqueueControllerError(host, 'reconcile_exception', error)- this.enqueueReconcileOutcome(host)+ this.enqueueControllerError(admittedHost, 'reconcile_exception', error)+ this.enqueueReconcileOutcome(admittedHost)this.observeReconcileLatency(source, 'error', dispatchedAt, admittedAt)throw error} finally {@@ -3582,7 +3693,19 @@ export class HostReconciler {)}- private async reconcileCore(host: HostCRD): Promise<void> {+ private async reconcileCore(host: HostCRD, revalidate?: () => HostCRD): Promise<void> {+ // A per-Host serializer orders work, but it does not invalidate an older+ // reconcile when the watch cache observes a newer spec while this body is+ // awaiting Kubernetes or issuer I/O. Re-check the captured authority,+ // identity, and spec generation at every material mutation boundary.+ // Individual API writes remain atomic at the Kubernetes resource level;+ // these checks prevent subsequent stale writes from spanning an observed+ // generation change.+ const revalidateHostMutationBoundary = (): void => {+ revalidate?.()+ }++ revalidateHostMutationBoundary()// Wake fast-path (Stage 4.3) BEFORE the heavy reconcile body: reconciles// are serialized PER HOST (serializeByHost), so a pending wake for THIS// Host must not wait behind token issuance, NetworkPolicies or the@@ -3591,6 +3714,7 @@ export class HostReconciler {// funnels through this same method, so a watch event dropped on disconnect// is recovered here.const forceFreshForWake = (await this.lifecycle.handleWakeFastPath(host)) === true+ revalidateHostMutationBoundary()// Track whether this host has desktop enabledconst isDesktop = !!(host.spec.desktop?.browser || host.spec.desktop?.x11)@@ -3601,11 +3725,18 @@ export class HostReconciler {}const secretResult = await this.validateHostSecret(host)+ revalidateHostMutationBoundary()if (!secretResult.ok) {if (secretResult.reason === 'SecretNotFound' ||secretResult.reason === 'SecretAccessDenied') {+ // This branch deletes every ephemeral runtime resource. The Secret+ // decision may have blocked on the API while Host watch authority or+ // the Host UID/spec generation changed. Revalidate at the destructive+ // commit boundary so a stale secretRef can never tear down the current+ // runtime; the recovered/current Host reconcile will decide again.+ revalidateHostMutationBoundary()await this.deleteHostRuntimeResources(host.name, host.namespace, {deleteWorkspacePvc: false,})@@ -3626,8 +3757,11 @@ export class HostReconciler {// Per-Host SA + Role + RoleBinding must exist BEFORE the Deployment,// otherwise the kubelet can't mount the SA token and the pod will// crash-loop until RBAC is created.+ revalidateHostMutationBoundary()await this.ensureHostServiceAccount(host)+ revalidateHostMutationBoundary()await this.ensureHostRole(host)+ revalidateHostMutationBoundary()await this.ensureHostRoleBinding(host)let mounts: ResolvedSfsMount[] = []@@ -3640,10 +3774,12 @@ export class HostReconciler {// will inject them.console.error(`[HostReconciler] Failed to resolve context mounts for "${host.name}":`, err)}+ revalidateHostMutationBoundary()// Stateless lifecycle (Stage 2): assess enable/reject and persist the// durable state to the Host status subresource BEFORE building the// Deployment, so replicas derive from the same assessment.let lifecycle = await this.lifecycle.assessLifecycle(host, mounts)+ revalidateHostMutationBoundary()// Drained-pre-scale guard (Stage 4.3): a pending wake must abort the// suspension IMMEDIATELY before replicas:0 derives from this assessment// — see StatelessLifecycleExecutor.resolveWakeBeforeScaleDown. A null@@ -3651,14 +3787,17 @@ export class HostReconciler {// pass (the periodic resync retries) rather than scaling to 0 on stale// data.const guardedLifecycle = await this.lifecycle.resolveWakeBeforeScaleDown(host, lifecycle)+ revalidateHostMutationBoundary()if (guardedLifecycle === null) {return}lifecycle = guardedLifecycle+ revalidateHostMutationBoundary()const lifecycleStatusCommitted = await this.lifecycle.writeLifecycleStatusToCluster(host,lifecycle)+ revalidateHostMutationBoundary()if (lifecycleStatusCommitted) {this.enqueueHostTelemetry(host, 'lifecycle_transition', lifecycle.effective.state, {status: 'committed',@@ -3669,7 +3808,9 @@ export class HostReconciler {})}+ revalidateHostMutationBoundary()await this.ensurePvc(host)+ revalidateHostMutationBoundary()await this.ensureService(host)// NetworkPolicies before Deployments. Calico/Cilium evaluate egress and@@ -3685,23 +3826,31 @@ export class HostReconciler {// surface it via HostRuntimeStatus instead of swallowing it.const npFailures: string[] = []try {+ revalidateHostMutationBoundary()await this.ensureMcpHostIngressNetworkPolicy(host)+ revalidateHostMutationBoundary()await this.ensureMcpHostGfsEgressNetworkPolicy(host)+ revalidateHostMutationBoundary()await this.ensureWorkflowApprovalReaderMcpHostIngressNetworkPolicy(host)} catch (err) {console.error(`[HostReconciler] Failed to ensure mcp-host NP for "${host.name}":`, err)npFailures.push(`mcp-host NP: ${(err as Error).message}`)}try {+ revalidateHostMutationBoundary()await this.ensureRpcProxyMcpHostIngressNetworkPolicy(host)+ revalidateHostMutationBoundary()await this.ensureRpcProxyHostEgressNetworkPolicy(host)} catch (err) {console.error(`[HostReconciler] Failed to ensure rpc-proxy host NP for "${host.name}":`, err)npFailures.push(`rpc-proxy NP: ${(err as Error).message}`)}+ revalidateHostMutationBoundary()await this.ensureDesktopNetworkPolicy(host)try {+ revalidateHostMutationBoundary()await this.ensureChannelReaderEgressNetworkPolicy(host)+ revalidateHostMutationBoundary()await this.ensureWorkflowApprovalReaderHostEgressNetworkPolicy(host)} catch (err) {console.error(`[HostReconciler] Failed to ensure channels egress NP for "${host.name}":`, err)@@ -3716,8 +3865,10 @@ export class HostReconciler {)if (bootstrapLifecycle !== lifecycle) {lifecycle = bootstrapLifecycle+ revalidateHostMutationBoundary()await this.lifecycle.writeLifecycleStatusToCluster(host, lifecycle)}+ revalidateHostMutationBoundary()// Bootstrap captures the scope contract used for issuance. The Deployment// guard below compares that contract with the live channel cache after this@@ -3726,23 +3877,28 @@ export class HostReconciler {forceFreshForWake,targetSuspended: lifecycle.effective.stateless && lifecycle.effective.state === 'suspended',})+ revalidateHostMutationBoundary()// replaceWithConflictRetry may wait and re-read after a 409, so each body is// rebuilt from a stable lifecycle plus token-scope pair before mutation.const resolveDeploymentLifecycle = async (): Promise<EffectiveHostLifecycle> => {+ revalidateHostMutationBoundary()const deploymentLifecycle = this.lifecycle.enforceCommunicationChannelPolicyBeforeDeployment(host.name,lifecycle)if (deploymentLifecycle !== lifecycle) {lifecycle = deploymentLifecycle+ revalidateHostMutationBoundary()await this.lifecycle.writeLifecycleStatusToCluster(host, lifecycle)}+ revalidateHostMutationBoundary()return lifecycle.effective}const ensureCurrentRuntimeTokenScope = async (): Promise<void> => {for (let attempt = 1; attempt <= 3; attempt++) {+ revalidateHostMutationBoundary()const currentScopeHash = HostReconciler.runtimeTokenScopeHash(host,this.hasChannelIngress(host)@@ -3754,6 +3910,7 @@ export class HostReconciler {targetSuspended:lifecycle.effective.stateless && lifecycle.effective.state === 'suspended',})+ revalidateHostMutationBoundary()const postProvisionScopeHash = HostReconciler.runtimeTokenScopeHash(host,this.hasChannelIngress(host)@@ -3773,6 +3930,7 @@ export class HostReconciler {const resolveDeploymentState = async (): Promise<DeploymentMutationState> => {for (let attempt = 1; attempt <= 3; attempt++) {+ revalidateHostMutationBoundary()await resolveDeploymentLifecycle()await ensureCurrentRuntimeTokenScope()const effective = await resolveDeploymentLifecycle()@@ -3781,6 +3939,7 @@ export class HostReconciler {this.hasChannelIngress(host))if (runtimeTokenProvision.scopeHash === currentScopeHash) {+ revalidateHostMutationBoundary()return {lifecycle: effective,runtimeTokenRevision: runtimeTokenProvision.revision,@@ -3797,6 +3956,7 @@ export class HostReconciler {)}+ revalidateHostMutationBoundary()await this.ensureDeployment(host,mounts,@@ -3804,6 +3964,7 @@ export class HostReconciler {lifecycle.effective,resolveDeploymentState)+ revalidateHostMutationBoundary()const suspended = lifecycle.effective.stateless && lifecycle.effective.state === 'suspended'if (suspended) {@@ -3812,6 +3973,7 @@ export class HostReconciler {this.lifecycle.markHostNotSuspended(host.name)}const ready = suspended ? false : await this.checkDeploymentReady(host.name, host.namespace)+ revalidateHostMutationBoundary()// If any per-Host NP failed to apply, mark the host as degraded:// deployed remains true (the pod is in place), but ready=false +// a message that names the missing security boundary. Operators see@@ -3847,6 +4009,7 @@ export class HostReconciler {() => this.reconcileChannelReaderDeployment(host),]) {try {+ revalidateHostMutationBoundary()await reconcileResource()} catch (err) {channelReaderFailures.push(err)@@ -3867,6 +4030,7 @@ export class HostReconciler {// Best-effort — checkChannelReaderStatus never throws.const ccCount = this.countCommunicationChannels(host.name)const channelReaderStatus = await this.checkChannelReaderStatus(host.name, ccCount)+ revalidateHostMutationBoundary()if (channelReaderFailures.length > 0) {// Overlay the reconcile error onto the status message so both signals// are visible (the deploy error may explain why the Deployment is missing).@@ -3908,11 +4072,13 @@ export class HostReconciler {namespace: string,opts?: { skipIf?: () => boolean }): Promise<void> {+ const capturedAuthority = this.captureHostMutationAuthority()// A DELETED event must not race an in-flight create/update for the same// Host: route it through the same per-Host serializer as reconcile(). The// global convergence tail no longer provides this ordering.await this.lifecycle.serializeByHost(name, async () => {- if (opts?.skipIf?.()) {+ this.requireHostMutationAuthority(`Host "${name}" delete`, capturedAuthority)+ if (this.resolveCurrentHost?.(name) !== undefined || opts?.skipIf?.()) {// Same vocabulary the watch path already reports for this condition// (reconcileHostWatchEvent), so the skip is observable, not silent.hostDeleteCleanupTotal.inc({ outcome: 'superseded' })@@ -4059,6 +4225,15 @@ export class HostReconciler {}try {await this.lifecycle.serializeByHost(hostName, async () => {+ // The fresh 404 and the cache omission are only destructive+ // authority while the same LIST -> WATCH generation remains live.+ // Revalidate inside the serializer: queued Host work can otherwise+ // outlive that generation and delete a same-name recreation whose+ // ADDED event has not reached the retired cache.+ if (!authorityValid()) {+ hostCleanupDeferredTotal.inc({ reason: 'watch_lost' })+ return+ }// F2 / #827 TOCTOU: a same-name Host recreated between the fresh read// above and admission into this serializer updates the current cache// (its ADDED event sets the cache before its reconcile runs, and thatdiff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 7de8392f2..d3f612e01 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -9,6 +9,7 @@ import {listAllGlobalFileSystems,listAllHosts,} from './k8sClient'+import { registry } from './metrics'import { ContextMapperServer } from './server'import type { HostCRD } from './types'@@ -32,6 +33,18 @@ async function flushMicrotasks(turns = 8): Promise<void> {}}+async function readInitialConvergenceMetric(+ name:+ | 'clerum_hcc_initial_convergence_retries_total'+ | 'clerum_hcc_initial_convergence_last_success_timestamp_seconds',+ lane: 'McpServer' | 'NetworkPolicy'+): Promise<number> {+ const metric = registry.getSingleMetric(name)+ if (!metric) throw new Error(`${name} is not registered`)+ const snapshot = await metric.get()+ return snapshot.values.find(entry => entry.labels.lane === lane)?.value ?? 0+}+async function requestReadyOverHttp(server: ContextMapperServer): Promise<{statusCode: number | undefinedbody: string@@ -75,6 +88,10 @@ function stubAuthoritativeInventoryWatch(})}+function markHostInventoryAuthoritative(watcher: McpServerWatcher): void {+ ;(watcher as any).hostCacheSynced = true+}+const mocks = vi.hoisted(() => {const listNamespacedCustomObject = vi.fn()const getNamespacedCustomObject = vi@@ -235,6 +252,7 @@ vi.mock('./hostReconciler', () => ({// B2: mock the CC cache-sync setter so McpServerWatcher constructor succeeds.setIsCommunicationChannelCacheSynced = vi.fn()patchChannelReaderRevisionAnnotation = vi.fn().mockResolvedValue(undefined)+ reconcileChannelReaderRevision = vi.fn().mockResolvedValue(undefined)},}))@@ -263,6 +281,7 @@ vi.mock('./sharedFileSystemReconciler', () => ({reconcileDelete = vi.fn()getStatus = vi.fn()setListContextRefs = vi.fn()+ isMountable = vi.fn().mockReturnValue(false)},}))@@ -344,6 +363,189 @@ describe('McpServerWatcher startup', () => {}})+ it.each(['LIST', 'WATCH'] as const)(+ 'stays live and recovers readiness after a transient Host %s bootstrap failure',+ async failureBoundary => {+ vi.useFakeTimers()+ let hostListAttempts = 0+ let hostWatchAttempts = 0+ mocks.listNamespacedCustomObject.mockImplementation(+ async ({ plural }: { plural: string }) => {+ if (plural === 'hosts') {+ hostListAttempts += 1+ if (failureBoundary === 'LIST' && hostListAttempts === 1) {+ throw new Error('host discovery temporarily unavailable')+ }+ return { metadata: { resourceVersion: 'host-recovery-rv' }, items: [] }+ }+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'cc-rv' }, items: [] }+ }+ return { items: [] }+ }+ )+ mocks.watch.mockImplementation(async path => {+ if (path.endsWith('/hosts')) {+ hostWatchAttempts += 1+ if (failureBoundary === 'WATCH' && hostWatchAttempts === 1) {+ throw new Error('host watch temporarily unavailable')+ }+ }+ return { abort: vi.fn() }+ })+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const watcher = new McpServerWatcher()+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')+ vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)+ vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)+ const server = new ContextMapperServer(watcher, 0, undefined, undefined, () =>+ watcher.isReadinessInventoryAuthoritative()+ )+ await server.start()++ try {+ await expect(watcher.start()).resolves.toBeUndefined()+ server.setReady(true)++ expect(watcher.isReadinessInventoryAuthoritative()).toBe(false)+ expect((await requestReadyOverHttp(server)).statusCode).toBe(503)+ await vi.waitFor(() => expect(mocks.serverFullReconcile).toHaveBeenCalledOnce())+ await vi.waitFor(() => expect(mocks.netPolFullReconcile).toHaveBeenCalledOnce())+ expect((watcher as any).hostCacheRecoveryTimer).not.toBeNull()++ await vi.advanceTimersByTimeAsync(5000)+ await vi.waitFor(() => expect(watcher.isReadinessInventoryAuthoritative()).toBe(true))+ await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledOnce())++ expect(hostListAttempts).toBe(2)+ expect(hostWatchAttempts).toBe(failureBoundary === 'LIST' ? 1 : 2)+ expect((watcher as any).ccAppliedLifecycleGeneration).toBe(1)+ expect((await requestReadyOverHttp(server)).statusCode).toBe(200)+ } finally {+ await server.stop()+ await watcher.stop()+ errorSpy.mockRestore()+ warnSpy.mockRestore()+ }+ }+ )++ it('cancels a pending Host bootstrap recovery when the watcher stops', async () => {+ vi.useFakeTimers()+ let hostListAttempts = 0+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'hosts') {+ hostListAttempts += 1+ throw new Error('host inventory remains unavailable')+ }+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'cc-rv' }, items: [] }+ }+ return { items: [] }+ })+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const watcher = new McpServerWatcher()+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')+ vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)+ vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)++ try {+ await watcher.start()+ expect((watcher as any).hostCacheRecoveryTimer).not.toBeNull()++ await watcher.stop()+ await vi.advanceTimersByTimeAsync(5000)++ expect(hostListAttempts).toBe(1)+ expect((watcher as any).hostCacheRecoveryTimer).toBeNull()+ expect((watcher as any).hostCacheRecoveryIntent).toBeNull()+ } finally {+ await watcher.stop()+ errorSpy.mockRestore()+ warnSpy.mockRestore()+ }+ })++ it('defers every Host-dependent effect while a bootstrap LIST lacks WATCH authority', async () => {+ vi.useFakeTimers()+ const staleHost = {+ metadata: {+ name: 'stale-bootstrap-host',+ namespace: 'mcp-host',+ generation: 1,+ uid: 'stale-bootstrap-host-uid',+ },+ spec: {+ host: 'stale-bootstrap-host',+ contextRef: 'bootstrap-context',+ secretRef: 'bootstrap-secret',+ model: { provider: 'openai', name: 'gpt-4o-mini' },+ },+ }+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'hosts') {+ return {+ metadata: { resourceVersion: 'stale-bootstrap-rv' },+ items: [staleHost],+ }+ }+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'cc-rv' }, items: [] }+ }+ return { items: [] }+ })+ mocks.watch.mockImplementation(async path => {+ if (path.endsWith('/hosts')) {+ throw new Error('host watch remains unavailable')+ }+ return { abort: vi.fn() }+ })+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const watcher = new McpServerWatcher()+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')+ vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)+ vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)+ const hostReconciler = (watcher as any).hostReconciler++ try {+ await watcher.start()+ expect(watcher.isReadinessInventoryAuthoritative()).toBe(false)++ expect(watcher.getHost('stale-bootstrap-host')).toBeUndefined()+ const ccWatchCallback = (watcher as any).getCommunicationChannelWatchCallback()+ await ccWatchCallback('ADDED', {+ metadata: { name: 'bootstrap-channel', namespace: 'channels' },+ spec: { hostRef: 'stale-bootstrap-host' },+ })+ ;(watcher as any).contexts.set('bootstrap-context', {+ name: 'bootstrap-context',+ namespace: 'mcp-server',+ spec: {+ contextId: 'bootstrap-context',+ sharedFileSystems: [{ name: 'bootstrap-sfs', mountPath: '/shared' }],+ },+ })+ await (watcher as any).reconcileHostsReferencingSfs('bootstrap-sfs')+ await (watcher as any).reconcileHostsReferencingContext('bootstrap-context')+ await (watcher as any).reconcileChannelReaderRevision('bootstrap-channel-secret', 'channels')++ expect(hostReconciler.reconcile).not.toHaveBeenCalled()+ expect(hostReconciler.patchChannelReaderRevisionAnnotation).not.toHaveBeenCalled()+ expect(hostReconciler.reconcileChannelReaderRevision).not.toHaveBeenCalled()+ expect((watcher as any).hostCacheRecoveryTimer).not.toBeNull()+ } finally {+ await watcher.stop()+ errorSpy.mockRestore()+ warnSpy.mockRestore()+ }+ })+it('starts McpServer and Context watches from their inventory resourceVersions', async () => {const watcher = new McpServerWatcher()@@ -675,6 +877,7 @@ 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()@@ -692,11 +895,11 @@ describe('McpServerWatcher startup', () => {expect(startGlobalFileSystemWatch).toHaveBeenCalledOnce()expect(watcher.isCommunicationChannelCacheSynced()).toBe(true)- // The control-plane lane is serial by design: NetworkPolicy full- // reconciliation cannot overlap the older McpServer fleet pass and- // therefore cannot run stale orphan cleanup after it.- initialServerFleet.resolve(undefined)- await vi.waitFor(() => expect(mocks.netPolFullReconcile).toHaveBeenCalledOnce())+ // 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.+ expect(mocks.serverFullReconcile).toHaveBeenCalledOnce()+ expect(mocks.netPolFullReconcile).toHaveBeenCalledOnce()} finally {initialServerFleet.resolve(undefined)initialNetworkPolicies.resolve(undefined)@@ -959,6 +1162,100 @@ describe('McpServerWatcher startup', () => {await watcher.stop()})+ it('continues a same-server reconciliation lane after a rejected operation', async () => {+ const watcher = new McpServerWatcher()+ const server = { name: 'retry-safe-server', namespace: 'mcp-server' }+ const order: string[] = []+ const firstStarted = deferred()+ const rejectFirst = deferred()++ const rejected = (watcher as any).enqueueMcpServerReconciliation(server, async () => {+ order.push('rejected')+ firstStarted.resolve(undefined)+ await rejectFirst.promise+ throw new Error('transient lane failure')+ }) as Promise<void>+ await firstStarted.promise+ const recovered = (watcher as any).enqueueMcpServerReconciliation(server, async () => {+ order.push('recovered')+ }) as Promise<void>+ rejectFirst.resolve(undefined)++ await expect(rejected).rejects.toThrow('transient lane failure')+ await expect(recovered).resolves.toBeUndefined()+ expect(order).toEqual(['rejected', 'recovered'])+ expect((watcher as any).mcpServerReconciliationQueues.size).toBe(0)+ await watcher.stop()+ })++ it('revalidates env-Secret matches inside each server lane before reconciling', async () => {+ const currentServer = {+ name: 'current-secret-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'clerum/current-secret-server:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ envSecret: { name: 'shared-env' },+ },+ }+ const staleServer = {+ name: 'stale-secret-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'clerum/stale-secret-server:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ envSecret: { name: 'shared-env' },+ },+ }+ const unrelatedServer = {+ name: 'unrelated-secret-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'clerum/unrelated-secret-server:test',+ transport: { type: 'streamableHttp' as const, port: 3000 },+ envSecret: { name: 'other-env' },+ },+ }+ const blockerStarted = deferred()+ const releaseBlocker = deferred()+ const watcher = new McpServerWatcher()+ const reconciler = (watcher as any).reconciler+ for (const server of [currentServer, staleServer, unrelatedServer]) {+ ;(watcher as any).servers.set(server.name, server)+ }++ const blocker = (watcher as any).enqueueMcpServerReconciliation(staleServer, async () => {+ blockerStarted.resolve(undefined)+ await releaseBlocker.promise+ })+ await blockerStarted.promise++ const convergence = watcher.reconcileByEnvSecret('shared-env', 'mcp-server')+ ;(watcher as any).servers.set(staleServer.name, {+ ...staleServer,+ spec: { ...staleServer.spec, envSecret: { name: 'replacement-env' } },+ })+ await vi.waitFor(() =>+ expect(reconciler.reconcile).toHaveBeenCalledWith(+ expect.objectContaining({ name: currentServer.name })+ )+ )+ releaseBlocker.resolve(undefined)+ await Promise.all([blocker, convergence])++ expect(reconciler.reconcile).toHaveBeenCalledTimes(1)+ expect(reconciler.reconcile).not.toHaveBeenCalledWith(+ expect.objectContaining({ name: staleServer.name })+ )+ expect(reconciler.reconcile).not.toHaveBeenCalledWith(+ expect.objectContaining({ name: unrelatedServer.name })+ )+ await watcher.stop()+ })+it('admits an initial server without egress while another initial server waits on DNS', async () => {const dnsBlockedServer = {name: 'dns-blocked-server',@@ -1529,6 +1826,12 @@ describe('McpServerWatcher startup', () => {releaseGfsList.resolve({ items: [staleGfs] })await Promise.all([sfsResync, gfsResync, sfsWatch, gfsWatch])+ expect(mocks.sfsFullReconcile).toHaveBeenCalledWith([+ expect.objectContaining({ name: 'current-sfs' }),+ ])+ expect(gfsReconciler.fullReconcile).toHaveBeenCalledWith([+ expect.objectContaining({ name: 'current-gfs' }),+ ])expect((watcher as any).sharedFileSystems.get('current-sfs')).toEqual(expect.objectContaining({ name: 'current-sfs' }))@@ -1540,6 +1843,41 @@ describe('McpServerWatcher startup', () => {await watcher.stop()})+ it('refreshes SFS and GFS caches and effects from an uncontested periodic inventory', async () => {+ const listedSfs = {+ metadata: { name: 'listed-sfs', namespace: 'mcp-host' },+ spec: { capacity: '1Gi' },+ }+ const listedGfs = {+ metadata: { name: 'listed-gfs', namespace: 'gfs' },+ spec: { capacity: '10Gi' },+ }+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'sharedfilesystems') return { items: [listedSfs] }+ if (plural === 'globalfilesystems') return { items: [listedGfs] }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()+ const gfsReconciler = (watcher as any).gfsReconciler+ const gfsFullReconcile = vi.spyOn(gfsReconciler, 'fullReconcile').mockResolvedValue(undefined)++ await Promise.all([(watcher as any).runSfsResync(), (watcher as any).runGfsResync()])++ expect((watcher as any).sharedFileSystems.get('listed-sfs')).toEqual(+ expect.objectContaining({ name: 'listed-sfs', spec: listedSfs.spec })+ )+ expect((watcher as any).globalFileSystems.get('listed-gfs')).toEqual(+ expect.objectContaining({ name: 'listed-gfs', spec: listedGfs.spec })+ )+ expect(mocks.sfsFullReconcile).toHaveBeenCalledWith([+ expect.objectContaining({ name: 'listed-sfs', spec: listedSfs.spec }),+ ])+ expect(gfsFullReconcile).toHaveBeenCalledWith([+ expect.objectContaining({ name: 'listed-gfs', spec: listedGfs.spec }),+ ])+ await watcher.stop()+ })+it('does not run queued fleet effects after the watcher stops', async () => {const initialServer = {name: 'initial-server',@@ -1590,6 +1928,34 @@ describe('McpServerWatcher startup', () => {expect(reconciler.reconcile).not.toHaveBeenCalled()})+ it.each([+ ['SharedFileSystem', 'enqueueSharedFileSystemReconciliation'],+ ['GlobalFileSystem', 'enqueueGlobalFileSystemReconciliation'],+ ] as const)(+ 'does not admit queued %s effects after the watcher stops',+ async (_, enqueueMethod) => {+ const firstStarted = deferred()+ const releaseFirst = deferred()+ const watcher = new McpServerWatcher()+ let queuedEffectRan = false++ const first = (watcher as any)[enqueueMethod](async () => {+ firstStarted.resolve(undefined)+ await releaseFirst.promise+ }) as Promise<void>+ await firstStarted.promise+ const queued = (watcher as any)[enqueueMethod](async () => {+ queuedEffectRan = true+ }) as Promise<void>++ await watcher.stop()+ releaseFirst.resolve(undefined)+ await Promise.all([first, queued])++ expect(queuedEffectRan).toBe(false)+ }+ )+it('keeps an incomplete McpServer inventory non-authoritative across NetworkPolicy retries', async () => {vi.useFakeTimers()const watcher = new McpServerWatcher()@@ -1657,7 +2023,7 @@ describe('McpServerWatcher startup', () => {await watcher.stop()})- it('retries failed initial McpServer convergence without delaying safe bootstrap', async () => {+ it('escalates and resets failed initial McpServer convergence without delaying bootstrap', async () => {vi.useFakeTimers()const server = {metadata: { name: 'initial-runtime', namespace: 'mcp-server' },@@ -1677,8 +2043,13 @@ describe('McpServerWatcher startup', () => {})mocks.serverFullReconcile.mockRejectedValueOnce(new Error('initial runtime reconciliation failed'))+ .mockRejectedValueOnce(new Error('initial runtime reconciliation still unavailable')).mockResolvedValueOnce(undefined)const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ const retryMetricBefore = await readInitialConvergenceMetric(+ 'clerum_hcc_initial_convergence_retries_total',+ 'McpServer'+ )const watcher = new McpServerWatcher()stubAuthoritativeInventoryWatch(watcher, 'McpServer')stubAuthoritativeInventoryWatch(watcher, 'Context')@@ -1693,7 +2064,50 @@ describe('McpServerWatcher startup', () => {await vi.advanceTimersByTimeAsync(5000)expect(mocks.serverFullReconcile).toHaveBeenCalledTimes(2)- watcher.stop()+ await vi.advanceTimersByTimeAsync(14_999)+ expect(mocks.serverFullReconcile).toHaveBeenCalledTimes(2)+ await vi.advanceTimersByTimeAsync(1)+ expect(mocks.serverFullReconcile).toHaveBeenCalledTimes(3)+ expect((watcher as any).initialConvergenceRetryAttempts.has('McpServer')).toBe(false)+ expect((watcher as any).initialConvergenceRetryTimers.has('McpServer')).toBe(false)+ expect(+ await readInitialConvergenceMetric(+ 'clerum_hcc_initial_convergence_retries_total',+ 'McpServer'+ )+ ).toBe(retryMetricBefore + 2)+ expect(+ await readInitialConvergenceMetric(+ 'clerum_hcc_initial_convergence_last_success_timestamp_seconds',+ 'McpServer'+ )+ ).toBeGreaterThan(0)++ await watcher.stop()+ errorSpy.mockRestore()+ })++ it('cancels a pending initial convergence retry when the watcher stops', async () => {+ vi.useFakeTimers()+ const watcher = new McpServerWatcher()+ ;(watcher as any).mcpServerCacheSynced = true+ mocks.serverFullReconcile.mockRejectedValueOnce(+ new Error('initial runtime reconciliation unavailable')+ )+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})++ await (watcher as any).runInitialMcpServerConvergence()++ expect(mocks.serverFullReconcile).toHaveBeenCalledTimes(1)+ expect((watcher as any).initialConvergenceRetryAttempts.get('McpServer')).toBe(1)+ expect((watcher as any).initialConvergenceRetryTimers.has('McpServer')).toBe(true)++ await watcher.stop()+ await vi.advanceTimersByTimeAsync(300_000)++ expect(mocks.serverFullReconcile).toHaveBeenCalledTimes(1)+ expect((watcher as any).initialConvergenceRetryAttempts.size).toBe(0)+ expect((watcher as any).initialConvergenceRetryTimers.size).toBe(0)errorSpy.mockRestore()})@@ -2721,6 +3135,7 @@ describe('McpServerWatcher wires CC counter into HostReconciler', () => {describe('McpServerWatcher.reconcileHostsReferencingCC', () => {it('re-reconciles the Host whose name matches the CC hostRef', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const hosts = (watcher as any).hosts as Map<string, { name: string; spec: any }>hosts.set('marketing', {name: 'marketing',@@ -2739,6 +3154,7 @@ describe('McpServerWatcher.reconcileHostsReferencingCC', () => {it('is a no-op when the hostRef does not match any cached Host', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const reconcileSpy = vi.spyOn(watcher.getHostReconciler(), 'reconcile').mockResolvedValue(undefined)@@ -2750,6 +3166,7 @@ describe('McpServerWatcher.reconcileHostsReferencingCC', () => {it('reports reconcile errors without throwing so the watch can schedule recovery', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const hosts = (watcher as any).hosts as Map<string, { name: string; spec: any }>hosts.set('marketing', {name: 'marketing',@@ -2767,6 +3184,7 @@ describe('McpServerWatcher.reconcileHostsReferencingCC', () => {it('schedules lifecycle convergence when a targeted CC event reconcile fails', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher);(watcher as any).hosts.set('marketing', {name: 'marketing',namespace: 'mcp-host',@@ -4400,6 +4818,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {.mockResolvedValue(undefined)await (watcher as any).startHostWatch('test-host-rv')if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ markHostInventoryAuthoritative(watcher)await hostWatchCallback('MODIFIED', {metadata: { name: 'retry-before-list', namespace: 'mcp-host', generation: 1 },@@ -4408,6 +4827,9 @@ describe('McpServerWatcher Host periodic resync serialization', () => {expect(reconcile).toHaveBeenCalledTimes(1)expect((watcher as any).hostWatchRetryTimers.size).toBe(1)+ // The active Host watch is then lost. A full request must recover a fresh+ // snapshot and retire the failed event's pending retry.+ ;(watcher as any).hostCacheSynced = falseawait (watcher as any).requestHostFleetReconcile('Periodic resync', undefined, 'full')expect((watcher as any).hostWatchRetryTimers.size).toBe(0)@@ -4575,6 +4997,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {})await (watcher as any).startHostWatch('test-host-rv')if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ markHostInventoryAuthoritative(watcher)const first = hostWatchCallback('MODIFIED', {metadata: { name: 'host-a', namespace: 'mcp-host', generation: 1 },@@ -4856,6 +5279,183 @@ describe('McpServerWatcher Host watch generation', () => {vi.useRealTimers()})+ it('folds a newer lifecycle generation into an in-flight Host inventory recovery', async () => {+ const hostListStarted = deferred()+ const hostList = deferred<{+ metadata: { resourceVersion: string }+ items: unknown[]+ }>()+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'hosts') {+ hostListStarted.resolve(undefined)+ return hostList.promise+ }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()+ const fleetRequest = vi+ .spyOn(watcher as any, 'requestHostFleetReconcile')+ .mockResolvedValue(undefined)++ const recovery = (watcher as any).recoverHostInventoryAndWatch(+ 'Host watch recovery convergence',+ 1,+ 'watch-recovery'+ ) as Promise<unknown>+ await hostListStarted.promise+ const joined = (watcher as any).recoverHostInventoryAndWatch(+ 'initial Host reconciliation',+ 2,+ 'cold-start'+ ) as Promise<unknown>++ expect(joined).toBe(recovery)+ hostList.resolve({ metadata: { resourceVersion: 'joined-host-rv' }, items: [] })+ await Promise.all([recovery, joined])++ expect(fleetRequest).toHaveBeenCalledOnce()+ expect(fleetRequest).toHaveBeenCalledWith('initial Host reconciliation', 2, 'full')+ await watcher.stop()+ })++ it('adopts a pending cold-start intent when a direct Host recovery starts first', async () => {+ vi.useFakeTimers()+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'hosts') {+ return { metadata: { resourceVersion: 'adopted-host-rv' }, items: [] }+ }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()+ const fleetRequest = vi+ .spyOn(watcher as any, 'requestHostFleetReconcile')+ .mockResolvedValue(undefined)++ ;(watcher as any).scheduleHostCacheRecovery({+ convergenceReason: 'initial Host reconciliation',+ ccLifecycleGeneration: 2,+ cause: 'cold-start',+ })+ expect((watcher as any).hostCacheRecoveryTimer).not.toBeNull()++ await (watcher as any).recoverHostInventoryAndWatch(+ 'Host watch recovery convergence',+ 1,+ 'watch-recovery'+ )++ expect(mocks.listNamespacedCustomObject).toHaveBeenCalledTimes(1)+ expect(fleetRequest).toHaveBeenCalledOnce()+ expect(fleetRequest).toHaveBeenCalledWith('initial Host reconciliation', 2, 'full')+ expect((watcher as any).hostCacheRecoveryTimer).toBeNull()+ expect((watcher as any).hostCacheRecoveryIntent).toBeNull()+ await watcher.stop()+ })++ it('folds a recovery intent scheduled while Host LIST is in flight into the successful pass', async () => {+ vi.useFakeTimers()+ const hostListStarted = deferred()+ const hostList = deferred<{+ metadata: { resourceVersion: string }+ items: unknown[]+ }>()+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'hosts') {+ hostListStarted.resolve(undefined)+ return hostList.promise+ }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()+ const fleetRequest = vi+ .spyOn(watcher as any, 'requestHostFleetReconcile')+ .mockResolvedValue(undefined)++ const recovery = (watcher as any).recoverHostInventoryAndWatch(+ 'Host watch recovery convergence',+ 1,+ 'watch-recovery'+ ) as Promise<unknown>+ await hostListStarted.promise+ ;(watcher as any).scheduleHostCacheRecovery({+ convergenceReason: 'CommunicationChannel event Host convergence',+ ccLifecycleGeneration: 3,+ cause: 'cold-start',+ })+ expect((watcher as any).hostCacheRecoveryTimer).not.toBeNull()+ hostList.resolve({ metadata: { resourceVersion: 'in-flight-intent-rv' }, items: [] })+ await recovery++ expect(fleetRequest).toHaveBeenCalledOnce()+ expect(fleetRequest).toHaveBeenCalledWith(+ 'CommunicationChannel event Host convergence',+ 3,+ 'full'+ )+ expect((watcher as any).hostCacheRecoveryTimer).toBeNull()+ expect((watcher as any).hostCacheRecoveryIntent).toBeNull()+ await watcher.stop()+ })++ it('preserves an in-flight recovery intent across failure and the scheduled retry', async () => {+ vi.useFakeTimers()+ const firstHostListStarted = deferred()+ const firstHostList = deferred<{+ metadata: { resourceVersion: string }+ items: unknown[]+ }>()+ let hostListCalls = 0+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural !== 'hosts') return { items: [] }+ hostListCalls += 1+ if (hostListCalls === 1) {+ firstHostListStarted.resolve(undefined)+ return firstHostList.promise+ }+ return { metadata: { resourceVersion: 'retry-preserved-rv' }, items: [] }+ })+ const watcher = new McpServerWatcher()+ const fleetRequest = vi+ .spyOn(watcher as any, 'requestHostFleetReconcile')+ .mockResolvedValue(undefined)+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})++ const recovery = (watcher as any).recoverHostInventoryAndWatch(+ 'Host watch recovery convergence',+ 1,+ 'watch-recovery'+ ) as Promise<unknown>+ await firstHostListStarted.promise+ ;(watcher as any).scheduleHostCacheRecovery({+ convergenceReason: 'CommunicationChannel event Host convergence',+ ccLifecycleGeneration: 3,+ cause: 'cold-start',+ })+ firstHostList.reject(new Error('transient Host LIST failure'))+ await expect(recovery).rejects.toThrow('transient Host LIST failure')++ expect((watcher as any).hostCacheRecoveryIntent).toEqual({+ convergenceReason: 'CommunicationChannel event Host convergence',+ ccLifecycleGeneration: 3,+ cause: 'cold-start',+ })+ expect((watcher as any).hostCacheRecoveryTimer).not.toBeNull()++ await vi.advanceTimersByTimeAsync(5_000)+ await vi.waitFor(() => expect(fleetRequest).toHaveBeenCalledOnce())++ expect(hostListCalls).toBe(2)+ expect(fleetRequest).toHaveBeenCalledWith(+ 'CommunicationChannel event Host convergence',+ 3,+ 'full'+ )+ expect((watcher as any).hostCacheRecoveryIntent).toBeNull()+ expect((watcher as any).hostCacheRecoveryTimer).toBeNull()+ errorSpy.mockRestore()+ await watcher.stop()+ })+it('rejects a Host snapshot that cannot anchor a continuing watch', async () => {mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {if (plural === 'hosts') return { metadata: {}, items: [] }@@ -5284,6 +5884,7 @@ describe('McpServerWatcher Host watch generation', () => {it('recovery diff enqueues an immediate per-Host delete for a disappeared Host (#827 item 1)', async () => {vi.clearAllMocks()const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const reconcileDelete = vi.spyOn(watcher.getHostReconciler(), 'reconcileDelete').mockResolvedValue(undefined)@@ -5315,6 +5916,7 @@ describe('McpServerWatcher Host watch generation', () => {it('recovery delete carries a live-cache fence for a Host recreated during admission (#827 F2 parity)', async () => {vi.clearAllMocks()const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const reconcileDelete = vi.spyOn(watcher.getHostReconciler(), 'reconcileDelete').mockResolvedValue(undefined)@@ -5349,6 +5951,7 @@ describe('McpServerWatcher Host watch generation', () => {it('recovery diff reconciles (does NOT delete) a same-name Host recreated with a new uid (#827 items 1+2)', async () => {vi.clearAllMocks()const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const reconcile = vi.spyOn(watcher.getHostReconciler(), 'reconcile').mockResolvedValue(undefined)@@ -5414,6 +6017,7 @@ describe('McpServerWatcher Host watch generation', () => {it('recovery urgently admits a wake-pending Host that is otherwise unchanged (§10.2 step 7 wake branch)', async () => {vi.clearAllMocks()const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const reconcile = vi.spyOn(watcher.getHostReconciler(), 'reconcile').mockResolvedValue(undefined)@@ -5510,6 +6114,7 @@ describe('McpServerWatcher Host watch generation', () => {.mockResolvedValue(undefined)await (watcher as any).startHostWatch('test-host-rv')if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ markHostInventoryAuthoritative(watcher)await hostWatchCallback('MODIFIED', {metadata: { name: 'retry-lane-host', namespace: 'mcp-host', generation: 2 },@@ -5560,6 +6165,7 @@ describe('McpServerWatcher Host watch generation', () => {await (watcher as any).startHostWatch('test-host-rv')const watchGeneration = (watcher as any).hostWatchGenerationif (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ markHostInventoryAuthoritative(watcher)await hostWatchCallback('ADDED', {metadata: { name: 'retry-host', namespace: 'mcp-host', generation: 1 },@@ -5601,6 +6207,7 @@ describe('McpServerWatcher Host watch generation', () => {.mockRejectedValue(new Error('persistent failure'))await (watcher as any).startHostWatch('test-host-rv')if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ markHostInventoryAuthoritative(watcher)await hostWatchCallback('ADDED', {metadata: { name: 'bounded-host', namespace: 'mcp-host', generation: 1 },@@ -5637,6 +6244,7 @@ describe('McpServerWatcher Host watch generation', () => {.mockResolvedValue(undefined)await (watcher as any).startHostWatch('test-host-rv')if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ markHostInventoryAuthoritative(watcher)await hostWatchCallback('ADDED', {metadata: { name: 'superseded-host', namespace: 'mcp-host', generation: 1 },@@ -5658,6 +6266,7 @@ describe('McpServerWatcher Host watch generation', () => {describe('McpServerWatcher.startCommunicationChannelWatch', () => {it('caches ADDED events and triggers Host reconcile', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const hosts = (watcher as any).hosts as Map<string, any>hosts.set('marketing', {name: 'marketing',@@ -5681,6 +6290,7 @@ describe('McpServerWatcher.startCommunicationChannelWatch', () => {it('removes from cache on DELETED and triggers Host reconcile', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const cache = (watcher as any).communicationChannels as Map<string, any>cache.set('cc-marketing', {name: 'cc-marketing',@@ -5709,6 +6319,7 @@ describe('McpServerWatcher.startCommunicationChannelWatch', () => {it('on MODIFIED with hostRef change, reconciles BOTH old and new hosts', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const cache = (watcher as any).communicationChannels as Map<string, any>cache.set('cc-1', {name: 'cc-1',@@ -5773,6 +6384,7 @@ describe('McpServerWatcher.startCommunicationChannelWatch', () => {describe('McpServerWatcher.startCommunicationChannelWatch — channel-reader revision rolls', () => {it('on CC ADDED, patches the new host channel-reader revision annotation', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const hosts = (watcher as any).hosts as Map<string, any>hosts.set('marketing', {name: 'marketing',@@ -5795,6 +6407,7 @@ describe('McpServerWatcher.startCommunicationChannelWatch — channel-reader revit('preserves credentialsSecretRef from the watch event into the cache', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const cache = (watcher as any).communicationChannels as Map<string, any>const hosts = (watcher as any).hosts as Map<string, any>hosts.set('marketing', {@@ -5825,6 +6438,7 @@ describe('McpServerWatcher.startCommunicationChannelWatch — channel-reader revit('on CC MODIFIED with hostRef change, patches BOTH old and new hosts', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const cache = (watcher as any).communicationChannels as Map<string, any>cache.set('cc-1', {name: 'cc-1',@@ -5859,6 +6473,7 @@ describe('McpServerWatcher.startCommunicationChannelWatch — channel-reader revit('on CC DELETED, patches the (former) host channel-reader revision annotation', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const cache = (watcher as any).communicationChannels as Map<string, any>cache.set('cc-marketing', {name: 'cc-marketing',@@ -5887,6 +6502,7 @@ describe('McpServerWatcher.startCommunicationChannelWatch — channel-reader revit('swallows patchChannelReaderRevisionAnnotation errors without breaking the watch loop', async () => {const watcher = new McpServerWatcher()+ markHostInventoryAuthoritative(watcher)const hosts = (watcher as any).hosts as Map<string, any>hosts.set('marketing', {name: 'marketing',diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex a7cd77fc7..e58f853aa 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -35,7 +35,13 @@ import {isMcpServerStatusOnlyUpdate,sameMcpServerDesiredRevision,} from './mcpServerSafety'-import { hostDeleteCleanupTotal, hostFleetRequestsTotal, hostWatchRecoverySeconds } from './metrics'+import {+ hostDeleteCleanupTotal,+ hostFleetRequestsTotal,+ hostWatchRecoverySeconds,+ initialConvergenceLastSuccessTimestampSeconds,+ initialConvergenceRetriesTotal,+} from './metrics'import { NetworkPolicyReconciler } from './networkPolicyReconciler'import { McpServerReconciler } from './reconciler'import { SharedFileSystemReconciler } from './sharedFileSystemReconciler'@@ -131,6 +137,38 @@ type HostWatchEventType = 'ADDED' | 'MODIFIED' | 'DELETED'type McpServerWatchEventType = 'ADDED' | 'MODIFIED' | 'DELETED'type InitialConvergenceLane = 'McpServer' | 'NetworkPolicy'+type HostInventoryRecoveryRequest = {+ convergenceReason: string+ ccLifecycleGeneration?: number+ cause: HostInventoryRecoveryCause+}++type ActiveHostInventoryRecovery = {+ request: HostInventoryRecoveryRequest+ promise: Promise<HostCRD[]>+}++function mergeHostInventoryRecoveryRequest(+ target: HostInventoryRecoveryRequest,+ requested: HostInventoryRecoveryRequest+): void {+ // Cold start is the stronger admission mode: its snapshot is consumed only+ // by the bounded full pass, whereas watch recovery also dispatches urgent+ // per-Host work. Preserve that mode when either joined caller requires it.+ if (requested.cause === 'cold-start' || target.cause !== 'cold-start') {+ target.convergenceReason = requested.convergenceReason+ }+ if (target.cause === 'cold-start' || requested.cause === 'cold-start') {+ target.cause = 'cold-start'+ }+ if (requested.ccLifecycleGeneration !== undefined) {+ target.ccLifecycleGeneration =+ target.ccLifecycleGeneration === undefined+ ? requested.ccLifecycleGeneration+ : Math.max(target.ccLifecycleGeneration, requested.ccLifecycleGeneration)+ }+}+/*** Serializes a reconciliation domain without turning a rejected operation into* a permanent queue failure. Kubernetes Watch invokes async callbacks without@@ -672,7 +710,8 @@ export class McpServerWatcher implements McpServerProvider {// (§10.2). Concurrent recovery signals reuse the in-flight promise so exactly// one LIST + WATCH is installed. Independent per-Host events no longer share a// process-wide convergence tail — they enter the per-Host serializer directly.- private hostRecoveryInFlight: Promise<HostCRD[]> | null = null+ private hostRecoveryInFlight: ActiveHostInventoryRecovery | null = null+ private hostCacheRecoveryIntent: HostInventoryRecoveryRequest | null = null// B2: tracks whether the CC snapshot is paired with a continuing watch.// Set to true only while a complete snapshot is paired with a live watch;// used by HostReconciler to make fail-closed lifecycle decisions.@@ -851,6 +890,37 @@ export class McpServerWatcher implements McpServerProvider {)}+ /**+ * Host-managed runtime mutation requires a LIST snapshot paired with its+ * continuing WATCH. This narrower predicate is also used by non-HTTP effect+ * producers while the broader readiness predicate additionally covers+ * McpServer and Context discovery authority.+ */+ isHostInventoryAuthoritative(): boolean {+ return !this.stopped && this.hostCacheSynced+ }++ /**+ * Fail closed at every Host-effect admission boundary while recovery owns+ * inventory authority. Preserve the reason/generation in the retry intent so+ * the successful LIST -> WATCH recovery's full pass applies the deferred+ * effect from current state instead of acting on the stale cache.+ */+ private admitHostDependentEffects(+ convergenceReason: string,+ ccLifecycleGeneration?: number+ ): boolean {+ if (this.isHostInventoryAuthoritative()) return true+ if (!this.stopped) {+ this.scheduleHostCacheRecovery({+ convergenceReason,+ ccLifecycleGeneration,+ cause: 'watch-recovery',+ })+ }+ return false+ }+private retireMcpServerWatch(expectedGeneration?: number): boolean {if (expectedGeneration !== undefined && expectedGeneration !== this.mcpWatchGeneration) {return false@@ -1323,24 +1393,38 @@ export class McpServerWatcher implements McpServerProvider {cause: HostInventoryRecoveryCause = 'watch-recovery'): Promise<HostCRD[]> {if (this.stopped) return Promise.resolve([])- if (this.hostRecoveryInFlight) return this.hostRecoveryInFlight- const recovery = this.performHostInventoryRecovery(- convergenceReason,- ccLifecycleGeneration,- cause- )- this.hostRecoveryInFlight = recovery+ const requested = { convergenceReason, ccLifecycleGeneration, cause }+ // A scheduled retry and an immediate caller are two entrances to the same+ // monotonic recovery intent. Adopt the pending request before choosing or+ // joining the active operation so a direct recovery cannot erase a stronger+ // cold-start cause or newer lifecycle generation when it cancels the timer.+ const request = this.hostCacheRecoveryIntent+ ? { ...this.hostCacheRecoveryIntent }+ : { ...requested }+ if (this.hostCacheRecoveryIntent) {+ mergeHostInventoryRecoveryRequest(request, requested)+ this.hostCacheRecoveryIntent = null+ if (this.hostCacheRecoveryTimer) {+ clearTimeout(this.hostCacheRecoveryTimer)+ this.hostCacheRecoveryTimer = null+ }+ }+ if (this.hostRecoveryInFlight) {+ mergeHostInventoryRecoveryRequest(this.hostRecoveryInFlight.request, request)+ return this.hostRecoveryInFlight.promise+ }+ const recovery = this.performHostInventoryRecovery(request)+ const active = { request, promise: recovery }+ this.hostRecoveryInFlight = activeconst clear = (): void => {- if (this.hostRecoveryInFlight === recovery) this.hostRecoveryInFlight = null+ if (this.hostRecoveryInFlight === active) this.hostRecoveryInFlight = null}void recovery.then(clear, clear)return recovery}private async performHostInventoryRecovery(- convergenceReason: string,- ccLifecycleGeneration: number | undefined,- cause: HostInventoryRecoveryCause+ request: HostInventoryRecoveryRequest): Promise<HostCRD[]> {const startedAt = Date.now()// Capture the pre-recovery inventory so step 7 can distinguish genuinely@@ -1386,11 +1470,19 @@ export class McpServerWatcher implements McpServerProvider {{ phase: 'total', outcome: 'success' },(Date.now() - startedAt) / 1000)+ // Effect producers can discover newer work while LIST/WATCH recovery is+ // already in flight. Fold that scheduled intent into this successful+ // operation before cancelling its timer so no lifecycle generation,+ // convergence reason, or stronger cold-start cause is discarded.+ if (this.hostCacheRecoveryIntent) {+ mergeHostInventoryRecoveryRequest(request, this.hostCacheRecoveryIntent)+ }if (this.hostCacheRecoveryTimer) {clearTimeout(this.hostCacheRecoveryTimer)this.hostCacheRecoveryTimer = null}- if (cause === 'watch-recovery') {+ this.hostCacheRecoveryIntent = null+ if (request.cause === 'watch-recovery') {this.enqueueRecoveredUrgentHosts(snapshot.hosts,previousNames,@@ -1405,7 +1497,11 @@ export class McpServerWatcher implements McpServerProvider {}// Request a coalesced background full pass, but do NOT await it before// declaring watch recovery complete.- void this.requestHostFleetReconcile(convergenceReason, ccLifecycleGeneration, 'full')+ void this.requestHostFleetReconcile(+ request.convergenceReason,+ request.ccLifecycleGeneration,+ 'full'+ )return snapshot.hosts} catch (error) {// Keep authority unknown, record the failure, and use the existing@@ -1417,7 +1513,7 @@ export class McpServerWatcher implements McpServerProvider {)if (!this.stopped) {console.error('[K8s] Host watch recovery failed:', error)- this.scheduleHostCacheRecovery()+ this.scheduleHostCacheRecovery(request)}throw error}@@ -1457,6 +1553,7 @@ export class McpServerWatcher implements McpServerProvider {private async dispatchUrgentHostReconcile(name: string): Promise<void> {if (this.stopped) return+ if (!this.admitHostDependentEffects('Recovered urgent Host convergence')) returnconst host = this.hosts.get(name)if (!host) returntry {@@ -1488,6 +1585,7 @@ export class McpServerWatcher implements McpServerProvider {private async dispatchRecoveredHostDelete(name: string): Promise<void> {if (this.stopped) return+ if (!this.admitHostDependentEffects('Recovered Host deletion convergence')) return// The fresh authoritative LIST already confirmed absence and the cache no// longer holds this Host, so cleanup is authorized. Route it through the// per-Host serializer (reconcileDelete → serializeByHost) so an older@@ -1519,13 +1617,30 @@ export class McpServerWatcher implements McpServerProvider {}}- private scheduleHostCacheRecovery(): void {- if (this.stopped || this.hostCacheRecoveryTimer) return+ private scheduleHostCacheRecovery(+ requested: HostInventoryRecoveryRequest = {+ convergenceReason: 'Host watch recovery convergence',+ cause: 'watch-recovery',+ }+ ): void {+ if (this.stopped) return+ if (this.hostCacheRecoveryIntent) {+ mergeHostInventoryRecoveryRequest(this.hostCacheRecoveryIntent, requested)+ } else {+ this.hostCacheRecoveryIntent = { ...requested }+ }+ if (this.hostCacheRecoveryTimer) returnthis.hostCacheRecoveryTimer = setTimeout(() => {this.hostCacheRecoveryTimer = null+ const request = this.hostCacheRecoveryIntent ?? requested+ this.hostCacheRecoveryIntent = null// Watch recovery is an independent operation, no longer coupled to a full// fleet pass. Recovery itself requests the background convergence pass.- void this.recoverHostInventoryAndWatch().catch(() => undefined)+ void this.recoverHostInventoryAndWatch(+ request.convergenceReason,+ request.ccLifecycleGeneration,+ request.cause+ ).catch(() => undefined)}, HOST_CACHE_RECOVERY_RETRY_MS)}@@ -1570,6 +1685,7 @@ export class McpServerWatcher implements McpServerProvider {source: HostReconcileSource = 'urgent'): Promise<void> {if (this.stopped) return+ if (!this.admitHostDependentEffects('Host watch event convergence')) returnif (!this.isCurrentHostWatchEvent(type, host, eventRevision)) {// #827: a DELETE that is no longer current because the cache now holds a// (recreated) same-name Host is a superseded delete — record it and do@@ -1664,6 +1780,7 @@ export class McpServerWatcher implements McpServerProvider {await this.recoverHostInventoryAndWatch()if (this.stopped) return}+ if (!this.isHostInventoryAuthoritative()) return// Reconcile the CURRENT cache. Fleet workers dispatch Host keys and// resolve the freshest cached spec at execution (see collectHostReconcile// Failures); only fullReconcile runs the authority-gated orphan cleanup.@@ -1892,6 +2009,9 @@ export class McpServerWatcher implements McpServerProvider {* Deployment template picks up (or drops) the volume + volumeMount.*/private async reconcileHostsReferencingSfs(sfsName: string): Promise<void> {+ if (!this.admitHostDependentEffects(`SharedFileSystem "${sfsName}" Host convergence`)) {+ return+ }const affectedContexts = new Set<string>()for (const ctx of this.contexts.values()) {if (ctx.spec.sharedFileSystems?.some(r => r.name === sfsName)) {@@ -1909,6 +2029,19 @@ export class McpServerWatcher implements McpServerProvider {}}+ /**+ * Reconcile Hosts affected by a Context change only while the Host cache is+ * authoritative. A recovery full pass consumes the current Context cache, so+ * deferral loses no effect and never acts on an unpaired Host LIST.+ */+ private async reconcileHostsReferencingContext(contextName: string): Promise<void> {+ if (!this.admitHostDependentEffects(`Context "${contextName}" Host convergence`)) return+ for (const host of this.hosts.values()) {+ if (host.spec.contextRef !== contextName) continue+ await this.hostReconciler.reconcile(host)+ }+ }+/*** Re-reconcile the Host whose name matches the given hostRef. Called by the* CommunicationChannel watch handler so per-Host channel-reader Deployment@@ -1921,6 +2054,9 @@ export class McpServerWatcher implements McpServerProvider {* its caller schedules bounded fleet convergence.*/private async reconcileHostsReferencingCC(hostRef: string): Promise<boolean> {+ if (!this.admitHostDependentEffects(`CommunicationChannel Host "${hostRef}" convergence`)) {+ return false+ }const host = this.hosts.get(hostRef)if (!host) return truetry {@@ -2012,9 +2148,23 @@ export class McpServerWatcher implements McpServerProvider {* tracker resolves the heartbeat's hostRef through this).*/getHost(name: string): HostCRD | undefined {+ if (!this.isHostInventoryAuthoritative()) return undefinedreturn this.hosts.get(name)}+ /**+ * Route channel credentials-Secret events through the same Host authority+ * boundary as watch, Context, SFS, and heartbeat effects.+ */+ async reconcileChannelReaderRevision(secretName: string, secretNamespace: string): Promise<void> {+ const convergenceReason = `CommunicationChannel Secret "${secretNamespace}/${secretName}" Host convergence`+ if (!this.ccCacheSynced) return+ if (!this.admitHostDependentEffects(convergenceReason)) {+ return+ }+ await this.hostReconciler.reconcileChannelReaderRevision(secretName, secretNamespace)+ }+/*** Trigger a reconcile for any cached McpServer whose `envSecret.name`* matches the given Secret. Used by SecretInformer to react to Secret@@ -2239,11 +2389,23 @@ export class McpServerWatcher implements McpServerProvider {this.ccLifecycleGeneration === 0? this.beginCommunicationChannelLifecycleTransition(): this.ccLifecycleGeneration- await this.recoverHostInventoryAndWatch(- 'initial Host reconciliation',- initialLifecycleGeneration,- 'cold-start'- )+ try {+ await this.recoverHostInventoryAndWatch(+ 'initial Host reconciliation',+ initialLifecycleGeneration,+ 'cold-start'+ )+ } catch (error) {+ // Host inventory is an essential readiness authority, but a transient+ // LIST/WATCH failure must not kill the retry that recovery just armed.+ // Continue startup with hostCacheSynced=false: the HTTP server stays live,+ // dynamic readiness remains 503, and recovery promotes readiness only+ // after a fresh LIST is paired with its continuing WATCH.+ console.warn(+ '[K8s] Initial Host inventory is unavailable; HCC remains unready while in-process recovery continues:',+ error+ )+ }const resyncSec = config.hostResyncIntervalSecif (resyncSec > 0) {@@ -2333,6 +2495,7 @@ export class McpServerWatcher implements McpServerProvider {await this.enqueueMcpServerReconciliation(laneOwner, work)},})+ initialConvergenceLastSuccessTimestampSeconds.set({ lane: 'McpServer' }, Date.now() / 1000)this.clearInitialConvergenceRetry('McpServer')} catch (error) {console.error('[K8s] Initial McpServer background reconciliation failed:', error)@@ -2372,6 +2535,10 @@ export class McpServerWatcher implements McpServerProvider {[...this.contexts.values()].find(context => context.spec.contextId === contextId),resolveCurrentServer: name => this.servers.get(name),})+ initialConvergenceLastSuccessTimestampSeconds.set(+ { lane: 'NetworkPolicy' },+ Date.now() / 1000+ )this.clearInitialConvergenceRetry('NetworkPolicy')} catch (error) {console.error('[K8s] Initial NetworkPolicy background reconciliation failed:', error)@@ -2397,6 +2564,7 @@ export class McpServerWatcher implements McpServerProvider {Math.min(attempt - 1, INITIAL_CONVERGENCE_RETRY_DELAYS_MS.length - 1)]this.initialConvergenceRetryAttempts.set(lane, attempt)+ initialConvergenceRetriesTotal.inc({ lane })console.warn(`[K8s] Scheduling initial ${lane} background convergence retry ${attempt} in ${delayMs}ms`)@@ -2619,6 +2787,14 @@ export class McpServerWatcher implements McpServerProvider {if (previousHostRef && previousHostRef !== cc.spec.hostRef) {affectedHostRefs.add(previousHostRef)}+ if (!this.isHostInventoryAuthoritative()) {+ const lifecycleGeneration = this.beginCommunicationChannelLifecycleTransition()+ this.admitHostDependentEffects(+ 'CommunicationChannel event Host convergence',+ lifecycleGeneration+ )+ return+ }let needsFleetRetry = falsefor (const hostRef of affectedHostRefs) {if (!(await this.reconcileHostsReferencingCC(hostRef))) {@@ -2786,11 +2962,15 @@ export class McpServerWatcher implements McpServerProvider {try {const cacheRevisionAtListStart = this.globalFileSystemCacheRevisionconst gfses = await listAllGlobalFileSystems()+ let reconcileInventory: GlobalFileSystemCRD[]if (cacheRevisionAtListStart === this.globalFileSystemCacheRevision) {this.globalFileSystems.clear()for (const gfs of gfses) this.globalFileSystems.set(gfs.name, gfs)+ reconcileInventory = gfses+ } else {+ reconcileInventory = [...this.globalFileSystems.values()]}- await this.gfsReconciler.fullReconcile(gfses)+ await this.gfsReconciler.fullReconcile(reconcileInventory)} catch (err) {console.error(`[K8s] GlobalFileSystem periodic resync failed: ${@@ -2809,9 +2989,13 @@ export class McpServerWatcher implements McpServerProvider {try {const cacheRevisionAtListStart = this.sharedFileSystemCacheRevisionconst sfses = await listAllSharedFileSystems()+ let reconcileInventory: SharedFileSystemCRD[]if (cacheRevisionAtListStart === this.sharedFileSystemCacheRevision) {this.sharedFileSystems.clear()for (const sfs of sfses) this.sharedFileSystems.set(sfs.name, sfs)+ reconcileInventory = sfses+ } else {+ reconcileInventory = [...this.sharedFileSystems.values()]}// Capture each SFS's mountability (PVC Bound) BEFORE reconciling so we can@@ -2821,11 +3005,11 @@ export class McpServerWatcher implements McpServerProvider {// on phase==='Ready': a transient wfc readiness dip while the PVC stays// Bound must NOT re-roll consumers — see resolveContextMounts.)const wasMountable = new Map<string, boolean>()- for (const sfs of sfses) {+ for (const sfs of reconcileInventory) {wasMountable.set(sfs.name, this.sharedFileSystemReconciler.isMountable(sfs))}- await this.sharedFileSystemReconciler.fullReconcile(sfses)+ await this.sharedFileSystemReconciler.fullReconcile(reconcileInventory)// #592 gap fix: heal the consuming mcp-host Deployments on a mountability// flip — inject the mount + affinity once the PVC binds, or drop it if the@@ -2835,7 +3019,7 @@ export class McpServerWatcher implements McpServerProvider {// an already-Bound SFS picked up on HCC restart still re-injects its mount// within one resync interval instead of waiting for the (much longer) Host// resync.- for (const sfs of sfses) {+ for (const sfs of reconcileInventory) {const nowMountable = this.sharedFileSystemReconciler.isMountable(sfs)if (nowMountable !== (wasMountable.get(sfs.name) ?? false)) {await this.reconcileHostsReferencingSfs(sfs.name)@@ -3442,10 +3626,7 @@ export class McpServerWatcher implements McpServerProvider {// Re-reconcile any Host that points at this Context so that changes to// spec.sharedFileSystems[] propagate into the mcp-host pod template.try {- for (const host of this.hosts.values()) {- if (host.spec.contextRef !== context.name) continue- await this.hostReconciler.reconcile(host)- }+ await this.reconcileHostsReferencingContext(context.name)} catch (error) {console.error(`[K8s] Host re-reconcile after Context "${context.name}" change failed:`,@@ -3596,6 +3777,7 @@ export class McpServerWatcher implements McpServerProvider {clearTimeout(this.hostCacheRecoveryTimer)this.hostCacheRecoveryTimer = null}+ this.hostCacheRecoveryIntent = nullif (this.mcpServerCacheRecoveryTimer) {clearTimeout(this.mcpServerCacheRecoveryTimer)this.mcpServerCacheRecoveryTimer = nulldiff --git a/host-context-controller/src/main.ts b/host-context-controller/src/main.tsindex d311ced40..0e2c03176 100644--- a/host-context-controller/src/main.ts+++ b/host-context-controller/src/main.ts@@ -211,9 +211,8 @@ async function main(): Promise<void> {if (!config.devMode && hostReconciler) {const kc = getKubeConfig()if (kc) {- const reconciler = hostReconcilerchannelSecretInformer = new SecretInformer(kc, config.channelsNamespace, evt => {- reconciler.reconcileChannelReaderRevision(evt.name, evt.namespace).catch(err => {+ watcher?.reconcileChannelReaderRevision(evt.name, evt.namespace).catch(err => {console.error('[Main] reconcileChannelReaderRevision failed:', err)})})diff --git a/host-context-controller/src/metrics.ts b/host-context-controller/src/metrics.tsindex 4de90228e..a47f22d5f 100644--- a/host-context-controller/src/metrics.ts+++ b/host-context-controller/src/metrics.ts@@ -47,9 +47,7 @@ function gauge(options: {* (15s), and wake (45s) budgets, plus longer diagnostic tails. Shared by every* HCC reconcile/recovery latency histogram.*/-const RECONCILE_LATENCY_BUCKETS = [- 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 15, 45, 120,-] as const+const RECONCILE_LATENCY_BUCKETS = [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 15, 45, 120] as const/** Idempotent Histogram helper mirroring counter()/gauge(). */function histogram(options: {@@ -81,6 +79,18 @@ export const networkPoliciesTotal = gauge({labelNames: ['layer'] as const,})+export const initialConvergenceRetriesTotal = counter({+ name: 'clerum_hcc_initial_convergence_retries_total',+ help: 'Initial background convergence retries scheduled after a failed fleet pass.',+ labelNames: ['lane'] as const,+})++export const initialConvergenceLastSuccessTimestampSeconds = gauge({+ name: 'clerum_hcc_initial_convergence_last_success_timestamp_seconds',+ help: 'Unix timestamp of the last successful initial background convergence pass.',+ labelNames: ['lane'] as const,+})+export const contextReconciliationsTotal = counter({name: 'clerum_hcc_context_reconciliations_total',help: 'Total Context CRD reconciliations',diff --git a/host-context-controller/src/statelessLifecycleExecutor.ts b/host-context-controller/src/statelessLifecycleExecutor.tsindex 81542832a..01d4fda77 100644--- a/host-context-controller/src/statelessLifecycleExecutor.ts+++ b/host-context-controller/src/statelessLifecycleExecutor.ts@@ -71,7 +71,15 @@ export interface StatelessLifecycleExecutorDeps {* serialization slot, so re-entering the per-host chain would* self-deadlock.*/- reconcileCore: (host: HostCRD) => Promise<void>+ reconcileCore: (host: HostCRD, revalidate?: () => HostCRD) => Promise<void>+ /**+ * Capture Host inventory authority at heartbeat dispatch time and return an+ * admission closure that revalidates that authority and resolves the current+ * same-identity Host inside this executor's per-Host serializer. The two-step+ * shape is intentional: capturing only after the queue drains cannot detect+ * an authority generation change that happened while the work was waiting.+ */+ prepareHostMutationAdmission?: (action: string, host: HostCRD) => () => HostCRDonLifecycleStatusCommitted?: (host: HostCRD, lifecycle: HostLifecycleStatus) => void}@@ -82,7 +90,8 @@ export class StatelessLifecycleExecutor {private readonly now: () => Dateprivate readonly countCommunicationChannels: (hostName: string) => numberprivate readonly isCommunicationChannelCacheSynced: () => boolean- private readonly reconcileCore: (host: HostCRD) => Promise<void>+ private readonly reconcileCore: (host: HostCRD, revalidate?: () => HostCRD) => Promise<void>+ private readonly prepareHostMutationAdmission: (action: string, host: HostCRD) => () => HostCRDprivate readonly onLifecycleStatusCommitted: (host: HostCRD,lifecycle: HostLifecycleStatus@@ -132,6 +141,8 @@ export class StatelessLifecycleExecutor {this.countCommunicationChannels = deps.countCommunicationChannelsthis.isCommunicationChannelCacheSynced = deps.isCommunicationChannelCacheSyncedthis.reconcileCore = deps.reconcileCore+ this.prepareHostMutationAdmission =+ deps.prepareHostMutationAdmission ?? ((_action, host) => () => host)this.onLifecycleStatusCommitted = deps.onLifecycleStatusCommitted ?? (() => {})StatelessLifecycleExecutor.warnSingleReplicaInvariantOnce()}@@ -671,15 +682,19 @@ export class StatelessLifecycleExecutor {metadata: {name: stringnamespace?: string+ uid?: string+ generation?: numberresourceVersion?: stringannotations?: Record<string, string>}spec: HostCRD['spec']status?: HostCRD['status']}- return {+ const fresh: HostCRD = {name: obj.metadata.name,namespace: obj.metadata.namespace ?? host.namespace,+ uid: obj.metadata.uid,+ generation: obj.metadata.generation,// Preserve resourceVersion so heartbeat-path status writers can pass it// back as an optimistic-concurrency precondition (D3). Dropping it here// would force every write to be an unconditioned last-write-wins patch.@@ -688,6 +703,8 @@ export class StatelessLifecycleExecutor {spec: obj.spec,status: obj.status,}+ this.requireSameHostIdentity(host, fresh)+ return fresh}/**@@ -716,17 +733,24 @@ export class StatelessLifecycleExecutor {reason: string,entryWakeHandledGeneration: number): Promise<SuspendFromHeartbeatOutcome> {- // L2: serialize on the host chain so a tracker-driven suspend never- // interleaves with a watch-driven wake reconcile for the same host.- return this.serializeByHost(host.name, () =>- this.suspendHostFromHeartbeatCore(host, reason, entryWakeHandledGeneration)+ return this.serializeHeartbeatMutation(+ 'heartbeat suspension',+ host,+ (admittedHost, revalidate) =>+ this.suspendHostFromHeartbeatCore(+ admittedHost,+ reason,+ entryWakeHandledGeneration,+ revalidate+ ))}private async suspendHostFromHeartbeatCore(host: HostCRD,reason: string,- entryWakeHandledGeneration: number+ entryWakeHandledGeneration: number,+ revalidate?: () => HostCRD): Promise<SuspendFromHeartbeatOutcome> {// FRESH GET (see readFreshHost): guard against the CURRENT server-side// lifecycle, not the caller's watch-cache snapshot. The guard is re-run@@ -741,6 +765,17 @@ export class StatelessLifecycleExecutor {const result = await this.patchStatusWithPrecondition(host,fresh => {+ // UID proves object identity, not decision freshness. A same-identity+ // Host may have advanced from stateless to stateful while the watch+ // cache trails the API. Re-evaluate the complete effective stateless+ // policy from every fresh read/retry before honoring old heartbeat+ // evidence.+ if (+ !this.sameHostSpecRevision(host, fresh) ||+ !this.effectiveLifecycleFromCache(fresh).stateless+ ) {+ return { skip: true }+ }const freshLifecycle = fresh.status?.lifecycleif (freshLifecycle?.state !== 'draining') {// Every legitimate suspend follows a durable `draining` write (the@@ -802,12 +837,34 @@ export class StatelessLifecycleExecutor {writtenStatus = { ...(fresh.status ?? {}), lifecycle }return this.fullStatusOps(writtenStatus)},- initialFresh+ initialFresh,+ revalidate)if ('skipped' in result || writtenStatus === undefined) {return skipOutcome}+ // Revalidate authority/UID immediately before follow-on effects, then read+ // once more from the API. The successful PATCH attempt's fresh object is+ // the exact spec on which the status write committed, but a wake/spec+ // update can land immediately AFTER that commit and BEFORE runtime+ // reconciliation. A linearizable follow-on GET observes both our durable+ // suspended write and any such newer same-UID update; the watch cache can+ // legitimately trail either one.+ const currentAtFollowOn = revalidate?.()+ if (currentAtFollowOn) this.requireSameHostIdentity(host, currentAtFollowOn)host.status = writtenStatus+ const reconcileHost = await this.readFreshHost(result.fresh)+ if (!this.sameHostSpecRevision(host, reconcileHost)) {+ const error = new Error(+ `Host spec generation changed before heartbeat suspension follow-on for "${host.name}"`+ )+ error.name = 'HostMutationSpecRevisionChangedError'+ throw error+ }+ const currentAfterFollowOnRead = revalidate?.()+ if (currentAfterFollowOnRead) {+ this.requireSameHostIdentity(host, currentAfterFollowOnRead)+ }this.lastWrittenLifecycleStatus.delete(host.name)this.logSuspendedApplied(host.name)console.log(@@ -816,18 +873,30 @@ export class StatelessLifecycleExecutor {// L2: call reconcileCore (not the serialized reconcile) — this method// already runs inside this host's serialization slot, so re-entering the// per-host chain here would self-deadlock.- await this.reconcileCore(host)+ await this.reconcileCore(reconcileHost, revalidate)+ // Preserve the historical caller-visible reflection contract even when+ // follow-on work correctly used a fresher API object. The tracker may hold+ // the originally admitted instance until the watch delivers the next+ // MODIFIED event; reflect the final authoritative outcome immediately so+ // it cannot make a second decision from the pre-follow-on status.+ host.uid = reconcileHost.uid+ host.generation = reconcileHost.generation+ host.resourceVersion = reconcileHost.resourceVersion+ host.annotations = reconcileHost.annotations+ host.spec = reconcileHost.spec+ host.status = reconcileHost.status// The wake fast-path / drained-pre-scale guard inside reconcile() may// have flipped the host back to active (a wake raced the suspension) —// in that case no scale-down happened, so no phase/metric is emitted.const wakePending =- this.wakeRequestedGeneration(host) > (host.status?.lifecycle?.wakeHandledGeneration ?? 0)- if (host.status?.lifecycle?.state !== 'suspended' || wakePending) {+ this.wakeRequestedGeneration(reconcileHost) >+ (reconcileHost.status?.lifecycle?.wakeHandledGeneration ?? 0)+ if (reconcileHost.status?.lifecycle?.state !== 'suspended' || wakePending) {// The durable suspended write DID commit (a racing wake revived the// host afterwards), so the drained evidence was honored: 'suspended'.return 'suspended'}- this.recordSuspendedApplied(host.name)+ this.recordSuspendedApplied(reconcileHost.name)return 'suspended'}@@ -838,12 +907,19 @@ export class StatelessLifecycleExecutor {* Throws on API failure — the tracker logs it loudly.*/async publishSuspendBlockedReason(host: HostCRD, reason: string): Promise<void> {- // L2: serialize on the host chain (see serializeByHost) so this status- // write never interleaves with a concurrent reconcile for the same host.- return this.serializeByHost(host.name, () => this.publishSuspendBlockedReasonCore(host, reason))+ return this.serializeHeartbeatMutation(+ 'heartbeat suspend-blocked reason publication',+ host,+ (admittedHost, revalidate) =>+ this.publishSuspendBlockedReasonCore(admittedHost, reason, revalidate)+ )}- private async publishSuspendBlockedReasonCore(host: HostCRD, reason: string): Promise<void> {+ private async publishSuspendBlockedReasonCore(+ host: HostCRD,+ reason: string,+ revalidate?: () => HostCRD+ ): Promise<void> {// FRESH GET (see readFreshHost): this is a suspend-BLOCKED reason// ANNOTATOR, not a state writer — it must NEVER change state, only stamp// the reason on top of the CURRENT server-side state. AP-1 (the 9th@@ -866,6 +942,12 @@ export class StatelessLifecycleExecutor {const result = await this.patchStatusWithPrecondition(host,fresh => {+ if (+ !this.sameHostSpecRevision(host, fresh) ||+ !this.effectiveLifecycleFromCache(fresh).stateless+ ) {+ return { skip: true }+ }const freshLifecycle = fresh.status?.lifecycleconst freshState = freshLifecycle?.state ?? 'active'if (freshState !== 'active') {@@ -889,7 +971,8 @@ export class StatelessLifecycleExecutor {writtenLifecycle = lifecyclereturn [{ op: 'add', path: '/status/lifecycle', value: lifecycle }]},- initialFresh+ initialFresh,+ revalidate)if ('skipped' in result || writtenLifecycle === undefined) {return@@ -926,17 +1009,18 @@ export class StatelessLifecycleExecutor {host: HostCRD,entryWakeHandledGeneration: number): Promise<void> {- // L2: serialize on the host chain (see serializeByHost) so the drain- // status write never interleaves with a concurrent reconcile for the- // same host.- return this.serializeByHost(host.name, () =>- this.markHostDrainingFromHeartbeatCore(host, entryWakeHandledGeneration)+ return this.serializeHeartbeatMutation(+ 'heartbeat draining transition',+ host,+ (admittedHost, revalidate) =>+ this.markHostDrainingFromHeartbeatCore(admittedHost, entryWakeHandledGeneration, revalidate))}private async markHostDrainingFromHeartbeatCore(host: HostCRD,- entryWakeHandledGeneration: number+ entryWakeHandledGeneration: number,+ revalidate?: () => HostCRD): Promise<void> {// FRESH GET (see readFreshHost): a stale `active` snapshot over an// actually-`suspended` CR would write `draining` (a running state) and@@ -948,6 +1032,12 @@ export class StatelessLifecycleExecutor {const result = await this.patchStatusWithPrecondition(host,fresh => {+ if (+ !this.sameHostSpecRevision(host, fresh) ||+ !this.effectiveLifecycleFromCache(fresh).stateless+ ) {+ return { skip: true }+ }const freshLifecycle = fresh.status?.lifecycleif ((freshLifecycle?.state ?? 'active') !== 'active') {return { skip: true }@@ -983,7 +1073,8 @@ export class StatelessLifecycleExecutor {writtenStatus = { ...(fresh.status ?? {}), lifecycle }return this.fullStatusOps(writtenStatus)},- initialFresh+ initialFresh,+ revalidate)if ('skipped' in result || writtenStatus === undefined) {return@@ -1010,13 +1101,17 @@ export class StatelessLifecycleExecutor {* heartbeat retries.*/async markHostActiveFromHeartbeat(host: HostCRD): Promise<void> {- // L2: serialize on the host chain (see serializeByHost) so the- // cancel-drain status write never interleaves with a concurrent- // reconcile for the same host.- return this.serializeByHost(host.name, () => this.markHostActiveFromHeartbeatCore(host))+ return this.serializeHeartbeatMutation(+ 'heartbeat cancel-drain transition',+ host,+ (admittedHost, revalidate) => this.markHostActiveFromHeartbeatCore(admittedHost, revalidate)+ )}- private async markHostActiveFromHeartbeatCore(host: HostCRD): Promise<void> {+ private async markHostActiveFromHeartbeatCore(+ host: HostCRD,+ revalidate?: () => HostCRD+ ): Promise<void> {// FRESH GET (see readFreshHost): a stale `draining` snapshot over an// actually-`suspended` CR must never resurrect it (and would regress// wakeHandledGeneration). Proceed only when the CURRENT server-side@@ -1029,6 +1124,12 @@ export class StatelessLifecycleExecutor {const result = await this.patchStatusWithPrecondition(host,fresh => {+ if (+ !this.sameHostSpecRevision(host, fresh) ||+ !this.effectiveLifecycleFromCache(fresh).stateless+ ) {+ return { skip: true }+ }const freshLifecycle = fresh.status?.lifecycleif (freshLifecycle?.state !== 'draining') {skippedNotDraining = freshLifecycle?.state ?? 'active'@@ -1041,7 +1142,8 @@ export class StatelessLifecycleExecutor {writtenStatus = { ...(fresh.status ?? {}), lifecycle }return this.fullStatusOps(writtenStatus)},- initialFresh+ initialFresh,+ revalidate)if ('skipped' in result || writtenStatus === undefined) {console.log(@@ -1417,19 +1519,31 @@ export class StatelessLifecycleExecutor {private async patchStatusWithPrecondition(host: HostCRD,build: (fresh: HostCRD) => Array<{ op: 'add'; path: string; value: unknown }> | { skip: true },- initialFresh?: HostCRD+ initialFresh?: HostCRD,+ revalidate?: () => HostCRD): Promise<{ fresh: HostCRD } | { skipped: true }> {const maxAttempts = 5let fresh = initialFreshfor (let attempt = 1; attempt <= maxAttempts; attempt += 1) {+ const currentAtAttempt = revalidate?.()+ if (currentAtAttempt) this.requireSameHostIdentity(host, currentAtAttempt)if (fresh === undefined) {fresh = await this.readFreshHost(host)}+ if (host.uid !== undefined && fresh.resourceVersion === undefined) {+ const error = new Error(+ `Host status mutation for "${host.name}" has no fresh resourceVersion; refusing an unconditioned write`+ )+ error.name = 'HostMutationPreconditionUnavailableError'+ throw error+ }const built = build(fresh)if ('skip' in built) {return { skipped: true }}try {+ const currentBeforePatch = revalidate?.()+ if (currentBeforePatch) this.requireSameHostIdentity(host, currentBeforePatch)await this.customApi.patchNamespacedCustomObjectStatus({group: GROUP,version: VERSION,@@ -1499,6 +1613,58 @@ export class StatelessLifecycleExecutor {return result}+ /**+ * Capture admission before enqueueing, then resolve the current Host only+ * after this mutation reaches the front of its own serializer. Keeping the+ * check here avoids wrapping a lifecycle call in HostReconciler's serializer,+ * which would recursively acquire the same Host chain and deadlock.+ */+ private serializeHeartbeatMutation<T>(+ action: string,+ host: HostCRD,+ work: (admittedHost: HostCRD, revalidate: () => HostCRD) => Promise<T>+ ): Promise<T> {+ const revalidate = this.prepareHostMutationAdmission(action, host)+ return this.serializeByHost(host.name, () => work(revalidate(), revalidate))+ }++ /**+ * A resourceVersion conflict can be caused by ordinary writes or by a+ * delete/recreate. Every fresh read, including every bounded 409 retry, must+ * remain on the Kubernetes UID that was admitted. Name equality is not an+ * identity fence. Production watch snapshots always carry UID; if only one+ * side carries it, fail closed rather than guessing.+ */+ private requireSameHostIdentity(expected: HostCRD, current: HostCRD): void {+ if (expected.uid === undefined && current.uid === undefined) return+ if (expected.uid === undefined || current.uid === undefined || expected.uid !== current.uid) {+ const error = new Error(+ `Host identity changed while mutating "${expected.name}"; refusing to cross a same-name recreation`+ )+ error.name = 'HostMutationIdentityChangedError'+ throw error+ }+ }++ /**+ * Heartbeat evidence belongs to one Host spec epoch. UID equality allows+ * status-only updates and retries, but a generation change can replace the+ * runtime inputs (context, Secret, image, lifecycle policy, etc.) while+ * remaining stateless. Never apply an older runtime's heartbeat decision to+ * that new spec. UID-less standalone fixtures retain their legacy behavior;+ * production objects (which carry UID) fail closed on a missing generation.+ */+ private sameHostSpecRevision(expected: HostCRD, current: HostCRD): boolean {+ if (expected.generation === undefined && current.generation === undefined) {+ return expected.uid === undefined && current.uid === undefined+ }+ return (+ expected.generation !== undefined &&+ current.generation !== undefined &&+ expected.generation === current.generation+ )+ }+/*** Drained-pre-scale guard (Stage 4.3): a pending wake must abort the* suspension IMMEDIATELY before replicas:0 derives from the assessment.diff --git a/host-context-controller/test/hostReconciler.heartbeat.test.ts b/host-context-controller/test/hostReconciler.heartbeat.test.tsindex 4e6593024..885477b13 100644--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts@@ -136,6 +136,20 @@ function createReconciler() {return { reconciler, appsApi, coreApi, networkingApi, rbacApi, customApi }}+function deferred<T = void>(): {+ promise: Promise<T>+ resolve: (value: T) => void+ reject: (reason?: unknown) => void+} {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+}+/** The mcp-host Deployment body sent to the K8s API (excludes channel-reader). */function hostDeploymentBody(appsApi: MockAppsApi, name: string): k8s.V1Deployment {const calls = [@@ -207,6 +221,716 @@ function freshHostRead(lifecycle?: {}}+describe('HostReconciler heartbeat mutation admission', () => {+ const heartbeatMutations = [+ {+ name: 'suspend',+ core: 'suspendHostFromHeartbeatCore',+ coreArgs: ['idle', 0] as const,+ freshLifecycle: { state: 'draining', wakeHandledGeneration: 0 } as const,+ invoke: (reconciler: HostReconciler, host: HostCRD) =>+ reconciler.suspendHostFromHeartbeat(host, 'idle', 0),+ },+ {+ name: 'suspend-blocked reason',+ core: 'publishSuspendBlockedReasonCore',+ coreArgs: ['suspend-blocked: activeTask'] as const,+ freshLifecycle: { state: 'active', wakeHandledGeneration: 0 } as const,+ invoke: (reconciler: HostReconciler, host: HostCRD) =>+ reconciler.publishSuspendBlockedReason(host, 'suspend-blocked: activeTask'),+ },+ {+ name: 'draining',+ core: 'markHostDrainingFromHeartbeatCore',+ coreArgs: [0] as const,+ freshLifecycle: { state: 'active', wakeHandledGeneration: 0 } as const,+ invoke: (reconciler: HostReconciler, host: HostCRD) =>+ reconciler.markHostDrainingFromHeartbeat(host, 0),+ },+ {+ name: 'cancel-drain',+ core: 'markHostActiveFromHeartbeatCore',+ coreArgs: [] as const,+ freshLifecycle: { state: 'draining', wakeHandledGeneration: 0 } as const,+ invoke: (reconciler: HostReconciler, host: HostCRD) =>+ reconciler.markHostActiveFromHeartbeat(host),+ },+ ] as const++ it.each(heartbeatMutations)(+ 'rejects queued $name work when Host authority changes before serializer admission',+ async ({ core, invoke }) => {+ const { reconciler } = createReconciler()+ const host = { ...makeStatelessHost(), uid: 'heartbeat-host-uid', generation: 1 }+ const authority = { current: { known: true, generation: 7 } }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => authority.current)+ const lifecycle = (reconciler as any).lifecycle+ const coreSpy = vi.spyOn(lifecycle, core).mockResolvedValue(undefined)+ const blockerStarted = deferred()+ const releaseBlocker = deferred()+ const occupied = lifecycle.serializeByHost(host.name, async () => {+ blockerStarted.resolve(undefined)+ await releaseBlocker.promise+ }) as Promise<void>+ await blockerStarted.promise++ const pending = invoke(reconciler, host)+ authority.current = { known: false, generation: 8 }+ releaseBlocker.resolve(undefined)+ await occupied++ await expect(pending).rejects.toThrow(/Host inventory authority/)+ expect(coreSpy).not.toHaveBeenCalled()+ }+ )++ it.each(heartbeatMutations)(+ 'rejects queued $name work when the Host UID changes before serializer admission',+ async ({ core, invoke }) => {+ const { reconciler } = createReconciler()+ const requested = { ...makeStatelessHost(), uid: 'heartbeat-host-old-uid', generation: 4 }+ let current = requested+ const authority = { current: { known: true, generation: 9 } }+ reconciler.setResolveCurrentHost(name => (name === requested.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => authority.current)+ const lifecycle = (reconciler as any).lifecycle+ const coreSpy = vi.spyOn(lifecycle, core).mockResolvedValue(undefined)+ const blockerStarted = deferred()+ const releaseBlocker = deferred()+ const occupied = lifecycle.serializeByHost(requested.name, async () => {+ blockerStarted.resolve(undefined)+ await releaseBlocker.promise+ }) as Promise<void>+ await blockerStarted.promise++ const pending = invoke(reconciler, requested)+ current = { ...requested, uid: 'heartbeat-host-new-uid', generation: 1 }+ releaseBlocker.resolve(undefined)+ await occupied++ await expect(pending).rejects.toThrow(/Host identity/)+ expect(coreSpy).not.toHaveBeenCalled()+ }+ )++ it.each(heartbeatMutations)(+ 'admits the latest same-UID same-spec Host snapshot for $name inside the heartbeat serializer',+ async ({ core, coreArgs, invoke }) => {+ const { reconciler } = createReconciler()+ const requested = { ...makeStatelessHost(), uid: 'heartbeat-host-uid', generation: 4 }+ const current = {+ ...requested,+ resourceVersion: 'cache-rv-latest',+ status: { lifecycle: { state: 'active' as const, wakeHandledGeneration: 2 } },+ }+ reconciler.setResolveCurrentHost(name => (name === requested.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 12 }))+ const lifecycle = (reconciler as any).lifecycle+ const coreSpy = vi.spyOn(lifecycle, core).mockResolvedValue(undefined)++ await invoke(reconciler, requested)++ expect(coreSpy).toHaveBeenCalledOnce()+ expect(coreSpy).toHaveBeenCalledWith(current, ...coreArgs, expect.any(Function))+ }+ )++ it.each(heartbeatMutations)(+ 'rejects a $name 409 retry that resolves to a recreated same-name Host',+ async ({ freshLifecycle, invoke }) => {+ const { reconciler, customApi } = createReconciler()+ const host = {+ ...makeStatelessHost({ status: { lifecycle: freshLifecycle } }),+ uid: 'heartbeat-host-old-uid',+ generation: 4,+ }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 15 }))+ customApi.getNamespacedCustomObject+ .mockResolvedValueOnce({+ ...freshHostRead(freshLifecycle),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-old',+ },+ })+ .mockResolvedValueOnce({+ ...freshHostRead(freshLifecycle),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: 'heartbeat-host-new-uid',+ generation: 1,+ resourceVersion: 'rv-new',+ },+ })+ customApi.patchNamespacedCustomObjectStatus+ .mockRejectedValueOnce({ code: 409 })+ .mockResolvedValueOnce(undefined)++ await expect(invoke(reconciler, host)).rejects.toThrow(/Host identity/)+ expect(customApi.getNamespacedCustomObject).toHaveBeenCalledTimes(2)+ expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(1)+ }+ )++ it.each(heartbeatMutations)(+ 'rejects queued $name work when the same Host advances to a new spec generation',+ async ({ core, invoke }) => {+ const { reconciler } = createReconciler()+ const requested = { ...makeStatelessHost(), uid: 'heartbeat-host-uid', generation: 4 }+ let current = requested+ reconciler.setResolveCurrentHost(name => (name === requested.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 13 }))+ const lifecycle = (reconciler as any).lifecycle+ const coreSpy = vi.spyOn(lifecycle, core).mockResolvedValue(undefined)+ const blockerStarted = deferred()+ const releaseBlocker = deferred()+ const occupied = lifecycle.serializeByHost(requested.name, async () => {+ blockerStarted.resolve(undefined)+ await releaseBlocker.promise+ }) as Promise<void>+ await blockerStarted.promise++ const pending = invoke(reconciler, requested)+ current = {+ ...requested,+ generation: 5,+ spec: { ...requested.spec, contextRef: 'new-runtime-context' },+ }+ releaseBlocker.resolve(undefined)+ await occupied++ await expect(pending).rejects.toThrow(/Host spec generation/)+ expect(coreSpy).not.toHaveBeenCalled()+ }+ )++ it.each(heartbeatMutations)(+ 'does not apply stale $name evidence to a newer same-UID stateless spec',+ async ({ freshLifecycle, invoke }) => {+ const { reconciler, customApi } = createReconciler()+ const host = {+ ...makeStatelessHost({ status: { lifecycle: freshLifecycle } }),+ uid: 'heartbeat-host-uid',+ generation: 4,+ }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 14 }))+ customApi.getNamespacedCustomObject.mockResolvedValue({+ ...freshHostRead(freshLifecycle),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 5,+ resourceVersion: 'rv-new-spec',+ },+ spec: { ...host.spec, contextRef: 'new-runtime-context' },+ })+ const reconcileCore = vi+ .spyOn(reconciler as any, 'reconcileCore')+ .mockResolvedValue(undefined)++ await invoke(reconciler, host)++ expect(customApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()+ expect(reconcileCore).not.toHaveBeenCalled()+ }+ )++ it.each(heartbeatMutations)(+ 'does not apply stale $name evidence after the same-UID Host becomes stateful',+ async ({ invoke }) => {+ const { reconciler, customApi } = createReconciler()+ const host = { ...makeStatelessHost(), uid: 'heartbeat-host-uid', generation: 4 }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 16 }))+ customApi.getNamespacedCustomObject.mockResolvedValue({+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 5,+ resourceVersion: 'rv-stateful',+ },+ spec: {+ ...host.spec,+ lifecycle: { stateless: false },+ },+ })+ const reconcileCore = vi+ .spyOn(reconciler as any, 'reconcileCore')+ .mockResolvedValue(undefined)++ await invoke(reconciler, host)++ expect(customApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()+ expect(reconcileCore).not.toHaveBeenCalled()+ }+ )++ it('does not retry stale heartbeat evidence after a 409 reveals a same-UID stateful spec', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = { ...makeStatelessHost(), uid: 'heartbeat-host-uid', generation: 4 }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 17 }))+ customApi.getNamespacedCustomObject+ .mockResolvedValueOnce({+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-stateless',+ },+ })+ .mockResolvedValueOnce({+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 5,+ resourceVersion: 'rv-stateful',+ },+ spec: {+ ...host.spec,+ lifecycle: { stateless: false },+ },+ })+ customApi.patchNamespacedCustomObjectStatus.mockRejectedValueOnce({ code: 409 })++ await reconciler.markHostDrainingFromHeartbeat(host, 0)++ expect(customApi.getNamespacedCustomObject).toHaveBeenCalledTimes(2)+ expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(1)+ })++ it('does not retry stale heartbeat evidence after a 409 reveals a newer stateless spec', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = { ...makeStatelessHost(), uid: 'heartbeat-host-uid', generation: 4 }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 17 }))+ customApi.getNamespacedCustomObject+ .mockResolvedValueOnce({+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-old-spec',+ },+ })+ .mockResolvedValueOnce({+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 5,+ resourceVersion: 'rv-new-spec',+ },+ spec: { ...host.spec, contextRef: 'new-runtime-context' },+ })+ customApi.patchNamespacedCustomObjectStatus.mockRejectedValueOnce({ code: 409 })++ await reconciler.markHostDrainingFromHeartbeat(host, 0)++ expect(customApi.getNamespacedCustomObject).toHaveBeenCalledTimes(2)+ expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(1)+ })++ it('revalidates authority after the fresh read and before the first status patch', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = { ...makeStatelessHost(), uid: 'heartbeat-host-uid', generation: 4 }+ const authority = { current: { known: true, generation: 18 } }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => authority.current)+ customApi.getNamespacedCustomObject.mockImplementation(async () => {+ authority.current = { known: false, generation: 19 }+ return {+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ resourceVersion: 'rv-authority-lost',+ },+ }+ })++ await expect(reconciler.markHostDrainingFromHeartbeat(host, 0)).rejects.toThrow(+ /Host inventory authority/+ )+ expect(customApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()+ })++ it('revalidates authority before a 409 retry performs another fresh read', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = { ...makeStatelessHost(), uid: 'heartbeat-host-uid', generation: 4 }+ const authority = { current: { known: true, generation: 21 } }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => authority.current)+ customApi.getNamespacedCustomObject.mockResolvedValue({+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-before-conflict',+ },+ })+ customApi.patchNamespacedCustomObjectStatus.mockImplementationOnce(async () => {+ authority.current = { known: false, generation: 22 }+ throw { code: 409 }+ })++ await expect(reconciler.markHostDrainingFromHeartbeat(host, 0)).rejects.toThrow(+ /Host inventory authority/+ )+ expect(customApi.getNamespacedCustomObject).toHaveBeenCalledTimes(1)+ expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(1)+ })++ it('does not reconcile runtime effects after suspend when the Host UID changes', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = {+ ...makeStatelessHost({+ status: { lifecycle: { state: 'draining', wakeHandledGeneration: 0 } },+ }),+ uid: 'heartbeat-host-old-uid',+ generation: 4,+ }+ let current = host+ reconciler.setResolveCurrentHost(name => (name === host.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 24 }))+ const reconcileCore = vi.spyOn(reconciler as any, 'reconcileCore').mockResolvedValue(undefined)+ customApi.getNamespacedCustomObject.mockResolvedValue({+ ...freshHostRead({ state: 'draining', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-suspend',+ },+ })+ customApi.patchNamespacedCustomObjectStatus.mockImplementationOnce(async () => {+ current = { ...host, uid: 'heartbeat-host-new-uid', generation: 1 }+ })++ await expect(reconciler.suspendHostFromHeartbeat(host, 'idle', 0)).rejects.toThrow(+ /Host identity/+ )+ expect(reconcileCore).not.toHaveBeenCalled()+ })++ it('reconciles suspend follow-on effects from the successful fresh same-UID Host spec', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = {+ ...makeStatelessHost({+ spec: { contextRef: 'latest-context' },+ status: { lifecycle: { state: 'draining', wakeHandledGeneration: 0 } },+ }),+ uid: 'heartbeat-host-uid',+ generation: 5,+ }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 26 }))+ const reconcileCore = vi.spyOn(reconciler as any, 'reconcileCore').mockResolvedValue(undefined)+ customApi.getNamespacedCustomObject+ .mockResolvedValueOnce({+ ...freshHostRead({ state: 'draining', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 5,+ resourceVersion: 'rv-suspend-current',+ },+ spec: { ...host.spec, contextRef: 'latest-context' },+ })+ .mockResolvedValue({+ ...freshHostRead({+ state: 'suspended',+ wakeHandledGeneration: 0,+ reason: 'idle',+ }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 5,+ resourceVersion: 'rv-suspend-committed',+ },+ spec: { ...host.spec, contextRef: 'latest-context' },+ })++ await reconciler.suspendHostFromHeartbeat(host, 'idle', 0)++ expect(reconcileCore).toHaveBeenCalledOnce()+ const reconciledHost = reconcileCore.mock.calls[0][0] as HostCRD+ expect(reconciledHost).toMatchObject({+ uid: host.uid,+ generation: 5,+ spec: expect.objectContaining({ contextRef: 'latest-context' }),+ })+ expect(reconciledHost.status?.lifecycle).toEqual({+ state: 'suspended',+ wakeHandledGeneration: 0,+ reason: 'idle',+ })+ })++ it('rejects a known-identity status write without a fresh resourceVersion', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = { ...makeStatelessHost(), uid: 'heartbeat-host-uid', generation: 4 }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 28 }))+ customApi.getNamespacedCustomObject.mockResolvedValue({+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: { name: host.name, namespace: host.namespace, uid: host.uid },+ })++ await expect(reconciler.markHostDrainingFromHeartbeat(host, 0)).rejects.toThrow(+ /no fresh resourceVersion/+ )+ expect(customApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()+ })++ it('retries a 409 on the same UID and uses the latest Host for suspend follow-on effects', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = {+ ...makeStatelessHost({+ status: { lifecycle: { state: 'draining', wakeHandledGeneration: 0 } },+ }),+ uid: 'heartbeat-host-uid',+ generation: 4,+ }+ let current = host+ reconciler.setResolveCurrentHost(name => (name === host.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 30 }))+ const reconcileCore = vi.spyOn(reconciler as any, 'reconcileCore').mockResolvedValue(undefined)+ customApi.getNamespacedCustomObject+ .mockResolvedValueOnce({+ ...freshHostRead({ state: 'draining', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-1',+ },+ })+ .mockResolvedValueOnce({+ ...freshHostRead({ state: 'draining', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-2',+ },+ spec: host.spec,+ })+ .mockResolvedValueOnce({+ ...freshHostRead({+ state: 'suspended',+ wakeHandledGeneration: 0,+ reason: 'idle',+ }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-3',+ },+ spec: host.spec,+ })+ customApi.patchNamespacedCustomObjectStatus+ .mockImplementationOnce(async () => {+ current = {+ ...host,+ resourceVersion: 'cache-rv-after-conflict',+ }+ throw { code: 409 }+ })+ .mockResolvedValueOnce(undefined)++ await reconciler.suspendHostFromHeartbeat(host, 'idle', 0)++ expect(customApi.getNamespacedCustomObject).toHaveBeenCalledTimes(3)+ expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(2)+ expect(reconcileCore.mock.calls[0][0]).toMatchObject({+ uid: host.uid,+ generation: 4,+ spec: expect.objectContaining({ contextRef: 'context-a' }),+ })+ })++ it('does not apply or record suspension when only the follow-on GET observes a newer spec', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = {+ ...makeStatelessHost({+ status: { lifecycle: { state: 'draining', wakeHandledGeneration: 0 } },+ }),+ uid: 'heartbeat-host-uid',+ generation: 4,+ }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 33 }))+ customApi.getNamespacedCustomObject+ .mockResolvedValueOnce({+ ...freshHostRead({ state: 'draining', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-suspend-write',+ },+ })+ .mockResolvedValueOnce({+ ...freshHostRead({+ state: 'suspended',+ wakeHandledGeneration: 0,+ reason: 'idle',+ }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 5,+ resourceVersion: 'rv-new-spec',+ },+ spec: {+ ...host.spec,+ contextRef: 'replacement-context',+ lifecycle: { stateless: false },+ },+ })+ const reconcileCore = vi.spyOn(reconciler as any, 'reconcileCore').mockResolvedValue(undefined)+ const recordSuspended = vi.spyOn((reconciler as any).lifecycle, 'recordSuspendedApplied')++ await expect(reconciler.suspendHostFromHeartbeat(host, 'idle', 0)).rejects.toThrow(+ /Host spec generation/+ )++ expect(reconcileCore).not.toHaveBeenCalled()+ expect(recordSuspended).not.toHaveBeenCalled()+ })++ it('rejects stale suspend follow-on work when the Host spec changes during Secret validation', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = {+ ...makeStatelessHost({+ status: { lifecycle: { state: 'draining', wakeHandledGeneration: 0 } },+ }),+ uid: 'heartbeat-host-uid',+ generation: 4,+ }+ let current = host+ reconciler.setResolveCurrentHost(name => (name === host.name ? current : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 34 }))+ customApi.getNamespacedCustomObject+ .mockResolvedValueOnce({+ ...freshHostRead({ state: 'draining', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-suspend-write',+ },+ })+ .mockResolvedValueOnce({+ ...freshHostRead({+ state: 'suspended',+ wakeHandledGeneration: 0,+ reason: 'idle',+ }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-suspend-follow-on',+ },+ })+ const secretReadStarted = deferred()+ const releaseSecretRead = deferred()+ vi.spyOn(reconciler as any, 'validateHostSecret').mockImplementation(async () => {+ secretReadStarted.resolve(undefined)+ await releaseSecretRead.promise+ return { ok: true }+ })+ const staleMutation = vi+ .spyOn(reconciler as any, 'ensureHostServiceAccount')+ .mockRejectedValue(new Error('stale follow-on mutation was admitted'))++ const pending = reconciler.suspendHostFromHeartbeat(host, 'idle', 0)+ await secretReadStarted.promise+ current = {+ ...host,+ generation: 5,+ spec: {+ ...host.spec,+ contextRef: 'replacement-context',+ lifecycle: { stateless: false },+ },+ }+ releaseSecretRead.resolve(undefined)++ await expect(pending).rejects.toThrow(/Host spec generation/)+ expect(staleMutation).not.toHaveBeenCalled()+ })++ it('does not record a suspended scale-down when follow-on reconcile handles a wake', async () => {+ const { reconciler, customApi } = createReconciler()+ const host = {+ ...makeStatelessHost({+ status: { lifecycle: { state: 'draining', wakeHandledGeneration: 0 } },+ }),+ uid: 'heartbeat-host-uid',+ generation: 4,+ }+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 32 }))+ customApi.getNamespacedCustomObject.mockResolvedValue({+ ...freshHostRead({ state: 'draining', wakeHandledGeneration: 0 }),+ metadata: {+ name: host.name,+ namespace: host.namespace,+ uid: host.uid,+ generation: 4,+ resourceVersion: 'rv-wake-follow-on',+ },+ })+ vi.spyOn(reconciler as any, 'reconcileCore').mockImplementation(async (...args: unknown[]) => {+ const reconcileHost = args[0] as HostCRD+ reconcileHost.annotations = { 'clerum.io/wake-requested': '1' }+ reconcileHost.status = {+ lifecycle: { state: 'active', wakeHandledGeneration: 1 },+ }+ })+ const recordSuspended = vi.spyOn((reconciler as any).lifecycle, 'recordSuspendedApplied')++ await expect(reconciler.suspendHostFromHeartbeat(host, 'idle', 0)).resolves.toBe('suspended')++ expect(recordSuspended).not.toHaveBeenCalled()+ })+})+describe('HostReconciler.suspendHostFromHeartbeat', () => {it("writes state='suspended' + reason 'idle' durably, then reconciles to replicas=0", async () => {const { reconciler, appsApi, customApi } = createReconciler()