Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): prioritize per-host reconciliation, wake admission, and delete convergence
Alfredo Lopez1bb0f11ad1bb
diff --git a/deploy/base/control-plane/host-context-controller.yaml b/deploy/base/control-plane/host-context-controller.yamlindex f054fe0b6..0d32a622f 100644--- a/deploy/base/control-plane/host-context-controller.yaml+++ b/deploy/base/control-plane/host-context-controller.yaml@@ -62,6 +62,12 @@ spec:value: "300"- name: HCC_HOST_K8S_REQUEST_TIMEOUT_MSvalue: "30000"+ # Bounded cross-Host concurrency for a full/lifecycle Host fleet pass.+ # Urgent per-Host events (ADDED/MODIFIED/DELETED/wake) are admitted+ # outside this budget, so the low default optimizes for Kubernetes API+ # stability rather than convergence speed (issue #791). Integer 1..8.+ - name: HCC_HOST_FULL_RECONCILE_CONCURRENCY+ value: "2"- name: CONTEXT_MAPPER_STDIO_BRIDGE_IMAGEvalue: clerum/stdio-bridge:0.9.5# workspace-files-controller (per-SharedFileSystem) — see config.ts wfc*diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex b3635ac43..9dc6dcbba 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.154",+ "version": "0.1.155","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.154",+ "version": "0.1.155","license": "MIT","dependencies": {"@clerum/image-policy": "file:../packages/image-policy",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 7b0c2ee3c..1cd6f061f 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.154",+ "version": "0.1.155","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/config.hostFullReconcileConcurrency.test.ts b/host-context-controller/src/config.hostFullReconcileConcurrency.test.tsnew file mode 100644index 000000000..ca5957b49--- /dev/null+++ b/host-context-controller/src/config.hostFullReconcileConcurrency.test.ts@@ -0,0 +1,53 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++const originalEnv = process.env++async function loadConfig(raw: string | undefined) {+ vi.resetModules()+ process.env = { ...originalEnv }+ if (raw === undefined) {+ delete process.env.HCC_HOST_FULL_RECONCILE_CONCURRENCY+ } else {+ process.env.HCC_HOST_FULL_RECONCILE_CONCURRENCY = raw+ }+ return import('./config')+}++afterEach(() => {+ process.env = originalEnv+ vi.resetModules()+})++describe('HCC_HOST_FULL_RECONCILE_CONCURRENCY', () => {+ it('defaults to 2 when unset', async () => {+ const { config } = await loadConfig(undefined)++ expect(config.hostFullReconcileConcurrency).toBe(2)+ })++ it('defaults to 2 for a blank value', async () => {+ const { config } = await loadConfig(' ')++ expect(config.hostFullReconcileConcurrency).toBe(2)+ })++ it.each([+ ['1', 1],+ ['2', 2],+ ['4', 4],+ ['8', 8],+ ])('accepts the bounded explicit integer %s', async (raw, expected) => {+ const { config } = await loadConfig(raw)++ expect(config.hostFullReconcileConcurrency).toBe(expected)+ })++ it.each(['0', '9', '-1', '1.5', '2x', 'NaN', 'Infinity'])(+ "fails configuration validation for the explicit value '%s'",+ async raw => {+ await expect(loadConfig(raw)).rejects.toThrow(+ `HCC_HOST_FULL_RECONCILE_CONCURRENCY must be an integer from 1 through 8, got '${raw}'`+ )+ }+ )+})diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.tsindex 4c9033a6c..fb5c805ea 100644--- a/host-context-controller/src/config.ts+++ b/host-context-controller/src/config.ts@@ -160,6 +160,11 @@ export interface Config {// convergence path. Watches keep their independent long-lived lifecycle.hostK8sRequestTimeoutMs: number+ // Bounded cross-Host concurrency for a full/lifecycle Host fleet pass. Urgent+ // per-Host events (ADDED/MODIFIED/DELETED/wake) are admitted outside this+ // budget. Integer 1..8, default 2 (see parseHostFullReconcileConcurrency).+ hostFullReconcileConcurrency: number+// Periodic SharedFileSystem fullReconcile interval (seconds). The SFS watch// fires only on SFS CRD changes, not on PVC binding / wfc pod readiness, so// this drives truthful-status auto-recovery (#592): a SharedFileSystem stuck@@ -251,6 +256,25 @@ export function parseHostK8sRequestTimeoutMs(raw: string | undefined): number {return parsed}+/**+ * HCC_HOST_FULL_RECONCILE_CONCURRENCY — bounded cross-Host concurrency for a+ * full/lifecycle Host fleet pass. Urgent per-Host events are admitted OUTSIDE+ * this budget, so a low default optimizes for Kubernetes API stability rather+ * than convergence speed. Integer 1..8 (1 = diagnostic serial mode), default 2.+ * Fails config load loudly on garbage: a silent default over a typo'd value+ * would mask an operator's intended concurrency in production.+ */+export function parseHostFullReconcileConcurrency(raw: string | undefined): number {+ if (raw === undefined || raw.trim() === '') return 2+ const parsed = Number(raw)+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 8) {+ throw new Error(+ `HCC_HOST_FULL_RECONCILE_CONCURRENCY must be an integer from 1 through 8, got '${raw}'`+ )+ }+ return parsed+}+export function validateRemovedStatelessCommunicationChannelPolicy(raw: string | undefined): void {if (raw === undefined || raw.trim() === '') returnthrow new Error(@@ -550,6 +574,9 @@ export const config: Config = {// Every finite Kubernetes request that can hold Host convergence gets its// own deadline. Watch streams are intentionally excluded.hostK8sRequestTimeoutMs: parseHostK8sRequestTimeoutMs(getEnv('HCC_HOST_K8S_REQUEST_TIMEOUT_MS')),+ hostFullReconcileConcurrency: parseHostFullReconcileConcurrency(+ getEnv('HCC_HOST_FULL_RECONCILE_CONCURRENCY')+ ),// Periodic SharedFileSystem resync (default 60s). Re-evaluates PVC bind + wfc// readiness so a transient Initializing/Degraded converges to Ready (#592).diff --git a/host-context-controller/src/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.tsindex af87512ae..e10c98a4d 100644--- a/host-context-controller/src/hostReconciler.test.ts+++ b/host-context-controller/src/hostReconciler.test.ts@@ -10,10 +10,24 @@ import {createMockNetworkingApi,createMockRbacApi,} from '../test/__fixtures__/testMocks'-import { HostFleetReconcileError, HostReconciler } from './hostReconciler'+import { HostFleetReconcileError, HostReconciler, destructiveCleanupAllowed } from './hostReconciler'import { HostK8sRequestTimeoutError } from './k8s/hostK8sApiClient'import { HostCRD } from './types'+function deferred<T = void>(): {+ promise: Promise<T>+ resolve: (value: T | PromiseLike<T>) => void+ reject: (reason?: unknown) => void+} {+ let resolve!: (value: T | PromiseLike<T>) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+}+vi.mock('./config', () => ({config: {hostNamespace: 'mcp-host',@@ -31,6 +45,7 @@ vi.mock('./config', () => ({rpcProxyNamespace: 'rpc-proxy',channelsNamespace: 'channels',hostK8sRequestTimeoutMs: 30_000,+ hostFullReconcileConcurrency: 2,mcpHostGatewayUrl: 'http://mcp-host-gateway',hostResources: {requests: { memory: '128Mi', cpu: '50m' },@@ -215,30 +230,23 @@ describe('HostReconciler Kubernetes request deadline wiring', () => {})})+function makeBasicReconciler() {+ return new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })+}+describe('HostReconciler fleet failure isolation', () => {- it('continues reconciling later Hosts and runs orphan sweeps after one Host fails', async () => {- const reconciler = new HostReconciler({} as k8s.KubeConfig, {- appsApi: asAppsApi(createMockAppsApi()),- coreApi: asCoreApi(createMockCoreApi()),- networkingApi: asNetworkingApi(createMockNetworkingApi()),- rbacApi: asRbacApi(createMockRbacApi()),- })- const internals = reconciler as unknown as {- listManagedHostDeployments(): Promise<k8s.V1Deployment[]>- sweepOrphanChannelReaderResources(hosts: string[]): Promise<void>- sweepOrphanHostNetworkPolicies(hosts: string[]): Promise<void>- }+ it('continues reconciling later Hosts and aggregates the failure', async () => {+ const reconciler = makeBasicReconciler()+ // Cleanup stays deferred (authority unwired), isolating reconcile behavior.const firstFailure = new Error('first Host failed')const reconcile = vi.spyOn(reconciler, 'reconcile').mockImplementation(async host => {if (host.name === 'host-a') throw firstFailure})- vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue([])- const channelSweep = vi- .spyOn(internals, 'sweepOrphanChannelReaderResources')- .mockResolvedValue()- const networkPolicySweep = vi- .spyOn(internals, 'sweepOrphanHostNetworkPolicies')- .mockResolvedValue()let thrown: unknowntry {@@ -248,34 +256,18 @@ describe('HostReconciler fleet failure isolation', () => {}expect(reconcile.mock.calls.map(([host]) => host.name)).toEqual(['host-a', 'host-b'])- expect(channelSweep).toHaveBeenCalledWith(['host-a', 'host-b'])- expect(networkPolicySweep).toHaveBeenCalledWith(['host-a', 'host-b'])- expect(thrown).toBeInstanceOf(AggregateError)expect(thrown).toBeInstanceOf(HostFleetReconcileError)expect((thrown as HostFleetReconcileError).hostFailures).toEqual([firstFailure])+ // Authority is unwired, so cleanup fail-closes (defers) rather than deleting.expect((thrown as HostFleetReconcileError).cleanupFailures).toEqual([])- expect((thrown as AggregateError).errors).toContain(firstFailure)})it('continues with Host B when Host A reaches its Kubernetes request deadline', async () => {- const reconciler = new HostReconciler({} as k8s.KubeConfig, {- appsApi: asAppsApi(createMockAppsApi()),- coreApi: asCoreApi(createMockCoreApi()),- networkingApi: asNetworkingApi(createMockNetworkingApi()),- rbacApi: asRbacApi(createMockRbacApi()),- })- const internals = reconciler as unknown as {- listManagedHostDeployments(): Promise<k8s.V1Deployment[]>- sweepOrphanChannelReaderResources(hosts: string[]): Promise<void>- sweepOrphanHostNetworkPolicies(hosts: string[]): Promise<void>- }+ const reconciler = makeBasicReconciler()const timeout = new HostK8sRequestTimeoutError('AppsV1Api.readNamespacedDeployment', 30_000)const reconcile = vi.spyOn(reconciler, 'reconcile').mockImplementation(async host => {if (host.name === 'host-a') throw timeout})- vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue([])- vi.spyOn(internals, 'sweepOrphanChannelReaderResources').mockResolvedValue()- vi.spyOn(internals, 'sweepOrphanHostNetworkPolicies').mockResolvedValue()let thrown: unknowntry {@@ -289,29 +281,16 @@ describe('HostReconciler fleet failure isolation', () => {expect((thrown as HostFleetReconcileError).hostFailures).toEqual([timeout])})- it('reports inventory and both sweep failures after every phase has run', async () => {- const reconciler = new HostReconciler({} as k8s.KubeConfig, {- appsApi: asAppsApi(createMockAppsApi()),- coreApi: asCoreApi(createMockCoreApi()),- networkingApi: asNetworkingApi(createMockNetworkingApi()),- rbacApi: asRbacApi(createMockRbacApi()),- })+ it('aggregates candidate-discovery list failures under known authority', async () => {+ const reconciler = makeBasicReconciler()+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(name => (name === 'host-a' ? makeHost({ name }) : undefined))+ vi.spyOn(reconciler, 'reconcile').mockResolvedValue()const internals = reconciler as unknown as {listManagedHostDeployments(): Promise<k8s.V1Deployment[]>- sweepOrphanChannelReaderResources(hosts: string[]): Promise<void>- sweepOrphanHostNetworkPolicies(hosts: string[]): Promise<void>}const inventoryFailure = new Error('Host Deployment inventory failed')- const channelSweepFailure = new Error('channel-reader sweep failed')- const networkPolicySweepFailure = new Error('NetworkPolicy sweep failed')- vi.spyOn(reconciler, 'reconcile').mockResolvedValue()vi.spyOn(internals, 'listManagedHostDeployments').mockRejectedValue(inventoryFailure)- const channelSweep = vi- .spyOn(internals, 'sweepOrphanChannelReaderResources')- .mockRejectedValue(channelSweepFailure)- const networkPolicySweep = vi- .spyOn(internals, 'sweepOrphanHostNetworkPolicies')- .mockRejectedValue(networkPolicySweepFailure)let thrown: unknowntry {@@ -320,46 +299,26 @@ describe('HostReconciler fleet failure isolation', () => {thrown = error}- expect(channelSweep).toHaveBeenCalledWith(['host-a'])- expect(networkPolicySweep).toHaveBeenCalledWith(['host-a'])- expect(thrown).toBeInstanceOf(AggregateError)+ expect(thrown).toBeInstanceOf(HostFleetReconcileError)expect((thrown as HostFleetReconcileError).hostFailures).toEqual([])- expect((thrown as HostFleetReconcileError).cleanupFailures).toEqual([- inventoryFailure,- channelSweepFailure,- networkPolicySweepFailure,- ])- expect((thrown as AggregateError).errors).toEqual([- inventoryFailure,- channelSweepFailure,- networkPolicySweepFailure,- ])+ expect((thrown as HostFleetReconcileError).cleanupFailures).toContain(inventoryFailure)})it('preserves simultaneous Host and cleanup failures after every phase has run', async () => {- const reconciler = new HostReconciler({} as k8s.KubeConfig, {- appsApi: asAppsApi(createMockAppsApi()),- coreApi: asCoreApi(createMockCoreApi()),- networkingApi: asNetworkingApi(createMockNetworkingApi()),- rbacApi: asRbacApi(createMockRbacApi()),- })- const internals = reconciler as unknown as {- listManagedHostDeployments(): Promise<k8s.V1Deployment[]>- sweepOrphanChannelReaderResources(hosts: string[]): Promise<void>- sweepOrphanHostNetworkPolicies(hosts: string[]): Promise<void>- }+ const reconciler = makeBasicReconciler()+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(name =>+ name === 'host-a' || name === 'host-b' ? makeHost({ name }) : undefined+ )const hostFailure = new Error('Host deployment failed')const cleanupFailure = new Error('Host inventory failed')const reconcile = vi.spyOn(reconciler, 'reconcile').mockImplementation(async host => {if (host.name === 'host-a') throw hostFailure})+ const internals = reconciler as unknown as {+ listManagedHostDeployments(): Promise<k8s.V1Deployment[]>+ }vi.spyOn(internals, 'listManagedHostDeployments').mockRejectedValue(cleanupFailure)- const channelSweep = vi- .spyOn(internals, 'sweepOrphanChannelReaderResources')- .mockResolvedValue()- const networkPolicySweep = vi- .spyOn(internals, 'sweepOrphanHostNetworkPolicies')- .mockResolvedValue()let thrown: unknowntry {@@ -369,53 +328,47 @@ describe('HostReconciler fleet failure isolation', () => {}expect(reconcile.mock.calls.map(([host]) => host.name)).toEqual(['host-a', 'host-b'])- expect(channelSweep).toHaveBeenCalledWith(['host-a', 'host-b'])- expect(networkPolicySweep).toHaveBeenCalledWith(['host-a', 'host-b'])expect(thrown).toBeInstanceOf(HostFleetReconcileError)expect((thrown as HostFleetReconcileError).hostFailures).toEqual([hostFailure])- expect((thrown as HostFleetReconcileError).cleanupFailures).toEqual([cleanupFailure])- expect((thrown as AggregateError).errors).toEqual([hostFailure, cleanupFailure])+ expect((thrown as HostFleetReconcileError).cleanupFailures).toContain(cleanupFailure)})- it('continues orphan cleanup and preserves nested sweep failures in the fleet error', async () => {+ it('deletes each confirmed orphan bundle and aggregates delete failures', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })const reconciler = new HostReconciler({} as k8s.KubeConfig, {appsApi: asAppsApi(createMockAppsApi()),coreApi: asCoreApi(createMockCoreApi()),networkingApi: asNetworkingApi(createMockNetworkingApi()),rbacApi: asRbacApi(createMockRbacApi()),+ customApi: { getNamespacedCustomObject: getObj } as unknown as k8s.CustomObjectsApi,})+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(() => undefined)const internals = reconciler as unknown as {listManagedHostDeployments(): Promise<k8s.V1Deployment[]>deleteHostRuntimeResources(name: string, namespace: string): Promise<void>- sweepOrphanChannelReaderResources(hosts: string[]): Promise<void>- sweepOrphanHostNetworkPolicies(hosts: string[]): Promise<void>}- const firstOrphanFailure = new Error('first orphan cleanup failed')- const channelListFailure = new Error('channel-reader list failed')- const channelDeleteFailure = new Error('channel-reader delete failed')- const networkListFailure = new Error('NetworkPolicy list failed')- const channelSweepFailure = new AggregateError(- [channelListFailure, channelDeleteFailure],- 'channel-reader sweep failed'- )- const networkSweepFailure = new AggregateError(- [networkListFailure],- 'NetworkPolicy sweep failed'- )+ const orphanFailure = new Error('first orphan cleanup failed')vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue([- { metadata: { name: 'orphan-a', namespace: 'mcp-host' } } as k8s.V1Deployment,- { metadata: { name: 'orphan-b', namespace: 'mcp-host' } } as k8s.V1Deployment,+ {+ metadata: {+ name: 'orphan-a',+ namespace: 'mcp-host',+ 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' },+ },+ } as k8s.V1Deployment,])- const deleteRuntime = vi+ const del = vi.spyOn(internals, 'deleteHostRuntimeResources')- .mockRejectedValueOnce(firstOrphanFailure)+ .mockRejectedValueOnce(orphanFailure).mockResolvedValueOnce()- const channelSweep = vi- .spyOn(internals, 'sweepOrphanChannelReaderResources')- .mockRejectedValue(channelSweepFailure)- const networkPolicySweep = vi- .spyOn(internals, 'sweepOrphanHostNetworkPolicies')- .mockRejectedValue(networkSweepFailure)let thrown: unknowntry {@@ -424,109 +377,500 @@ describe('HostReconciler fleet failure isolation', () => {thrown = error}- expect(deleteRuntime.mock.calls.map(([name]) => name)).toEqual(['orphan-a', 'orphan-b'])- expect(channelSweep).toHaveBeenCalledWith([])- expect(networkPolicySweep).toHaveBeenCalledWith([])- expect(thrown).toBeInstanceOf(AggregateError)- expect((thrown as AggregateError).errors).toEqual([- firstOrphanFailure,- channelSweepFailure,- networkSweepFailure,- ])- expect(channelSweepFailure.errors).toEqual([channelListFailure, channelDeleteFailure])- expect(networkSweepFailure.errors).toEqual([networkListFailure])+ expect(del.mock.calls.map(([name]) => name).sort()).toEqual(['orphan-a', 'orphan-b'])+ expect(getObj).toHaveBeenCalledTimes(2)+ expect(thrown).toBeInstanceOf(HostFleetReconcileError)+ expect((thrown as HostFleetReconcileError).cleanupFailures).toContain(orphanFailure)+ })+})++function makeCleanupReconciler(customApi: { getNamespacedCustomObject: ReturnType<typeof vi.fn> }) {+ return new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ customApi: customApi as unknown as k8s.CustomObjectsApi,+ })+}++describe('HostReconciler bounded fleet workers', () => {+ it('admits at most the configured number of Host reconciles concurrently', async () => {+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })+ // Isolate reconcile concurrency from the cleanup phase.+ vi.spyOn(reconciler as unknown as { collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]> }, 'collectHostCleanupFailures').mockResolvedValue([])+ let active = 0+ let maxActive = 0+ const gates: Array<() => void> = []+ vi.spyOn(reconciler, 'reconcile').mockImplementation(async () => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.push(resolve))+ active -= 1+ })+ const hosts = ['h1', 'h2', 'h3', 'h4'].map(name => makeHost({ name }))+ const pass = reconciler.fullReconcile(hosts)++ // Only two workers may run at once; the pool must not admit h3/h4 yet.+ await vi.waitFor(() => expect(gates.length).toBe(2))+ expect(maxActive).toBe(2)++ // Drain: each release lets the pool admit the next queued Host key.+ for (let i = 0; i < hosts.length; i++) {+ await vi.waitFor(() => expect(gates.length).toBeGreaterThan(0))+ gates.shift()!()+ }+ await pass+ expect(maxActive).toBe(2)})- it('continues every channel-reader resource sweep and aggregates non-404 failures', async () => {- const deploymentListFailure = new Error('Deployment list failed')- const serviceDeleteFailure = new Error('Service delete failed')- const secretListFailure = new Error('Secret list failed')- const appsApi = createMockAppsApi()- appsApi.listNamespacedDeployment.mockRejectedValue(deploymentListFailure)- const coreApi = Object.assign(createMockCoreApi(), {- listNamespacedService: vi.fn().mockResolvedValue({- items: [- {+ it('keeps urgent per-Host events outside the fleet worker budget', async () => {+ const reconciler = new HostReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),+ rbacApi: asRbacApi(createMockRbacApi()),+ })+ vi.spyOn(reconciler as unknown as { collectHostCleanupFailures(...args: unknown[]): Promise<unknown[]> }, 'collectHostCleanupFailures').mockResolvedValue([])+ let active = 0+ let maxActive = 0+ const gates = new Map<string, () => void>()+ vi.spyOn(reconciler, 'reconcile').mockImplementation(async host => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.set(host.name, resolve))+ active -= 1+ })+ const fleetHosts = ['f1', 'f2', 'f3', 'f4'].map(name => makeHost({ name }))+ const pass = reconciler.fullReconcile(fleetHosts)+ await vi.waitFor(() => expect(gates.size).toBe(2)) // fleet budget saturated++ // An urgent event for an unrelated Host must still be admitted immediately,+ // even though the fleet workers already occupy the whole budget.+ const urgent = reconciler.reconcile(makeHost({ name: 'urgent' }), 'urgent')+ await vi.waitFor(() => expect(gates.has('urgent')).toBe(true))+ expect(maxActive).toBe(3) // 2 fleet + 1 urgent++ // Drain repeatedly so the remaining fleet workers (f3/f4) are admitted and+ // released as earlier ones finish.+ const settled = Promise.all([pass, urgent])+ for (let i = 0; i < 12; i++) {+ for (const [name, resolve] of [...gates]) {+ gates.delete(name)+ resolve()+ }+ await Promise.resolve()+ await Promise.resolve()+ }+ await settled+ })+})++describe('HostReconciler bounded orphan cleanup (Addendum 2)', () => {+ it('deletes orphan bundles through the bounded worker pool, never an unbounded fan-out', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(() => undefined) // every candidate is an orphan+ const internals = reconciler as unknown as {+ listManagedHostDeployments(): Promise<k8s.V1Deployment[]>+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>+ }+ vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue(+ ['orphan-a', 'orphan-b', 'orphan-c', 'orphan-d'].map(+ name =>+ ({metadata: {- name: 'channel-reader-orphan',+ name,+ namespace: 'mcp-host',labels: {- app: 'channel-reader','clerum.io/managed-by': 'host-context-controller',- 'clerum.io/host': 'orphan',+ 'clerum.io/host': name,},},- },- ],- }),+ }) as k8s.V1Deployment+ )+ )+ let active = 0+ let maxActive = 0+ const gates: Array<() => void> = []+ vi.spyOn(internals, 'deleteHostRuntimeResources').mockImplementation(async () => {+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.push(resolve))+ active -= 1})- coreApi.deleteNamespacedService.mockRejectedValue(serviceDeleteFailure)- coreApi.listNamespacedSecret.mockRejectedValue(secretListFailure)++ const pass = reconciler.fullReconcile([])++ // Bound = HCC_HOST_FULL_RECONCILE_CONCURRENCY (2): only two orphan bundles+ // delete at once; the pool must not admit orphan-c/orphan-d yet.+ await vi.waitFor(() => expect(gates.length).toBe(2))+ expect(maxActive).toBe(2)++ for (let i = 0; i < 4; i++) {+ await vi.waitFor(() => expect(gates.length).toBeGreaterThan(0))+ gates.shift()!()+ }+ await pass+ expect(maxActive).toBe(2)+ })+})++describe('HostReconciler bounded channel-reader revision fan-out (Addendum 2)', () => {+ it('patches every affected Host through the bounded worker pool', async () => {const reconciler = new HostReconciler({} as k8s.KubeConfig, {- appsApi: asAppsApi(appsApi),- coreApi: asCoreApi(coreApi),+ appsApi: asAppsApi(createMockAppsApi()),+ coreApi: asCoreApi(createMockCoreApi()),networkingApi: asNetworkingApi(createMockNetworkingApi()),rbacApi: asRbacApi(createMockRbacApi()),})- const internals = reconciler as unknown as {- sweepOrphanChannelReaderResources(hosts: string[]): Promise<void>- }+ ;(+ reconciler as unknown as {+ setFindCommunicationChannelsByCredentialsSecretName(fn: () => unknown[]): void+ }+ ).setFindCommunicationChannelsByCredentialsSecretName(() =>+ ['h1', 'h2', 'h3', 'h4'].map(hostRef => ({ spec: { hostRef } }))+ )+ let active = 0+ let maxActive = 0+ const patched: string[] = []+ const gates: Array<() => void> = []+ vi.spyOn(+ reconciler as unknown as {+ patchChannelReaderRevisionAnnotation(name: string): Promise<void>+ },+ 'patchChannelReaderRevisionAnnotation'+ ).mockImplementation(async (name: string) => {+ patched.push(name)+ active += 1+ maxActive = Math.max(maxActive, active)+ await new Promise<void>(resolve => gates.push(resolve))+ active -= 1+ })- let thrown: unknown- try {- await internals.sweepOrphanChannelReaderResources([])- } catch (error) {- thrown = error+ const pass = reconciler.reconcileChannelReaderRevision('shared-secret', 'channels')++ // Bound = 2: at most two affected Hosts patch concurrently.+ await vi.waitFor(() => expect(gates.length).toBe(2))+ expect(maxActive).toBe(2)++ for (let i = 0; i < 4; i++) {+ await vi.waitFor(() => expect(gates.length).toBeGreaterThan(0))+ gates.shift()!()}+ await pass++ expect(maxActive).toBe(2)+ // Complete fan-out: every affected Host is patched exactly once.+ expect(patched.sort()).toEqual(['h1', 'h2', 'h3', 'h4'])+ })+})- expect(coreApi.listNamespacedService).toHaveBeenCalled()- expect(coreApi.deleteNamespacedService).toHaveBeenCalled()- expect(coreApi.listNamespacedSecret).toHaveBeenCalled()- expect(thrown).toBeInstanceOf(AggregateError)- expect((thrown as AggregateError).errors).toEqual([- deploymentListFailure,- serviceDeleteFailure,- secretListFailure,+describe('HostReconciler #827 cleanup hardening', () => {+ it('suppresses the delete when the Host reappears in cache after the fresh read (F2 TOCTOU)', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 3 }))+ // resolveCurrentHost reports "absent" during discovery and the authority+ // gate, then "present" on the re-check INSIDE the per-Host serializer —+ // modelling a same-name Host recreated in the admission window. The F2+ // in-serializer re-check must suppress the destructive delete.+ let calls = 0+ reconciler.setResolveCurrentHost(name => {+ calls += 1+ return calls >= 3 ? makeHost({ name }) : undefined+ })+ const internals = reconciler as unknown as {+ listManagedHostDeployments(): Promise<k8s.V1Deployment[]>+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>+ }+ vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue([+ {+ metadata: {+ name: 'gone',+ namespace: 'mcp-host',+ labels: { 'clerum.io/managed-by': 'host-context-controller', 'clerum.io/host': 'gone' },+ },+ } as k8s.V1Deployment,])+ const del = vi.spyOn(internals, 'deleteHostRuntimeResources').mockResolvedValue()++ await reconciler.fullReconcile([])++ expect(getObj).toHaveBeenCalledTimes(1) // the fresh read happened (said absent)+ expect(del).not.toHaveBeenCalled() // but the in-serializer re-check suppressed the delete})- it('continues NetworkPolicy namespaces and aggregates list and delete failures', async () => {- const listFailure = new Error('channels NetworkPolicy list failed')- const deleteFailure = new Error('mcp-host NetworkPolicy delete failed')- const networkingApi = createMockNetworkingApi()- networkingApi.listNamespacedNetworkPolicy- .mockRejectedValueOnce(listFailure)- .mockResolvedValueOnce({- items: [- {- metadata: {- name: 'mcp-host-orphan-egress',- labels: { 'clerum.io/host': 'orphan' },+ it('discovers an orphan from a surviving owned resource when the Deployment is already gone (#827 item 4)', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(() => undefined) // "gone" absent from cache+ const internals = reconciler as unknown as {+ listManagedHostDeployments(): Promise<k8s.V1Deployment[]>+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>+ }+ // The Deployment sentinel is already gone...+ vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue([])+ // ...but a PVC leftover survives with ownership labels in the host namespace.+ ;(+ reconciler as unknown as {+ coreApi: { listNamespacedPersistentVolumeClaim: ReturnType<typeof vi.fn> }+ }+ ).coreApi.listNamespacedPersistentVolumeClaim.mockResolvedValue({+ items: [+ {+ metadata: {+ name: 'gone-workspace',+ namespace: 'mcp-host',+ labels: {+ 'clerum.io/managed-by': 'host-context-controller',+ 'clerum.io/host': 'gone',},},- ],- })- .mockResolvedValueOnce({ items: [] })- networkingApi.deleteNamespacedNetworkPolicy.mockRejectedValue(deleteFailure)+ },+ ],+ })+ const del = vi.spyOn(internals, 'deleteHostRuntimeResources').mockResolvedValue()++ await reconciler.fullReconcile([])++ // The surviving PVC alone identified the orphan Host and drove its bundle delete.+ expect(getObj).toHaveBeenCalledWith(expect.objectContaining({ name: 'gone' }))+ expect(del).toHaveBeenCalledWith('gone', 'mcp-host')+ })+})++describe('HostReconciler delete serialization', () => {+ it('serializes a delete behind an in-flight reconcile for the same Host', async () => {const reconciler = new HostReconciler({} as k8s.KubeConfig, {appsApi: asAppsApi(createMockAppsApi()),coreApi: asCoreApi(createMockCoreApi()),- networkingApi: asNetworkingApi(networkingApi),+ networkingApi: asNetworkingApi(createMockNetworkingApi()),rbacApi: asRbacApi(createMockRbacApi()),})+ const order: string[] = []+ const reconcileGate = deferred()+ vi.spyOn(+ reconciler as unknown as { reconcileCore(...args: unknown[]): Promise<void> },+ 'reconcileCore'+ ).mockImplementation(async () => {+ order.push('reconcile:start')+ await reconcileGate.promise+ order.push('reconcile:end')+ })+ vi.spyOn(+ reconciler as unknown as { deleteHostRuntimeResources(...args: unknown[]): Promise<void> },+ 'deleteHostRuntimeResources'+ ).mockImplementation(async () => {+ order.push('delete:start')+ order.push('delete:end')+ })++ const reconcilePromise = reconciler.reconcile(makeHost({ name: 'chatllm' }))+ const deletePromise = reconciler.reconcileDelete('chatllm', 'mcp-host')+ await Promise.resolve()+ await Promise.resolve()+ // The delete must NOT begin while the same Host's reconcile is in flight.+ expect(order).toEqual(['reconcile:start'])++ reconcileGate.resolve()+ await Promise.all([reconcilePromise, deletePromise])+ expect(order).toEqual(['reconcile:start', 'reconcile:end', 'delete:start', 'delete:end'])+ })+})++describe('HostReconciler destructiveCleanupAllowed property', () => {+ it('permits deletion only with known authority, a stable generation, cache omission, and a confirmed 404', () => {+ expect(+ destructiveCleanupAllowed({+ watchAuthorityKnown: true,+ capturedWatchGeneration: 7,+ currentWatchGeneration: 7,+ currentCacheOmitsHost: true,+ freshAuthoritativeRead: 'confirmed404',+ })+ ).toBe(true)+ })++ it.each([+ ['authority unknown', { watchAuthorityKnown: false }],+ ['generation drifted', { currentWatchGeneration: 8 }],+ ['host still present in cache', { currentCacheOmitsHost: false }],+ ['fresh read present', { freshAuthoritativeRead: 'present' as const }],+ ['fresh read errored', { freshAuthoritativeRead: 'error' as const }],+ ])('refuses deletion when %s', (_label, override) => {+ expect(+ destructiveCleanupAllowed({+ watchAuthorityKnown: true,+ capturedWatchGeneration: 7,+ currentWatchGeneration: 7,+ currentCacheOmitsHost: true,+ freshAuthoritativeRead: 'confirmed404',+ ...override,+ })+ ).toBe(false)+ })+})++describe('HostReconciler cleanup authority gate', () => {+ function orphanDeployment(hostName: string) {+ return {+ metadata: {+ name: hostName,+ namespace: 'mcp-host',+ labels: {+ 'clerum.io/managed-by': 'host-context-controller',+ 'clerum.io/host': hostName,+ },+ },+ } as k8s.V1Deployment+ }++ function wireCleanup(+ reconciler: HostReconciler,+ opts: {+ authority: { known: boolean; generation: number }+ currentAuthority?: { known: boolean; generation: number }+ cache: Set<string>+ candidates: k8s.V1Deployment[]+ }+ ) {+ let firstCall = true+ reconciler.setHostWatchAuthority(() => {+ if (firstCall) {+ firstCall = false+ return opts.authority+ }+ return opts.currentAuthority ?? opts.authority+ })+ reconciler.setResolveCurrentHost(name =>+ opts.cache.has(name) ? makeHost({ name }) : undefined+ )const internals = reconciler as unknown as {- sweepOrphanHostNetworkPolicies(hosts: string[]): Promise<void>+ listManagedHostDeployments(): Promise<k8s.V1Deployment[]>+ deleteHostRuntimeResources(name: string, namespace: string): Promise<void>}+ vi.spyOn(internals, 'listManagedHostDeployments').mockResolvedValue(opts.candidates)+ return vi.spyOn(internals, 'deleteHostRuntimeResources').mockResolvedValue()+ }- let thrown: unknown- try {- await internals.sweepOrphanHostNetworkPolicies([])- } catch (error) {- thrown = error- }+ it('deletes an orphan bundle after a fresh 404 while authority is known and stable', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ const del = wireCleanup(reconciler, {+ authority: { known: true, generation: 3 },+ cache: new Set(),+ candidates: [orphanDeployment('gone-host')],+ })++ await reconciler.fullReconcile([])++ expect(getObj).toHaveBeenCalledTimes(1)+ expect(del).toHaveBeenCalledWith('gone-host', 'mcp-host')+ })++ it('retains a candidate that is still present in the current cache', async () => {+ const getObj = vi.fn()+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ const del = wireCleanup(reconciler, {+ authority: { known: true, generation: 3 },+ cache: new Set(['live-host']),+ candidates: [orphanDeployment('live-host')],+ })++ await reconciler.fullReconcile([])++ expect(getObj).not.toHaveBeenCalled()+ expect(del).not.toHaveBeenCalled()+ })++ it('defers all cleanup when watch authority is unknown', async () => {+ const getObj = vi.fn()+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ const del = wireCleanup(reconciler, {+ authority: { known: false, generation: 3 },+ cache: new Set(),+ candidates: [orphanDeployment('gone-host')],+ })++ await reconciler.fullReconcile([])++ expect(getObj).not.toHaveBeenCalled()+ expect(del).not.toHaveBeenCalled()+ })++ it('defers all cleanup when the watch generation changed during the pass', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ const del = wireCleanup(reconciler, {+ authority: { known: true, generation: 3 },+ currentAuthority: { known: true, generation: 4 },+ cache: new Set(),+ candidates: [orphanDeployment('gone-host')],+ })++ await reconciler.fullReconcile([])++ 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 })+ const del = wireCleanup(reconciler, {+ authority: { known: true, generation: 3 },+ cache: new Set(),+ candidates: [orphanDeployment('maybe-gone')],+ })++ await reconciler.fullReconcile([])++ expect(getObj).toHaveBeenCalledTimes(1)+ expect(del).not.toHaveBeenCalled()+ })++ it('retains an orphan whose fresh authoritative read shows it present', async () => {+ const getObj = vi.fn().mockResolvedValue({ metadata: { name: 'reappeared' } })+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ const del = wireCleanup(reconciler, {+ authority: { known: true, generation: 3 },+ cache: new Set(),+ candidates: [orphanDeployment('reappeared')],+ })++ await reconciler.fullReconcile([])++ expect(getObj).toHaveBeenCalledTimes(1)+ expect(del).not.toHaveBeenCalled()+ })++ it('never deletes a candidate whose owning Host cannot be derived from labels', async () => {+ const getObj = vi.fn()+ const reconciler = makeCleanupReconciler({ getNamespacedCustomObject: getObj })+ const del = wireCleanup(reconciler, {+ authority: { known: true, generation: 3 },+ cache: new Set(),+ candidates: [+ {+ metadata: {+ name: 'unlabeled',+ namespace: 'mcp-host',+ labels: { 'clerum.io/managed-by': 'host-context-controller' },+ },+ } as k8s.V1Deployment,+ ],+ })++ await reconciler.fullReconcile([])- expect(networkingApi.listNamespacedNetworkPolicy).toHaveBeenCalledTimes(3)- expect(networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)- expect(thrown).toBeInstanceOf(AggregateError)- expect((thrown as AggregateError).errors).toEqual([listFailure, deleteFailure])+ expect(getObj).not.toHaveBeenCalled()+ expect(del).not.toHaveBeenCalled()})})diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex c6ca15041..aa17fbbd2 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -50,9 +50,88 @@ import {preserveServiceAssignedFields,replaceWithConflictRetry,} from './utils'+import {+ hostCleanupDeferredTotal,+ hostReconcileDurationSeconds,+ hostReconcileInFlight,+ hostReconcileQueueWaitSeconds,+} from './metrics'export type { EffectiveHostLifecycle } from './statelessLifecycle.types'+const HOST_GROUP = 'clerum.io'+const HOST_VERSION = 'v1alpha1'+const HOST_PLURAL = 'hosts'++/**+ * Lane label for a Host reconcile, used only for low-cardinality telemetry:+ * `urgent` (a direct watch ADDED/MODIFIED/DELETED/wake event), `retry` (a+ * bounded watch-reconcile retry), or `fleet` (a bounded background full/+ * lifecycle worker). Never a host name, user, or team.+ */+export type HostReconcileSource = 'urgent' | 'retry' | 'fleet'++/** Immutable Host watch authority snapshot captured at a full-pass boundary. */+export type HostWatchAuthoritySnapshot = { known: boolean; generation: number }++/**+ * 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+ * generation captured at pass start still matches the current generation, the+ * current cache omits the Host, AND a fresh authoritative read confirmed a 404.+ * Any weaker evidence defers.+ */+export function destructiveCleanupAllowed(input: {+ watchAuthorityKnown: boolean+ capturedWatchGeneration: number+ currentWatchGeneration: number+ currentCacheOmitsHost: boolean+ freshAuthoritativeRead: 'confirmed404' | 'present' | 'error'+}): boolean {+ return (+ input.watchAuthorityKnown &&+ input.capturedWatchGeneration === input.currentWatchGeneration &&+ input.currentCacheOmitsHost &&+ input.freshAuthoritativeRead === 'confirmed404'+ )+}++/**+ * Dependency-free bounded worker pool. Dispatches `keys` across at most+ * `concurrency` lanes; each lane pulls the next key, runs `worker`, and+ * collects (never swallows) failures so aggregation stays complete. Lane+ * startup is ordered so the first `concurrency` keys begin in input order.+ */+async function runBoundedHostWorkers(+ keys: string[],+ concurrency: number,+ worker: (key: string) => Promise<void>+): Promise<unknown[]> {+ const failures: unknown[] = []+ if (keys.length === 0) return failures+ let cursor = 0+ const runLane = async (): Promise<void> => {+ for (;;) {+ const index = cursor+ cursor += 1+ if (index >= keys.length) return+ try {+ await worker(keys[index])+ } catch (error) {+ failures.push(error)+ }+ }+ }+ const lanes = Math.max(1, Math.min(concurrency, keys.length))+ const runners: Promise<void>[] = []+ for (let i = 0; i < lanes; i += 1) runners.push(runLane())+ await Promise.all(runners)+ return failures+}++/** A managed resource considered for orphan cleanup, keyed by owning Host. */+type CleanupCandidate = { owner: string | undefined; kind: string; name: string }+/*** The workflow-control scopes a first-party Host's mcp-host control token needs* for the full channel-workflow surface (list/read/trigger + the Telegram/Slack@@ -275,6 +354,23 @@ export class HostReconciler {// B2: whether the CC cache initial-list has completed. Defaults to false// (safe: preserves existing Deployment replicas until wired by McpServerWatcher).private ccCacheSyncedFn: () => boolean = () => false+ /**+ * Resolve the current cached Host object by name. Wired by McpServerWatcher+ * from its live Host cache so a fleet worker reconciles the freshest spec and+ * so orphan cleanup compares candidates with the CURRENT inventory rather than+ * the pass snapshot. `null` (unwired) means callers fall back to the pass+ * snapshot for reconcile, and cleanup stays fail-closed (authority unknown).+ */+ private resolveCurrentHost: ((name: string) => HostCRD | undefined) | null = null+ /**+ * Snapshot the current Host watch authority + generation. Wired by+ * McpServerWatcher. Default is fail-closed (unknown) so orphan cleanup never+ * runs until the real authority getter is installed.+ */+ private hostWatchAuthority: () => HostWatchAuthoritySnapshot = () => ({+ known: false,+ generation: 0,+ })constructor(kc: k8s.KubeConfig, deps?: HostReconcilerDeps) {this.appsApi =@@ -364,6 +460,25 @@ export class HostReconciler {this.ccCacheSyncedFn = fn}+ /**+ * Late-bound setter for the live Host cache resolver. A fleet worker resolves+ * the current cached Host at execution time (skipping absent/superseded+ * entries), and orphan cleanup uses it to compare candidates with the CURRENT+ * inventory. Wired by McpServerWatcher from its `hosts` cache.+ */+ setResolveCurrentHost(fn: (name: string) => HostCRD | undefined): void {+ this.resolveCurrentHost = fn+ }++ /**+ * Late-bound setter for the Host watch authority/generation snapshot. Wired by+ * McpServerWatcher so orphan cleanup can require known authority and a stable+ * watch generation before deleting anything.+ */+ setHostWatchAuthority(fn: () => HostWatchAuthoritySnapshot): void {+ this.hostWatchAuthority = fn+ }+/*** Late-bound setter for the host-ref lookup used by* `patchChannelReaderRevisionAnnotation` to discover Secret(s) referenced@@ -1979,9 +2094,19 @@ export class HostReconciler {if (affectedCCs.length === 0) returnconst affectedHosts = new Set<string>(affectedCCs.map(cc => cc.spec.hostRef))- for (const hostName of affectedHosts) {- await this.patchChannelReaderRevisionAnnotation(hostName)- }+ // Addendum 2: each affected Host patches only its own `channel-reader-<host>`+ // Deployment annotation — a disjoint, order-independent, idempotent write set+ // per Host (§10.4 inventory). Fan out through the bounded worker pool+ // (reusing HCC_HOST_FULL_RECONCILE_CONCURRENCY) so a shared credentials-Secret+ // change touching many Hosts is not head-of-line blocked, while never issuing+ // an unbounded burst at the K8s API. patchChannelReaderRevisionAnnotation+ // still swallows its own per-Host errors, so this method continues not to+ // throw (runBoundedHostWorkers never rethrows).+ await runBoundedHostWorkers(+ Array.from(affectedHosts),+ config.hostFullReconcileConcurrency,+ hostName => this.patchChannelReaderRevisionAnnotation(hostName)+ )}buildDeployment(@@ -3328,19 +3453,42 @@ export class HostReconciler {throwCleanupFailures(failures, `Failed to delete runtime resources for Host "${name}"`)}- async reconcile(host: HostCRD): Promise<void> {+ async reconcile(host: HostCRD, source: HostReconcileSource = 'urgent'): Promise<void> {+ const dispatchedAt = Date.now()return this.lifecycle.serializeByHost(host.name, async () => {+ const admittedAt = Date.now()+ hostReconcileInFlight.inc({ lane: source })try {await this.reconcileCore(host)this.enqueueReconcileOutcome(host)+ this.observeReconcileLatency(source, 'success', dispatchedAt, admittedAt)} catch (error) {this.enqueueControllerError(host, 'reconcile_exception', error)this.enqueueReconcileOutcome(host)+ this.observeReconcileLatency(source, 'error', dispatchedAt, admittedAt)throw error+ } finally {+ hostReconcileInFlight.dec({ lane: source })}})}+ private observeReconcileLatency(+ source: HostReconcileSource,+ outcome: 'success' | 'error',+ dispatchedAt: number,+ admittedAt: number+ ): void {+ hostReconcileQueueWaitSeconds.observe(+ { lane: source, outcome },+ Math.max(0, admittedAt - dispatchedAt) / 1000+ )+ hostReconcileDurationSeconds.observe(+ { source, outcome },+ Math.max(0, Date.now() - admittedAt) / 1000+ )+ }+private async reconcileCore(host: HostCRD): Promise<void> {// Wake fast-path (Stage 4.3) BEFORE the heavy reconcile body: the Host// watch callback is serial across the whole fleet, so a pending wake@@ -3644,216 +3792,283 @@ export class HostReconciler {}async reconcileDelete(name: string, namespace: string): Promise<void> {- await this.deleteHostRuntimeResources(name, namespace)- this.clearStatus(name)- this.desktopHosts.delete(name)+ // 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 () => {+ await this.deleteHostRuntimeResources(name, namespace)+ this.clearStatus(name)+ this.desktopHosts.delete(name)+ })}- private async collectHostReconcileFailures(desiredHosts: HostCRD[]): Promise<unknown[]> {- const failures: unknown[] = []- for (const host of desiredHosts) {+ /**+ * Reconcile the fleet with bounded cross-Host concurrency. Dispatches Host+ * KEYS (not stale object snapshots): each worker resolves the CURRENT cached+ * Host at execution time and skips entries the cache no longer holds+ * (superseded by a delete/newer event). Failures are aggregated completely.+ */+ private async collectHostReconcileFailures(+ desiredHosts: HostCRD[],+ source: HostReconcileSource+ ): Promise<unknown[]> {+ const snapshotByName = new Map(desiredHosts.map(h => [h.name, h]))+ const resolve = this.resolveCurrentHost ?? ((name: string) => snapshotByName.get(name))+ const keys = desiredHosts.map(h => h.name)+ return runBoundedHostWorkers(keys, config.hostFullReconcileConcurrency, async name => {+ const host = resolve(name)+ if (!host) return // absent/superseded since the pass captured its snapshottry {- await this.reconcile(host)+ await this.reconcile(host, source)} catch (error) {- console.error(`[HostReconciler] Fleet reconcile failed for Host "${host.name}":`, error)- failures.push(error)+ console.error(`[HostReconciler] Fleet reconcile failed for Host "${name}":`, error)+ throw error}- }- return failures+ })}- private async collectHostCleanupFailures(desiredHosts: HostCRD[]): Promise<unknown[]> {+ /**+ * Orphan cleanup with the §10.5 authority contract (replaces the accidental+ * safety the removed global tail used to provide):+ * - runs only with known watch authority and the SAME generation captured at+ * pass start;+ * - compares candidates with the CURRENT cache, not the pass snapshot;+ * - groups candidates by owning logical Host from ownership labels; a+ * candidate with no derivable owner is NEVER deleted (deferred + recorded);+ * - performs ONE fresh authoritative Host read per orphan Host; a confirmed+ * 404 (while authority stays valid) authorizes deleting that Host's entire+ * owned bundle INSIDE the Host's per-Host serializer;+ * - defers (with a bounded reason) on unknown authority, generation drift,+ * watch loss, a present read, or a failed read.+ */+ private async collectHostCleanupFailures(+ capturedAuthority: HostWatchAuthoritySnapshot+ ): Promise<unknown[]> {const failures: unknown[] = []- let existingDeployments: k8s.V1Deployment[] = []+ const authorityValid = (): boolean => {+ const current = this.hostWatchAuthority()+ return (+ capturedAuthority.known &&+ current.known &&+ capturedAuthority.generation === current.generation+ )+ }++ if (!authorityValid()) {+ const current = this.hostWatchAuthority()+ const reason = !capturedAuthority.known || !current.known ? 'authority_unknown' : 'generation_changed'+ hostCleanupDeferredTotal.inc({ reason })+ console.warn(`[HostReconciler] Deferring orphan cleanup: ${reason}`)+ return failures+ }++ let candidates: CleanupCandidate[]try {- existingDeployments = await this.listManagedHostDeployments()+ candidates = await this.gatherCleanupCandidates(failures)} catch (error) {- console.error('[HostReconciler] Failed to list managed host deployments:', error)failures.push(error)+ return failures}- const desiredNames = new Set(desiredHosts.map(h => h.name))- for (const deployment of existingDeployments) {- const name = deployment.metadata?.name || ''- const namespace = deployment.metadata?.namespace || config.hostNamespace- if (!desiredNames.has(name)) {- try {- await this.deleteHostRuntimeResources(name, namespace)- } catch (error) {- console.error(`[HostReconciler] Fleet cleanup failed for orphan Host "${name}":`, error)- failures.push(error)- }++ const cacheHasHost = (name: string): boolean =>+ this.resolveCurrentHost ? this.resolveCurrentHost(name) !== undefined : false++ const orphanHosts = new Set<string>()+ for (const candidate of candidates) {+ if (!candidate.owner) {+ // Never delete a resource whose owning Host cannot be derived.+ hostCleanupDeferredTotal.inc({ reason: 'no_owner_label' })+ console.warn(+ `[HostReconciler] Deferring orphan candidate ${candidate.kind}/${candidate.name}: no derivable owning Host`+ )+ continue}+ if (cacheHasHost(candidate.owner)) continue // still present → retain+ orphanHosts.add(candidate.owner)}- const knownHostNames = desiredHosts.map(h => h.name)- for (const sweep of [- () => this.sweepOrphanChannelReaderResources(knownHostNames),- () => this.sweepOrphanHostNetworkPolicies(knownHostNames),- ]) {- try {- await sweep()- } catch (error) {- failures.push(error)+ // §10.5 destructive cleanup runs per orphan logical Host. Each Host's owned+ // write set is disjoint (§10.4 inventory) and each destructive bundle runs+ // inside that Host's own `serializeByHost` chain, so distinct orphan Hosts+ // are provably independent. Addendum 2: dispatch them through the same+ // bounded worker pool as the fleet (reusing HCC_HOST_FULL_RECONCILE_CONCURRENCY)+ // instead of a serial `for … await` — never an unbounded fan-out at the K8s+ // API. Same-Host ordering is still guaranteed by serializeByHost, and delete+ // failures still aggregate completely because runBoundedHostWorkers collects+ // every lane's throw.+ const cleanupFailures = await runBoundedHostWorkers(+ Array.from(orphanHosts),+ config.hostFullReconcileConcurrency,+ async hostName => {+ if (!authorityValid()) {+ hostCleanupDeferredTotal.inc({ reason: 'watch_lost' })+ console.warn(+ `[HostReconciler] Deferring orphan cleanup for "${hostName}": watch authority lost`+ )+ return+ }+ const presence = await this.readHostPresence(hostName)+ if (presence === 'present') return // reappeared → retain+ if (presence === 'error') {+ hostCleanupDeferredTotal.inc({ reason: 'fresh_read_failed' })+ return+ }+ if (+ !destructiveCleanupAllowed({+ watchAuthorityKnown: this.hostWatchAuthority().known,+ capturedWatchGeneration: capturedAuthority.generation,+ currentWatchGeneration: this.hostWatchAuthority().generation,+ currentCacheOmitsHost: !cacheHasHost(hostName),+ freshAuthoritativeRead: 'confirmed404',+ })+ ) {+ hostCleanupDeferredTotal.inc({ reason: 'watch_lost' })+ return+ }+ try {+ await this.lifecycle.serializeByHost(hostName, async () => {+ // 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 that+ // reconcile serializes ahead of this delete). Re-check the current+ // cache INSIDE the serializer so a just-recreated Host's bundle is+ // never deleted by this stale cleanup.+ if (cacheHasHost(hostName)) {+ hostCleanupDeferredTotal.inc({ reason: 'recreated' })+ return+ }+ await this.deleteHostRuntimeResources(hostName, config.hostNamespace)+ })+ } catch (error) {+ console.error(+ `[HostReconciler] Fleet cleanup failed for orphan Host "${hostName}":`,+ error+ )+ throw error+ }}- }+ )+ failures.push(...cleanupFailures)return failures}- async reconcileHosts(desiredHosts: HostCRD[]): Promise<void> {- const hostFailures = await this.collectHostReconcileFailures(desiredHosts)- if (hostFailures.length > 0) {- throw new HostFleetReconcileError(hostFailures, [])+ /**+ * List every managed resource that could be an orphan and derive its owning+ * logical Host from ownership labels. List failures are collected into+ * `listFailures` (reported by the caller) so a partial discovery still cleans+ * what it could confidently attribute. Candidates never drive a delete on+ * their own — the caller applies the fresh-read authority gate.+ */+ private async gatherCleanupCandidates(listFailures: unknown[]): Promise<CleanupCandidate[]> {+ const candidates: CleanupCandidate[] = []+ const pushOwner = (kind: string, name: string | undefined, owner: string | undefined): void => {+ if (!name) return+ candidates.push({ kind, name, owner })}- }- async fullReconcile(desiredHosts: HostCRD[]): Promise<void> {- const hostFailures = await this.collectHostReconcileFailures(desiredHosts)- const cleanupFailures = await this.collectHostCleanupFailures(desiredHosts)- if (hostFailures.length > 0 || cleanupFailures.length > 0) {- throw new HostFleetReconcileError(hostFailures, cleanupFailures)+ try {+ for (const deployment of await this.listManagedHostDeployments()) {+ pushOwner(+ 'Deployment',+ deployment.metadata?.name,+ deployment.metadata?.labels?.[HOST_LABEL]+ )+ }+ } catch (error) {+ console.error('[HostReconciler] Failed to list managed host deployments:', error)+ listFailures.push(error)}- }- private async listManagedHostDeployments(): Promise<k8s.V1Deployment[]> {- const response = await this.appsApi.listNamespacedDeployment({- namespace: config.hostNamespace,- labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,- })- return (response.items || []).filter(item => item.metadata?.labels?.[HOST_LABEL])- }-- /**- * Sweep orphan channel-reader resources from the channels namespace.- * Lists Deployments and Secrets carrying our management labels, then- * deletes those whose clerum.io/host label points at a Host that no- * longer exists. Catches CRDs deleted while HCC was down (UI cascade- * may have been skipped or interrupted).- */- private async sweepOrphanChannelReaderResources(knownHosts: string[]): Promise<void> {- const known = new Set(knownHosts)- const ns = config.channelsNamespace- const failures: unknown[] = []-- // Deployment sweep+ const channelsNs = config.channelsNamespace+ const managed = (labels: Record<string, string> | undefined): boolean =>+ labels?.[MANAGED_BY_LABEL] === MANAGED_BY_VALUEtry {- const list = await this.appsApi.listNamespacedDeployment({ namespace: ns })+ const list = await this.appsApi.listNamespacedDeployment({ namespace: channelsNs })for (const dep of list.items ?? []) {- const labels = dep.metadata?.labels ?? {}- if (labels.app !== 'channel-reader') continue- if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) continue- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = dep.metadata?.name- if (!name) continue- try {- await this.appsApi.deleteNamespacedDeployment({- name,- namespace: ns,- })- console.log(`[HostReconciler] orphan sweep deleted Deployment ${name}`)- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan Deployment delete failed:`, err)- failures.push(err)- }- }+ const labels = dep.metadata?.labels+ if (labels?.app !== 'channel-reader' || !managed(labels)) continue+ pushOwner('ChannelReaderDeployment', dep.metadata?.name, labels[HOST_LABEL])}- } catch (err) {- console.warn('[HostReconciler] orphan Deployment sweep list failed:', err)- failures.push(err)+ } catch (error) {+ console.warn('[HostReconciler] channel-reader Deployment candidate list failed:', error)+ listFailures.push(error)}-- // Service sweeptry {- const list = await this.coreApi.listNamespacedService({ namespace: ns })+ const list = await this.coreApi.listNamespacedService({ namespace: channelsNs })for (const svc of list.items ?? []) {- const labels = svc.metadata?.labels ?? {}- if (labels.app !== 'channel-reader') continue- if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) continue- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = svc.metadata?.name- if (!name) continue- try {- await this.coreApi.deleteNamespacedService({- name,- namespace: ns,- })- console.log(`[HostReconciler] orphan sweep deleted Service ${name}`)- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan Service delete failed:`, err)- failures.push(err)- }- }+ const labels = svc.metadata?.labels+ if (labels?.app !== 'channel-reader' || !managed(labels)) continue+ pushOwner('ChannelReaderService', svc.metadata?.name, labels[HOST_LABEL])}- } catch (err) {- console.warn('[HostReconciler] orphan Service sweep list failed:', err)- failures.push(err)- }-- // Secret sweep — server-side label filter limits the list response to- // Secrets HCC created. The channels-namespace Role grants `secrets: delete`- // broadly because K8s RBAC has no resourceName wildcards, but the actual- // operation here only ever sees managed Secrets, and the in-loop label- // guard below is a defense-in-depth check against any future code path- // that drops the labelSelector.- const sweepLabelSelector = [- `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,- 'clerum.io/component=channel-reader',- ].join(',')+ } catch (error) {+ console.warn('[HostReconciler] channel-reader Service candidate list failed:', error)+ listFailures.push(error)+ }try {const list = await this.coreApi.listNamespacedSecret({- namespace: ns,- labelSelector: sweepLabelSelector,+ namespace: channelsNs,+ labelSelector: [`${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`, 'clerum.io/component=channel-reader'].join(','),})for (const sec of list.items ?? []) {- const labels = sec.metadata?.labels ?? {}- // Belt-and-suspenders: re-verify the managed-by + component labels- // even though the labelSelector should already have filtered them.- // If a future bug drops the selector, this prevents an unscoped- // delete sweep across the channels namespace.- if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE) continue- if (labels['clerum.io/component'] !== 'channel-reader') continue- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = sec.metadata?.name- if (!name) continue- try {- await this.coreApi.deleteNamespacedSecret({- name,- namespace: ns,- })- // Structured audit line — every Secret deletion HCC performs.- // Operators tail this to monitor unexpected deletes.- console.log(- `[HostReconciler] AUDIT: orphan sweep deleted Secret name=${name} ns=${ns} host=${host}`- )- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan Secret delete failed:`, err)- failures.push(err)- }+ const labels = sec.metadata?.labels+ if (!managed(labels) || labels?.['clerum.io/component'] !== 'channel-reader') continue+ pushOwner('ChannelReaderSecret', sec.metadata?.name, labels[HOST_LABEL])+ }+ } catch (error) {+ console.warn('[HostReconciler] channel-reader Secret candidate list failed:', error)+ listFailures.push(error)+ }++ // #827 (Addendum 4 item 4): partial-leftover discovery. A bundle whose+ // Deployment — and even its NetworkPolicies — are already gone must still be+ // discovered from ANY surviving owned resource. List every owned kind HCC+ // writes in the host namespace by ownership label and derive the owner from+ // clerum.io/host; a candidate without a derivable owner is never deleted by+ // the caller (§10.5).+ const hostNs = config.hostNamespace+ const managedSelector = `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`+ const gatherOwnedKind = async (+ kind: string,+ list: () => Promise<{+ items?: Array<{ metadata?: { name?: string; labels?: Record<string, string> } }>+ }>+ ): Promise<void> => {+ try {+ const res = await list()+ for (const item of res.items ?? []) {+ if (!managed(item.metadata?.labels)) continue+ pushOwner(kind, item.metadata?.name, item.metadata?.labels?.[HOST_LABEL])}+ } catch (error) {+ console.warn(`[HostReconciler] ${kind} candidate list failed in ${hostNs}:`, error)+ listFailures.push(error)}- } catch (err) {- console.warn('[HostReconciler] orphan Secret sweep list failed:', err)- failures.push(err)}- throwCleanupFailures(failures, 'Failed to sweep orphan channel-reader resources')- }+ await gatherOwnedKind('Service', () =>+ this.coreApi.listNamespacedService({ namespace: hostNs, labelSelector: managedSelector })+ )+ await gatherOwnedKind('PersistentVolumeClaim', () =>+ this.coreApi.listNamespacedPersistentVolumeClaim({+ namespace: hostNs,+ labelSelector: managedSelector,+ })+ )+ await gatherOwnedKind('ServiceAccount', () =>+ this.coreApi.listNamespacedServiceAccount({+ namespace: hostNs,+ labelSelector: managedSelector,+ })+ )+ await gatherOwnedKind('Secret', () =>+ this.coreApi.listNamespacedSecret({ namespace: hostNs, labelSelector: managedSelector })+ )+ await gatherOwnedKind('Role', () =>+ this.rbacApi.listNamespacedRole({ namespace: hostNs, labelSelector: managedSelector })+ )+ await gatherOwnedKind('RoleBinding', () =>+ this.rbacApi.listNamespacedRoleBinding({ namespace: hostNs, labelSelector: managedSelector })+ )- /**- * Sweep orphan per-Host NetworkPolicies in both `channels` and `mcp-host`- * namespaces. Lists NPs carrying our managed-by label, deletes those whose- * clerum.io/host points at a Host that no longer exists.- *- * Filter is `clerum.io/managed-by=host-context-controller` — leaves the- * static base policies (no managed-by label) untouched.- */- private async sweepOrphanHostNetworkPolicies(knownHosts: string[]): Promise<void> {- const known = new Set(knownHosts)- const failures: unknown[] = []for (const ns of [config.channelsNamespace, config.hostNamespace, config.rpcProxyNamespace]) {try {const list = await this.networkingApi.listNamespacedNetworkPolicy({@@ -3861,28 +4076,67 @@ export class HostReconciler {labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,})for (const np of list.items ?? []) {- const labels = np.metadata?.labels ?? {}- const host = labels[HOST_LABEL]- if (!host || known.has(host)) continue- const name = np.metadata?.name- if (!name) continue- try {- await this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace: ns })- console.log(`[HostReconciler] orphan sweep deleted NetworkPolicy ${name} in ${ns}`)- } catch (err) {- if (getErrorCode(err) !== 404) {- console.warn(`[HostReconciler] orphan NP delete failed:`, err)- failures.push(err)- }- }+ pushOwner('NetworkPolicy', np.metadata?.name, np.metadata?.labels?.[HOST_LABEL])}- } catch (err) {- console.warn(`[HostReconciler] orphan NP sweep list failed in ${ns}:`, err)- failures.push(err)+ } catch (error) {+ console.warn(`[HostReconciler] NetworkPolicy candidate list failed in ${ns}:`, error)+ listFailures.push(error)}}- throwCleanupFailures(failures, 'Failed to sweep orphan Host NetworkPolicies')++ return candidates}++ /**+ * One fresh authoritative Host read. `absent` is a confirmed 404 (the Host is+ * genuinely gone). `present` means the Host reappeared. `error` (timeout,+ * forbidden, 5xx) is deliberately NOT surfaced as a pass failure — the caller+ * defers with a bounded reason, matching the §13.2 cleanup matrix.+ */+ private async readHostPresence(name: string): Promise<'absent' | 'present' | 'error'> {+ try {+ await this.customApi.getNamespacedCustomObject({+ group: HOST_GROUP,+ version: HOST_VERSION,+ namespace: config.hostNamespace,+ plural: HOST_PLURAL,+ name,+ })+ return 'present'+ } catch (error) {+ if (getErrorCode(error) === 404) return 'absent'+ console.warn(`[HostReconciler] Fresh authoritative read for orphan "${name}" failed:`, error)+ return 'error'+ }+ }++ async reconcileHosts(desiredHosts: HostCRD[]): Promise<void> {+ const hostFailures = await this.collectHostReconcileFailures(desiredHosts, 'fleet')+ if (hostFailures.length > 0) {+ throw new HostFleetReconcileError(hostFailures, [])+ }+ }++ async fullReconcile(desiredHosts: HostCRD[]): Promise<void> {+ // Capture watch authority + generation at pass start (§10.5 step 1) so+ // cleanup can prove nothing shifted underneath it before deleting.+ const capturedAuthority = this.hostWatchAuthority()+ const hostFailures = await this.collectHostReconcileFailures(desiredHosts, 'fleet')+ // Cleanup runs only after every fleet worker has settled.+ const cleanupFailures = await this.collectHostCleanupFailures(capturedAuthority)+ if (hostFailures.length > 0 || cleanupFailures.length > 0) {+ throw new HostFleetReconcileError(hostFailures, cleanupFailures)+ }+ }++ private async listManagedHostDeployments(): Promise<k8s.V1Deployment[]> {+ const response = await this.appsApi.listNamespacedDeployment({+ namespace: config.hostNamespace,+ labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`,+ })+ return (response.items || []).filter(item => item.metadata?.labels?.[HOST_LABEL])+ }+}function canonicalStringify(obj: Record<string, unknown>): string {diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex cdf5223f1..c88ce4e8b 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -141,6 +141,10 @@ vi.mock('./hostReconciler', () => ({reconcile = vi.fn()reconcileDelete = vi.fn()setResolveContextMounts = vi.fn()+ // §10.4/§10.5 wiring: McpServerWatcher injects the live Host-cache resolver+ // and the watch-authority snapshot into HostReconciler at construction.+ setResolveCurrentHost = vi.fn()+ setHostWatchAuthority = vi.fn()// Stores the injected callback so tests can invoke it directly._countCommunicationChannelsFn: ((host: string) => number) | null = nullsetCountCommunicationChannels = vi.fn().mockImplementation(function (@@ -1035,7 +1039,15 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {firstFleetPass.resolve(undefined)await failClosedPass- await vi.waitFor(() => expect(mocks.hostReconcileHosts).toHaveBeenCalledTimes(2))+ // Post §10.2: the first lifecycle pass drove Host watch recovery (cache+ // was unsynced), which requested a background full pass (step 8). The+ // successful CC-recovery lifecycle requests merged into that single+ // trailing pass (full wins the merge), so exactly ONE trailing pass runs+ // — now a full pass. This test protects the CC-recovery dedup semantic:+ // concurrent recoveries collapse to one LIST, failed recoveries queue no+ // pass, and a successful recovery queues exactly one trailing pass.+ await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(1))+ expect(mocks.hostReconcileHosts).toHaveBeenCalledTimes(1)expect(mocks.listNamespacedCustomObject.mock.calls.filter(([request]) => request.plural === 'communicationchannels'@@ -1230,12 +1242,19 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {await (watcher as any).performHostResync()expect(mocks.hostReconcileHosts).toHaveBeenCalledTimes(2)- expect(mocks.hostFullReconcile).toHaveBeenCalledOnce()+ // Two full passes: the first is the background pass Host watch recovery+ // requested (§10.2 step 8) when the first lifecycle pass synced the cache;+ // the second is the periodic resync. The protected semantic — a successful+ // resync consumes the pending lifecycle retry rather than running it as a+ // third lifecycle pass — is asserted by hostReconcileHosts staying at 2.+ expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(2)expect((watcher as any).ccAppliedLifecycleGeneration).toBe(lifecycleGeneration)await vi.advanceTimersByTimeAsync(300000)expect(mocks.hostReconcileHosts).toHaveBeenCalledTimes(2)- expect(mocks.hostFullReconcile).toHaveBeenCalledOnce()+ // Still two full passes after the retry window elapses — no additional+ // lifecycle retry was queued (it was consumed by the resync above).+ expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(2)} finally {errorSpy.mockRestore()watcher.stop()@@ -1915,13 +1934,20 @@ describe('McpServerWatcher Host periodic resync serialization', () => {finishActivePass()await Promise.all([first, second, third])- expect(mocks.hostReconcileHosts).toHaveBeenCalledTimes(2)+ // One active lifecycle pass (fleetV1) plus exactly ONE trailing pass — the+ // coalescing semantic this test protects. The two later lifecycle requests+ // did not each spawn a pass; they merged into a single trailing pass. That+ // trailing pass is now a FULL pass because the first lifecycle pass drove+ // Host watch recovery on the unsynced cache, which requested a background+ // full pass (§10.2 step 8) that wins the merge over lifecycle. It reconciles+ // the newest cache (fleetV2), and never overlaps the active pass.+ expect(mocks.hostReconcileHosts).toHaveBeenCalledTimes(1)expect(mocks.hostReconcileHosts).toHaveBeenNthCalledWith(1,fleetV1.map(host => expect.objectContaining({ name: host.metadata.name })))- expect(mocks.hostReconcileHosts).toHaveBeenNthCalledWith(- 2,+ expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(1)+ expect(mocks.hostFullReconcile).toHaveBeenCalledWith(fleetV2.map(host => expect.objectContaining({ name: host.metadata.name })))expect(listCount).toBe(1)@@ -2015,9 +2041,15 @@ describe('McpServerWatcher Host periodic resync serialization', () => {expect(mocks.hostReconcileHosts).toHaveBeenCalledOnce()expect(mocks.hostFullReconcile).toHaveBeenCalledOnce()+ // Protected semantic: a full request is NOT covered by active lifecycle-only+ // work and queues a separate trailing full pass (one lifecycle + one full+ // pass above). The hosts LIST happens exactly ONCE now: §10.2 decouples+ // watch recovery from the fleet pass, so the trailing full pass reconciles+ // the already-synced cache instead of re-LISTing (the old contract LISTed+ // per pass).expect(mocks.listNamespacedCustomObject.mock.calls.filter(([request]) => request.plural === 'hosts')- ).toHaveLength(2)+ ).toHaveLength(1)watcher.stop()})@@ -2054,9 +2086,15 @@ describe('McpServerWatcher Host periodic resync serialization', () => {expect(mocks.hostReconcileHosts).toHaveBeenCalledOnce()expect(mocks.hostFullReconcile).toHaveBeenCalledOnce()+ // Protected semantic: a full request is NOT covered by active lifecycle-only+ // work and queues a separate trailing full pass (one lifecycle + one full+ // pass above). The hosts LIST happens exactly ONCE now: §10.2 decouples+ // watch recovery from the fleet pass, so the trailing full pass reconciles+ // the already-synced cache instead of re-LISTing (the old contract LISTed+ // per pass).expect(mocks.listNamespacedCustomObject.mock.calls.filter(([request]) => request.plural === 'hosts')- ).toHaveLength(2)+ ).toHaveLength(1)watcher.stop()})@@ -2097,11 +2135,17 @@ describe('McpServerWatcher Host periodic resync serialization', () => {finishLifecyclePass()await Promise.all([active, pendingFull, latestLifecycle])+ // Protected semantic: a newer lifecycle generation arriving while a full+ // pass is pending does NOT displace the full coverage — it merges in (full+ // wins), so exactly one lifecycle + one full pass run and the newest+ // generation is applied. The hosts LIST happens once now (§10.2 decouples+ // recovery from the fleet pass; the trailing full pass reuses the synced+ // cache rather than re-LISTing).expect(mocks.hostReconcileHosts).toHaveBeenCalledOnce()expect(mocks.hostFullReconcile).toHaveBeenCalledOnce()expect(mocks.listNamespacedCustomObject.mock.calls.filter(([request]) => request.plural === 'hosts')- ).toHaveLength(2)+ ).toHaveLength(1)expect((watcher as any).ccAppliedLifecycleGeneration).toBe(secondGeneration)watcher.stop()})@@ -2210,7 +2254,16 @@ describe('McpServerWatcher Host periodic resync serialization', () => {generation: 2,spec: { lifecycle: { stateless: true } },})- expect(watcher.getHostReconciler().reconcile).not.toHaveBeenCalled()+ // Generation fence (the protected semantic): the retired-stream callback+ // (canonical-host generation 1) must never drive a reconcile. Under §10.2+ // recovery step 7 the freshly-LISTed canonical-host IS urgently reconciled —+ // but only at generation 2, never the stale generation-1 payload from the+ // retired stream. Assert every reconcile call carried the fresh generation.+ const reconcile = watcher.getHostReconciler().reconcile as unknown as ReturnType<typeof vi.fn>+ expect(reconcile).toHaveBeenCalled()+ for (const [host] of reconcile.mock.calls) {+ expect(host).toMatchObject({ name: 'canonical-host', generation: 2 })+ }watcher.stop()})@@ -2263,14 +2316,27 @@ describe('McpServerWatcher Host periodic resync serialization', () => {expect((watcher as any).hostWatchRetryTimers.size).toBe(0)expect((watcher as any).latestHostWatchEventRevisions.size).toBe(0)await vi.advanceTimersByTimeAsync(5000)- expect(reconcile).toHaveBeenCalledTimes(1)+ // Protected semantic: the pending retry for the failed gen-1 event is+ // CANCELLED when the full snapshot retires the stream — it must not fire+ // after its 5s delay. The gen-1 event is therefore reconciled exactly once+ // (the original failed attempt, never re-run by the retry). Under §10.2+ // recovery step 7 the freshly-LISTed gen-2 host is separately reconciled;+ // that is new, legitimate work, not the cancelled retry.+ const gen1Calls = reconcile.mock.calls.filter(([host]) => host?.generation === 1)+ const gen2Calls = reconcile.mock.calls.filter(([host]) => host?.generation === 2)+ expect(gen1Calls).toHaveLength(1)+ expect(gen2Calls).toHaveLength(1)expect(mocks.hostFullReconcile).toHaveBeenCalledWith([expect.objectContaining({ name: 'retry-before-list', generation: 2 }),])watcher.stop()})- it('orders Host watch mutations after an active full pass once LIST has completed', async () => {+ // §10.3 replaces the old global-tail head-of-line contract (independent Host+ // events waited behind an active full pass). The two tests below assert the+ // new contract: an independent Host is admitted immediately during a blocked+ // pass, and same-Host events still reach the per-Host chain in causal order.+ it('admits an independent Host watch event while a full pass is blocked', async () => {vi.clearAllMocks()const fullReconcile = deferred()const order: string[] = []@@ -2290,18 +2356,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {)mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {if (plural !== 'hosts') return { items: [] }- return {- items: [- {- metadata: { name: 'updated-host', namespace: 'mcp-host', generation: 1 },- spec: { host: 'updated-host', lifecycle: { stateless: false } },- },- {- metadata: { name: 'deleted-host', namespace: 'mcp-host', generation: 1 },- spec: { host: 'deleted-host' },- },- ],- }+ return { metadata: { resourceVersion: 'blocked-pass-rv' }, items: [] }})mocks.hostFullReconcile.mockImplementation(async () => {order.push('full:start')@@ -2313,13 +2368,11 @@ describe('McpServerWatcher Host periodic resync serialization', () => {const reconcile = vi.spyOn(hostReconciler, 'reconcile').mockImplementation(async host => {order.push(`watch:${host.name}:${host.generation}`)})- const reconcileDelete = vi- .spyOn(hostReconciler, 'reconcileDelete')- .mockImplementation(async name => {- order.push(`delete:${name}`)- })await (watcher as any).startHostWatch('test-host-rv')if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ // Cache already synced: the full pass blocks purely on the mocked+ // fullReconcile and does not drive recovery, isolating admission behavior.+ ;(watcher as any).hostCacheSynced = trueconst full = (watcher as any).requestHostFleetReconcile('Periodic resync',@@ -2327,22 +2380,77 @@ describe('McpServerWatcher Host periodic resync serialization', () => {'full') as Promise<void>await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledOnce())- const modified = hostWatchCallback('MODIFIED', {- metadata: { name: 'updated-host', namespace: 'mcp-host', generation: 2 },- spec: { host: 'updated-host', lifecycle: { stateless: true } },- })- const deleted = hostWatchCallback('DELETED', {- metadata: { name: 'deleted-host', namespace: 'mcp-host', generation: 2 },- spec: { host: 'deleted-host' },++ // A watch event for an INDEPENDENT Host must reconcile without waiting for+ // the blocked full pass — the removed global tail no longer gates it.+ const independent = hostWatchCallback('MODIFIED', {+ metadata: { name: 'independent-host', namespace: 'mcp-host', generation: 5 },+ spec: { host: 'independent-host', lifecycle: { stateless: true } },})+ await vi.waitFor(() =>+ expect(reconcile).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'independent-host', generation: 5 }),+ 'urgent' // direct watch admission reconciles on the urgent lane (F1)+ )+ )+ // Independent Host progressed while the full pass is still blocked.+ expect(order).toContain('watch:independent-host:5')+ expect(order).not.toContain('full:end')- await Promise.resolve()- expect(reconcile).not.toHaveBeenCalled()- expect(reconcileDelete).not.toHaveBeenCalled()fullReconcile.resolve()- await Promise.all([full, modified, deleted])+ await Promise.all([full, independent])+ expect(order).toContain('full:end')+ watcher.stop()+ })- expect(order).toEqual(['full:start', 'full:end', 'watch:updated-host:2', 'delete:deleted-host'])+ it('dispatches same-Host watch events to the per-Host chain in causal order', async () => {+ vi.clearAllMocks()+ const order: string[] = []+ type HostWatchCallback = (type: string, host: unknown) => Promise<void>+ let hostWatchCallback: HostWatchCallback | undefined+ mocks.watch.mockImplementation(+ async (path: string, _query: unknown, callback: HostWatchCallback) => {+ if (path.endsWith('/hosts')) hostWatchCallback = callback+ return { abort: vi.fn() }+ }+ )+ mocks.listNamespacedCustomObject.mockImplementation(async () => ({ items: [] }))+ const watcher = new McpServerWatcher()+ const hostReconciler = watcher.getHostReconciler()+ // The reconcile()/reconcileDelete() spies stand in for the per-Host chain;+ // the actual serializeByHost non-overlap guarantee is proven in+ // hostReconciler.test.ts (delete serialization). Here we assert the+ // k8sClient dispatch order for the SAME Host is causal and the final cache+ // state belongs to the newest event (§13.1: N+1 follows the same chain).+ vi.spyOn(hostReconciler, 'reconcile').mockImplementation(async (host: HostCRD) => {+ order.push(`reconcile:${host.name}:${host.generation}`)+ })+ vi.spyOn(hostReconciler, 'reconcileDelete').mockImplementation(async (name: string) => {+ order.push(`delete:${name}`)+ })+ await (watcher as any).startHostWatch('same-host-rv')+ if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ ;(watcher as any).hostCacheSynced = true++ await hostWatchCallback('MODIFIED', {+ metadata: { name: 'same-host', namespace: 'mcp-host', generation: 1 },+ spec: { host: 'same-host', lifecycle: { stateless: false } },+ })+ await hostWatchCallback('MODIFIED', {+ metadata: { name: 'same-host', namespace: 'mcp-host', generation: 2 },+ spec: { host: 'same-host', lifecycle: { stateless: true } },+ })+ await hostWatchCallback('DELETED', {+ metadata: { name: 'same-host', namespace: 'mcp-host', generation: 3 },+ spec: { host: 'same-host' },+ })++ expect(order).toEqual([+ 'reconcile:same-host:1',+ 'reconcile:same-host:2',+ 'delete:same-host',+ ])+ expect((watcher as any).hosts.has('same-host')).toBe(false)watcher.stop()})@@ -2391,9 +2499,8 @@ describe('McpServerWatcher Host periodic resync serialization', () => {watcher.stop()})- it('drops a Host event that is still queued when the watcher stops', async () => {+ it('drops a Host event that arrives after the watcher stops', async () => {vi.clearAllMocks()- const fullReconcile = deferred()let hostWatchCallback: ((type: string, apiObj: any) => Promise<void>) | undefinedmocks.watch.mockImplementation(async (@@ -2409,32 +2516,28 @@ describe('McpServerWatcher Host periodic resync serialization', () => {if (plural === 'hosts') return { items: [] }return { items: [] }})- mocks.hostFullReconcile.mockImplementation(() => fullReconcile.promise)const watcher = new McpServerWatcher()const reconcile = vi.spyOn(watcher.getHostReconciler(), 'reconcile').mockResolvedValue(undefined)await (watcher as any).startHostWatch('test-host-rv')if (!hostWatchCallback) throw new Error('Host watch callback was not installed')+ ;(watcher as any).hostCacheSynced = true- const full = (watcher as any).requestHostFleetReconcile(- 'Periodic resync',- undefined,- 'full'- ) as Promise<void>- await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledOnce())- const queuedEvent = hostWatchCallback('ADDED', {+ // §10.3 removes the global tail, so independent Host events dispatch+ // immediately rather than queuing behind a pass. The drop-on-stop guarantee+ // is now the stopped-guard: a watch event that arrives AFTER the watcher has+ // stopped must not start any reconcile work. Asserted deterministically by+ // awaiting the callback then flushing a microtask — no wait-on-absence.+ watcher.stop()+ const lateEvent = hostWatchCallback('ADDED', {metadata: { name: 'stopped-host', namespace: 'mcp-host', generation: 1 },spec: { host: 'stopped-host', lifecycle: { stateless: true } },})+ await lateEventawait Promise.resolve()expect(reconcile).not.toHaveBeenCalled()-- watcher.stop()- fullReconcile.resolve()- await Promise.all([full, queuedEvent])-- expect(reconcile).not.toHaveBeenCalled()+ expect((watcher as any).hosts.has('stopped-host')).toBe(false)})it('settles the active caller and lets shutdown unblock a promoted trailing pass', async () => {@@ -2455,10 +2558,13 @@ describe('McpServerWatcher Host periodic resync serialization', () => {const trailingPass = new Promise<void>(resolve => {resolveTrailingPass = resolve})- mocks.hostReconcileHosts- .mockReset()- .mockImplementationOnce(() => activePass)- .mockImplementationOnce(() => trailingPass)+ mocks.hostReconcileHosts.mockReset().mockImplementationOnce(() => activePass)+ // The trailing pass is a FULL pass now: the active lifecycle pass drove Host+ // watch recovery on the unsynced cache, which requested a background full+ // pass (§10.2 step 8) that the later lifecycle request merged into (full+ // wins). Block that full pass so it stays running until shutdown unblocks+ // the promoted trailing waiter — the semantic this test protects.+ mocks.hostFullReconcile.mockReset().mockImplementation(() => trailingPass)const watcher = new McpServerWatcher()const activeGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()const activeRequest = (watcher as any).requestHostFleetReconcile(@@ -2480,7 +2586,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {try {resolveActivePass()await activeRequest- await vi.waitFor(() => expect(mocks.hostReconcileHosts).toHaveBeenCalledTimes(2))+ await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(1))expect(trailingSettled).toBe(false)watcher.stop()@@ -2561,8 +2667,15 @@ describe('McpServerWatcher Host periodic resync serialization', () => {await Promise.all([staleRequest, currentRequest])expect(hostListCount).toBe(1)- expect(mocks.hostReconcileHosts).toHaveBeenCalledTimes(1)- expect(mocks.hostReconcileHosts).toHaveBeenCalledWith([+ // Protected semantic: the stale-generation lifecycle pass is ABANDONED (its+ // generation no longer matches the current one), so no lifecycle pass runs+ // its work; only the latest work applies, to the freshly-LISTed canonical+ // cache. That latest work now runs as a FULL pass, because Host watch+ // recovery (driven by the first pass) requested a background full pass+ // (§10.2 step 8) into which the current lifecycle request merged (full wins).+ expect(mocks.hostReconcileHosts).not.toHaveBeenCalled()+ expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(1)+ expect(mocks.hostFullReconcile).toHaveBeenCalledWith([expect.objectContaining({ name: 'canonical-host' }),])expect((watcher as any).hosts.get('canonical-host')).toMatchObject({@@ -2857,7 +2970,7 @@ describe('McpServerWatcher Host watch generation', () => {watcher.stop()})- it('re-arms recovery when a closed watch recovery request is covered by its active full pass', async () => {+ it('recovers a closed watch independently of an active full pass', async () => {vi.useFakeTimers()const firstFullReconcile = deferred()let snapshotSequence = 0@@ -2895,25 +3008,37 @@ describe('McpServerWatcher Host watch generation', () => {'full') as Promise<void>+ // The first full pass drives watch recovery: LIST #1 + watch from host-rv-1,+ // then blocks inside the (mocked) fullReconcile.await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledOnce())- doneCallbacks[0](null)- expect((watcher as any).hostCacheSynced).toBe(false)-- await vi.advanceTimersByTimeAsync(5000)expect(snapshotSequence).toBe(1)- expect((watcher as any).hostCacheRecoveryTimer).toBeNull()- firstFullReconcile.resolve(undefined)- await full+ // The watch closes while the full pass is still blocked.+ doneCallbacks[0](null)+ expect((watcher as any).hostCacheSynced).toBe(false)expect((watcher as any).hostCacheRecoveryTimer).not.toBeNull()+ // §10.2 decouples watch recovery from the fleet pass. Under the OLD contract+ // the closed-watch recovery request was COVERED (deferred) by the active+ // full pass, so no re-LIST happened until the pass finished. Now recovery is+ // an independent, deduplicated operation: when its retry timer fires it+ // re-establishes LIST -> WATCH immediately (snapshot #2, fresh watch from the+ // new resourceVersion) WITHOUT waiting for the still-blocked full pass, and+ // marks authority known again. This test protects that independence plus the+ // re-arm-on-close semantic.await vi.advanceTimersByTimeAsync(5000)- await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(2))expect(snapshotSequence).toBe(2)+ expect((watcher as any).hostCacheSynced).toBe(true)expect(watchQueries).toEqual([{ resourceVersion: 'host-rv-1' },{ resourceVersion: 'host-rv-2' },])+ expect((watcher as any).hostCacheRecoveryTimer).toBeNull()++ // The still-blocked original full pass resolving afterward does not disturb+ // the independently recovered watch authority.+ firstFullReconcile.resolve(undefined)+ await fullexpect((watcher as any).hostCacheSynced).toBe(true)watcher.stop()})@@ -2996,7 +3121,15 @@ describe('McpServerWatcher Host watch generation', () => {})expect(callbacks).toHaveLength(2)- expect(reconcile).not.toHaveBeenCalled()+ // Generation fence (the protected semantic): the delayed MODIFIED delivered+ // on the retired stream (transition-host generation 1) is ignored — it must+ // never drive a reconcile and must not overwrite the cache. Under §10.2+ // recovery step 7 the freshly-LISTed transition-host IS urgently reconciled,+ // but only at generation 2, never the stale generation-1 payload.+ expect(reconcile).toHaveBeenCalled()+ for (const [host] of reconcile.mock.calls) {+ expect(host).toMatchObject({ name: 'transition-host', generation: 2 })+ }expect((watcher as any).hosts.get('transition-host')).toMatchObject({generation: 2,spec: { lifecycle: { stateless: true } },@@ -3049,6 +3182,126 @@ describe('McpServerWatcher Host watch generation', () => {watcher.stop()})+ it('recovery diff enqueues an immediate per-Host delete for a disappeared Host (#827 item 1)', async () => {+ vi.clearAllMocks()+ const watcher = new McpServerWatcher()+ const reconcileDelete = vi+ .spyOn(watcher.getHostReconciler(), 'reconcileDelete')+ .mockResolvedValue(undefined)+ // Fresh authoritative snapshot holds only "live-host"; "gone-host" was in the+ // pre-recovery inventory (previousNames) and has genuinely disappeared.+ ;(watcher as any).enqueueRecoveredHostDeletes(+ [{ name: 'live-host', namespace: 'mcp-host', uid: 'u1', spec: { host: 'live-host' } }],+ new Set(['live-host', 'gone-host'])+ )+ await vi.waitFor(() => expect(reconcileDelete).toHaveBeenCalledWith('gone-host', 'mcp-host'))+ // A Host still present in the fresh snapshot is never deleted.+ expect(reconcileDelete).not.toHaveBeenCalledWith('live-host', 'mcp-host')+ watcher.stop()+ })++ 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()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockResolvedValue(undefined)+ const reconcileDelete = vi+ .spyOn(watcher.getHostReconciler(), 'reconcileDelete')+ .mockResolvedValue(undefined)+ // The recreated Host is the CURRENT cache entry the urgent dispatch resolves.+ ;(watcher as any).hosts.set('x', {+ name: 'x',+ namespace: 'mcp-host',+ uid: 'uid-B',+ generation: 1,+ spec: { host: 'x' },+ })+ // Same name, same generation (reset to 1), but a DIFFERENT uid than before.+ ;(watcher as any).enqueueRecoveredUrgentHosts(+ [{ name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 1, spec: { host: 'x' } }],+ new Set(['x']),+ new Map([['x', 1]]),+ new Map([['x', 'uid-A']])+ )+ // The snapshot still contains "x" by name, so the recovery-delete diff never+ // treats it as a disappearance.+ ;(watcher as any).enqueueRecoveredHostDeletes(+ [{ name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 1, spec: { host: 'x' } }],+ new Set(['x'])+ )+ await vi.waitFor(() =>+ expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ name: 'x' }), 'urgent')+ )+ expect(reconcileDelete).not.toHaveBeenCalled()+ watcher.stop()+ })++ it('suppresses a watch event whose identity (uid) differs from the cached Host (#827 item 2)', () => {+ const watcher = new McpServerWatcher()+ ;(watcher as any).hosts.set('x', { name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 3 })+ ;(watcher as any).latestHostWatchEventRevisions.set('x', 7)+ // A stale MODIFIED carrying the OLD identity must not act on the recreated one.+ expect(+ (watcher as any).isCurrentHostWatchEvent(+ 'MODIFIED',+ { name: 'x', namespace: 'mcp-host', uid: 'uid-A', generation: 3 },+ 7+ )+ ).toBe(false)+ // The current identity is admitted.+ expect(+ (watcher as any).isCurrentHostWatchEvent(+ 'MODIFIED',+ { name: 'x', namespace: 'mcp-host', uid: 'uid-B', generation: 3 },+ 7+ )+ ).toBe(true)+ watcher.stop()+ })++ it('reconciles a retried Host watch event on the "retry" lane, not "urgent" (F1)', async () => {+ vi.useFakeTimers()+ let hostWatchCallback: ((type: string, apiObj: any) => Promise<void>) | undefined+ mocks.watch.mockImplementation(+ async (+ _path: string,+ _params: object,+ callback: (type: string, apiObj: any) => Promise<void>+ ) => {+ hostWatchCallback = callback+ return { abort: vi.fn() }+ }+ )+ const watcher = new McpServerWatcher()+ const reconcile = vi+ .spyOn(watcher.getHostReconciler(), 'reconcile')+ .mockRejectedValueOnce(new Error('transient'))+ .mockResolvedValue(undefined)+ await (watcher as any).startHostWatch('test-host-rv')+ if (!hostWatchCallback) throw new Error('Host watch callback was not installed')++ await hostWatchCallback('MODIFIED', {+ metadata: { name: 'retry-lane-host', namespace: 'mcp-host', generation: 2 },+ spec: { host: 'retry-lane-host', lifecycle: { stateless: true } },+ })+ // First attempt is the direct/urgent admission.+ expect(reconcile).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({ name: 'retry-lane-host' }),+ 'urgent'+ )+ await vi.advanceTimersByTimeAsync(5000)+ // The retry attempt populates the distinct "retry" lane.+ expect(reconcile).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ name: 'retry-lane-host' }),+ 'retry'+ )+ watcher.stop()+ vi.useRealTimers()+ })+it('automatically retries a transient Host watch reconciliation failure', async () => {vi.useFakeTimers()let hostWatchCallback: ((type: string, apiObj: any) => Promise<void>) | undefineddiff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex c452d9c4c..09effb0e1 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -17,7 +17,17 @@ import { config } from './config'import { gfsDefaultFactoryConfig } from './gfsConfig'import { GfsReconciler } from './gfsReconciler'import { ControlApiGfsSeedClient } from './gfsSeedClient'-import { HostFleetReconcileError, HostReconciler, type ResolvedSfsMount } from './hostReconciler'+import {+ HostFleetReconcileError,+ HostReconciler,+ type HostReconcileSource,+ type ResolvedSfsMount,+} from './hostReconciler'+import {+ hostDeleteCleanupTotal,+ hostFleetRequestsTotal,+ hostWatchRecoverySeconds,+} from './metrics'import {type InfrastructureTelemetryReporter,createInfrastructureTelemetryReporter,@@ -84,6 +94,9 @@ const COMMUNICATION_CHANNEL_CACHE_RECOVERY_RETRY_MS = 5000const COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 300000]const HOST_CACHE_RECOVERY_RETRY_MS = 5000const HOST_WATCH_RECONCILE_RETRY_DELAYS_MS = [5000, 15000, 30000]+// Wake-pending Hosts get immediate per-Host admission after watch recovery+// (§10.2 step 7) rather than waiting for the background fleet pass.+const WAKE_REQUESTED_ANNOTATION = 'clerum.io/wake-requested'type CommunicationChannelSnapshot = {channels: CommunicationChannelCRD[]@@ -289,6 +302,7 @@ async function listHostSnapshot(): Promise<HostSnapshot> {metadata: {name: stringnamespace?: string+ uid?: stringgeneration?: numberresourceVersion?: stringannotations?: Record<string, string>@@ -301,6 +315,7 @@ async function listHostSnapshot(): Promise<HostSnapshot> {const hosts = list.items.map(item => ({name: item.metadata.name,namespace: item.metadata.namespace || config.hostNamespace,+ uid: item.metadata.uid,generation: item.metadata.generation,resourceVersion: item.metadata.resourceVersion,annotations: item.metadata.annotations,@@ -555,10 +570,11 @@ export class McpServerWatcher implements McpServerProvider {private readonly hostWatchRetryAttempts = new Map<string, number>()private hostCacheSynced = falseprivate hostCacheRecoveryTimer: ReturnType<typeof setTimeout> | null = null- // Host events and inventory passes share one mutation tail. A watch paired- // with the LIST resourceVersion makes queued events causally newer than the- // immutable snapshot reconciled ahead of them.- private hostConvergenceTail: Promise<void> = Promise.resolve()+ // Host watch LIST-to-WATCH recovery is a dedicated, deduplicated operation+ // (§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// 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.@@ -658,6 +674,17 @@ export class McpServerWatcher implements McpServerProvider {this.hostReconciler.setIsCommunicationChannelCacheSynced(() =>this.isCommunicationChannelCacheSynced())+ // A fleet worker resolves the freshest cached Host at execution (skipping+ // entries a delete/newer event has since removed), and orphan cleanup+ // compares candidates with the CURRENT inventory rather than a pass snapshot.+ this.hostReconciler.setResolveCurrentHost(name => this.hosts.get(name))+ // Orphan cleanup requires known watch authority and a stable watch+ // generation; expose both so cleanup fail-closes while authority is unknown+ // or the watch has been retired mid-pass.+ this.hostReconciler.setHostWatchAuthority(() => ({+ known: this.hostCacheSynced,+ generation: this.hostWatchGeneration,+ }))// Per-CC credentials Secret migration: HostReconciler computes the// channel-reader credentials-revision annotation by hashing the Secret(s)// referenced by all CCs of a host. Wire both finders so@@ -833,49 +860,200 @@ export class McpServerWatcher implements McpServerProvider {for (const host of snapshot.hosts) this.hosts.set(host.name, host)}- private async recoverHostInventoryAndWatch(): Promise<HostCRD[]> {+ /**+ * Dedicated, deduplicated Host watch LIST-to-WATCH recovery (§10.2). Watch+ * authority recovers independently of the background fleet convergence pass:+ * concurrent recovery signals reuse the in-flight promise so exactly one LIST+ * + WATCH is installed, and authority is declared known ONLY after the WATCH+ * is established. On success it enqueues discovered new/changed/wake-pending+ * Hosts through their per-Host chains (step 7) and requests — without awaiting+ * — a coalesced background full pass (step 8).+ */+ private recoverHostInventoryAndWatch(): Promise<HostCRD[]> {+ if (this.stopped) return Promise.resolve([])+ if (this.hostRecoveryInFlight) return this.hostRecoveryInFlight+ const recovery = this.performHostInventoryRecovery()+ this.hostRecoveryInFlight = recovery+ const clear = (): void => {+ if (this.hostRecoveryInFlight === recovery) this.hostRecoveryInFlight = null+ }+ void recovery.then(clear, clear)+ return recovery+ }++ private async performHostInventoryRecovery(): Promise<HostCRD[]> {+ const startedAt = Date.now()+ // Capture the pre-recovery inventory so step 7 can distinguish genuinely+ // new/changed Hosts from ones the fleet pass will converge anyway.+ const previousNames = new Set(this.hosts.keys())+ const previousGenerations = new Map<string, number | undefined>(+ [...this.hosts.values()].map(host => [host.name, host.generation])+ )+ // #827: capture identities so recovery can tell a same-name recreation from+ // a genuine disappearance and reconcile the former rather than delete it.+ const previousUids = new Map<string, string | undefined>(+ [...this.hosts.values()].map(host => [host.name, host.uid])+ )this.retireHostWatch()- const snapshot = await listHostSnapshot()- if (this.stopped) return []- if (!snapshot.resourceVersion) {- throw new Error('Host snapshot missing resourceVersion')+ try {+ const listStartedAt = Date.now()+ const snapshot = await listHostSnapshot()+ if (this.stopped) return []+ if (!snapshot.resourceVersion) {+ throw new Error('Host snapshot missing resourceVersion')+ }+ hostWatchRecoverySeconds.observe(+ { phase: 'list', outcome: 'success' },+ (Date.now() - listStartedAt) / 1000+ )+ this.installHostSnapshot(snapshot)+ const watchStartedAt = Date.now()+ const watchGeneration = await this.startHostWatch(snapshot.resourceVersion)+ if (+ this.stopped ||+ watchGeneration !== this.hostWatchGeneration ||+ this.hostWatchRequest === null+ ) {+ throw new Error('Host snapshot could not be paired with an active watch')+ }+ // Authority is known ONLY after the WATCH is installed.+ this.hostCacheSynced = true+ hostWatchRecoverySeconds.observe(+ { phase: 'watch', outcome: 'success' },+ (Date.now() - watchStartedAt) / 1000+ )+ hostWatchRecoverySeconds.observe(+ { phase: 'total', outcome: 'success' },+ (Date.now() - startedAt) / 1000+ )+ if (this.hostCacheRecoveryTimer) {+ clearTimeout(this.hostCacheRecoveryTimer)+ this.hostCacheRecoveryTimer = null+ }+ this.enqueueRecoveredUrgentHosts(+ snapshot.hosts,+ previousNames,+ previousGenerations,+ previousUids+ )+ // Addendum 4 (#827): a Host present before recovery and absent from the+ // fresh authoritative snapshot genuinely disappeared. Enqueue an immediate+ // per-Host delete cleanup so a DELETE lost to watch retirement is never+ // silently dropped.+ this.enqueueRecoveredHostDeletes(snapshot.hosts, previousNames)+ // Request a coalesced background full pass, but do NOT await it before+ // declaring watch recovery complete.+ void this.requestHostFleetReconcile('Host watch recovery convergence', undefined, 'full')+ return snapshot.hosts+ } catch (error) {+ // Keep authority unknown, record the failure, and use the existing+ // bounded retry policy.+ this.hostCacheSynced = false+ hostWatchRecoverySeconds.observe(+ { phase: 'total', outcome: 'failure' },+ (Date.now() - startedAt) / 1000+ )+ if (!this.stopped) {+ console.error('[K8s] Host watch recovery failed:', error)+ this.scheduleHostCacheRecovery()+ }+ throw error}+ }- this.installHostSnapshot(snapshot)- const watchGeneration = await this.startHostWatch(snapshot.resourceVersion)- if (- this.stopped ||- watchGeneration !== this.hostWatchGeneration ||- this.hostWatchRequest === null- ) {- throw new Error('Host snapshot could not be paired with an active watch')+ /**+ * §10.2 step 7: give genuinely new, changed, or wake-pending Hosts immediate+ * per-Host admission after recovery rather than waiting for the background+ * fleet pass. Each dispatch resolves the CURRENT cached Host at execution and+ * enters that Host's serializer, so it is ordered against any concurrent watch+ * event for the same Host.+ */+ private enqueueRecoveredUrgentHosts(+ hosts: HostCRD[],+ previousNames: Set<string>,+ previousGenerations: Map<string, number | undefined>,+ previousUids: Map<string, string | undefined>+ ): void {+ for (const host of hosts) {+ const isNew = !previousNames.has(host.name)+ const previousGeneration = previousGenerations.get(host.name)+ const changed =+ previousGeneration !== undefined &&+ host.generation !== undefined &&+ host.generation !== previousGeneration+ // #827: a same-name Host recreated during the watch gap carries a fresh+ // uid; its generation may even reset to 1 and look "unchanged", so an+ // identity change is itself urgent work.+ const previousUid = previousUids.get(host.name)+ const recreated =+ previousUid !== undefined && host.uid !== undefined && host.uid !== previousUid+ const wakePending = host.annotations?.[WAKE_REQUESTED_ANNOTATION] !== undefined+ if (!isNew && !changed && !recreated && !wakePending) continue+ void this.dispatchUrgentHostReconcile(host.name)+ }+ }++ private async dispatchUrgentHostReconcile(name: string): Promise<void> {+ if (this.stopped) return+ const host = this.hosts.get(name)+ if (!host) return+ try {+ await this.hostReconciler.reconcile(host, 'urgent')+ } catch (error) {+ console.error(`[K8s] Urgent Host reconcile failed for "${name}":`, error)}+ }- this.hostCacheSynced = true- if (this.hostCacheRecoveryTimer) {- clearTimeout(this.hostCacheRecoveryTimer)- this.hostCacheRecoveryTimer = null+ /**+ * §10.2 + Addendum 4 (#827): a Host present in the pre-recovery inventory but+ * ABSENT from the fresh authoritative snapshot has genuinely disappeared. An+ * accepted DELETED event invalidated when the watch retired is thereby+ * replaced by this authoritative absence check and never silently lost. Each+ * confirmed deletion is dispatched IMMEDIATELY through its own per-Host chain+ * (reconcileDelete serializes internally) — never queued behind other Hosts'+ * convergence; the compensating full-pass sweep remains only a safety net. A+ * same-name recreation is present in the snapshot by name and so is never in+ * the disappeared set (it is reconciled by enqueueRecoveredUrgentHosts).+ */+ private enqueueRecoveredHostDeletes(hosts: HostCRD[], previousNames: Set<string>): void {+ const snapshotNames = new Set(hosts.map(host => host.name))+ for (const name of previousNames) {+ if (snapshotNames.has(name)) continue // still present (or recreated) → not a disappearance+ hostDeleteCleanupTotal.inc({ outcome: 'queued' })+ void this.dispatchRecoveredHostDelete(name)+ }+ }++ private async dispatchRecoveredHostDelete(name: string): Promise<void> {+ if (this.stopped) 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+ // in-flight reconcile for the same Host cannot recreate its resources after+ // cleanup.+ hostDeleteCleanupTotal.inc({ outcome: 'confirmed' })+ try {+ await this.hostReconciler.reconcileDelete(name, config.hostNamespace)+ hostDeleteCleanupTotal.inc({ outcome: 'completed' })+ } catch (error) {+ hostDeleteCleanupTotal.inc({ outcome: 'retried' })+ console.error(+ `[K8s] Recovered Host delete cleanup failed for "${name}"; the safety-net sweep will retry:`,+ error+ )}- return snapshot.hosts}private scheduleHostCacheRecovery(): void {if (this.stopped || this.hostCacheRecoveryTimer) returnthis.hostCacheRecoveryTimer = setTimeout(() => {this.hostCacheRecoveryTimer = null- void this.requestHostFleetReconcile('Host watch recovery', undefined, 'full')+ // 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)}, HOST_CACHE_RECOVERY_RETRY_MS)}- private serializeHostConvergence<T>(work: () => Promise<T>): Promise<T> {- const result = this.hostConvergenceTail.then(work)- this.hostConvergenceTail = result.then(- () => undefined,- () => undefined- )- return result- }-private isCurrentHostWatchEvent(type: HostWatchEventType,host: HostCRD,@@ -885,6 +1063,14 @@ export class McpServerWatcher implements McpServerProvider {if (type === 'DELETED') return !this.hosts.has(host.name)const current = this.hosts.get(host.name)if (!current) return false+ // #827 identity fence: a same-name Host that was deleted and recreated+ // carries a fresh metadata.uid. If the cache already holds a DIFFERENT+ // identity for this name, this event describes a superseded object and must+ // not act on the current one. uid complements (never replaces) the+ // generation fence below and the §10.5 fresh read on the cleanup path.+ if (current.uid !== undefined && host.uid !== undefined && current.uid !== host.uid) {+ return false+ }if (current.generation === undefined || host.generation === undefined) return truereturn current.generation <= host.generation}@@ -905,13 +1091,23 @@ export class McpServerWatcher implements McpServerProvider {private async reconcileHostWatchEvent(type: HostWatchEventType,host: HostCRD,- eventRevision: number+ eventRevision: number,+ source: HostReconcileSource = 'urgent'): Promise<void> {- if (this.stopped || !this.isCurrentHostWatchEvent(type, host, eventRevision)) return+ if (this.stopped) return+ if (!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+ // NOT delete the new identity's resources.+ if (type === 'DELETED' && this.hosts.has(host.name)) {+ hostDeleteCleanupTotal.inc({ outcome: 'superseded' })+ }+ return+ }if (type === 'DELETED') {await this.hostReconciler.reconcileDelete(host.name, host.namespace)} else {- await this.hostReconciler.reconcile(host)+ await this.hostReconciler.reconcile(host, source)}}@@ -959,9 +1155,9 @@ export class McpServerWatcher implements McpServerProvider {return}try {- await this.serializeHostConvergence(() =>- this.reconcileHostWatchEvent(type, host, eventRevision)- )+ // F1: a retry is a distinct reconcile lane from first-attempt load — an+ // operator must be able to tell a retry storm from fresh admission.+ await this.reconcileHostWatchEvent(type, host, eventRevision, 'retry')this.completeHostWatchEvent(host.name, eventRevision)} catch (error) {console.error(`[K8s] Host watch reconciliation retry failed for ${host.name}:`, error)@@ -970,7 +1166,7 @@ export class McpServerWatcher implements McpServerProvider {}private performHostFleetReconcile(request: HostFleetReconcileRequest): Promise<void> {- return this.serializeHostConvergence(() => this.performHostFleetReconcileOnce(request))+ return this.performHostFleetReconcileOnce(request)}private async performHostFleetReconcileOnce(request: HostFleetReconcileRequest): Promise<void> {@@ -984,19 +1180,23 @@ export class McpServerWatcher implements McpServerProvider {return}try {- let hosts: HostCRD[]- if (mode === 'full') {- hosts = await this.recoverHostInventoryAndWatch()+ // Watch authority recovers as an independent, deduplicated operation. A+ // fleet pass only needs to ensure the LIST -> WATCH is established when+ // continuity was lost; it never drives the watch restart on every pass+ // (that would re-LIST forever). Recovery, once synced, requests its own+ // background convergence pass.+ if (!this.hostCacheSynced) {+ await this.recoverHostInventoryAndWatch()if (this.stopped) 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.+ const hosts = [...this.hosts.values()]+ if (mode === 'full') {console.log(`[K8s] Reconciling ${hosts.length} Host(s) after ${reason}`)await this.hostReconciler.fullReconcile(hosts)} else {- // Lifecycle convergence consumes the resourceVersion-continuing Host- // cache and never runs destructive orphan cleanup. If continuity was- // lost, rebuild LIST -> WATCH first so no Host can be missed.- hosts = this.hostCacheSynced- ? [...this.hosts.values()]- : await this.recoverHostInventoryAndWatch()if (this.stopped ||(ccLifecycleGeneration !== undefined &&@@ -1014,6 +1214,7 @@ export class McpServerWatcher implements McpServerProvider {console.log(`[K8s] Completed Host reconciliation after ${reason}`)}} catch (error) {+ hostFleetRequestsTotal.inc({ result: 'failed' })console.error(`[K8s] Host reconciliation after ${reason} failed:`, error)if (!this.stopped && ccLifecycleGeneration !== undefined) {if (error instanceof HostFleetReconcileError && error.hostFailures.length === 0) {@@ -1068,9 +1269,11 @@ export class McpServerWatcher implements McpServerProvider {}const active = this.hostFleetReconcileInFlightif (!active) {+ hostFleetRequestsTotal.inc({ result: 'started' })return this.waitForHostFleetOrShutdown(this.startHostFleetReconcile(request))}if (hostFleetRequestCovers(active, request)) {+ hostFleetRequestsTotal.inc({ result: 'coalesced' })return this.waitForHostFleetOrShutdown(active.promise)}@@ -1090,6 +1293,8 @@ export class McpServerWatcher implements McpServerProvider {this.hostFleetReconcilePending.mode = merged.modethis.hostFleetReconcilePending.ccLifecycleGeneration = merged.ccLifecycleGeneration}+ // The request did not start its own pass; it is queued behind the active one.+ hostFleetRequestsTotal.inc({ result: 'coalesced' })return this.waitForHostFleetOrShutdown(this.hostFleetReconcilePending.promise)}@@ -1112,6 +1317,7 @@ export class McpServerWatcher implements McpServerProvider {pending.resolve()return}+ hostFleetRequestsTotal.inc({ result: 'trailing' })const trailing = this.startHostFleetReconcile(pending)void trailing.then(pending.resolve, pending.resolve)}@@ -2389,6 +2595,7 @@ export class McpServerWatcher implements McpServerProvider {metadata: {name: stringnamespace?: string+ uid?: stringgeneration?: numberresourceVersion?: stringannotations?: Record<string, string>@@ -2401,6 +2608,7 @@ export class McpServerWatcher implements McpServerProvider {const host: HostCRD = {name: apiObj.metadata.name,namespace: apiObj.metadata.namespace || config.hostNamespace,+ uid: apiObj.metadata.uid,generation: apiObj.metadata.generation,resourceVersion: apiObj.metadata.resourceVersion,annotations: apiObj.metadata.annotations,@@ -2422,9 +2630,10 @@ export class McpServerWatcher implements McpServerProvider {}try {- await this.serializeHostConvergence(() =>- this.reconcileHostWatchEvent(eventType, host, eventRevision)- )+ // Direct dispatch (§10.3): reconcileHostWatchEvent enters the per-Host+ // serializer inside reconcile()/reconcileDelete(). The removed+ // process-wide convergence tail no longer gates independent Hosts.+ await this.reconcileHostWatchEvent(eventType, host, eventRevision)this.completeHostWatchEvent(host.name, eventRevision)} catch (error) {console.error(`[K8s] Host reconciliation failed for ${host.name}:`, error)diff --git a/host-context-controller/src/metrics.ts b/host-context-controller/src/metrics.tsindex 5dd7c2549..4de90228e 100644--- a/host-context-controller/src/metrics.ts+++ b/host-context-controller/src/metrics.ts@@ -4,7 +4,7 @@* Uses a dedicated Registry to avoid polluting the global default registry.* Metrics follow the naming convention: clerum_hcc_<metric>_<unit>.*/-import { Counter, Gauge, Registry } from 'prom-client'+import { Counter, Gauge, Histogram, Registry } from 'prom-client'const REGISTRY_KEY = Symbol.for('clerum.hcc.prometheus.registry')type MetricsGlobal = typeof globalThis & { [REGISTRY_KEY]?: Registry }@@ -42,6 +42,33 @@ function gauge(options: {})}+/**+ * Buckets spanning sub-second admission through the urgent (5s), watch-recovery+ * (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++/** Idempotent Histogram helper mirroring counter()/gauge(). */+function histogram(options: {+ name: string+ help: string+ labelNames?: readonly string[]+ buckets?: readonly number[]+}): Histogram<string> {+ const existing = registry.getSingleMetric(options.name)+ if (existing) return existing as Histogram<string>+ return new Histogram({+ name: options.name,+ help: options.help,+ labelNames: [...(options.labelNames ?? [])],+ buckets: [...(options.buckets ?? RECONCILE_LATENCY_BUCKETS)],+ registers: [registry],+ })+}+export const mcpServersTotal = gauge({name: 'clerum_hcc_mcpservers_total',help: 'Total number of McpServer CRDs tracked by HCC',@@ -123,3 +150,56 @@ export const administrativeOutcomeReporterTotal = counter({help: 'Administrative outcome reporter enqueue, flush, and drop outcomes.',labelNames: ['result'] as const,})++// ── Host reconciliation scheduler telemetry (issue #791 follow-up) ──+// Low-cardinality labels only — never host names, users, teams, or session IDs.++export const hostReconcileQueueWaitSeconds = histogram({+ name: 'clerum_hcc_host_reconcile_queue_wait_seconds',+ help: 'Seconds a Host reconcile waited between dispatch and its per-Host chain admitting it.',+ labelNames: ['lane', 'outcome'] as const,+})++export const hostReconcileDurationSeconds = histogram({+ name: 'clerum_hcc_host_reconcile_duration_seconds',+ help: 'Seconds a Host reconcile body executed after admission to its per-Host chain.',+ labelNames: ['source', 'outcome'] as const,+})++export const hostReconcileInFlight = gauge({+ name: 'clerum_hcc_host_reconcile_in_flight',+ help: 'Host reconciles currently executing, by lane (urgent/retry/fleet).',+ labelNames: ['lane'] as const,+})++export const hostWatchRecoverySeconds = histogram({+ name: 'clerum_hcc_host_watch_recovery_seconds',+ help: 'Seconds for Host watch LIST-to-WATCH recovery phases (list/watch/total).',+ labelNames: ['phase', 'outcome'] as const,+})++export const hostFleetRequestsTotal = counter({+ name: 'clerum_hcc_host_fleet_requests_total',+ help: 'Host fleet reconcile requests by coalescing result (started/coalesced/trailing/failed).',+ labelNames: ['result'] as const,+})++export const hostCleanupDeferredTotal = counter({+ name: 'clerum_hcc_host_cleanup_deferred_total',+ help: 'Orphan Host cleanup deferrals by bounded reason.',+ labelNames: ['reason'] as const,+})++// #827 (Addendum 4 item 5): bounded, low-cardinality Host deletion cleanup+// counter. `outcome` is a small fixed set — never a Host name — so cardinality+// stays flat regardless of fleet size.+// queued — a disappeared Host was enqueued for authoritative delete cleanup+// confirmed — the fresh authoritative snapshot confirmed the Host is gone+// completed — the delete cleanup finished (bundle removed / already absent)+// retried — a delete cleanup failed and is left to the safety-net sweep+// superseded — a stale delete was suppressed because a same-name Host was recreated+export const hostDeleteCleanupTotal = counter({+ name: 'clerum_hcc_host_delete_cleanup_total',+ help: 'Host deletion cleanup by outcome (queued/confirmed/completed/retried/superseded).',+ labelNames: ['outcome'] as const,+})diff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.tsindex 0e51e7216..a7488dc7d 100644--- a/host-context-controller/src/types.ts+++ b/host-context-controller/src/types.ts@@ -434,6 +434,14 @@ export interface HostCRD {name: stringnamespace: stringgeneration?: number+ /**+ * metadata.uid — the Kubernetes-assigned stable identity of THIS Host object.+ * A same-name Host deleted and recreated gets a fresh uid, so uid (not name or+ * generation) is what distinguishes a genuine deletion from a same-name+ * recreation on every destructive path (#827). Undefined for snapshots that+ * predate uid capture; identity fences treat "unknown" conservatively.+ */+ uid?: string/*** metadata.resourceVersion of the CR at the time it was read. Preserved by* readFreshHost so the heartbeat-path status writers can pass it back as andiff --git a/host-context-controller/test/__fixtures__/testMocks.ts b/host-context-controller/test/__fixtures__/testMocks.tsindex b621deda0..73a8bae2c 100644--- a/host-context-controller/test/__fixtures__/testMocks.ts+++ b/host-context-controller/test/__fixtures__/testMocks.ts@@ -36,6 +36,8 @@ export type MockCoreApi = {createNamespacedServiceAccount: MockApiMethodreadNamespacedServiceAccount: MockApiMethoddeleteNamespacedServiceAccount: MockApiMethod+ listNamespacedServiceAccount: MockApiMethod+ listNamespacedPersistentVolumeClaim: MockApiMethodlistNamespacedPod: MockApiMethod}@@ -65,6 +67,8 @@ export type MockRbacApi = {createNamespacedRoleBinding: MockApiMethodreadNamespacedRoleBinding: MockApiMethoddeleteNamespacedRoleBinding: MockApiMethod+ listNamespacedRole: MockApiMethod+ listNamespacedRoleBinding: MockApiMethod}function hostNameFromResourceName(name = ''): string {@@ -184,6 +188,9 @@ export function createMockCoreApi(): MockCoreApi {} as MockK8sResource)),deleteNamespacedServiceAccount: vi.fn().mockResolvedValue({}),+ // #827 partial-leftover discovery lists these owned kinds by ownership label.+ listNamespacedServiceAccount: vi.fn().mockResolvedValue({ items: [] }),+ listNamespacedPersistentVolumeClaim: vi.fn().mockResolvedValue({ items: [] }),// wfc pod node-placement lookup for the stateless SFS co-location check.listNamespacedPod: vi.fn().mockResolvedValue({ items: [] }),}@@ -241,6 +248,9 @@ export function createMockRbacApi(): MockRbacApi {} as MockK8sResource)),deleteNamespacedRoleBinding: vi.fn().mockResolvedValue({}),+ // #827 partial-leftover discovery lists RBAC by ownership label.+ listNamespacedRole: vi.fn().mockResolvedValue({ items: [] }),+ listNamespacedRoleBinding: vi.fn().mockResolvedValue({ items: [] }),}}diff --git a/host-context-controller/test/channelReaderRevision.test.ts b/host-context-controller/test/channelReaderRevision.test.tsindex 26a76955d..1a4cbbe58 100644--- a/host-context-controller/test/channelReaderRevision.test.ts+++ b/host-context-controller/test/channelReaderRevision.test.ts@@ -21,6 +21,7 @@ vi.mock('../src/config', () => ({channelsNamespace: 'channels',channelReaderImage: 'clerum/channel-reader:test',channelReaderImagePullPolicy: 'IfNotPresent',+ hostFullReconcileConcurrency: 2,},}))diff --git a/host-context-controller/test/hostReconciler.networkpolicy.test.ts b/host-context-controller/test/hostReconciler.networkpolicy.test.tsindex f1de23109..cf13bdedd 100644--- a/host-context-controller/test/hostReconciler.networkpolicy.test.ts+++ b/host-context-controller/test/hostReconciler.networkpolicy.test.ts@@ -22,6 +22,7 @@ vi.mock('../src/config', () => ({hostNamespace: 'mcp-host',rpcProxyNamespace: 'rpc-proxy',channelsNamespace: 'channels',+ hostFullReconcileConcurrency: 2,channelReaderImage: 'clerum/channel-reader:test',channelReaderImagePullPolicy: 'IfNotPresent',hostImage: 'clerum/mcp-host:0.6.0',@@ -99,7 +100,7 @@ const HOST: HostCRD = {},}-function createReconciler() {+function createReconciler(customApi?: { getNamespacedCustomObject: ReturnType<typeof vi.fn> }) {const appsApi = createMockAppsApi()const coreApi = createMockCoreApi()const networkingApi = createMockNetworkingApi()@@ -110,6 +111,7 @@ function createReconciler() {coreApi: asCoreApi(coreApi),networkingApi: asNetworkingApi(networkingApi),rbacApi: asRbacApi(rbacApi),+ ...(customApi ? { customApi: customApi as unknown as k8s.CustomObjectsApi } : {}),})return { reconciler, mocks: { appsApi, coreApi, networkingApi, rbacApi } }@@ -318,33 +320,44 @@ describe('HostReconciler.deleteHostNetworkPolicies', () => {})})-describe('HostReconciler.fullReconcile — sweepOrphanHostNetworkPolicies wiring', () => {- // Regression guard: Phase 6 wired sweepOrphanHostNetworkPolicies into fullReconcile.- // This test ensures the wiring survives future refactors; the sweep method itself- // is exercised by the describe block below.- it('invokes sweepOrphanHostNetworkPolicies with the known host names', async () => {- const { reconciler } = createReconciler()-- // Stub per-Host work and channel-reader sweep to no-ops so only the NP- // sweep call is observable.- vi.spyOn(reconciler, 'reconcile').mockResolvedValue(undefined)- vi.spyOn(reconciler as any, 'listManagedHostDeployments').mockResolvedValue([])- vi.spyOn(reconciler as any, 'sweepOrphanChannelReaderResources').mockResolvedValue(undefined)-- const sweepSpy = vi- .spyOn(reconciler as any, 'sweepOrphanHostNetworkPolicies')- .mockResolvedValue(undefined)-- await reconciler.fullReconcile([HOST])-- expect(sweepSpy).toHaveBeenCalledTimes(1)- expect(sweepSpy).toHaveBeenCalledWith(['chatllm'])+describe('HostReconciler.fullReconcile — orphan NetworkPolicy cleanup wiring', () => {+ // The Phase-6 `sweepOrphanHostNetworkPolicies` method was folded into the+ // §10.5 authority-gated cleanup: under known watch authority a full pass+ // gathers managed NetworkPolicies (across all three managed namespaces) as+ // orphan candidates, then applies the fresh-read authority gate before any+ // bundle deletion. This proves the NP sweep is still wired into fullReconcile.+ it('gathers managed NetworkPolicy candidates across all managed namespaces during a full pass', async () => {+ const { reconciler, mocks } = createReconciler()+ // Known + stable watch authority so cleanup runs instead of deferring.+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))++ await reconciler.fullReconcile([])++ for (const namespace of ['channels', 'mcp-host', 'rpc-proxy']) {+ expect(mocks.networkingApi.listNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ namespace,+ labelSelector: 'clerum.io/managed-by=host-context-controller',+ })+ )+ }})})-describe('HostReconciler.sweepOrphanHostNetworkPolicies', () => {- it('deletes NPs whose clerum.io/host label is not in knownHosts', async () => {- const { reconciler, mocks } = createReconciler()+describe('HostReconciler orphan NetworkPolicy authority-gated cleanup', () => {+ // Preserves the three semantics of the removed sweepOrphanHostNetworkPolicies,+ // now realized through the §10.5 discover-owner + delete-owned-bundle path:+ // (A) an orphan NP (clerum.io/host not a live host, fresh 404 confirmed) →+ // that host's owned NP bundle is deleted;+ // (B) an NP whose owning host is still present → retained;+ // (C) an unlabeled/static NP (no derivable owner) → never touched.+ it('deletes the owned NP bundle for an orphan host and retains a live host', async () => {+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const { reconciler, mocks } = createReconciler({ getNamespacedCustomObject: getObj })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(name =>+ name === 'livehost' ? { ...HOST, name: 'livehost' } : undefined+ );(mocks.networkingApi.listNamespacedNetworkPolicy as any).mockImplementation(({ namespace }: { namespace: string }) => {if (namespace === 'channels') {@@ -377,8 +390,12 @@ describe('HostReconciler.sweepOrphanHostNetworkPolicies', () => {})- await (reconciler as any).sweepOrphanHostNetworkPolicies(['livehost'])+ await reconciler.fullReconcile([])+ // (A) stale host confirmed gone (fresh 404) → its owned per-Host NPs deleted+ // via the bundle; (B) the live host is never read nor deleted.+ expect(getObj).toHaveBeenCalledWith(expect.objectContaining({ name: 'stalehost' }))+ expect(getObj).not.toHaveBeenCalledWith(expect.objectContaining({ name: 'livehost' }))expect(mocks.networkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({name: 'channel-reader-stalehost-egress',namespace: 'channels',@@ -389,8 +406,11 @@ describe('HostReconciler.sweepOrphanHostNetworkPolicies', () => {})})- it('does not touch NPs without managed-by label (e.g. static base policies)', async () => {- const { reconciler, mocks } = createReconciler()+ it('never touches an NP whose owning Host cannot be derived from labels (static base policies)', async () => {+ const getObj = vi.fn()+ const { reconciler, mocks } = createReconciler({ getNamespacedCustomObject: getObj })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(() => undefined);(mocks.networkingApi.listNamespacedNetworkPolicy as any).mockResolvedValue({items: [{@@ -403,8 +423,44 @@ describe('HostReconciler.sweepOrphanHostNetworkPolicies', () => {],})- await (reconciler as any).sweepOrphanHostNetworkPolicies([])+ await reconciler.fullReconcile([])+ // (C) No derivable owner → deferred before any fresh read, never deleted.+ expect(getObj).not.toHaveBeenCalled()expect(mocks.networkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()})++ it('defers NP cleanup and deletes nothing when watch authority is unknown', async () => {+ // §10.5 gate proven on purpose: unknown watch authority short-circuits the+ // whole cleanup before any candidate is gathered, so a real orphan NP is+ // left intact rather than risking a wrong delete.+ const getObj = vi.fn()+ const { reconciler, mocks } = createReconciler({ getNamespacedCustomObject: getObj })+ reconciler.setHostWatchAuthority(() => ({ known: false, generation: 1 }))+ reconciler.setResolveCurrentHost(() => undefined)+ ;(mocks.networkingApi.listNamespacedNetworkPolicy as any).mockResolvedValue({+ items: [+ {+ metadata: {+ name: 'channel-reader-stalehost-egress',+ namespace: 'channels',+ labels: {+ 'clerum.io/managed-by': 'host-context-controller',+ 'clerum.io/host': 'stalehost',+ },+ },+ },+ ],+ })+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)++ await reconciler.fullReconcile([])++ expect(getObj).not.toHaveBeenCalled()+ expect(mocks.networkingApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('Deferring orphan cleanup: authority_unknown')+ )+ warn.mockRestore()+ })})diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.tsindex bec0d1a74..dbe54f200 100644--- a/host-context-controller/test/hostReconciler.test.ts+++ b/host-context-controller/test/hostReconciler.test.ts@@ -29,6 +29,7 @@ vi.mock('../src/config', () => ({hostNamespace: 'mcp-host',rpcProxyNamespace: 'rpc-proxy',channelsNamespace: 'channels',+ hostFullReconcileConcurrency: 2,channelReaderImage: 'clerum/channel-reader:test',channelReaderImagePullPolicy: 'IfNotPresent',hostImage: 'clerum/mcp-host:0.6.0',@@ -142,6 +143,12 @@ function createReconciler(infrastructureTelemetryReporter?: InfrastructureTelemetryReporteradministrativeOutcomeReporter?: AdministrativeOutcomeReporternewTelemetryOccurrenceId?: () => string+ // §10.5 orphan cleanup performs ONE fresh authoritative Host read+ // (`customApi.getNamespacedCustomObject`) per orphan logical Host. Tests+ // that exercise the authority-gated cleanup wire a mock here so a confirmed+ // 404 authorizes deletion; without it the reconciler lazily constructs a+ // real client that would never resolve under test.+ customApi?: { getNamespacedCustomObject: ReturnType<typeof vi.fn> }} = {}) {const appsApi = createMockAppsApi()@@ -157,6 +164,9 @@ function createReconciler(infrastructureTelemetryReporter: options.infrastructureTelemetryReporter,administrativeOutcomeReporter: options.administrativeOutcomeReporter,newTelemetryOccurrenceId: options.newTelemetryOccurrenceId,+ ...(options.customApi+ ? { customApi: options.customApi as unknown as k8s.CustomObjectsApi }+ : {}),})return { reconciler, appsApi, coreApi, networkingApi, rbacApi }@@ -493,14 +503,26 @@ describe('HostReconciler', () => {})it('removes orphaned host runtime resources during full reconcile', async () => {- const { reconciler, appsApi, coreApi } = createReconciler()+ // §10.5 authority-gated cleanup: an orphan managed Deployment is discovered,+ // its owning Host is confirmed gone by a fresh 404 while watch authority is+ // known and stable, and the whole owned bundle (Deployment/Service/PVC) is+ // deleted through that Host's per-Host serializer.+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const { reconciler, appsApi, coreApi } = createReconciler({+ customApi: { getNamespacedCustomObject: getObj },+ })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(() => undefined) // current cache omits every hostappsApi.listNamespacedDeployment.mockResolvedValue({items: [{metadata: {name: 'orphan-host',namespace: 'mcp-host',- labels: { 'clerum.io/host': 'orphan-host' },+ labels: {+ 'clerum.io/managed-by': 'host-context-controller',+ 'clerum.io/host': 'orphan-host',+ },},},],@@ -508,6 +530,8 @@ describe('HostReconciler', () => {await reconciler.fullReconcile([])+ // The fresh authoritative Host read gates the delete.+ expect(getObj).toHaveBeenCalledWith(expect.objectContaining({ name: 'orphan-host' }))expect(appsApi.deleteNamespacedDeployment).toHaveBeenCalledWith({name: 'orphan-host',namespace: 'mcp-host',@@ -1426,7 +1450,16 @@ describe('reconcile / reconcileDelete with channel-reader', () => {describe('orphan sweep on fullReconcile (channel-reader)', () => {it('deletes channel-reader Deployments without a matching Host', async () => {- const { reconciler, appsApi } = createReconciler()+ // §10.5: an orphan is DISCOVERED via its channel-reader Deployment candidate,+ // its owning Host is confirmed gone by a fresh 404 under known/stable watch+ // authority, and that Host's owned bundle (which cascades to the channels-ns+ // channel-reader Deployment) is deleted. The live Host "a" is retained.+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const { reconciler, appsApi } = createReconciler({+ customApi: { getNamespacedCustomObject: getObj },+ })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(name => (name === 'a' ? makeHost({ name }) : undefined))// listNamespacedDeployment is called twice during fullReconcile:// 1) mcp-host ns (with labelSelector) for the existing host orphan sweep// 2) channels ns (no labelSelector) for the channel-reader sweep@@ -1465,8 +1498,14 @@ describe('orphan sweep on fullReconcile (channel-reader)', () => {})appsApi.deleteNamespacedDeployment.mockResolvedValue({})- await reconciler.fullReconcile([makeHost({ name: 'a' })])+ // Desired list is empty: "a" is live purely by current-cache presence+ // (setResolveCurrentHost above), which is what §10.5 retention keys on.+ await reconciler.fullReconcile([])+ // The orphan ("orphan") got a fresh authoritative read; the live host ("a")+ // stayed in cache and was never read/deleted.+ expect(getObj).toHaveBeenCalledWith(expect.objectContaining({ name: 'orphan' }))+ expect(getObj).not.toHaveBeenCalledWith(expect.objectContaining({ name: 'a' }))expect(appsApi.deleteNamespacedDeployment).toHaveBeenCalledWith({name: 'channel-reader-orphan',namespace: 'channels',@@ -1481,8 +1520,21 @@ describe('orphan sweep on fullReconcile (channel-reader)', () => {})})- it('deletes channel-reader Secrets without a matching Host', async () => {- const { reconciler, coreApi } = createReconciler()+ it('deletes the owning Host bundle for an orphan discovered via a channel-reader Secret', async () => {+ // The old per-name Secret sweep became discover-owner + delete-the-Host-bundle+ // (§10.5): a managed channel-reader Secret whose owning Host is gone is a+ // DISCOVERY signal. Its owner ("orphan") is confirmed absent by a fresh 404+ // under known/stable authority, and that Host's entire owned bundle is+ // deleted through its per-Host serializer. The live host "a" is retained.+ // (The bundle deletes the Host's own managed Secrets — e.g.+ // `channel-reader-orphan-mcp-host-runtime-auth` — not an arbitrary+ // discovered name, so we assert at the bundle boundary.)+ const getObj = vi.fn().mockRejectedValue({ code: 404 })+ const { reconciler, coreApi } = createReconciler({+ customApi: { getNamespacedCustomObject: getObj },+ })+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 1 }))+ reconciler.setResolveCurrentHost(name => (name === 'a' ? makeHost({ name }) : undefined))coreApi.listNamespacedSecret.mockResolvedValue({items: [{@@ -1509,18 +1561,67 @@ describe('orphan sweep on fullReconcile (channel-reader)', () => {},],})- coreApi.deleteNamespacedSecret.mockResolvedValue({})+ const deleteBundle = vi+ .spyOn(reconciler as any, 'deleteHostRuntimeResources')+ .mockResolvedValue(undefined)- await reconciler.fullReconcile([makeHost({ name: 'a' })])+ // Desired list is empty: "a" is live purely by current-cache presence+ // (setResolveCurrentHost above), which is what §10.5 retention keys on.+ await reconciler.fullReconcile([])- expect(coreApi.deleteNamespacedSecret).toHaveBeenCalledWith({- name: 'channel-reader-orphan-credentials',- namespace: 'channels',+ expect(getObj).toHaveBeenCalledWith(expect.objectContaining({ name: 'orphan' }))+ expect(deleteBundle).toHaveBeenCalledWith('orphan', 'mcp-host')+ expect(deleteBundle).not.toHaveBeenCalledWith('a', 'mcp-host')+ })++ it('defers the orphan bundle and deletes nothing when watch authority is unknown', async () => {+ // §10.5 gate proven on purpose: unknown watch authority short-circuits the+ // whole cleanup BEFORE any candidate is gathered or any fresh read is made,+ // so nothing is deleted even though an orphan channel-reader Deployment is+ // present. This is the accidental safety the removed global tail used to+ // provide, now made explicit.+ const getObj = vi.fn()+ const { reconciler, appsApi } = createReconciler({+ customApi: { getNamespacedCustomObject: getObj },})- expect(coreApi.deleteNamespacedSecret).not.toHaveBeenCalledWith({- name: 'channel-reader-a-credentials',+ reconciler.setHostWatchAuthority(() => ({ known: false, generation: 1 }))+ reconciler.setResolveCurrentHost(() => undefined)+ appsApi.listNamespacedDeployment.mockImplementation(({ namespace }: { namespace: string }) =>+ namespace === 'channels'+ ? Promise.resolve({+ items: [+ {+ metadata: {+ name: 'channel-reader-orphan',+ namespace: 'channels',+ labels: {+ app: 'channel-reader',+ 'clerum.io/host': 'orphan',+ 'clerum.io/managed-by': 'host-context-controller',+ },+ },+ },+ ],+ })+ : Promise.resolve({ items: [] })+ )+ const deleteBundle = vi+ .spyOn(reconciler as any, 'deleteHostRuntimeResources')+ .mockResolvedValue(undefined)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)++ await reconciler.fullReconcile([])++ expect(getObj).not.toHaveBeenCalled()+ expect(deleteBundle).not.toHaveBeenCalled()+ expect(appsApi.deleteNamespacedDeployment).not.toHaveBeenCalledWith({+ name: 'channel-reader-orphan',namespace: 'channels',})+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('Deferring orphan cleanup: authority_unknown')+ )+ warn.mockRestore()})it('does NOT delete Secrets missing the clerum.io/managed-by label', async () => {