Skip to content

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

TypeScript

fix(hcc): fence cross-resource convergence mutations

Alfredo Lopezaacf3350deaf
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 949683f89..b9aaeba07 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.167",
+ "version": "0.1.168",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.167",
+ "version": "0.1.168",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index 44a681873..947dc9a61 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.167",
+ "version": "0.1.168",
"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/__tests__/reconciler.remote.test.ts b/host-context-controller/src/__tests__/reconciler.remote.test.ts
index f7beaaf38..642ae4d7a 100644
--- a/host-context-controller/src/__tests__/reconciler.remote.test.ts
+++ b/host-context-controller/src/__tests__/reconciler.remote.test.ts
@@ -1149,11 +1149,14 @@ describe('McpServerReconciler remote egress proxy', () => {
})
it('should clear status tracking after delete', async () => {
+ let current: McpServerCRD | undefined = REMOTE_SERVER
+ reconciler.setResolveCurrentServer(() => current)
// First reconcile to populate status
await reconciler.reconcile(REMOTE_SERVER)
expect(reconciler.getStatus('mcp-sentry-remote').deployed).toBe(true)
// Then delete
+ current = undefined
await reconciler.reconcileDelete('mcp-sentry-remote', 'mcp-server')
const status = reconciler.getStatus('mcp-sentry-remote')
expect(status.deployed).toBe(false)
diff --git a/host-context-controller/src/bindingPolicyReconciler.test.ts b/host-context-controller/src/bindingPolicyReconciler.test.ts
index b2fd2bc8f..64cffe433 100644
--- a/host-context-controller/src/bindingPolicyReconciler.test.ts
+++ b/host-context-controller/src/bindingPolicyReconciler.test.ts
@@ -2,6 +2,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import * as k8s from '@kubernetes/client-node'
import { BindingDef, BindingPolicyReconciler } from './bindingPolicyReconciler'
+function deferred<T = void>() {
+ let resolve!: (value: T | PromiseLike<T>) => void
+ const promise = new Promise<T>(res => {
+ resolve = res
+ })
+ return { promise, resolve }
+}
+
function makeMockNetworkingApi() {
return {
createNamespacedNetworkPolicy: vi.fn().mockResolvedValue({}),
@@ -95,6 +103,35 @@ describe('BindingPolicyReconciler', () => {
expect(mockApi.replaceNamespacedNetworkPolicy).toHaveBeenCalled()
})
+ it('does not replace or start another apply after its authority lease is retired', async () => {
+ const readStarted = deferred()
+ const releaseRead = deferred<{ metadata: { resourceVersion: string } }>()
+ mockApi.createNamespacedNetworkPolicy.mockRejectedValue({ code: 409 })
+ mockApi.readNamespacedNetworkPolicy.mockImplementationOnce(async () => {
+ readStarted.resolve()
+ return releaseRead.promise
+ })
+ let current = true
+
+ const reconcile = reconciler.reconcileBindings(
+ 'my-recipe',
+ singleBinding,
+ 'redis-mcp',
+ 'redis-mcp',
+ { isCurrent: () => current }
+ )
+ await readStarted.promise
+
+ current = false
+ releaseRead.resolve({ metadata: { resourceVersion: '1' } })
+ await reconcile
+
+ // The first create was authorized and returned 409 without mutating. Once
+ // the lease is retired, no replacement or second policy apply may start.
+ expect(mockApi.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
it('cleanupBindings deletes policies in both namespaces', async () => {
mockApi.listNamespacedNetworkPolicy.mockResolvedValue({
items: [{ metadata: { name: 'bind-my-recipe-a-b-egress' } }],
@@ -108,6 +145,61 @@ describe('BindingPolicyReconciler', () => {
expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalled()
})
+ it('does not delete listed policies when a same-name recipe is recreated during LIST', async () => {
+ const bothListsStarted = deferred()
+ const releaseLists = deferred<{
+ items: Array<{ metadata: { name: string } }>
+ }>()
+ let listCalls = 0
+ mockApi.listNamespacedNetworkPolicy.mockImplementation(async () => {
+ listCalls += 1
+ if (listCalls === 2) bothListsStarted.resolve()
+ return releaseLists.promise
+ })
+ let recipeRecreated = false
+ const deleteAllowed = vi.fn(async () => !recipeRecreated)
+
+ const cleanup = reconciler.cleanupBindings('my-recipe', { deleteAllowed })
+ await bothListsStarted.promise
+
+ recipeRecreated = true
+ releaseLists.resolve({
+ items: [{ metadata: { name: 'bind-my-recipe-a-b-egress' } }],
+ })
+ await cleanup
+
+ expect(deleteAllowed).toHaveBeenCalledTimes(2)
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('rejects cleanup when listing binding policies fails', async () => {
+ mockApi.listNamespacedNetworkPolicy.mockRejectedValue(new Error('transient LIST failure'))
+
+ await expect(reconciler.cleanupBindings('my-recipe')).rejects.toThrow(
+ 'Failed to clean up binding policies for recipe "my-recipe"'
+ )
+ })
+
+ it('rejects cleanup when deleting a binding policy fails with a non-404 error', async () => {
+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({
+ items: [{ metadata: { name: 'bind-my-recipe-a-b-egress' } }],
+ })
+ mockApi.deleteNamespacedNetworkPolicy.mockRejectedValue(new Error('transient DELETE failure'))
+
+ await expect(reconciler.cleanupBindings('my-recipe')).rejects.toThrow(
+ 'Failed to clean up binding policies for recipe "my-recipe"'
+ )
+ })
+
+ it('treats a 404 while deleting binding policies as successful cleanup', async () => {
+ mockApi.listNamespacedNetworkPolicy.mockResolvedValue({
+ items: [{ metadata: { name: 'bind-my-recipe-a-b-egress' } }],
+ })
+ mockApi.deleteNamespacedNetworkPolicy.mockRejectedValue({ code: 404 })
+
+ await expect(reconciler.cleanupBindings('my-recipe')).resolves.toBeUndefined()
+ })
+
it('uses _from for ingress rules (K8s client ObjectSerializer maps _from → from)', async () => {
await reconciler.reconcileBindings('my-recipe', singleBinding, 'redis-mcp')
diff --git a/host-context-controller/src/bindingPolicyReconciler.ts b/host-context-controller/src/bindingPolicyReconciler.ts
index b0486d63c..0f081e64f 100644
--- a/host-context-controller/src/bindingPolicyReconciler.ts
+++ b/host-context-controller/src/bindingPolicyReconciler.ts
@@ -37,6 +37,14 @@ export interface BindingDef {
protocol?: 'TCP' | 'UDP'
}
+export interface BindingPolicyReconcileOptions {
+ isCurrent?: () => boolean
+}
+
+export interface BindingPolicyCleanupOptions {
+ deleteAllowed?: () => Promise<boolean>
+}
+
export class BindingPolicyReconciler {
private networkingApi: k8s.NetworkingV1Api
private mcpServerNamespace: string
@@ -60,70 +68,86 @@ export class BindingPolicyReconciler {
recipeName: string,
bindings: BindingDef[],
mcpWorkloadName: string,
- mcpServerName = mcpWorkloadName
+ mcpServerName = mcpWorkloadName,
+ options: BindingPolicyReconcileOptions = {}
): Promise<void> {
+ const isCurrent = options.isCurrent ?? (() => true)
+ if (!isCurrent()) return
console.log(`[BindingNP] Reconciling ${bindings.length} binding(s) for recipe "${recipeName}"`)
- await Promise.all(
- bindings.map(async binding => {
- const protocol = binding.protocol ?? 'TCP'
+ // Sequence writes so authority can be rechecked between every Kubernetes
+ // effect. A retired pass must not start the next binding policy mutation.
+ for (const binding of bindings) {
+ if (!isCurrent()) return
+ const protocol = binding.protocol ?? 'TCP'
- // Determine namespaces based on which workload is the MCP server.
- // The MCP workload (with transport) lives in mcp-server namespace,
- // the other workload lives in sandbox-recipes namespace.
- const fromIsMcp = binding.from === mcpWorkloadName
- const fromNs = fromIsMcp ? this.mcpServerNamespace : SANDBOX_NAMESPACE
- const toNs = fromIsMcp ? SANDBOX_NAMESPACE : this.mcpServerNamespace
- const fromPodSelector: Record<string, string> = fromIsMcp
- ? { [MCPSERVER_LABEL]: mcpServerName }
- : { app: binding.from }
- const toPodSelector: Record<string, string> = fromIsMcp
- ? { app: binding.to }
- : { [MCPSERVER_LABEL]: mcpServerName }
+ // Determine namespaces based on which workload is the MCP server.
+ // The MCP workload (with transport) lives in mcp-server namespace,
+ // the other workload lives in sandbox-recipes namespace.
+ const fromIsMcp = binding.from === mcpWorkloadName
+ const fromNs = fromIsMcp ? this.mcpServerNamespace : SANDBOX_NAMESPACE
+ const toNs = fromIsMcp ? SANDBOX_NAMESPACE : this.mcpServerNamespace
+ const fromPodSelector: Record<string, string> = fromIsMcp
+ ? { [MCPSERVER_LABEL]: mcpServerName }
+ : { app: binding.from }
+ const toPodSelector: Record<string, string> = fromIsMcp
+ ? { app: binding.to }
+ : { [MCPSERVER_LABEL]: mcpServerName }
- const egressName = this.policyName(recipeName, binding.from, binding.to, 'egress')
- const egressPolicy = this.buildEgressPolicy(
- egressName,
- recipeName,
- fromPodSelector,
- toPodSelector,
- fromNs,
- toNs,
- binding.port,
- protocol
- )
- const ingressName = this.policyName(recipeName, binding.from, binding.to, 'ingress')
- const ingressPolicy = this.buildIngressPolicy(
- ingressName,
- recipeName,
- fromPodSelector,
- toPodSelector,
- fromNs,
- toNs,
- binding.port,
- protocol
- )
+ const egressName = this.policyName(recipeName, binding.from, binding.to, 'egress')
+ const egressPolicy = this.buildEgressPolicy(
+ egressName,
+ recipeName,
+ fromPodSelector,
+ toPodSelector,
+ fromNs,
+ toNs,
+ binding.port,
+ protocol
+ )
+ const ingressName = this.policyName(recipeName, binding.from, binding.to, 'ingress')
+ const ingressPolicy = this.buildIngressPolicy(
+ ingressName,
+ recipeName,
+ fromPodSelector,
+ toPodSelector,
+ fromNs,
+ toNs,
+ binding.port,
+ protocol
+ )
- // Egress and ingress target different namespaces — safe to parallelize
- await Promise.all([
- this.applyPolicy(egressName, egressPolicy, fromNs),
- this.applyPolicy(ingressName, ingressPolicy, toNs),
- ])
- })
- )
+ if (!isCurrent()) return
+ await this.applyPolicy(egressName, egressPolicy, fromNs, isCurrent)
+ if (!isCurrent()) return
+ await this.applyPolicy(ingressName, ingressPolicy, toNs, isCurrent)
+ }
}
/**
* Delete all binding-scoped NetworkPolicies for a recipe.
*/
- async cleanupBindings(recipeName: string): Promise<void> {
+ async cleanupBindings(
+ recipeName: string,
+ options: BindingPolicyCleanupOptions = {}
+ ): Promise<void> {
console.log(`[BindingNP] Cleaning up binding policies for recipe "${recipeName}"`)
- // Delete from both namespaces in parallel (independent operations)
- await Promise.all([
- this.deletePoliciesForRecipe(recipeName, SANDBOX_NAMESPACE),
- this.deletePoliciesForRecipe(recipeName, this.mcpServerNamespace),
+ // LIST operations are read-only and namespace-independent. Each resulting
+ // delete is separately authorized after its LIST completes.
+ const results = await Promise.allSettled([
+ this.deletePoliciesForRecipe(recipeName, SANDBOX_NAMESPACE, options.deleteAllowed),
+ this.deletePoliciesForRecipe(recipeName, this.mcpServerNamespace, options.deleteAllowed),
])
+ const failures = results.flatMap(result =>
+ result.status === 'rejected' ? [result.reason] : []
+ )
+ if (failures.length > 0) {
+ throw new AggregateError(
+ failures,
+ `Failed to clean up binding policies for recipe "${recipeName}"`
+ )
+ }
}
// ─── Policy Builders ────────────────────────────────────────────
@@ -242,43 +266,49 @@ export class BindingPolicyReconciler {
private async applyPolicy(
name: string,
policy: k8s.V1NetworkPolicy,
- namespace: string
+ namespace: string,
+ isCurrent: () => boolean
): Promise<void> {
- await applyNetworkPolicy(this.networkingApi, name, namespace, policy, '[BindingNP]')
+ await applyNetworkPolicy(this.networkingApi, name, namespace, policy, '[BindingNP]', isCurrent)
}
- private async deletePoliciesForRecipe(recipeName: string, namespace: string): Promise<void> {
+ private async deletePoliciesForRecipe(
+ recipeName: string,
+ namespace: string,
+ deleteAllowed?: () => Promise<boolean>
+ ): Promise<void> {
+ let response: k8s.V1NetworkPolicyList
try {
- const response = await this.networkingApi.listNamespacedNetworkPolicy({
+ response = await this.networkingApi.listNamespacedNetworkPolicy({
namespace,
labelSelector: `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE},${POLICY_TYPE_LABEL}=binding-allow,${RECIPE_LABEL}=${recipeName}`,
})
-
- await Promise.all(
- (response.items || []).map(async policy => {
- const policyName = policy.metadata?.name
- if (!policyName) {
- console.warn(`[BindingNP] Skipping policy with no name in ${namespace}`)
- return
- }
- try {
- await this.networkingApi.deleteNamespacedNetworkPolicy({
- name: policyName,
- namespace,
- })
- console.log(`[BindingNP] Deleted policy "${policyName}" in ${namespace}`)
- } catch (error: unknown) {
- if (getErrorCode(error) !== 404) {
- console.error(`[BindingNP] Failed to delete policy "${policyName}":`, error)
- }
- }
- })
- )
} catch (error) {
console.error(
`[BindingNP] Failed to list policies for recipe "${recipeName}" in ${namespace}:`,
error
)
+ throw error
+ }
+
+ for (const policy of response.items || []) {
+ const policyName = policy.metadata?.name
+ if (!policyName) {
+ console.warn(`[BindingNP] Skipping policy with no name in ${namespace}`)
+ continue
+ }
+ try {
+ if (deleteAllowed && !(await deleteAllowed())) return
+ await this.networkingApi.deleteNamespacedNetworkPolicy({
+ name: policyName,
+ namespace,
+ })
+ console.log(`[BindingNP] Deleted policy "${policyName}" in ${namespace}`)
+ } catch (error: unknown) {
+ if (getErrorCode(error) === 404) continue
+ console.error(`[BindingNP] Failed to delete policy "${policyName}":`, error)
+ throw error
+ }
}
}
}
diff --git a/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts b/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
index 52f2bbc5b..0e38b4c6d 100644
--- a/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
+++ b/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
@@ -47,6 +47,7 @@ function coordinator(overrides: CoordinatorOverrides = {}) {
const instance = new ExternalEgressConvergenceCoordinator({
listServers: () => [...servers.values()],
getCurrentServer: name => servers.get(name),
+ inventoryAuthoritative: () => true,
sameDesiredRevision: (left, right) =>
left.uid === right.uid &&
left.generation === right.generation &&
@@ -498,9 +499,11 @@ describe('ExternalEgressConvergenceCoordinator', () => {
const state = new Map<string, McpServerCRD>([[selected.name, selected]])
const mutationStarted = deferred()
const releaseMutation = deferred()
+ let selectedLease: (() => boolean) | undefined
const { instance } = coordinator({
getCurrentServer: name => state.get(name),
- mutate: async () => {
+ mutate: async (_type, _server, options) => {
+ selectedLease = options.isCurrent
mutationStarted.resolve()
await releaseMutation.promise
},
@@ -508,18 +511,47 @@ describe('ExternalEgressConvergenceCoordinator', () => {
const gates = instance.prepareStartupGates([selected])
await mutationStarted.promise
+ expect(selectedLease?.()).toBe(true)
state.set(current.name, current)
+ expect(selectedLease?.()).toBe(false)
releaseMutation.resolve()
await expect(gates.waitFor(selected)).resolves.toBe(false)
instance.stop()
})
+ it('retires a direct mutation lease when desired revision changes in place', async () => {
+ const selected = server('web-search', 1)
+ const replacement = server('web-search', 2)
+ const mutationStarted = deferred()
+ const releaseMutation = deferred()
+ let selectedLease: (() => boolean) | undefined
+ const { instance, servers } = coordinator({
+ mutate: async (_type, _server, options) => {
+ selectedLease = options.isCurrent
+ mutationStarted.resolve()
+ await releaseMutation.promise
+ },
+ })
+ servers.set(selected.name, selected)
+
+ const mutation = instance.reconcile('MODIFIED', selected)
+ await mutationStarted.promise
+ expect(selectedLease?.()).toBe(true)
+
+ servers.set(replacement.name, replacement)
+ expect(selectedLease?.()).toBe(false)
+ releaseMutation.resolve()
+ await mutation
+ instance.stop()
+ })
+
it('does not start a second mutation after stop releases an in-flight wait', async () => {
const firstMutation = deferred()
const selected = server('web-search')
const mutate = vi.fn(async () => firstMutation.promise)
- const { instance } = coordinator({ mutate })
+ const { instance, servers } = coordinator({ mutate })
+ servers.set(selected.name, selected)
const first = instance.reconcile('MODIFIED', selected)
await vi.waitFor(() => expect(mutate).toHaveBeenCalledOnce())
@@ -546,7 +578,8 @@ describe('ExternalEgressConvergenceCoordinator', () => {
await releases[index].promise
active -= 1
})
- const { instance } = coordinator({ mutate })
+ const { instance, servers } = coordinator({ mutate })
+ servers.set(selected.name, selected)
const first = instance.reconcile('MODIFIED', selected)
await starts[0].promise
@@ -565,6 +598,65 @@ describe('ExternalEgressConvergenceCoordinator', () => {
}
})
+ it('rechecks a caller lease after waiting for an in-flight mutation', async () => {
+ const firstMutation = deferred()
+ const selected = server('web-search')
+ let current = true
+ const mutate = vi.fn(async () => firstMutation.promise)
+ const { instance, servers } = coordinator({ mutate })
+ servers.set(selected.name, selected)
+
+ const first = instance.reconcile('MODIFIED', selected)
+ await vi.waitFor(() => expect(mutate).toHaveBeenCalledOnce())
+ const waiting = instance.reconcile('MODIFIED', selected, {
+ isCurrent: () => current,
+ })
+ current = false
+ firstMutation.resolve()
+ await Promise.all([first, waiting])
+
+ expect(mutate).toHaveBeenCalledOnce()
+ instance.stop()
+ })
+
+ it('keeps a retry pending while inventory authority is unavailable', async () => {
+ vi.useFakeTimers()
+ const selected = server('web-search')
+ let authoritative = false
+ const { instance, replay, servers } = coordinator({
+ inventoryAuthoritative: () => authoritative,
+ })
+ servers.set(selected.name, selected)
+
+ instance.scheduleRetry('ADDED', selected)
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(replay).not.toHaveBeenCalled()
+
+ authoritative = true
+ await vi.advanceTimersByTimeAsync(14_999)
+ expect(replay).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(replay).toHaveBeenCalledOnce()
+ instance.stop()
+ })
+
+ it('skips periodic resync while inventory authority is unavailable', async () => {
+ const selected = server('web-search')
+ let authoritative = false
+ const { instance, mutate, servers } = coordinator({
+ inventoryAuthoritative: () => authoritative,
+ })
+ servers.set(selected.name, selected)
+
+ await instance.runResync()
+ expect(mutate).not.toHaveBeenCalled()
+
+ authoritative = true
+ await instance.runResync()
+ expect(mutate).toHaveBeenCalledOnce()
+ instance.stop()
+ })
+
it('does not resume periodic work from jitter after stop', async () => {
vi.useFakeTimers()
vi.spyOn(Math, 'random').mockReturnValue(0.5)
@@ -614,7 +706,10 @@ describe('ExternalEgressConvergenceCoordinator', () => {
await instance.reconcile('DELETED', selected, { deleteAllowed })
- expect(mutate).toHaveBeenCalledWith('DELETED', selected, { deleteAllowed })
+ expect(mutate).toHaveBeenCalledWith('DELETED', selected, {
+ deleteAllowed,
+ isCurrent: expect.any(Function),
+ })
expect(deleteAllowed).not.toHaveBeenCalled()
instance.stop()
})
diff --git a/host-context-controller/src/externalEgressConvergenceCoordinator.ts b/host-context-controller/src/externalEgressConvergenceCoordinator.ts
index cfbf90ea0..25d9df936 100644
--- a/host-context-controller/src/externalEgressConvergenceCoordinator.ts
+++ b/host-context-controller/src/externalEgressConvergenceCoordinator.ts
@@ -19,15 +19,19 @@ type ExternalEgressRetryIntent = {
type ExternalEgressMutationOptions = {
deleteAllowed?: () => Promise<boolean>
+ isCurrent: () => boolean
}
-type ExternalEgressReconcileOptions = ExternalEgressMutationOptions & {
+type ExternalEgressReconcileOptions = {
+ deleteAllowed?: () => Promise<boolean>
retry?: ExternalEgressRetryHandle
+ isCurrent?: () => boolean
}
type ExternalEgressCoordinatorDependencies = {
listServers: () => McpServerCRD[]
getCurrentServer: (name: string) => McpServerCRD | undefined
+ inventoryAuthoritative: () => boolean
sameDesiredRevision: (left: McpServerCRD, right: McpServerCRD) => boolean
enqueue: (server: McpServerCRD, work: () => Promise<void>) => Promise<void>
mutate: (
@@ -129,7 +133,10 @@ export class ExternalEgressConvergenceCoordinator {
return run
}
- prepareStartupGates(servers: McpServerCRD[]): ExternalEgressStartupGates {
+ prepareStartupGates(
+ servers: McpServerCRD[],
+ isCurrent: () => boolean = this.dependencies.inventoryAuthoritative
+ ): ExternalEgressStartupGates {
const gates = new Map<string, Promise<boolean>>()
const selectedServers = servers
.filter(server => (server.spec.egressBindings?.length ?? 0) > 0)
@@ -150,10 +157,10 @@ export class ExternalEgressConvergenceCoordinator {
const key = this.key(selected)
const gate = limiter
.run(async () => {
- if (this.stopped) return false
+ if (this.stopped || !isCurrent()) return false
let ready = false
await this.dependencies.enqueue(selected, async () => {
- if (this.stopped) return
+ if (this.stopped || !isCurrent()) return
const current = this.dependencies.getCurrentServer(selected.name)
if (
!current ||
@@ -165,10 +172,11 @@ export class ExternalEgressConvergenceCoordinator {
try {
// Startup is an egress-only gate. Any pre-existing retry intent is
// completed only by its full replay, never by this mutation.
- await this.reconcile('MODIFIED', current)
+ await this.reconcile('MODIFIED', current, { isCurrent })
const latest = this.dependencies.getCurrentServer(selected.name)
ready =
!this.stopped &&
+ isCurrent() &&
latest !== undefined &&
latest.namespace === selected.namespace &&
this.dependencies.sameDesiredRevision(selected, latest)
@@ -197,19 +205,21 @@ export class ExternalEgressConvergenceCoordinator {
server: McpServerCRD,
options: ExternalEgressReconcileOptions = {}
): Promise<ExternalEgressRetryHandle | undefined> {
- if (this.stopped || (options.retry && !options.retry.isCurrent())) return undefined
+ if (!this.reconcileIsCurrent(type, server, options)) return undefined
const key = this.key(server)
let existing = this.inFlight.get(key)
while (existing) {
console.warn(`[K8s] Waiting for external egress reconcile for ${key}; already in flight`)
await existing
- if (this.stopped || (options.retry && !options.retry.isCurrent())) return undefined
+ if (!this.reconcileIsCurrent(type, server, options)) return undefined
existing = this.inFlight.get(key)
}
+ if (!this.reconcileIsCurrent(type, server, options)) return undefined
const completion = options.retry ?? this.currentRetryHandle(key)
const run = this.dependencies.mutate(type, server, {
deleteAllowed: options.deleteAllowed,
+ isCurrent: () => this.reconcileIsCurrent(type, server, options),
})
this.inFlight.set(key, run)
try {
@@ -293,13 +303,25 @@ export class ExternalEgressConvergenceCoordinator {
this.retrySlots.set(key, slot)
void this.retryLimiter
.run(async () => {
- if (this.stopped || this.retrySlots.get(key) !== slot) return
+ if (
+ this.stopped ||
+ this.retrySlots.get(key) !== slot ||
+ !this.dependencies.inventoryAuthoritative()
+ ) {
+ return
+ }
// Do not capture intent before the limiter. Churn while capacity is
// saturated is represented by one slot and resolved latest-wins here.
const admittedIntent = this.retryIntents.get(key)
if (!admittedIntent) return
await this.dependencies.enqueue(admittedIntent.server, async () => {
- if (this.stopped || this.retrySlots.get(key) !== slot) return
+ if (
+ this.stopped ||
+ this.retrySlots.get(key) !== slot ||
+ !this.dependencies.inventoryAuthoritative()
+ ) {
+ return
+ }
// The keyed queue may also wait. Resolve the intent again so only the
// latest desired revision or absence is replayed.
const currentIntent = this.retryIntents.get(key)
@@ -343,7 +365,7 @@ export class ExternalEgressConvergenceCoordinator {
}
private async runResyncCore(): Promise<void> {
- if (this.stopped) return
+ if (this.stopped || !this.dependencies.inventoryAuthoritative()) return
const servers = this.dependencies
.listServers()
.filter(server => (server.spec.egressBindings?.length ?? 0) > 0)
@@ -355,7 +377,7 @@ export class ExternalEgressConvergenceCoordinator {
const workers = Array.from(
{ length: Math.min(EXTERNAL_EGRESS_MAX_CONCURRENCY, servers.length) },
async () => {
- while (!this.stopped) {
+ while (!this.stopped && this.dependencies.inventoryAuthoritative()) {
const server = servers[index++]
if (!server) return
const key = this.key(server)
@@ -365,10 +387,10 @@ export class ExternalEgressConvergenceCoordinator {
}
const jitterMs = Math.floor(Math.random() * EXTERNAL_EGRESS_RESYNC_JITTER_MS)
if (jitterMs > 0) await delay(jitterMs)
- if (this.stopped) return
+ if (this.stopped || !this.dependencies.inventoryAuthoritative()) return
await this.dependencies.enqueue(server, async () => {
- if (this.stopped) return
+ if (this.stopped || !this.dependencies.inventoryAuthoritative()) return
// The fleet snapshot selects work only. Desired state is resolved
// after jitter and after entering the per-server FIFO lane.
const current = this.dependencies.getCurrentServer(server.name)
@@ -387,7 +409,9 @@ export class ExternalEgressConvergenceCoordinator {
}
// Periodic refresh is egress-only and therefore cannot complete
// a retry intent that may appear while the mutation is running.
- await this.reconcile('MODIFIED', current)
+ await this.reconcile('MODIFIED', current, {
+ isCurrent: this.dependencies.inventoryAuthoritative,
+ })
} catch (error) {
console.error(`[K8s] External egress periodic resync failed for ${key}:`, error)
this.scheduleRetry('MODIFIED', current)
@@ -400,7 +424,7 @@ export class ExternalEgressConvergenceCoordinator {
}
private async replayIntent(intent: ExternalEgressRetryIntent): Promise<void> {
- if (this.stopped) return
+ if (this.stopped || !this.dependencies.inventoryAuthoritative()) return
const handle = this.retryHandle(intent)
if (!handle.isCurrent()) return
@@ -411,6 +435,25 @@ export class ExternalEgressConvergenceCoordinator {
await this.dependencies.replay(type, server, handle)
}
+ private reconcileIsCurrent(
+ type: ExternalEgressWatchEventType,
+ server: McpServerCRD,
+ options: ExternalEgressReconcileOptions
+ ): boolean {
+ const callerIsCurrent =
+ !this.stopped &&
+ (!options.retry || options.retry.isCurrent()) &&
+ (!options.isCurrent || options.isCurrent())
+ if (!callerIsCurrent || type === 'DELETED') return callerIsCurrent
+
+ const current = this.dependencies.getCurrentServer(server.name)
+ return (
+ current !== undefined &&
+ current.namespace === server.namespace &&
+ this.dependencies.sameDesiredRevision(server, current)
+ )
+ }
+
private currentRetryHandle(key: string): ExternalEgressRetryHandle | undefined {
const intent = this.retryIntents.get(key)
return intent ? this.retryHandle(intent) : undefined
diff --git a/host-context-controller/src/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.ts
index 152234ee3..e5b77d8f5 100644
--- a/host-context-controller/src/hostReconciler.test.ts
+++ b/host-context-controller/src/hostReconciler.test.ts
@@ -1095,6 +1095,151 @@ describe('HostReconciler Host inventory mutation authority', () => {
expect(reconcileCore).not.toHaveBeenCalled()
})
+ it('rejects a queued fleet worker after Context authority retires and recovers', async () => {
+ const reconciler = makeBasicReconciler()
+ const hostA = makeHost({ name: 'context-authority-a' })
+ const hostB = makeHost({ name: 'context-authority-b' })
+ const hosts = new Map([
+ [hostA.name, hostA],
+ [hostB.name, hostB],
+ ])
+ reconciler.setResolveCurrentHost(name => hosts.get(name))
+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 7 }))
+ const mutationAuthority = {
+ current: {
+ known: true,
+ hostGeneration: 7,
+ contextGeneration: 11,
+ },
+ }
+ ;(reconciler as any).setHostMutationAuthority(() => mutationAuthority.current)
+ const reconcileCore = vi.spyOn(reconciler as any, 'reconcileCore').mockResolvedValue(undefined)
+ vi.spyOn(reconciler as any, 'collectHostCleanupFailures').mockResolvedValue([])
+ const blockerStarted = deferred()
+ const releaseBlocker = deferred()
+ const occupied = (reconciler as any).lifecycle.serializeByHost(hostB.name, async () => {
+ blockerStarted.resolve(undefined)
+ await releaseBlocker.promise
+ }) as Promise<void>
+ await blockerStarted.promise
+
+ const fleet = reconciler.fullReconcile([hostA, hostB])
+ await vi.waitFor(() => expect(reconcileCore).toHaveBeenCalledWith(hostA, expect.any(Function)))
+
+ // Context retired and recovered to a fresh LIST -> WATCH generation while
+ // Host authority remained continuously known: a host-only lease would miss
+ // this ABA transition and admit Host B with stale derived mounts.
+ mutationAuthority.current = {
+ known: true,
+ hostGeneration: 7,
+ contextGeneration: 13,
+ }
+ releaseBlocker.resolve(undefined)
+ await occupied
+
+ await expect(fleet).rejects.toBeInstanceOf(HostFleetReconcileError)
+ expect(reconcileCore).toHaveBeenCalledTimes(1)
+ expect(reconcileCore).not.toHaveBeenCalledWith(hostB, expect.any(Function))
+ })
+
+ it('retires a Host reconcile when its Context is superseded within the same watch', async () => {
+ const reconciler = makeBasicReconciler()
+ const host = {
+ ...makeHost({ name: 'context-revision-race', contextRef: 'context-a' }),
+ uid: 'context-revision-race-uid',
+ generation: 5,
+ }
+ const contextV1 = { name: 'context-a', spec: { sharedFileSystems: [] } }
+ const contextV2 = {
+ name: 'context-a',
+ spec: {
+ sharedFileSystems: [{ name: 'documents', mountPath: '/contexts/documents' }],
+ },
+ }
+ let selectedContext: unknown = contextV1
+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))
+ reconciler.setHostMutationAuthority(() => ({
+ known: true,
+ hostGeneration: 7,
+ contextGeneration: 11,
+ }))
+ reconciler.setResolveHostMutationDependencies(() => [selectedContext])
+
+ const secretReadStarted = deferred()
+ const releaseSecretRead = deferred()
+ vi.spyOn(reconciler as any, 'validateHostSecret').mockImplementation(async () => {
+ secretReadStarted.resolve(undefined)
+ await releaseSecretRead.promise
+ return { ok: true }
+ })
+ const ensureServiceAccount = vi
+ .spyOn(reconciler as any, 'ensureHostServiceAccount')
+ .mockResolvedValue(undefined)
+
+ const pending = reconciler.reconcile(host)
+ await secretReadStarted.promise
+ selectedContext = contextV2
+ releaseSecretRead.resolve(undefined)
+
+ await expect(pending).rejects.toThrow(/Host mutation dependency changed/)
+ expect(ensureServiceAccount).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ [
+ 'referenced SharedFileSystem revision',
+ { name: 'documents', spec: { storageClassName: 'fast-v1' } },
+ { name: 'documents', spec: { storageClassName: 'fast-v2' } },
+ ],
+ ['referenced SharedFileSystem mountability', true, false],
+ [
+ 'Host-scoped CommunicationChannel revision',
+ { name: 'telegram', spec: { hostRef: 'dependency-race' } },
+ {
+ name: 'telegram',
+ spec: {
+ hostRef: 'dependency-race',
+ credentialsSecretRef: { name: 'telegram-v2' },
+ },
+ },
+ ],
+ ])('retires a Host reconcile when its %s changes', async (_label, original, replacement) => {
+ const reconciler = makeBasicReconciler()
+ const host = {
+ ...makeHost({ name: 'dependency-race', contextRef: 'context-a' }),
+ uid: 'dependency-race-uid',
+ generation: 5,
+ }
+ const context = { name: 'context-a', spec: { sharedFileSystems: [] } }
+ let selectedDependency: unknown = original
+ reconciler.setResolveCurrentHost(name => (name === host.name ? host : undefined))
+ reconciler.setHostMutationAuthority(() => ({
+ known: true,
+ hostGeneration: 7,
+ contextGeneration: 11,
+ }))
+ reconciler.setResolveHostMutationDependencies(() => [context, selectedDependency])
+
+ const secretReadStarted = deferred()
+ const releaseSecretRead = deferred()
+ vi.spyOn(reconciler as any, 'validateHostSecret').mockImplementation(async () => {
+ secretReadStarted.resolve(undefined)
+ await releaseSecretRead.promise
+ return { ok: true }
+ })
+ const ensureServiceAccount = vi
+ .spyOn(reconciler as any, 'ensureHostServiceAccount')
+ .mockResolvedValue(undefined)
+
+ const pending = reconciler.reconcile(host)
+ await secretReadStarted.promise
+ selectedDependency = replacement
+ releaseSecretRead.resolve(undefined)
+
+ await expect(pending).rejects.toThrow(/Host mutation dependency changed/)
+ expect(ensureServiceAccount).not.toHaveBeenCalled()
+ })
+
it('does not delete runtime after a Secret rejection when Host authority changes in flight', async () => {
const reconciler = makeBasicReconciler()
const host = { ...makeHost({ name: 'secret-authority-race' }), uid: 'host-uid', generation: 3 }
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 34e321911..ac253d7c7 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -77,16 +77,29 @@ export type HostReconcileSource = 'urgent' | 'retry' | 'fleet'
/** Immutable Host watch authority snapshot captured at a full-pass boundary. */
export type HostWatchAuthoritySnapshot = { known: boolean; generation: number }
+/**
+ * Immutable lease for every inventory that contributes to a Host mutation.
+ * Host resources come from the Host watch; mounted SharedFileSystems come from
+ * the Context watch. Keeping both generations prevents a false-stable
+ * Host-only lease when Context retires and recovers during queued work.
+ */
+export type HostMutationAuthoritySnapshot = {
+ known: boolean
+ hostGeneration: number
+ contextGeneration: number
+}
+
class HostInventoryAuthorityUnavailableError extends Error {
constructor(
action: string,
- captured: HostWatchAuthoritySnapshot,
- current: HostWatchAuthoritySnapshot
+ captured: HostMutationAuthoritySnapshot,
+ current: HostMutationAuthoritySnapshot
) {
super(
`Host inventory authority changed before ${action} admission ` +
- `(captured known=${captured.known} generation=${captured.generation}, ` +
- `current known=${current.known} generation=${current.generation})`
+ `(captured known=${captured.known} hostGeneration=${captured.hostGeneration} ` +
+ `contextGeneration=${captured.contextGeneration}, current known=${current.known} ` +
+ `hostGeneration=${current.hostGeneration} contextGeneration=${current.contextGeneration})`
)
this.name = 'HostInventoryAuthorityUnavailableError'
}
@@ -106,6 +119,13 @@ class HostMutationSpecRevisionChangedError extends Error {
}
}
+class HostMutationDependencyChangedError extends Error {
+ constructor(action: string, hostName: string) {
+ super(`Host mutation dependency changed before ${action} admission for "${hostName}"`)
+ this.name = 'HostMutationDependencyChangedError'
+ }
+}
+
/**
* 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
@@ -415,6 +435,27 @@ export class HostReconciler {
known: false,
generation: 0,
})
+ /**
+ * Positive Host mutations depend on Host plus Context authority. The default
+ * preserves the standalone HostReconciler contract by deriving a Host-only
+ * lease; McpServerWatcher wires the complete composite lease.
+ */
+ private hostMutationAuthority: () => HostMutationAuthoritySnapshot = () => {
+ const host = this.hostWatchAuthority()
+ return {
+ known: host.known,
+ hostGeneration: host.generation,
+ contextGeneration: 0,
+ }
+ }
+ /**
+ * Exact revisions of the cross-resource inputs selected by a Host. Watch
+ * generations fence LIST -> WATCH authority, but normal MODIFIED events stay
+ * in the same generation. The watcher supplies the selected Context,
+ * referenced SharedFileSystems plus mountability, and Host-scoped
+ * CommunicationChannels so unrelated fleet changes do not retire this lease.
+ */
+ private resolveHostMutationDependencies: ((host: HostCRD) => readonly unknown[]) | null = null
constructor(kc: k8s.KubeConfig, deps?: HostReconcilerDeps) {
this.appsApi =
@@ -525,23 +566,36 @@ export class HostReconciler {
this.hostWatchAuthority = fn
}
+ setHostMutationAuthority(fn: () => HostMutationAuthoritySnapshot): void {
+ this.hostMutationAuthority = fn
+ }
+
+ setResolveHostMutationDependencies(fn: (host: HostCRD) => readonly unknown[]): void {
+ this.resolveHostMutationDependencies = fn
+ }
+
/**
* A standalone HostReconciler receives an explicit Host object and has no
* watch-backed cache to fence. Once a live-cache resolver is wired (the
* production McpServerWatcher path), every mutation captures and revalidates
* Host LIST -> WATCH authority at its actual serializer admission boundary.
*/
- private captureHostMutationAuthority(): HostWatchAuthoritySnapshot | null {
- return this.resolveCurrentHost === null ? null : this.hostWatchAuthority()
+ private captureHostMutationAuthority(): HostMutationAuthoritySnapshot | null {
+ return this.resolveCurrentHost === null ? null : this.hostMutationAuthority()
}
private requireHostMutationAuthority(
action: string,
- captured: HostWatchAuthoritySnapshot | null
+ captured: HostMutationAuthoritySnapshot | null
): void {
if (captured === null) return
- const current = this.hostWatchAuthority()
- if (!captured.known || !current.known || captured.generation !== current.generation) {
+ const current = this.hostMutationAuthority()
+ if (
+ !captured.known ||
+ !current.known ||
+ captured.hostGeneration !== current.hostGeneration ||
+ captured.contextGeneration !== current.contextGeneration
+ ) {
throw new HostInventoryAuthorityUnavailableError(action, captured, current)
}
}
@@ -554,13 +608,20 @@ export class HostReconciler {
*/
private prepareHostMutationAdmission(action: string, requested: HostCRD): () => HostCRD {
const capturedAuthority = this.captureHostMutationAuthority()
- return this.makeHostMutationAdmission(action, requested, capturedAuthority)
+ const capturedDependencies = this.resolveHostMutationDependencies?.(requested)
+ return this.makeHostMutationAdmission(
+ action,
+ requested,
+ capturedAuthority,
+ capturedDependencies
+ )
}
private makeHostMutationAdmission(
action: string,
requested: HostCRD,
- capturedAuthority: HostWatchAuthoritySnapshot | null
+ capturedAuthority: HostMutationAuthoritySnapshot | null,
+ capturedDependencies: readonly unknown[] | undefined
): () => HostCRD {
return () => {
this.requireHostMutationAuthority(action, capturedAuthority)
@@ -581,6 +642,16 @@ export class HostReconciler {
) {
throw new HostMutationSpecRevisionChangedError(action, requested.name)
}
+ if (this.resolveHostMutationDependencies !== null) {
+ const currentDependencies = this.resolveHostMutationDependencies(current)
+ const sameDependencies =
+ capturedDependencies !== undefined &&
+ capturedDependencies.length === currentDependencies.length &&
+ capturedDependencies.every((value, index) => Object.is(value, currentDependencies[index]))
+ if (!sameDependencies) {
+ throw new HostMutationDependencyChangedError(action, requested.name)
+ }
+ }
return current
}
}
@@ -2193,7 +2264,12 @@ export class HostReconciler {
const admittedHost = resolveCurrentHost?.(hostName)
if (resolveCurrentHost !== null && admittedHost === undefined) return
const revalidate = admittedHost
- ? this.makeHostMutationAdmission(action, admittedHost, capturedAuthority)
+ ? this.makeHostMutationAdmission(
+ action,
+ admittedHost,
+ capturedAuthority,
+ this.resolveHostMutationDependencies?.(admittedHost)
+ )
: () => this.requireHostMutationAuthority(action, capturedAuthority)
revalidate()
@@ -3658,6 +3734,7 @@ export class HostReconciler {
async reconcile(host: HostCRD, source: HostReconcileSource = 'urgent'): Promise<void> {
const dispatchedAt = Date.now()
const capturedAuthority = this.captureHostMutationAuthority()
+ const capturedDependencies = this.resolveHostMutationDependencies?.(host)
return this.lifecycle.serializeByHost(host.name, async () => {
this.requireHostMutationAuthority(`Host "${host.name}" reconcile`, capturedAuthority)
const admittedHost = this.resolveCurrentHost ? this.resolveCurrentHost(host.name) : host
@@ -3665,7 +3742,8 @@ export class HostReconciler {
const revalidate = this.makeHostMutationAdmission(
`Host "${host.name}" reconcile`,
admittedHost,
- capturedAuthority
+ capturedAuthority,
+ capturedDependencies
)
const admittedAt = Date.now()
hostReconcileInFlight.inc({ lane: source })
diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.ts
index 507c08976..7c2a9e3ed 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -11,7 +11,7 @@ import {
} from './k8sClient'
import { registry } from './metrics'
import { ContextMapperServer } from './server'
-import type { HostCRD } from './types'
+import type { HostCRD, McpServerCRD } from './types'
function deferred<T = void>(): {
promise: Promise<T>
@@ -90,6 +90,17 @@ function stubAuthoritativeInventoryWatch(
function markHostInventoryAuthoritative(watcher: McpServerWatcher): void {
;(watcher as any).hostCacheSynced = true
+ ;(watcher as any).contextCacheSynced = true
+}
+
+function markMcpServerInventoryAuthoritative(watcher: McpServerWatcher): void {
+ ;(watcher as any).mcpServerCacheSynced = true
+}
+
+function newContextAuthoritativeWatcher(): McpServerWatcher {
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).contextCacheSynced = true
+ return watcher
}
const mocks = vi.hoisted(() => {
@@ -233,6 +244,14 @@ vi.mock('./hostReconciler', () => ({
// and the watch-authority snapshot into HostReconciler at construction.
setResolveCurrentHost = vi.fn()
setHostWatchAuthority = vi.fn()
+ setHostMutationAuthority = vi.fn()
+ _hostMutationDependenciesFn: ((host: HostCRD) => readonly unknown[]) | null = null
+ setResolveHostMutationDependencies = vi.fn().mockImplementation(function (
+ this: { _hostMutationDependenciesFn: ((host: HostCRD) => readonly unknown[]) | null },
+ fn: (host: HostCRD) => readonly unknown[]
+ ) {
+ this._hostMutationDependenciesFn = fn
+ })
// Stores the injected callback so tests can invoke it directly.
_countCommunicationChannelsFn: ((host: string) => number) | null = null
setCountCommunicationChannels = vi.fn().mockImplementation(function (
@@ -547,6 +566,52 @@ describe('McpServerWatcher startup', () => {
}
})
+ it('defers Host fleet convergence until both Host and Context inventories are authoritative', async () => {
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).hostCacheSynced = true
+ ;(watcher as any).contextCacheSynced = false
+ ;(watcher as any).hosts.set('context-dependent-host', {
+ name: 'context-dependent-host',
+ namespace: 'mcp-host',
+ spec: {
+ host: 'context-dependent-host',
+ contextRef: 'current-context',
+ secretRef: 'host-secret',
+ },
+ })
+
+ await (watcher as any).performHostFleetReconcileOnce({
+ reason: 'Context authority test',
+ mode: 'full',
+ })
+
+ expect(mocks.hostFullReconcile).not.toHaveBeenCalled()
+ ;(watcher as any).contextCacheSynced = true
+ await (watcher as any).performHostFleetReconcileOnce({
+ reason: 'Context authority recovered',
+ mode: 'full',
+ })
+
+ expect(mocks.hostFullReconcile).toHaveBeenCalledOnce()
+ expect(mocks.hostFullReconcile).toHaveBeenCalledWith([
+ expect.objectContaining({ name: 'context-dependent-host' }),
+ ])
+ await watcher.stop()
+ })
+
+ it('applies a pending CommunicationChannel lifecycle generation during Context recovery', async () => {
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).hostCacheSynced = true
+ ;(watcher as any).contextCacheSynced = false
+ const pendingGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
+
+ await (watcher as any).recoverContextInventoryAndWatch()
+ await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledOnce())
+
+ expect((watcher as any).ccAppliedLifecycleGeneration).toBe(pendingGeneration)
+ await watcher.stop()
+ })
+
it('starts McpServer and Context watches from their inventory resourceVersions', async () => {
const watcher = new McpServerWatcher()
@@ -1150,7 +1215,8 @@ describe('McpServerWatcher startup', () => {
await flushMicrotasks()
expect(reconciler.reconcile).toHaveBeenCalledWith(
- expect.objectContaining({ name: 'current-server' })
+ expect.objectContaining({ name: 'current-server' }),
+ { isCurrent: expect.any(Function) }
)
releaseEgress.resolve(undefined)
@@ -1158,7 +1224,8 @@ describe('McpServerWatcher startup', () => {
expect(reconciliationOrder).toEqual(['watch', 'initial'])
expect(reconciler.reconcile).toHaveBeenLastCalledWith(
- expect.objectContaining({ name: 'current-server' })
+ expect.objectContaining({ name: 'current-server' }),
+ { isCurrent: expect.any(Function) }
)
await watcher.stop()
})
@@ -1223,6 +1290,7 @@ describe('McpServerWatcher startup', () => {
const blockerStarted = deferred()
const releaseBlocker = deferred()
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const reconciler = (watcher as any).reconciler
for (const server of [currentServer, staleServer, unrelatedServer]) {
;(watcher as any).servers.set(server.name, server)
@@ -1241,18 +1309,120 @@ describe('McpServerWatcher startup', () => {
})
await vi.waitFor(() =>
expect(reconciler.reconcile).toHaveBeenCalledWith(
- expect.objectContaining({ name: currentServer.name })
+ expect.objectContaining({ name: currentServer.name }),
+ { isCurrent: expect.any(Function) }
)
)
releaseBlocker.resolve(undefined)
await Promise.all([blocker, convergence])
expect(reconciler.reconcile).toHaveBeenCalledTimes(1)
- expect(reconciler.reconcile).not.toHaveBeenCalledWith(
- expect.objectContaining({ name: staleServer.name })
+ expect(
+ reconciler.reconcile.mock.calls.some(
+ ([server]: [McpServerCRD]) => server.name === staleServer.name
+ )
+ ).toBe(false)
+ expect(
+ reconciler.reconcile.mock.calls.some(
+ ([server]: [McpServerCRD]) => server.name === unrelatedServer.name
+ )
+ ).toBe(false)
+ await watcher.stop()
+ })
+
+ it('defers env-Secret reconciliation until the McpServer inventory is authoritative', async () => {
+ const selected = {
+ name: 'authority-fenced-secret-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'clerum/authority-fenced-secret-server:test',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ envSecret: { name: 'shared-env' },
+ },
+ }
+ const watcher = new McpServerWatcher()
+ const reconciler = (watcher as any).reconciler
+ ;(watcher as any).servers.set(selected.name, selected)
+ ;(watcher as any).mcpServerCacheSynced = false
+
+ await watcher.reconcileByEnvSecret('shared-env', 'mcp-server')
+
+ expect(reconciler.reconcile).not.toHaveBeenCalled()
+
+ markMcpServerInventoryAuthoritative(watcher)
+ await watcher.reconcileByEnvSecret('shared-env', 'mcp-server')
+
+ expect(reconciler.reconcile).toHaveBeenCalledOnce()
+ expect(reconciler.reconcile).toHaveBeenCalledWith(
+ expect.objectContaining({ name: selected.name }),
+ { isCurrent: expect.any(Function) }
)
- expect(reconciler.reconcile).not.toHaveBeenCalledWith(
- expect.objectContaining({ name: unrelatedServer.name })
+ await watcher.stop()
+ })
+
+ it('fences Context-triggered SharedFileSystem convergence to the current Context lease', async () => {
+ const context = {
+ name: 'sfs-context',
+ namespace: 'mcp-server',
+ spec: {
+ contextId: 'sfs-context',
+ sharedFileSystems: [{ name: 'shared-data', mountPath: '/shared' }],
+ },
+ }
+ const sharedFileSystem = {
+ name: 'shared-data',
+ namespace: 'mcp-host',
+ spec: {},
+ }
+ const watcher = new McpServerWatcher()
+ const reconciler = (watcher as any).sharedFileSystemReconciler
+ ;(watcher as any).sharedFileSystems.set(sharedFileSystem.name, sharedFileSystem)
+
+ await (watcher as any).reconcileSharedFileSystemsReferencedByContext(
+ undefined,
+ context,
+ () => false
+ )
+
+ expect(reconciler.reconcile).not.toHaveBeenCalled()
+
+ await (watcher as any).reconcileSharedFileSystemsReferencedByContext(
+ undefined,
+ context,
+ () => true
+ )
+
+ expect(reconciler.reconcile).toHaveBeenCalledOnce()
+ expect(reconciler.reconcile).toHaveBeenCalledWith(
+ expect.objectContaining({ name: sharedFileSystem.name })
+ )
+ await watcher.stop()
+ })
+
+ it('fences Context-triggered Host convergence to the current Context lease', async () => {
+ const watcher = new McpServerWatcher()
+ markHostInventoryAuthoritative(watcher)
+ ;(watcher as any).hosts.set('context-host', {
+ name: 'context-host',
+ namespace: 'mcp-host',
+ spec: {
+ host: 'context-host',
+ contextRef: 'context-a',
+ secretRef: 'host-secret',
+ },
+ })
+ const hostReconciler = (watcher as any).hostReconciler
+
+ await (watcher as any).reconcileHostsReferencingContext('context-a', () => false)
+
+ expect(hostReconciler.reconcile).not.toHaveBeenCalled()
+
+ await (watcher as any).reconcileHostsReferencingContext('context-a', () => true)
+
+ expect(hostReconciler.reconcile).toHaveBeenCalledOnce()
+ expect(hostReconciler.reconcile).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'context-host' })
)
await watcher.stop()
})
@@ -1380,7 +1550,8 @@ describe('McpServerWatcher startup', () => {
await flushMicrotasks()
expect(netPol.reconcileContext).toHaveBeenCalledWith(
- expect.objectContaining({ name: 'current-context' })
+ expect.objectContaining({ name: 'current-context' }),
+ { isCurrent: expect.any(Function) }
)
releaseFullReconcile.resolve(undefined)
@@ -1388,7 +1559,8 @@ describe('McpServerWatcher startup', () => {
expect(reconciliationOrder).toEqual(['watch', 'initial'])
expect(netPol.reconcileContext).toHaveBeenLastCalledWith(
- expect.objectContaining({ name: 'current-context' })
+ expect.objectContaining({ name: 'current-context' }),
+ { isCurrent: expect.any(Function) }
)
await watcher.stop()
})
@@ -1453,7 +1625,8 @@ describe('McpServerWatcher startup', () => {
expect.objectContaining({
name: contextName,
spec: expect.objectContaining({ contextId, description: 'recreated' }),
- })
+ }),
+ { isCurrent: expect.any(Function) }
)
await watcher.stop()
})
@@ -1581,6 +1754,7 @@ describe('McpServerWatcher startup', () => {
const oldStarted = deferred()
const releaseOld = deferred()
const order: string[] = []
+ let oldLease: (() => boolean) | undefined
let contextWatchCallback:
| ((type: string, apiObj: typeof newContext) => Promise<void>)
| undefined
@@ -1591,15 +1765,18 @@ describe('McpServerWatcher startup', () => {
const watcher = new McpServerWatcher()
;(watcher as any).contexts.set(oldContext.name, oldContext)
const netPol = (watcher as any).netPolReconciler
- netPol.reconcileContext.mockImplementation(async (context: typeof oldContext) => {
- if (context.spec.description === 'old') {
- oldStarted.resolve(undefined)
- await releaseOld.promise
- order.push('old')
- return
+ netPol.reconcileContext.mockImplementation(
+ async (context: typeof oldContext, options: { isCurrent: () => boolean }) => {
+ if (context.spec.description === 'old') {
+ oldLease = options.isCurrent
+ oldStarted.resolve(undefined)
+ await releaseOld.promise
+ order.push('old')
+ return
+ }
+ order.push('new')
}
- order.push('new')
- })
+ )
await (watcher as any).startContextWatch('context-policy-rv')
const serverEvent = (watcher as any).getMcpServerWatchCallback()('MODIFIED', server)
@@ -1608,6 +1785,7 @@ describe('McpServerWatcher startup', () => {
await flushMicrotasks()
expect(netPol.reconcileContext).toHaveBeenCalledTimes(1)
+ expect(oldLease?.()).toBe(false)
releaseOld.resolve(undefined)
await Promise.all([serverEvent, contextEvent])
@@ -1615,11 +1793,64 @@ describe('McpServerWatcher startup', () => {
expect(netPol.reconcileContext).toHaveBeenLastCalledWith(
expect.objectContaining({
spec: expect.objectContaining({ description: 'new' }),
- })
+ }),
+ { isCurrent: expect.any(Function) }
)
await watcher.stop()
})
+ it('retires a blocked Context policy lease when MODIFIED replaces it in the same watch', async () => {
+ const oldContext = {
+ metadata: { name: 'same-stream-context', namespace: 'mcp-server' },
+ spec: {
+ contextId: 'same-stream-context',
+ description: 'old',
+ mcpServers: ['old-server'],
+ },
+ }
+ const newContext = {
+ metadata: oldContext.metadata,
+ spec: {
+ ...oldContext.spec,
+ description: 'new',
+ mcpServers: ['new-server'],
+ },
+ }
+ const mutationStarted = deferred()
+ const releaseMutation = deferred()
+ let oldLease: (() => boolean) | undefined
+ let contextWatchCallback:
+ | ((type: string, apiObj: typeof oldContext) => Promise<void>)
+ | undefined
+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {
+ contextWatchCallback = callback
+ return { abort: vi.fn() }
+ })
+ const watcher = new McpServerWatcher()
+ const netPol = (watcher as any).netPolReconciler
+ netPol.reconcileContext.mockImplementationOnce(
+ async (_context: unknown, options: { isCurrent: () => boolean }) => {
+ oldLease = options.isCurrent
+ mutationStarted.resolve()
+ await releaseMutation.promise
+ }
+ )
+ await (watcher as any).startContextWatch('same-stream-context-rv')
+ ;(watcher as any).contextCacheSynced = true
+ ;(watcher as any).mcpServerCacheSynced = true
+
+ const oldReconcile = contextWatchCallback!('MODIFIED', oldContext)
+ await mutationStarted.promise
+ expect(oldLease?.()).toBe(true)
+
+ const newReconcile = contextWatchCallback!('MODIFIED', newContext)
+ expect(oldLease?.()).toBe(false)
+
+ releaseMutation.resolve()
+ await Promise.all([oldReconcile, newReconcile])
+ await watcher.stop()
+ })
+
it('keeps live control-plane events responsive during a periodic external-egress fleet resync', async () => {
const server = {
name: 'periodic-egress-server',
@@ -1646,6 +1877,7 @@ describe('McpServerWatcher startup', () => {
})
const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0)
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
;(watcher as any).servers.set(server.name, server)
const netPol = (watcher as any).netPolReconciler
netPol.reconcileExternalEgress.mockImplementationOnce(async () => {
@@ -1662,7 +1894,8 @@ describe('McpServerWatcher startup', () => {
const liveEvent = contextWatchCallback!('MODIFIED', context)
await flushMicrotasks()
expect(netPol.reconcileContext).toHaveBeenCalledWith(
- expect.objectContaining({ name: 'live-context' })
+ expect.objectContaining({ name: 'live-context' }),
+ { isCurrent: expect.any(Function) }
)
releaseResync.resolve(undefined)
@@ -1671,6 +1904,60 @@ describe('McpServerWatcher startup', () => {
randomSpy.mockRestore()
})
+ it('retires a blocked periodic egress lease when MODIFIED replaces it in the same watch', async () => {
+ const oldServer = {
+ name: 'same-stream-egress',
+ namespace: 'mcp-server',
+ uid: 'same-stream-egress-uid',
+ generation: 1,
+ spec: {
+ contextRef: 'default',
+ image: 'clerum/same-stream-egress:old',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ egressBindings: [{ dns: 'old.example', port: 443 }],
+ },
+ }
+ const newServer = {
+ metadata: {
+ name: oldServer.name,
+ namespace: oldServer.namespace,
+ uid: oldServer.uid,
+ generation: 2,
+ },
+ spec: {
+ ...oldServer.spec,
+ image: 'clerum/same-stream-egress:new',
+ egressBindings: [{ dns: 'new.example', port: 443 }],
+ },
+ }
+ const mutationStarted = deferred()
+ const releaseMutation = deferred()
+ let oldLease: (() => boolean) | undefined
+ const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
+ ;(watcher as any).servers.set(oldServer.name, oldServer)
+ const netPol = (watcher as any).netPolReconciler
+ netPol.reconcileExternalEgress.mockImplementationOnce(
+ async (_server: unknown, options: { isCurrent: () => boolean }) => {
+ oldLease = options.isCurrent
+ mutationStarted.resolve()
+ await releaseMutation.promise
+ }
+ )
+ vi.spyOn(Math, 'random').mockReturnValue(0)
+
+ const periodic = (watcher as any).runExternalEgressResync() as Promise<void>
+ await mutationStarted.promise
+ expect(oldLease?.()).toBe(true)
+
+ const replacement = (watcher as any).getMcpServerWatchCallback()('MODIFIED', newServer)
+ expect(oldLease?.()).toBe(false)
+
+ releaseMutation.resolve()
+ await Promise.all([periodic, replacement])
+ await watcher.stop()
+ })
+
it('uses the latest cached McpServer after periodic external-egress jitter', async () => {
vi.useFakeTimers()
const staleServer = {
@@ -1716,7 +2003,8 @@ describe('McpServerWatcher startup', () => {
spec: expect.objectContaining({
egressBindings: [{ dns: 'new.example', port: 443 }],
}),
- })
+ }),
+ { isCurrent: expect.any(Function) }
)
await watcher.stop()
randomSpy.mockRestore()
@@ -1905,49 +2193,292 @@ describe('McpServerWatcher startup', () => {
name: 'initial-server',
namespace: 'mcp-server',
spec: {
- contextRef: 'default',
- image: 'clerum/initial-server:test',
- transport: { type: 'streamableHttp' as const, port: 3000 },
- egressBindings: [{ dns: 'initial.example', port: 443 }],
- },
- }
- const queuedServer = {
- metadata: { name: 'queued-server', namespace: 'mcp-server' },
- spec: {
- contextRef: 'default',
- image: 'clerum/queued-server:test',
+ contextRef: 'default',
+ image: 'clerum/initial-server:test',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ egressBindings: [{ dns: 'initial.example', port: 443 }],
+ },
+ }
+ const queuedServer = {
+ metadata: { name: 'queued-server', namespace: 'mcp-server' },
+ spec: {
+ contextRef: 'default',
+ image: 'clerum/queued-server:test',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ },
+ }
+ const egressStarted = deferred()
+ const releaseEgress = deferred()
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).mcpServerCacheSynced = true
+ ;(watcher as any).servers.set(initialServer.name, initialServer)
+ const netPol = (watcher as any).netPolReconciler
+ netPol.reconcileExternalEgress.mockImplementationOnce(async () => {
+ egressStarted.resolve(undefined)
+ await releaseEgress.promise
+ })
+ const reconciler = (watcher as any).reconciler
+ mocks.serverFullReconcile.mockImplementationOnce(async (servers, options) => {
+ await Promise.all(
+ servers.map((selected: { name: string }) =>
+ options.runEffect(selected.name, () => reconciler.reconcile(selected))
+ )
+ )
+ })
+
+ const initial = (watcher as any).runInitialMcpServerConvergence()
+ await egressStarted.promise
+ const queuedWatch = (watcher as any).getMcpServerWatchCallback()('MODIFIED', queuedServer)
+
+ await watcher.stop()
+ releaseEgress.resolve(undefined)
+ await Promise.all([initial, queuedWatch])
+
+ expect(mocks.serverFullReconcile).toHaveBeenCalledOnce()
+ expect(reconciler.reconcile).not.toHaveBeenCalled()
+ })
+
+ it('coalesces overlapping McpServer fleet passes into one trailing current-cache pass', async () => {
+ const firstPassStarted = deferred()
+ const releaseFirstPass = deferred()
+ const snapshots: string[][] = []
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).mcpServerCacheSynced = true
+ ;(watcher as any).servers.set('first-server', {
+ name: 'first-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'clerum/first-server:test',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ },
+ })
+ mocks.serverFullReconcile
+ .mockImplementationOnce(async (servers: Array<{ name: string }>) => {
+ snapshots.push(servers.map(server => server.name))
+ firstPassStarted.resolve(undefined)
+ await releaseFirstPass.promise
+ })
+ .mockImplementationOnce(async (servers: Array<{ name: string }>) => {
+ snapshots.push(servers.map(server => server.name))
+ })
+
+ const first = (watcher as any).runInitialMcpServerConvergence()
+ await firstPassStarted.promise
+ ;(watcher as any).servers.set('second-server', {
+ name: 'second-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'clerum/second-server:test',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ },
+ })
+ const second = (watcher as any).runInitialMcpServerConvergence()
+ const third = (watcher as any).runInitialMcpServerConvergence()
+
+ expect(mocks.serverFullReconcile).toHaveBeenCalledTimes(1)
+ releaseFirstPass.resolve(undefined)
+ await Promise.all([first, second, third])
+
+ expect(mocks.serverFullReconcile).toHaveBeenCalledTimes(2)
+ expect(snapshots).toEqual([['first-server'], ['first-server', 'second-server']])
+ await watcher.stop()
+ })
+
+ it('coalesces overlapping NetworkPolicy fleet passes into one trailing current-cache pass', async () => {
+ const firstPassStarted = deferred()
+ const releaseFirstPass = deferred()
+ const snapshots: string[][] = []
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).contextCacheSynced = true
+ ;(watcher as any).mcpServerCacheSynced = true
+ ;(watcher as any).contexts.set('first-context', {
+ name: 'first-context',
+ namespace: 'mcp-server',
+ spec: { contextId: 'first-context', mcpServers: [] },
+ })
+ mocks.netPolFullReconcile
+ .mockImplementationOnce(async (contexts: Array<{ name: string }>) => {
+ snapshots.push(contexts.map(context => context.name))
+ firstPassStarted.resolve(undefined)
+ await releaseFirstPass.promise
+ })
+ .mockImplementationOnce(async (contexts: Array<{ name: string }>) => {
+ snapshots.push(contexts.map(context => context.name))
+ })
+
+ const first = (watcher as any).runInitialNetworkPolicyConvergence()
+ await firstPassStarted.promise
+ ;(watcher as any).contexts.set('second-context', {
+ name: 'second-context',
+ namespace: 'mcp-server',
+ spec: { contextId: 'second-context', mcpServers: [] },
+ })
+ const second = (watcher as any).runInitialNetworkPolicyConvergence()
+ const third = (watcher as any).runInitialNetworkPolicyConvergence()
+
+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(1)
+ releaseFirstPass.resolve(undefined)
+ await Promise.all([first, second, third])
+
+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(2)
+ expect(snapshots).toEqual([['first-context'], ['first-context', 'second-context']])
+ await watcher.stop()
+ })
+
+ it('fences an McpServer fleet pass when its LIST-to-WATCH authority is retired', async () => {
+ const egressStarted = deferred()
+ const releaseEgress = deferred()
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).mcpServerCacheSynced = true
+ ;(watcher as any).mcpWatchGeneration = 7
+ ;(watcher as any).initialConvergenceRetryAttempts.set('McpServer', 3)
+ ;(watcher as any).servers.set('stale-server', {
+ name: 'stale-server',
+ namespace: 'mcp-server',
+ generation: 1,
+ spec: {
+ contextRef: 'default',
+ image: 'clerum/stale-server:v1',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ egressBindings: [{ dns: 'stale.example', port: 443 }],
+ },
+ })
+ const netPol = (watcher as any).netPolReconciler
+ const reconciler = (watcher as any).reconciler
+ netPol.reconcileExternalEgress.mockImplementationOnce(async () => {
+ egressStarted.resolve(undefined)
+ await releaseEgress.promise
+ })
+ mocks.serverFullReconcile.mockImplementation(async (servers, options) => {
+ await Promise.all(
+ servers.map((selected: { name: string }) =>
+ options.runEffect(selected.name, () => reconciler.reconcile(selected))
+ )
+ )
+ })
+
+ const stalePass = (watcher as any).runInitialMcpServerConvergence()
+ await egressStarted.promise
+ ;(watcher as any).mcpServerCacheSynced = false
+ ;(watcher as any).mcpWatchGeneration = 8
+ const trailing = (watcher as any).runInitialMcpServerConvergence()
+ releaseEgress.resolve(undefined)
+ await Promise.all([stalePass, trailing])
+
+ expect(reconciler.reconcile).not.toHaveBeenCalled()
+ expect((watcher as any).initialConvergenceRetryAttempts.get('McpServer')).toBe(3)
+ ;(watcher as any).servers.set('stale-server', {
+ name: 'stale-server',
+ namespace: 'mcp-server',
+ generation: 2,
+ spec: {
+ contextRef: 'default',
+ image: 'clerum/stale-server:v2',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ egressBindings: [{ dns: 'current.example', port: 443 }],
+ },
+ })
+ ;(watcher as any).mcpServerCacheSynced = true
+ await (watcher as any).runInitialMcpServerConvergence()
+
+ expect(reconciler.reconcile).toHaveBeenCalledOnce()
+ expect(reconciler.reconcile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ generation: 2,
+ spec: expect.objectContaining({ image: 'clerum/stale-server:v2' }),
+ })
+ )
+ expect((watcher as any).initialConvergenceRetryAttempts.has('McpServer')).toBe(false)
+ await watcher.stop()
+ })
+
+ it('fences NetworkPolicy positive effects when their inventory leases are retired', async () => {
+ const firstPassStarted = deferred()
+ const releaseFirstPass = deferred()
+ const appliedContexts: string[] = []
+ const appliedServers: string[] = []
+ let pass = 0
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).contextCacheSynced = true
+ ;(watcher as any).mcpServerCacheSynced = true
+ ;(watcher as any).contextWatchGeneration = 11
+ ;(watcher as any).mcpWatchGeneration = 13
+ ;(watcher as any).initialConvergenceRetryAttempts.set('NetworkPolicy', 4)
+ ;(watcher as any).contexts.set('stale-context', {
+ name: 'stale-context',
+ namespace: 'mcp-server',
+ spec: { contextId: 'stale-context', mcpServers: ['stale-server'] },
+ })
+ ;(watcher as any).servers.set('stale-server', {
+ name: 'stale-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'stale-context',
+ image: 'clerum/stale-server:v1',
transport: { type: 'streamableHttp' as const, port: 3000 },
},
- }
- const egressStarted = deferred()
- const releaseEgress = deferred()
- const watcher = new McpServerWatcher()
- ;(watcher as any).mcpServerCacheSynced = true
- ;(watcher as any).servers.set(initialServer.name, initialServer)
- const netPol = (watcher as any).netPolReconciler
- netPol.reconcileExternalEgress.mockImplementationOnce(async () => {
- egressStarted.resolve(undefined)
- await releaseEgress.promise
})
- const reconciler = (watcher as any).reconciler
- mocks.serverFullReconcile.mockImplementationOnce(async (servers, options) => {
+ mocks.netPolFullReconcile.mockImplementation(async (contexts, servers, options) => {
+ pass += 1
+ if (pass === 1) {
+ firstPassStarted.resolve(undefined)
+ await releaseFirstPass.promise
+ }
await Promise.all(
- servers.map((selected: { name: string }) =>
- options.runEffect(selected.name, () => reconciler.reconcile(selected))
+ contexts.map((context: { spec: { contextId: string } }) =>
+ options.runContextEffect(context.spec.contextId, async () => {
+ appliedContexts.push(context.spec.contextId)
+ })
+ )
+ )
+ await Promise.all(
+ servers.map((server: { name: string }) =>
+ options.runServerEffect(server.name, async () => {
+ appliedServers.push(server.name)
+ })
)
)
})
- const initial = (watcher as any).runInitialMcpServerConvergence()
- await egressStarted.promise
- const queuedWatch = (watcher as any).getMcpServerWatchCallback()('MODIFIED', queuedServer)
+ const stalePass = (watcher as any).runInitialNetworkPolicyConvergence()
+ await firstPassStarted.promise
+ ;(watcher as any).contextCacheSynced = false
+ ;(watcher as any).mcpServerCacheSynced = false
+ ;(watcher as any).contextWatchGeneration = 12
+ ;(watcher as any).mcpWatchGeneration = 14
+ const trailing = (watcher as any).runInitialNetworkPolicyConvergence()
+ releaseFirstPass.resolve(undefined)
+ await Promise.all([stalePass, trailing])
+
+ expect(appliedContexts).toEqual([])
+ expect(appliedServers).toEqual([])
+ expect((watcher as any).initialConvergenceRetryAttempts.get('NetworkPolicy')).toBe(4)
+ ;(watcher as any).contexts.clear()
+ ;(watcher as any).servers.clear()
+ ;(watcher as any).contexts.set('current-context', {
+ name: 'current-context',
+ namespace: 'mcp-server',
+ spec: { contextId: 'current-context', mcpServers: ['current-server'] },
+ })
+ ;(watcher as any).servers.set('current-server', {
+ name: 'current-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'current-context',
+ image: 'clerum/current-server:v2',
+ transport: { type: 'streamableHttp' as const, port: 3000 },
+ },
+ })
+ ;(watcher as any).contextCacheSynced = true
+ ;(watcher as any).mcpServerCacheSynced = true
+ await (watcher as any).runInitialNetworkPolicyConvergence()
+ expect(appliedContexts).toEqual(['current-context'])
+ expect(appliedServers).toEqual(['current-server'])
+ expect((watcher as any).initialConvergenceRetryAttempts.has('NetworkPolicy')).toBe(false)
await watcher.stop()
- releaseEgress.resolve(undefined)
- await Promise.all([initial, queuedWatch])
-
- expect(mocks.serverFullReconcile).toHaveBeenCalledOnce()
- expect(reconciler.reconcile).not.toHaveBeenCalled()
})
it.each([
@@ -1978,32 +2509,32 @@ describe('McpServerWatcher startup', () => {
}
)
- it('keeps an incomplete McpServer inventory non-authoritative across NetworkPolicy retries', async () => {
- vi.useFakeTimers()
+ it('defers NetworkPolicy full convergence until both inventories are authoritative', async () => {
const watcher = new McpServerWatcher()
;(watcher as any).contextCacheSynced = true
;(watcher as any).mcpServerCacheSynced = false
- mocks.netPolFullReconcile
- .mockRejectedValueOnce(new Error('initial NetworkPolicy reconciliation failed'))
- .mockResolvedValueOnce(undefined)
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ ;(watcher as any).initialConvergenceRetryAttempts.set('NetworkPolicy', 2)
await (watcher as any).runInitialNetworkPolicyConvergence()
- await vi.advanceTimersByTimeAsync(5000)
- expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(2)
+ expect(mocks.netPolFullReconcile).not.toHaveBeenCalled()
+ expect((watcher as any).initialConvergenceRetryAttempts.get('NetworkPolicy')).toBe(2)
+ ;(watcher as any).mcpServerCacheSynced = true
+ await (watcher as any).runInitialNetworkPolicyConvergence()
+
+ expect(mocks.netPolFullReconcile).toHaveBeenCalledOnce()
expect(mocks.netPolFullReconcile).toHaveBeenLastCalledWith(
[],
[],
expect.objectContaining({
- serverInventoryComplete: false,
+ serverInventoryComplete: true,
ensureDefaults: false,
contextInventoryAuthoritative: expect.any(Function),
serverInventoryAuthoritative: expect.any(Function),
})
)
+ expect((watcher as any).initialConvergenceRetryAttempts.has('NetworkPolicy')).toBe(false)
await watcher.stop()
- errorSpy.mockRestore()
})
it('fences NetworkPolicy orphan cleanup to the inventory generations captured by the pass', async () => {
@@ -2453,6 +2984,7 @@ describe('McpServerWatcher external egress retries', () => {
it('retries failed external egress reconciliation from an ADDED event', async () => {
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const netPol = (watcher as any).netPolReconciler
const reconciler = (watcher as any).reconciler
const bindingReconciler = (watcher as any).bindingReconciler
@@ -2489,20 +3021,120 @@ describe('McpServerWatcher external egress retries', () => {
expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(2)
expect(reconciler.reconcile).toHaveBeenCalledTimes(1)
expect(reconciler.reconcile).toHaveBeenCalledWith(
- expect.objectContaining({ name: 'redis-tools' })
+ expect.objectContaining({ name: 'redis-tools' }),
+ { isCurrent: expect.any(Function) }
)
expect(bindingReconciler.reconcileBindings).toHaveBeenCalledTimes(1)
expect(netPol.reconcileContext).toHaveBeenCalledWith(
expect.objectContaining({
spec: expect.objectContaining({ contextId: 'context1' }),
- })
+ }),
+ { isCurrent: expect.any(Function) }
)
watcher.stop()
})
+ it('retires a binding-policy lease when a same-watch MODIFIED supersedes the server', async () => {
+ const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
+ const bindingReconciler = (watcher as any).bindingReconciler
+ const bindingStarted = deferred()
+ const releaseBinding = deferred()
+ bindingReconciler.reconcileBindings.mockImplementationOnce(async () => {
+ bindingStarted.resolve(undefined)
+ await releaseBinding.promise
+ })
+ const annotations = {
+ 'clerum.io/recipe-bindings': JSON.stringify([
+ { from: 'redis-tools', to: 'downstream', port: 443 },
+ ]),
+ }
+ const original = {
+ ...serverObject,
+ metadata: {
+ ...serverObject.metadata,
+ uid: 'redis-tools-uid',
+ generation: 1,
+ annotations,
+ },
+ }
+ const replacement = {
+ ...original,
+ metadata: { ...original.metadata, generation: 2 },
+ spec: { ...original.spec, image: 'redis-tools:v2' },
+ }
+ const watchCallback = (watcher as any).getMcpServerWatchCallback()
+
+ const originalEffect = watchCallback('ADDED', original)
+ await bindingStarted.promise
+ const replacementEffect = watchCallback('MODIFIED', replacement)
+
+ const originalOptions = bindingReconciler.reconcileBindings.mock.calls[0][4]
+ expect(originalOptions).toEqual({ isCurrent: expect.any(Function) })
+ expect(originalOptions.isCurrent()).toBe(false)
+
+ releaseBinding.resolve(undefined)
+ await Promise.all([originalEffect, replacementEffect])
+
+ expect(bindingReconciler.reconcileBindings).toHaveBeenCalledTimes(2)
+ expect(bindingReconciler.reconcileBindings).toHaveBeenLastCalledWith(
+ 'redis-tools',
+ expect.any(Array),
+ 'redis-tools',
+ 'redis-tools',
+ { isCurrent: expect.any(Function) }
+ )
+ await watcher.stop()
+ })
+
+ it('retires binding cleanup when a same-name McpServer is recreated during DELETE', async () => {
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).mcpServerCacheSynced = true
+ const bindingReconciler = (watcher as any).bindingReconciler
+ const cleanupStarted = deferred()
+ const releaseCleanup = deferred()
+ bindingReconciler.cleanupBindings.mockImplementationOnce(async () => {
+ cleanupStarted.resolve(undefined)
+ await releaseCleanup.promise
+ })
+ const deleted = {
+ ...serverObject,
+ metadata: {
+ ...serverObject.metadata,
+ uid: 'redis-tools-old-uid',
+ generation: 1,
+ },
+ }
+ const recreated = {
+ ...serverObject,
+ metadata: {
+ ...serverObject.metadata,
+ uid: 'redis-tools-new-uid',
+ generation: 1,
+ },
+ spec: { ...serverObject.spec, image: 'redis-tools:recreated' },
+ }
+ const watchCallback = (watcher as any).getMcpServerWatchCallback()
+
+ const deleteEffect = watchCallback('DELETED', deleted)
+ await cleanupStarted.promise
+ const recreateEffect = watchCallback('ADDED', recreated)
+
+ const cleanupOptions = bindingReconciler.cleanupBindings.mock.calls[0][1]
+ expect(cleanupOptions).toEqual({ deleteAllowed: expect.any(Function) })
+ await expect(cleanupOptions.deleteAllowed()).resolves.toBe(false)
+
+ releaseCleanup.resolve(undefined)
+ await Promise.all([deleteEffect, recreateEffect])
+
+ expect(bindingReconciler.cleanupBindings).toHaveBeenCalledTimes(1)
+ await watcher.stop()
+ })
+
it('retries the complete pipeline when a no-egress runtime reconcile fails', async () => {
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const reconciler = (watcher as any).reconciler
const noEgressServer = {
...serverObject,
@@ -2528,6 +3160,7 @@ describe('McpServerWatcher external egress retries', () => {
it('retries runtime reconciliation when external egress is ready but runtime reconcile fails', async () => {
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const netPol = (watcher as any).netPolReconciler
const reconciler = (watcher as any).reconciler
netPol.reconcileExternalEgress.mockResolvedValue(undefined)
@@ -2547,7 +3180,8 @@ describe('McpServerWatcher external egress retries', () => {
expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(2)
expect(reconciler.reconcile).toHaveBeenCalledTimes(2)
expect(reconciler.reconcile).toHaveBeenLastCalledWith(
- expect.objectContaining({ name: 'redis-tools' })
+ expect.objectContaining({ name: 'redis-tools' }),
+ { isCurrent: expect.any(Function) }
)
watcher.stop()
@@ -2555,6 +3189,7 @@ describe('McpServerWatcher external egress retries', () => {
it('keeps retry attempts bounded when runtime fails after an external egress retry succeeds', async () => {
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const netPol = (watcher as any).netPolReconciler
const reconciler = (watcher as any).reconciler
netPol.reconcileExternalEgress.mockRejectedValueOnce(new Error('api temporarily unavailable'))
@@ -2580,7 +3215,8 @@ describe('McpServerWatcher external egress retries', () => {
expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(3)
expect(reconciler.reconcile).toHaveBeenCalledTimes(2)
expect(reconciler.reconcile).toHaveBeenLastCalledWith(
- expect.objectContaining({ name: 'redis-tools' })
+ expect.objectContaining({ name: 'redis-tools' }),
+ { isCurrent: expect.any(Function) }
)
watcher.stop()
@@ -2588,6 +3224,7 @@ describe('McpServerWatcher external egress retries', () => {
it('continues a pending runtime pipeline during periodic external egress resync', async () => {
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const netPol = (watcher as any).netPolReconciler
const reconciler = (watcher as any).reconciler
netPol.reconcileExternalEgress.mockResolvedValue(undefined)
@@ -2618,6 +3255,7 @@ describe('McpServerWatcher external egress retries', () => {
it('keeps retrying an ADDED pipeline at the capped delay until it recovers', async () => {
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const netPol = (watcher as any).netPolReconciler
const reconciler = (watcher as any).reconciler
netPol.reconcileExternalEgress
@@ -2672,12 +3310,15 @@ describe('McpServerWatcher external egress retries', () => {
expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(5)
expect(reconciler.reconcileDelete).toHaveBeenCalledWith('redis-tools', 'mcp-server')
- expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools')
+ expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools', {
+ deleteAllowed: expect.any(Function),
+ })
watcher.stop()
})
it('bounds concurrent durable retries across McpServers', async () => {
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const reconciler = (watcher as any).reconciler
const release = deferred()
let active = 0
@@ -2715,6 +3356,7 @@ describe('McpServerWatcher external egress retries', () => {
it('replays a retry against the watcher generation current when the timer executes', async () => {
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const selected = {
name: 'generation-fenced-server',
namespace: 'mcp-server',
@@ -2807,7 +3449,9 @@ describe('McpServerWatcher external egress retries', () => {
expect.any(Function)
)
expect(reconciler.reconcileDelete).toHaveBeenCalledWith('redis-tools', 'mcp-server')
- expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools')
+ expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools', {
+ deleteAllowed: expect.any(Function),
+ })
watcher.stop()
})
@@ -2837,12 +3481,51 @@ describe('McpServerWatcher external egress retries', () => {
expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(1)
expect(reconciler.reconcileDelete).toHaveBeenCalledWith('redis-tools', 'mcp-server')
- expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools')
+ expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools', {
+ deleteAllowed: expect.any(Function),
+ })
expect(mocks.getNamespacedCustomObject).toHaveBeenCalledTimes(4)
watcher.stop()
})
+ it('retries the full DELETE pipeline when inventory authority is lost between cleanup stages', async () => {
+ const watcher = new McpServerWatcher()
+ ;(watcher as any).mcpServerCacheSynced = true
+ const netPol = (watcher as any).netPolReconciler
+ const reconciler = (watcher as any).reconciler
+ const bindingReconciler = (watcher as any).bindingReconciler
+ reconciler.reconcileDelete.mockImplementationOnce(async () => {
+ ;(watcher as any).mcpServerCacheSynced = false
+ })
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ const watchCallback = (watcher as any).getMcpServerWatchCallback()
+ await expect(watchCallback('DELETED', serverObject)).resolves.toBeUndefined()
+
+ expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(1)
+ expect(reconciler.reconcileDelete).toHaveBeenCalledWith('redis-tools', 'mcp-server')
+ expect(bindingReconciler.cleanupBindings).not.toHaveBeenCalled()
+
+ await vi.advanceTimersByTimeAsync(5000)
+
+ expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(1)
+ expect(reconciler.reconcileDelete).toHaveBeenCalledTimes(1)
+ expect(bindingReconciler.cleanupBindings).not.toHaveBeenCalled()
+ ;(watcher as any).mcpServerCacheSynced = true
+ await vi.advanceTimersByTimeAsync(14_999)
+ expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(2)
+ expect(reconciler.reconcileDelete).toHaveBeenCalledTimes(2)
+ expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools', {
+ deleteAllowed: expect.any(Function),
+ })
+
+ watcher.stop()
+ })
+
it('retires queued McpServer work immediately when its watch ends', async () => {
const blockerStarted = deferred()
const releaseBlocker = deferred()
@@ -2917,7 +3600,8 @@ describe('McpServerWatcher external egress retries', () => {
uid: 'redis-tools-new-uid',
generation: 1,
spec: expect.objectContaining({ image: 'redis-tools:recreated' }),
- })
+ }),
+ { isCurrent: expect.any(Function) }
)
watcher.stop()
@@ -3034,7 +3718,8 @@ describe('McpServerWatcher external egress retries', () => {
expect.objectContaining({
generation: 2,
spec: expect.objectContaining({ image: 'redis-tools:new' }),
- })
+ }),
+ { isCurrent: expect.any(Function) }
)
watcher.stop()
@@ -3061,6 +3746,7 @@ describe('McpServerWatcher external egress retries', () => {
it('periodic resync reuses external egress reconciliation for cached servers with bindings', async () => {
const watcher = new McpServerWatcher()
+ markMcpServerInventoryAuthoritative(watcher)
const netPol = (watcher as any).netPolReconciler
netPol.reconcileExternalEgress.mockResolvedValue(undefined)
vi.spyOn(Math, 'random').mockReturnValue(0)
@@ -3115,6 +3801,7 @@ describe('McpServerWatcher external egress retries', () => {
namespace: 'mcp-server',
spec: serverObject.spec,
}
+ ;(watcher as any).servers.set(server.name, server)
netPol.reconcileExternalEgress.mockImplementationOnce(async () => {
mutationStarted.resolve(undefined)
await releaseMutation.promise
@@ -3149,6 +3836,7 @@ describe('McpServerWatcher external egress retries', () => {
namespace: 'mcp-server',
spec: serverObject.spec,
}
+ ;(watcher as any).servers.set(server.name, server)
netPol.reconcileExternalEgress.mockImplementationOnce(async () => {
mutationStarted.resolve(undefined)
await releaseMutation.promise
@@ -3234,6 +3922,88 @@ describe('McpServerWatcher wires CC counter into HostReconciler', () => {
})
})
+describe('McpServerWatcher Host mutation dependency wiring', () => {
+ it('tracks only the selected Context, referenced SFS state, and Host-scoped channels', () => {
+ const watcher = new McpServerWatcher()
+ const host = {
+ name: 'alpha-host',
+ namespace: 'mcp-host',
+ spec: { contextRef: 'alpha-context' },
+ } as HostCRD
+ const context = {
+ name: 'alpha-context',
+ namespace: 'mcp-server',
+ spec: {
+ contextId: 'alpha-context',
+ sharedFileSystems: [{ name: 'documents', mountPath: '/contexts/documents' }],
+ },
+ }
+ const documentsV1 = {
+ name: 'documents',
+ namespace: 'mcp-host',
+ spec: { storageClassName: 'fast-v1' },
+ }
+ const alphaChannelV1 = {
+ name: 'telegram-alpha',
+ namespace: 'channels',
+ spec: { hostRef: 'alpha-host' },
+ }
+ ;(watcher as any).contexts.set(context.name, context)
+ ;(watcher as any).sharedFileSystems.set(documentsV1.name, documentsV1)
+ ;(watcher as any).communicationChannels.set(alphaChannelV1.name, alphaChannelV1)
+ ;(watcher as any).ccCacheSynced = true
+ ;(watcher as any).ccWatchGeneration = 7
+ const sfsReconciler = (watcher as any).sharedFileSystemReconciler
+ sfsReconciler.isMountable.mockReturnValue(true)
+ const hostReconciler = watcher.getHostReconciler() as any
+ const resolveDependencies = hostReconciler._hostMutationDependenciesFn
+
+ const original = resolveDependencies(host)
+ expect(original).toEqual([context, true, 7, documentsV1, true, alphaChannelV1])
+ ;(watcher as any).sharedFileSystems.set('unrelated', {
+ name: 'unrelated',
+ namespace: 'mcp-host',
+ spec: {},
+ })
+ ;(watcher as any).communicationChannels.set('telegram-beta', {
+ name: 'telegram-beta',
+ namespace: 'channels',
+ spec: { hostRef: 'beta-host' },
+ })
+ const afterUnrelatedChanges = resolveDependencies(host)
+ expect(
+ original.every((value: unknown, index: number) =>
+ Object.is(value, afterUnrelatedChanges[index])
+ )
+ ).toBe(true)
+
+ const documentsV2 = {
+ ...documentsV1,
+ spec: { storageClassName: 'fast-v2' },
+ }
+ ;(watcher as any).sharedFileSystems.set(documentsV2.name, documentsV2)
+ const afterSfsRevision = resolveDependencies(host)
+ expect(afterSfsRevision[3]).toBe(documentsV2)
+ expect(afterSfsRevision[3]).not.toBe(original[3])
+
+ sfsReconciler.isMountable.mockReturnValue(false)
+ const afterMountabilityChange = resolveDependencies(host)
+ expect(afterMountabilityChange[4]).toBe(false)
+
+ const alphaChannelV2 = {
+ ...alphaChannelV1,
+ spec: {
+ ...alphaChannelV1.spec,
+ credentialsSecretRef: { name: 'telegram-alpha-v2' },
+ },
+ }
+ ;(watcher as any).communicationChannels.set(alphaChannelV2.name, alphaChannelV2)
+ const afterChannelRevision = resolveDependencies(host)
+ expect(afterChannelRevision.at(-1)).toBe(alphaChannelV2)
+ expect(afterChannelRevision.at(-1)).not.toBe(original.at(-1))
+ })
+})
+
describe('McpServerWatcher.reconcileHostsReferencingCC', () => {
it('re-reconciles the Host whose name matches the CC hostRef', async () => {
const watcher = new McpServerWatcher()
@@ -3464,7 +4234,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const cache = (watcher as any).communicationChannels as Map<string, any>
cache.set('partial-channel', {
name: 'partial-channel',
@@ -3504,7 +4274,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
if (plural === 'hosts') return { items: [host] }
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const cache = (watcher as any).communicationChannels as Map<string, any>
cache.set('watch-observed-channel', {
name: 'watch-observed-channel',
@@ -3545,7 +4315,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
mocks.hostReconcileHosts
.mockImplementationOnce(() => firstFleetPass.promise)
.mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const lifecycleGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
const failClosedPass = (watcher as any).requestHostFleetReconcile(
@@ -3621,7 +4391,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
})
const fleetFailure = new Error('fleet did not converge')
mocks.hostReconcileHosts.mockRejectedValueOnce(fleetFailure).mockResolvedValueOnce(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const lifecycleGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
@@ -3663,7 +4433,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
if (hostListAttempts === 1) throw inventoryFailure
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const lifecycleGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
@@ -3694,7 +4464,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
return { items: [] }
})
mocks.hostFullReconcile.mockRejectedValueOnce(new HostFleetReconcileError([], [cleanupFailure]))
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const lifecycleGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
@@ -3726,7 +4496,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
mocks.hostFullReconcile
.mockRejectedValueOnce(new HostFleetReconcileError([hostFailure], [cleanupFailure]))
.mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
;(watcher as any).ccCacheSynced = true
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const lifecycleGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
@@ -3767,7 +4537,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
mocks.hostReconcileHosts
.mockRejectedValueOnce(new Error('lifecycle pass failed'))
.mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const lifecycleGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
;(watcher as any).ccCacheSynced = true
@@ -3812,7 +4582,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
return { items: [] }
})
mocks.hostReconcileHosts.mockRejectedValue(new Error('persistent fleet failure'))
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const lifecycleGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
@@ -3858,7 +4628,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
mocks.hostReconcileHosts
.mockRejectedValueOnce(new Error('old generation failed'))
.mockResolvedValueOnce(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
@@ -3892,7 +4662,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
}
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const cache = (watcher as any).communicationChannels as Map<string, any>
cache.set('previous-channel', {
name: 'previous-channel',
@@ -3933,7 +4703,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
return { abort: vi.fn() }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const scheduleSpy = vi
.spyOn(watcher as any, 'scheduleCommunicationChannelCacheRecovery')
.mockImplementation(() => {})
@@ -3991,7 +4761,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
.mockImplementationOnce(() => firstHostConvergence.promise)
.mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const firstRecovery = (watcher as any).recoverCommunicationChannelCache() as Promise<boolean>
try {
@@ -4049,7 +4819,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
}
)
.mockResolvedValue({ abort: vi.fn() })
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
try {
await expect((watcher as any).recoverCommunicationChannelCache()).resolves.toBe(false)
@@ -4082,7 +4852,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
return { items: [] }
})
mocks.watch.mockImplementationOnce(() => pendingWatch.promise)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const recovery = (watcher as any).recoverCommunicationChannelCache() as Promise<boolean>
try {
@@ -4127,7 +4897,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
return { abort: vi.fn() }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const scheduleSpy = vi
.spyOn(watcher as any, 'scheduleCommunicationChannelCacheRecovery')
.mockImplementation(() => {})
@@ -4189,7 +4959,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
maxActivePasses = Math.max(maxActivePasses, activePasses)
activePasses -= 1
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
stubAuthoritativeInventoryWatch(watcher, 'McpServer')
stubAuthoritativeInventoryWatch(watcher, 'Context')
vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)
@@ -4242,7 +5012,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
return { abort }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
;(watcher as any).ccCacheSynced = true
await (watcher as any).startCommunicationChannelWatch('504')
@@ -4276,7 +5046,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
return requests[callbacks.length - 1]
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const scheduleSpy = vi
.spyOn(watcher as any, 'scheduleCommunicationChannelCacheRecovery')
.mockImplementation(() => {})
@@ -4327,7 +5097,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
const abort = vi.fn()
const watchRequest = { abort }
mocks.watch.mockReset().mockResolvedValue(watchRequest)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
await (watcher as any).startHostWatch('stream-rv')
await vi.advanceTimersByTimeAsync(30_001)
@@ -4362,7 +5132,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
.mockReset()
.mockImplementationOnce(() => activePass)
.mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
;(watcher as any).ccCacheSynced = true
;(watcher as any).hostFleetScheduler.markLifecycleApplied(
(watcher as any).ccLifecycleGeneration
@@ -4411,7 +5181,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
return { items: [] }
})
mocks.watch.mockReset().mockResolvedValue({ abort: vi.fn() })
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
;(watcher as any).hostCacheSynced = true
const first = (watcher as any).requestHostFleetReconcile(
@@ -4431,7 +5201,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
it('does not invent another fleet transition during a failed periodic cache recovery', async () => {
vi.clearAllMocks()
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
;(watcher as any).ccCacheSynced = false
const recover = vi
.spyOn(watcher as any, 'recoverCommunicationChannelCache')
@@ -4449,7 +5219,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
it('coalesces the newest Host input revision into the serialized trailing pass', async () => {
vi.clearAllMocks()
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const activePass = deferred()
const requests: Array<{ inputRevision: number }> = []
vi.spyOn(watcher as any, 'performHostFleetReconcile').mockImplementation(
@@ -4517,7 +5287,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
maxActivePasses = Math.max(maxActivePasses, activePasses)
activePasses -= 1
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const firstGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
const first = (watcher as any).requestHostFleetReconcile(
'first',
@@ -4570,7 +5340,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
it('uses fresh lifecycle inventory without replacing newer Host watch-cache entries', async () => {
vi.clearAllMocks()
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const initialHost = {
name: 'stateless-primary',
namespace: 'mcp-host',
@@ -4635,7 +5405,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
.mockReset()
.mockImplementationOnce(() => lifecyclePass)
.mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const generation = (watcher as any).beginCommunicationChannelLifecycleTransition()
const lifecycle = (watcher as any).requestHostFleetReconcile(
'CommunicationChannel interruption',
@@ -4680,7 +5450,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
.mockReset()
.mockImplementationOnce(() => lifecyclePass)
.mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const generation = (watcher as any).beginCommunicationChannelLifecycleTransition()
const lifecycle = (watcher as any).requestHostFleetReconcile(
'CommunicationChannel recovery',
@@ -4725,7 +5495,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
.mockReset()
.mockImplementationOnce(() => lifecyclePass)
.mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const firstGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
const active = (watcher as any).requestHostFleetReconcile(
'CommunicationChannel interruption',
@@ -4772,7 +5542,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
})
mocks.hostFullReconcile.mockReset().mockResolvedValue(undefined)
mocks.hostReconcileHosts.mockReset().mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const firstGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
const full = (watcher as any).requestHostFleetReconcile(
'initial Host reconciliation',
@@ -4824,7 +5594,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
return { items: [] }
})
mocks.hostFullReconcile.mockReset().mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
await (watcher as any).startHostWatch('test-host-rv')
if (!hostWatchCallback) throw new Error('Host watch callback was not installed')
@@ -4909,7 +5679,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
return { items: [] }
})
mocks.hostFullReconcile.mockReset().mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
.mockRejectedValueOnce(new Error('transient event failure'))
@@ -4980,7 +5750,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
await fullReconcile.promise
order.push('full:end')
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const hostReconciler = watcher.getHostReconciler()
const reconcile = vi.spyOn(hostReconciler, 'reconcile').mockImplementation(async host => {
order.push(`watch:${host.name}:${host.generation}`)
@@ -5033,7 +5803,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
}
)
mocks.listNamespacedCustomObject.mockImplementation(async () => ({ items: [] }))
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const hostReconciler = watcher.getHostReconciler()
// The reconcile()/reconcileDelete() spies stand in for the per-Host chain;
// the actual serializeByHost non-overlap guarantee is proven in
@@ -5084,7 +5854,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
return { abort: vi.fn() }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const order: string[] = []
const timeout = new HostK8sRequestTimeoutError('AppsV1Api.readNamespacedDeployment', 30_000)
const reconcile = vi
@@ -5131,7 +5901,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
if (plural === 'hosts') return { items: [] }
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
.mockResolvedValue(undefined)
@@ -5180,7 +5950,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
// 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 watcher = newContextAuthoritativeWatcher()
const activeGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
const activeRequest = (watcher as any).requestHostFleetReconcile(
'startup',
@@ -5226,7 +5996,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
resolveActivePass = resolve
})
mocks.hostReconcileHosts.mockReset().mockImplementationOnce(() => activePass)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const activeGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
const activeRequest = (watcher as any).requestHostFleetReconcile(
'active',
@@ -5265,7 +6035,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
return inventory
})
mocks.hostReconcileHosts.mockReset().mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const staleGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
const staleRequest = (watcher as any).requestHostFleetReconcile(
'stale transition',
@@ -5319,7 +6089,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
if (plural === 'hosts') return hostInventory
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const run = (watcher as any).requestHostFleetReconcile('shutdown race') as Promise<void>
await vi.waitFor(() => {
@@ -5344,7 +6114,7 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
it('releases the periodic single-flight guard after a rejected pass', async () => {
vi.clearAllMocks()
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const failure = new Error('transient resync failure')
const performSpy = vi
.spyOn(watcher as any, 'performHostResync')
@@ -5390,7 +6160,7 @@ describe('McpServerWatcher Host watch generation', () => {
}
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const fleetRequest = vi
.spyOn(watcher as any, 'requestHostFleetReconcile')
.mockResolvedValue(undefined)
@@ -5424,7 +6194,7 @@ describe('McpServerWatcher Host watch generation', () => {
}
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const fleetRequest = vi
.spyOn(watcher as any, 'requestHostFleetReconcile')
.mockResolvedValue(undefined)
@@ -5464,7 +6234,7 @@ describe('McpServerWatcher Host watch generation', () => {
}
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const fleetRequest = vi
.spyOn(watcher as any, 'requestHostFleetReconcile')
.mockResolvedValue(undefined)
@@ -5512,7 +6282,7 @@ describe('McpServerWatcher Host watch generation', () => {
}
return { metadata: { resourceVersion: 'retry-preserved-rv' }, items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const fleetRequest = vi
.spyOn(watcher as any, 'requestHostFleetReconcile')
.mockResolvedValue(undefined)
@@ -5559,7 +6329,7 @@ describe('McpServerWatcher Host watch generation', () => {
if (plural === 'hosts') return { metadata: {}, items: [] }
return { items: [] }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
await (watcher as any).requestHostFleetReconcile('Periodic resync', undefined, 'full')
@@ -5595,7 +6365,7 @@ describe('McpServerWatcher Host watch generation', () => {
if (watchQueries.length === 1) throw new Error('watch connection failed')
return { abort: vi.fn() }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
await (watcher as any).requestHostFleetReconcile('Periodic resync', undefined, 'full')
@@ -5639,7 +6409,7 @@ describe('McpServerWatcher Host watch generation', () => {
if (path.endsWith('/hosts')) return lateRequest.promise
return { abort: vi.fn() }
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const requested = (watcher as any).requestHostFleetReconcile(
'Periodic resync',
@@ -5682,7 +6452,7 @@ describe('McpServerWatcher Host watch generation', () => {
return { abort: vi.fn() }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
await (watcher as any).startHostWatch('initial-rv')
;(watcher as any).hostCacheSynced = true
@@ -5722,7 +6492,7 @@ describe('McpServerWatcher Host watch generation', () => {
return { abort: vi.fn() }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
.mockRejectedValueOnce(new Error('transient event failure'))
@@ -5799,7 +6569,7 @@ describe('McpServerWatcher Host watch generation', () => {
mocks.hostFullReconcile
.mockImplementationOnce(() => firstFullReconcile.promise)
.mockResolvedValue(undefined)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const full = (watcher as any).requestHostFleetReconcile(
'Periodic resync',
undefined,
@@ -5865,7 +6635,7 @@ describe('McpServerWatcher Host watch generation', () => {
],
}
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
await (watcher as any).startHostWatch('test-host-rv')
await (watcher as any).requestHostFleetReconcile('Periodic resync', undefined, 'full')
@@ -5906,7 +6676,7 @@ describe('McpServerWatcher Host watch generation', () => {
],
}
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
.mockResolvedValue(undefined)
@@ -5960,7 +6730,7 @@ describe('McpServerWatcher Host watch generation', () => {
],
}
})
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const reconcileDelete = vi
.spyOn(watcher.getHostReconciler(), 'reconcileDelete')
.mockResolvedValue(undefined)
@@ -5982,7 +6752,7 @@ describe('McpServerWatcher Host watch generation', () => {
it('recovery diff enqueues an immediate per-Host delete for a disappeared Host (#827 item 1)', async () => {
vi.clearAllMocks()
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
markHostInventoryAuthoritative(watcher)
const reconcileDelete = vi
.spyOn(watcher.getHostReconciler(), 'reconcileDelete')
@@ -6014,7 +6784,7 @@ describe('McpServerWatcher Host watch generation', () => {
// short-circuits on snapshotNames.has(name) and never dispatches at all.
it('recovery delete carries a live-cache fence for a Host recreated during admission (#827 F2 parity)', async () => {
vi.clearAllMocks()
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
markHostInventoryAuthoritative(watcher)
const reconcileDelete = vi
.spyOn(watcher.getHostReconciler(), 'reconcileDelete')
@@ -6049,7 +6819,7 @@ describe('McpServerWatcher Host watch generation', () => {
it('recovery diff reconciles (does NOT delete) a same-name Host recreated with a new uid (#827 items 1+2)', async () => {
vi.clearAllMocks()
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
markHostInventoryAuthoritative(watcher)
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
@@ -6086,7 +6856,7 @@ describe('McpServerWatcher Host watch generation', () => {
})
it('suppresses a watch event whose identity (uid) differs from the cached Host (#827 item 2)', () => {
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
;(watcher as any).hosts.set('x', {
name: 'x',
namespace: 'mcp-host',
@@ -6115,7 +6885,7 @@ describe('McpServerWatcher Host watch generation', () => {
it('recovery urgently admits a wake-pending Host that is otherwise unchanged (§10.2 step 7 wake branch)', async () => {
vi.clearAllMocks()
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
markHostInventoryAuthoritative(watcher)
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
@@ -6158,7 +6928,7 @@ describe('McpServerWatcher Host watch generation', () => {
it('recovery does NOT urgently dispatch a fully-unchanged Host with no wake annotation', async () => {
vi.clearAllMocks()
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
.mockResolvedValue(undefined)
@@ -6206,7 +6976,7 @@ describe('McpServerWatcher Host watch generation', () => {
return { abort: vi.fn() }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
.mockRejectedValueOnce(new Error('transient'))
@@ -6249,7 +7019,7 @@ describe('McpServerWatcher Host watch generation', () => {
return { abort: vi.fn() }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const unrelatedHost = {
name: 'unrelated-host',
namespace: 'mcp-host',
@@ -6300,7 +7070,7 @@ describe('McpServerWatcher Host watch generation', () => {
return { abort: vi.fn() }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
.mockRejectedValue(new Error('persistent failure'))
@@ -6336,7 +7106,7 @@ describe('McpServerWatcher Host watch generation', () => {
return { abort: vi.fn() }
}
)
- const watcher = new McpServerWatcher()
+ const watcher = newContextAuthoritativeWatcher()
const reconcile = vi
.spyOn(watcher.getHostReconciler(), 'reconcile')
.mockRejectedValueOnce(new Error('stale event failed'))
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index 815c54b12..796958d30 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -141,6 +141,11 @@ type HostInventoryRecoveryCause = 'cold-start' | 'watch-recovery'
type HostWatchEventType = 'ADDED' | 'MODIFIED' | 'DELETED'
type InitialConvergenceLane = 'McpServer' | 'NetworkPolicy'
+type ActiveInitialConvergenceRun = {
+ trailingRequested: boolean
+ promise: Promise<void>
+}
+
type HostInventoryRecoveryRequest = {
convergenceReason: string
ccLifecycleGeneration?: number
@@ -673,10 +678,10 @@ export class McpServerWatcher implements McpServerProvider {
private readonly externalEgressCoordinator = new ExternalEgressConvergenceCoordinator({
listServers: () => [...this.servers.values()],
getCurrentServer: name => this.servers.get(name),
+ inventoryAuthoritative: () => !this.stopped && this.mcpServerCacheSynced,
sameDesiredRevision: sameMcpServerDesiredRevision,
enqueue: (server, work) => this.enqueueMcpServerReconciliation(server, work),
- mutate: (type, server, options) =>
- this.performExternalEgressMutation(type, server, options.deleteAllowed),
+ mutate: (type, server, options) => this.performExternalEgressMutation(type, server, options),
replay: (type, server, retry) =>
this.reconcileMcpServerWatchEvent(type, server, this.mcpWatchGeneration, retry),
})
@@ -685,6 +690,10 @@ export class McpServerWatcher implements McpServerProvider {
ReturnType<typeof setTimeout>
>()
private readonly initialConvergenceRetryAttempts = new Map<InitialConvergenceLane, number>()
+ private readonly initialConvergenceRuns = new Map<
+ InitialConvergenceLane,
+ ActiveInitialConvergenceRun
+ >()
// McpServer and Context effects serialize by resource identity, so one slow
// fleet member cannot block unrelated live events while same-resource
// updates still retain last-writer ordering. SFS/GFS keep their established
@@ -778,6 +787,24 @@ export class McpServerWatcher implements McpServerProvider {
known: this.hostCacheSynced,
generation: this.hostWatchGeneration,
}))
+ this.hostReconciler.setHostMutationAuthority(() => ({
+ known: this.hostCacheSynced && this.contextCacheSynced,
+ hostGeneration: this.hostWatchGeneration,
+ contextGeneration: this.contextWatchGeneration,
+ }))
+ this.hostReconciler.setResolveHostMutationDependencies(host => {
+ const context = this.contexts.get(host.spec.contextRef)
+ const dependencies: unknown[] = [context, this.ccCacheSynced, this.ccWatchGeneration]
+ for (const ref of context?.spec.sharedFileSystems ?? []) {
+ const sfs = this.sharedFileSystems.get(ref.name)
+ dependencies.push(sfs, sfs ? this.sharedFileSystemReconciler.isMountable(sfs) : false)
+ }
+ const channels = this.findCommunicationChannelsByHostRef(host.name).sort((a, b) =>
+ a.name.localeCompare(b.name)
+ )
+ dependencies.push(...channels)
+ return dependencies
+ })
// 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
@@ -829,6 +856,15 @@ export class McpServerWatcher implements McpServerProvider {
return !this.stopped && this.hostCacheSynced
}
+ /**
+ * Host runtime state is derived from both the Host and Context inventories:
+ * Context owns the SharedFileSystem mount set rendered into each Host pod.
+ * Mutation must therefore stop when either LIST -> WATCH pair is unavailable.
+ */
+ private isHostEffectInventoryAuthoritative(): boolean {
+ return this.isHostInventoryAuthoritative() && this.contextCacheSynced
+ }
+
/**
* Fail closed at every Host-effect admission boundary while recovery owns
* inventory authority. Preserve the reason/generation in the retry intent so
@@ -839,8 +875,8 @@ export class McpServerWatcher implements McpServerProvider {
convergenceReason: string,
ccLifecycleGeneration?: number
): boolean {
- if (this.isHostInventoryAuthoritative()) return true
- if (!this.stopped) {
+ if (this.isHostEffectInventoryAuthoritative()) return true
+ if (!this.stopped && !this.hostCacheSynced) {
this.scheduleHostCacheRecovery({
convergenceReason,
ccLifecycleGeneration,
@@ -925,6 +961,14 @@ export class McpServerWatcher implements McpServerProvider {
return enter(0)
}
+ private hasMcpServerInventoryAuthority(watchGeneration: number): boolean {
+ return this.mcpServerCacheSynced && this.mcpWatchGeneration === watchGeneration
+ }
+
+ private hasContextInventoryAuthority(watchGeneration: number): boolean {
+ return this.contextCacheSynced && this.contextWatchGeneration === watchGeneration
+ }
+
private async mcpServerAbsentForDelete(
name: string,
namespace: string,
@@ -932,8 +976,7 @@ export class McpServerWatcher implements McpServerProvider {
): Promise<boolean> {
if (!customObjectsApi) return false
return confirmAuthoritativeMcpServerAbsence({
- inventoryAuthoritative: () =>
- this.mcpServerCacheSynced && this.mcpWatchGeneration === watchGeneration,
+ inventoryAuthoritative: () => this.hasMcpServerInventoryAuthority(watchGeneration),
resolveCurrent: () => this.servers.get(name),
readCurrent: () =>
customObjectsApi.getNamespacedCustomObject({
@@ -951,7 +994,20 @@ export class McpServerWatcher implements McpServerProvider {
watchGeneration: number
): Promise<boolean> {
try {
- return await this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration)
+ const authorized = await this.mcpServerAbsentForDelete(
+ server.name,
+ server.namespace,
+ watchGeneration
+ )
+ if (!authorized && !this.hasMcpServerInventoryAuthority(watchGeneration)) {
+ console.warn(
+ `[K8s] McpServer inventory authority changed while deleting ${server.name}; ` +
+ 'full cleanup deferred until retry'
+ )
+ this.scheduleExternalEgressRetry('DELETED', server)
+ this.changeCallback?.()
+ }
+ return authorized
} catch (error) {
console.error(
`[K8s] Authoritative absence check failed for deleted McpServer ${server.name}; ` +
@@ -1139,7 +1195,15 @@ export class McpServerWatcher implements McpServerProvider {
void this.runInitialNetworkPolicyConvergence()
void this.runInitialSharedFileSystemConvergence()
if (this.hostCacheSynced) {
- void this.requestHostFleetReconcile('Context cache recovery', undefined, 'full')
+ const pendingCcLifecycleGeneration =
+ this.ccLifecycleGeneration > this.ccAppliedLifecycleGeneration
+ ? this.ccLifecycleGeneration
+ : undefined
+ void this.requestHostFleetReconcile(
+ 'Context cache recovery',
+ pendingCcLifecycleGeneration,
+ 'full'
+ )
}
return true
} catch (error) {
@@ -1685,7 +1749,7 @@ export class McpServerWatcher implements McpServerProvider {
await this.recoverHostInventoryAndWatch()
if (this.stopped) return
}
- if (!this.isHostInventoryAuthoritative()) return
+ if (!this.isHostEffectInventoryAuthoritative()) 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.
@@ -1810,21 +1874,29 @@ export class McpServerWatcher implements McpServerProvider {
private reconcileSharedFileSystemsReferencedByContext(
prevContext: ContextCRD | undefined,
- nextContext: ContextCRD | undefined
+ nextContext: ContextCRD | undefined,
+ isCurrent: () => boolean = () => true
): Promise<void> {
- return this.enqueueSharedFileSystemReconciliation(() =>
- this.reconcileSharedFileSystemsReferencedByContextCore(prevContext, nextContext)
- )
+ return this.enqueueSharedFileSystemReconciliation(async () => {
+ if (!isCurrent()) return
+ await this.reconcileSharedFileSystemsReferencedByContextCore(
+ prevContext,
+ nextContext,
+ isCurrent
+ )
+ })
}
private async reconcileSharedFileSystemsReferencedByContextCore(
prevContext: ContextCRD | undefined,
- nextContext: ContextCRD | undefined
+ nextContext: ContextCRD | undefined,
+ isCurrent: () => boolean
): Promise<void> {
const names = new Set<string>()
for (const r of prevContext?.spec.sharedFileSystems ?? []) names.add(r.name)
for (const r of nextContext?.spec.sharedFileSystems ?? []) names.add(r.name)
for (const name of names) {
+ if (!isCurrent()) return
const sfs = this.sharedFileSystems.get(name)
if (!sfs) continue
try {
@@ -1866,9 +1938,14 @@ export class McpServerWatcher implements McpServerProvider {
* authoritative. A recovery full pass consumes the current Context cache, so
* deferral loses no effect and never acts on an unpaired Host LIST.
*/
- private async reconcileHostsReferencingContext(contextName: string): Promise<void> {
+ private async reconcileHostsReferencingContext(
+ contextName: string,
+ isCurrent: () => boolean = () => true
+ ): Promise<void> {
+ if (!isCurrent()) return
if (!this.admitHostDependentEffects(`Context "${contextName}" Host convergence`)) return
for (const host of this.hosts.values()) {
+ if (!isCurrent()) return
if (host.spec.contextRef !== contextName) continue
await this.hostReconciler.reconcile(host)
}
@@ -2004,12 +2081,15 @@ export class McpServerWatcher implements McpServerProvider {
* event.
*/
async reconcileByEnvSecret(secretName: string, secretNamespace: string): Promise<void> {
+ const inventoryGeneration = this.mcpWatchGeneration
+ if (!this.hasMcpServerInventoryAuthority(inventoryGeneration)) return
const selected = [...this.servers.values()].filter(
server => server.namespace === secretNamespace && server.spec.envSecret?.name === secretName
)
await Promise.all(
selected.map(server =>
this.enqueueMcpServerReconciliation(server, async () => {
+ if (!this.hasMcpServerInventoryAuthority(inventoryGeneration)) return
const current = this.servers.get(server.name)
if (
!current ||
@@ -2022,7 +2102,18 @@ export class McpServerWatcher implements McpServerProvider {
console.log(
`[K8s] Re-reconciling McpServer "${current.name}" after Secret "${secretName}" change`
)
- await this.reconciler.reconcile(current)
+ await this.reconciler.reconcile(current, {
+ isCurrent: () => {
+ if (!this.hasMcpServerInventoryAuthority(inventoryGeneration)) return false
+ const latest = this.servers.get(current.name)
+ return (
+ latest !== undefined &&
+ latest.namespace === secretNamespace &&
+ latest.spec.envSecret?.name === secretName &&
+ sameMcpServerDesiredRevision(current, latest)
+ )
+ },
+ })
} catch (err) {
console.error(`[K8s] Secret-triggered reconcile failed for "${current.name}":`, err)
}
@@ -2296,15 +2387,19 @@ export class McpServerWatcher implements McpServerProvider {
}
private runInitialMcpServerConvergence(): Promise<void> {
- return this.runInitialMcpServerConvergenceCore()
+ return this.runInitialConvergence('McpServer')
}
private async runInitialMcpServerConvergenceCore(): Promise<void> {
if (!this.mcpServerCacheSynced) return
+ const inventoryGeneration = this.mcpWatchGeneration
+ const inventoryAuthoritative = () => this.hasMcpServerInventoryAuthority(inventoryGeneration)
try {
const initialServers = [...this.servers.values()]
- const initialExternalEgressGates =
- this.externalEgressCoordinator.prepareStartupGates(initialServers)
+ const initialExternalEgressGates = this.externalEgressCoordinator.prepareStartupGates(
+ initialServers,
+ inventoryAuthoritative
+ )
if (this.stopped) return
console.log('[K8s] Running initial McpServer background reconciliation...')
await this.reconciler.fullReconcile(initialServers, {
@@ -2315,10 +2410,14 @@ export class McpServerWatcher implements McpServerProvider {
namespace: config.namespace,
}
if (!(await initialExternalEgressGates.waitFor(laneOwner))) return
- if (this.stopped) return
- await this.enqueueMcpServerReconciliation(laneOwner, work)
+ if (!inventoryAuthoritative()) return
+ await this.enqueueMcpServerReconciliation(laneOwner, async () => {
+ if (!inventoryAuthoritative()) return
+ await work()
+ })
},
})
+ if (!inventoryAuthoritative()) return
initialConvergenceLastSuccessTimestampSeconds.set({ lane: 'McpServer' }, Date.now() / 1000)
this.clearInitialConvergenceRetry('McpServer')
} catch (error) {
@@ -2328,30 +2427,75 @@ export class McpServerWatcher implements McpServerProvider {
}
private runInitialNetworkPolicyConvergence(): Promise<void> {
- return this.runInitialNetworkPolicyConvergenceCore()
+ return this.runInitialConvergence('NetworkPolicy')
+ }
+
+ private runInitialConvergence(lane: InitialConvergenceLane): Promise<void> {
+ const active = this.initialConvergenceRuns.get(lane)
+ if (active) {
+ active.trailingRequested = true
+ return active.promise
+ }
+
+ const run: ActiveInitialConvergenceRun = {
+ trailingRequested: false,
+ promise: Promise.resolve(),
+ }
+ this.initialConvergenceRuns.set(lane, run)
+ run.promise = Promise.resolve()
+ .then(async () => {
+ do {
+ run.trailingRequested = false
+ if (lane === 'McpServer') {
+ await this.runInitialMcpServerConvergenceCore()
+ } else {
+ await this.runInitialNetworkPolicyConvergenceCore()
+ }
+ } while (!this.stopped && run.trailingRequested)
+ })
+ .finally(() => {
+ if (this.initialConvergenceRuns.get(lane) === run) {
+ this.initialConvergenceRuns.delete(lane)
+ }
+ })
+ return run.promise
}
private async runInitialNetworkPolicyConvergenceCore(): Promise<void> {
- if (!this.contextCacheSynced) return
+ // A NetworkPolicy full pass mixes Context- and McpServer-derived positive
+ // effects with orphan cleanup. Running it from a partial inventory would
+ // be neither a full convergence nor safe evidence of success. Recovery of
+ // either missing LIST -> WATCH pair schedules a fresh current-cache pass.
+ if (!this.contextCacheSynced || !this.mcpServerCacheSynced) return
try {
const initialContexts = [...this.contexts.values()]
const initialServers = [...this.servers.values()]
const contextInventoryGeneration = this.contextWatchGeneration
const serverInventoryGeneration = this.mcpWatchGeneration
+ const serverInventoryComplete = this.mcpServerCacheSynced
+ const contextInventoryAuthoritative = () =>
+ this.hasContextInventoryAuthority(contextInventoryGeneration)
+ const serverInventoryAuthoritative = () =>
+ this.hasMcpServerInventoryAuthority(serverInventoryGeneration)
console.log('[K8s] Running initial NetworkPolicy background reconciliation...')
await this.netPolReconciler.fullReconcile(initialContexts, initialServers, {
- serverInventoryComplete: this.mcpServerCacheSynced,
+ serverInventoryComplete,
ensureDefaults: false,
- contextInventoryAuthoritative: () =>
- this.contextCacheSynced && this.contextWatchGeneration === contextInventoryGeneration,
- serverInventoryAuthoritative: () =>
- this.mcpServerCacheSynced && this.mcpWatchGeneration === serverInventoryGeneration,
- runContextEffect: (contextId, work) => this.enqueueContextReconciliation(contextId, work),
+ contextInventoryAuthoritative,
+ serverInventoryAuthoritative,
+ runContextEffect: (contextId, work) =>
+ this.enqueueContextReconciliation(contextId, async () => {
+ if (!contextInventoryAuthoritative() || !serverInventoryAuthoritative()) return
+ await work()
+ }),
runServerEffect: (serverName, work) => {
const selected = this.servers.get(serverName)
return this.enqueueMcpServerReconciliation(
selected ?? { name: serverName, namespace: config.namespace },
- work
+ async () => {
+ if (!serverInventoryAuthoritative()) return
+ await work()
+ }
)
},
resolveCurrentContext: name => this.contexts.get(name),
@@ -2359,6 +2503,7 @@ export class McpServerWatcher implements McpServerProvider {
[...this.contexts.values()].find(context => context.spec.contextId === contextId),
resolveCurrentServer: name => this.servers.get(name),
})
+ if (!contextInventoryAuthoritative() || !serverInventoryAuthoritative()) return
initialConvergenceLastSuccessTimestampSeconds.set(
{ lane: 'NetworkPolicy' },
Date.now() / 1000
@@ -2917,6 +3062,10 @@ export class McpServerWatcher implements McpServerProvider {
): Promise<void> {
if (this.stopped || watchGeneration !== this.mcpWatchGeneration) return
if (retry && !retry.isCurrent()) return
+ if (retry && !this.hasMcpServerInventoryAuthority(watchGeneration)) {
+ this.scheduleExternalEgressRetry(type, server)
+ return
+ }
const current = this.servers.get(server.name)
if (type === 'DELETED') {
// A same-name recreation may already be accepted while this callback
@@ -2926,6 +3075,12 @@ export class McpServerWatcher implements McpServerProvider {
if (!current || current.namespace !== server.namespace) return
server = current
}
+ const deleteAllowed = () =>
+ this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration)
+ const contextInventoryGeneration = this.contextWatchGeneration
+ const contextPolicyInventoryIsCurrent = (): boolean =>
+ this.mcpServerWatchEffectIsCurrent(server, watchGeneration) &&
+ this.hasContextInventoryAuthority(contextInventoryGeneration)
// External egress is part of the workload's pre-start contract. Reconcile
// it before HCC creates or updates any managed runtime Deployment so a
@@ -2933,7 +3088,12 @@ export class McpServerWatcher implements McpServerProvider {
let retryCompletion: ExternalEgressRetryHandle | undefined
if (type === 'ADDED' || type === 'MODIFIED') {
try {
- retryCompletion = await this.runExternalEgressOnce(type, server, { retry })
+ retryCompletion = await this.runExternalEgressOnce(type, server, {
+ retry,
+ isCurrent: () =>
+ this.mcpServerWatchEffectIsCurrent(server, watchGeneration) &&
+ (!retry || this.hasMcpServerInventoryAuthority(watchGeneration)),
+ })
} catch (error) {
console.error(
`[K8s] External egress reconciliation failed for ${server.name}; runtime reconciliation blocked:`,
@@ -2944,13 +3104,15 @@ export class McpServerWatcher implements McpServerProvider {
return
}
} else {
- const deleteAllowed = () =>
- this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration)
if (!(await this.authorizeMcpServerDeleteOrRetry(server, watchGeneration))) return
try {
retryCompletion = await this.runExternalEgressOnce(type, server, {
deleteAllowed,
retry,
+ isCurrent: () =>
+ !this.stopped &&
+ watchGeneration === this.mcpWatchGeneration &&
+ (!retry || this.hasMcpServerInventoryAuthority(watchGeneration)),
})
} catch (error) {
console.error(
@@ -2964,6 +3126,10 @@ export class McpServerWatcher implements McpServerProvider {
}
if (type === 'ADDED' || type === 'MODIFIED') {
+ if (retry && !this.hasMcpServerInventoryAuthority(watchGeneration)) {
+ this.scheduleExternalEgressRetry(type, server)
+ return
+ }
if (!this.mcpServerWatchEffectIsCurrent(server, watchGeneration)) return
server = this.servers.get(server.name)!
} else if (!(await this.authorizeMcpServerDeleteOrRetry(server, watchGeneration))) {
@@ -2973,7 +3139,10 @@ export class McpServerWatcher implements McpServerProvider {
// Trigger deployment reconciliation.
try {
if (type === 'ADDED' || type === 'MODIFIED') {
- await this.reconciler.reconcile(server)
+ const currentServer = server
+ await this.reconciler.reconcile(currentServer, {
+ isCurrent: () => this.mcpServerWatchEffectIsCurrent(currentServer, watchGeneration),
+ })
} else if (type === 'DELETED') {
await this.reconciler.reconcileDelete(server.name, server.namespace)
}
@@ -2999,11 +3168,15 @@ export class McpServerWatcher implements McpServerProvider {
const bindings: BindingDef[] = JSON.parse(bindingsJson)
const recipeName = server.labels?.['clerum.io/recipe'] ?? server.name
const mcpWorkloadName = server.labels?.['clerum.io/workload'] ?? server.name
+ const bindingServer = server
await this.bindingReconciler.reconcileBindings(
recipeName,
bindings,
mcpWorkloadName,
- server.name
+ bindingServer.name,
+ {
+ isCurrent: () => this.mcpServerWatchEffectIsCurrent(bindingServer, watchGeneration),
+ }
)
if (!this.mcpServerWatchEffectIsCurrent(server, watchGeneration)) return
server = this.servers.get(server.name)!
@@ -3025,12 +3198,16 @@ export class McpServerWatcher implements McpServerProvider {
) {
return
}
- await this.netPolReconciler.reconcileContext(currentContext)
+ await this.netPolReconciler.reconcileContext(currentContext, {
+ isCurrent: () =>
+ contextPolicyInventoryIsCurrent() &&
+ this.contexts.get(currentContext.name) === currentContext,
+ })
})
}
} else if (type === 'DELETED') {
const recipeName = server.labels?.['clerum.io/recipe'] ?? server.name
- await this.bindingReconciler.cleanupBindings(recipeName)
+ await this.bindingReconciler.cleanupBindings(recipeName, { deleteAllowed })
}
} catch (error) {
console.error(`[K8s] Binding/egress reconciliation failed for ${server.name}:`, error)
@@ -3089,6 +3266,7 @@ export class McpServerWatcher implements McpServerProvider {
options: {
deleteAllowed?: () => Promise<boolean>
retry?: ExternalEgressRetryHandle
+ isCurrent?: () => boolean
} = {}
): Promise<ExternalEgressRetryHandle | undefined> {
return this.externalEgressCoordinator.reconcile(type, server, options)
@@ -3101,9 +3279,17 @@ export class McpServerWatcher implements McpServerProvider {
private async performExternalEgressMutation(
type: ExternalEgressWatchEventType,
server: McpServerCRD,
- deleteAllowed?: () => Promise<boolean>
+ options: {
+ deleteAllowed?: () => Promise<boolean>
+ isCurrent: () => boolean
+ }
): Promise<void> {
if (type === 'DELETED') {
+ const deleteAllowed = async (): Promise<boolean> => {
+ if (!options.isCurrent()) return false
+ if (options.deleteAllowed && !(await options.deleteAllowed())) return false
+ return options.isCurrent()
+ }
await this.netPolReconciler.cleanupExternalEgress(
server.name,
server.namespace,
@@ -3112,7 +3298,9 @@ export class McpServerWatcher implements McpServerProvider {
)
return
}
- await this.netPolReconciler.reconcileExternalEgress(server)
+ await this.netPolReconciler.reconcileExternalEgress(server, {
+ isCurrent: options.isCurrent,
+ })
}
/**
@@ -3157,7 +3345,13 @@ export class McpServerWatcher implements McpServerProvider {
// change so SharedFileSystem.status.mountedByContexts stays in sync
// without waiting for an SFS-level event.
const nextForSfs = type === 'DELETED' ? undefined : context
- void this.reconcileSharedFileSystemsReferencedByContext(previous, nextForSfs)
+ const contextInventoryAuthoritative = () => this.hasContextInventoryAuthority(watchGeneration)
+ const serverInventoryGeneration = this.mcpWatchGeneration
+ void this.reconcileSharedFileSystemsReferencedByContext(
+ previous,
+ nextForSfs,
+ contextInventoryAuthoritative
+ )
const previousContextId = previous?.spec.contextId
const effectContextIds =
@@ -3187,7 +3381,13 @@ export class McpServerWatcher implements McpServerProvider {
return
}
if (type === 'ADDED' || type === 'MODIFIED') {
- await this.netPolReconciler.reconcileContext(current!)
+ const selectedContext = current!
+ await this.netPolReconciler.reconcileContext(selectedContext, {
+ isCurrent: () =>
+ contextInventoryAuthoritative() &&
+ this.hasMcpServerInventoryAuthority(serverInventoryGeneration) &&
+ this.contexts.get(selectedContext.name) === selectedContext,
+ })
} else if (type === 'DELETED') {
const deleteAllowed = () =>
this.contextAbsentForDelete(context.name, context.namespace, watchGeneration)
@@ -3210,7 +3410,7 @@ export class McpServerWatcher implements McpServerProvider {
// Re-reconcile any Host that points at this Context so that changes to
// spec.sharedFileSystems[] propagate into the mcp-host pod template.
try {
- await this.reconcileHostsReferencingContext(context.name)
+ await this.reconcileHostsReferencingContext(context.name, contextInventoryAuthoritative)
} catch (error) {
console.error(
`[K8s] Host re-reconcile after Context "${context.name}" change failed:`,
diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index 9e8afce2f..71a1904ea 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -7,6 +7,17 @@ import { confirmAuthoritativeMcpServerAbsence } from './mcpServerSafety'
import { NetworkPolicyReconciler, PUBLIC_EGRESS_EXCEPT_CIDRS } from './networkPolicyReconciler'
import { ContextCRD, McpServerCRD } from './types'
+function deferred<T = void>(): {
+ promise: Promise<T>
+ resolve: (value: T | PromiseLike<T>) => void
+} {
+ let resolve!: (value: T | PromiseLike<T>) => void
+ const promise = new Promise<T>(res => {
+ resolve = res
+ })
+ return { promise, resolve }
+}
+
vi.mock('./mcpServerSafety', async () => {
const actual = await vi.importActual<typeof import('./mcpServerSafety')>('./mcpServerSafety')
return {
@@ -420,6 +431,134 @@ describe('NetworkPolicyReconciler', () => {
)
})
+ it('does not mutate policies after its combined inventory authority lease is retired', async () => {
+ const cache = new Map<string, McpServerCRD>()
+ cache.set('mongo', {
+ name: 'mongo',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'dev',
+ image: 'mongo:latest',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ })
+ const inventoryListed = deferred()
+ const releaseInventory = deferred<{ items: k8s.V1NetworkPolicy[] }>()
+ mockApi.listNamespacedNetworkPolicy.mockImplementationOnce(async () => {
+ inventoryListed.resolve(undefined)
+ return releaseInventory.promise
+ })
+ const rec = makeReconciler(mockApi, cache)
+ let contextGeneration = 4
+ let serverGeneration = 8
+ const capturedContextGeneration = contextGeneration
+ const capturedServerGeneration = serverGeneration
+ const context: ContextCRD = {
+ name: 'dev',
+ namespace: 'mcp-server',
+ spec: { contextId: 'dev', mcpServers: ['mongo'] },
+ }
+
+ const reconcile = rec.reconcileContext(context, {
+ isCurrent: () =>
+ contextGeneration === capturedContextGeneration &&
+ serverGeneration === capturedServerGeneration,
+ })
+ await inventoryListed.promise
+
+ contextGeneration = 6
+ serverGeneration = 10
+ releaseInventory.resolve({ items: [] })
+ await reconcile
+
+ expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('does not mutate a Context policy from a mixed McpServer cache revision', async () => {
+ const cache = new Map<string, McpServerCRD>()
+ cache.set('mongo', {
+ name: 'mongo',
+ namespace: 'mcp-server',
+ uid: 'mongo-uid',
+ generation: 1,
+ spec: {
+ contextRef: 'dev',
+ image: 'mongo:old',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ })
+ const inventoryListed = deferred()
+ const releaseInventory = deferred<{ items: k8s.V1NetworkPolicy[] }>()
+ mockApi.listNamespacedNetworkPolicy.mockImplementationOnce(async () => {
+ inventoryListed.resolve(undefined)
+ return releaseInventory.promise
+ })
+ const rec = makeReconciler(mockApi, cache)
+ const context: ContextCRD = {
+ name: 'dev',
+ namespace: 'mcp-server',
+ spec: { contextId: 'dev', mcpServers: ['mongo'] },
+ }
+
+ const reconcile = rec.reconcileContext(context)
+ await inventoryListed.promise
+ cache.set('mongo', {
+ name: 'mongo',
+ namespace: 'mcp-server',
+ uid: 'mongo-uid',
+ generation: 2,
+ spec: {
+ contextRef: 'dev',
+ image: 'mongo:new',
+ transport: { type: 'streamableHttp', port: 4000 },
+ },
+ })
+ releaseInventory.resolve({ items: [] })
+ await reconcile
+
+ expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
+ it('does not adopt an McpServer that appeared after Context selection', async () => {
+ const cache = new Map<string, McpServerCRD>()
+ const inventoryListed = deferred()
+ const releaseInventory = deferred<{ items: k8s.V1NetworkPolicy[] }>()
+ mockApi.listNamespacedNetworkPolicy.mockImplementationOnce(async () => {
+ inventoryListed.resolve(undefined)
+ return releaseInventory.promise
+ })
+ const rec = makeReconciler(mockApi, cache)
+ const context: ContextCRD = {
+ name: 'dev',
+ namespace: 'mcp-server',
+ spec: { contextId: 'dev', mcpServers: ['late-server'] },
+ }
+
+ const reconcile = rec.reconcileContext(context)
+ await inventoryListed.promise
+ cache.set('late-server', {
+ name: 'late-server',
+ namespace: 'mcp-server',
+ uid: 'late-server-uid',
+ generation: 1,
+ spec: {
+ contextRef: 'dev',
+ image: 'late-server:new',
+ transport: { type: 'streamableHttp', port: 3000 },
+ },
+ })
+ releaseInventory.resolve({ items: [] })
+ await reconcile
+
+ expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
it('creates L2 egress counterpart in mcp-host namespace (bidirectional)', async () => {
const cache = new Map<string, McpServerCRD>()
cache.set('mongo', {
@@ -643,6 +782,45 @@ describe('NetworkPolicyReconciler', () => {
)
})
+ it('does not mutate policy or status after its McpServer authority lease is retired', async () => {
+ const dnsStarted = deferred()
+ const releaseDns = deferred<string[]>()
+ vi.mocked(dns.resolve4).mockImplementationOnce(async () => {
+ dnsStarted.resolve(undefined)
+ return releaseDns.promise
+ })
+ let inventoryGeneration = 7
+ const capturedGeneration = inventoryGeneration
+ const server: McpServerCRD = {
+ name: 'authority-race-mcp',
+ namespace: 'mcp-server',
+ uid: 'authority-race-uid',
+ generation: 3,
+ spec: {
+ contextRef: 'dev',
+ image: 'authority-race:test',
+ transport: { type: 'streamableHttp', port: 3000 },
+ egressBindings: [{ dns: 'api.openai.com', port: 443 }],
+ },
+ }
+
+ const reconcile = reconciler.reconcileExternalEgress(server, {
+ isCurrent: () => inventoryGeneration === capturedGeneration,
+ })
+ await dnsStarted.promise
+
+ // Retire and recover to a different generation. The recovered cache is
+ // authoritative again, but never for this stale pass.
+ inventoryGeneration = 9
+ releaseDns.resolve(['1.2.3.4'])
+ await reconcile
+
+ expect(mockApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(mockCustomApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()
+ })
+
it('identity-fences the status patch and preserves unrelated conditions', async () => {
mockCustomApi.getNamespacedCustomObjectStatus.mockResolvedValueOnce({
metadata: {
@@ -1355,6 +1533,89 @@ describe('NetworkPolicyReconciler', () => {
expect(reconcileContext).not.toHaveBeenCalled()
})
+ it('retires a full-pass Context lease when the selected object is replaced', async () => {
+ const selected: ContextCRD = {
+ name: 'full-pass-context',
+ namespace: 'mcp-server',
+ spec: { contextId: 'full-pass-context', description: 'old', mcpServers: [] },
+ }
+ const replacement: ContextCRD = {
+ ...selected,
+ spec: { ...selected.spec, description: 'new' },
+ }
+ let current = selected
+ let selectedLease: (() => boolean) | undefined
+ const mutationStarted = deferred()
+ const releaseMutation = deferred()
+ vi.spyOn(reconciler, 'reconcileContext').mockImplementationOnce(async (_context, options) => {
+ selectedLease = options?.isCurrent
+ mutationStarted.resolve(undefined)
+ await releaseMutation.promise
+ })
+
+ const fullPass = reconciler.fullReconcile([selected], [], {
+ ensureDefaults: false,
+ contextInventoryAuthoritative: () => true,
+ serverInventoryAuthoritative: () => true,
+ resolveCurrentContext: () => current,
+ })
+ await mutationStarted.promise
+ expect(selectedLease?.()).toBe(true)
+
+ current = replacement
+ expect(selectedLease?.()).toBe(false)
+ releaseMutation.resolve(undefined)
+ await fullPass
+ })
+
+ it('retires a full-pass external-egress lease when desired state is replaced', async () => {
+ const selected: McpServerCRD = {
+ name: 'full-pass-egress',
+ namespace: 'mcp-server',
+ uid: 'full-pass-egress-uid',
+ generation: 1,
+ spec: {
+ contextRef: 'dev',
+ image: 'full-pass-egress:old',
+ transport: { type: 'streamableHttp', port: 3000 },
+ egressBindings: [{ dns: 'old.example', port: 443 }],
+ },
+ }
+ const replacement: McpServerCRD = {
+ ...selected,
+ generation: 2,
+ spec: {
+ ...selected.spec,
+ image: 'full-pass-egress:new',
+ egressBindings: [{ dns: 'new.example', port: 443 }],
+ },
+ }
+ let current = selected
+ let selectedLease: (() => boolean) | undefined
+ const mutationStarted = deferred()
+ const releaseMutation = deferred()
+ vi.spyOn(reconciler, 'reconcileExternalEgress').mockImplementationOnce(
+ async (_server, options) => {
+ selectedLease = options?.isCurrent
+ mutationStarted.resolve(undefined)
+ await releaseMutation.promise
+ }
+ )
+
+ const fullPass = reconciler.fullReconcile([], [selected], {
+ ensureDefaults: false,
+ serverInventoryAuthoritative: () => true,
+ resolveCurrentServer: () => current,
+ })
+ await mutationStarted.promise
+ expect(selectedLease?.()).toBe(true)
+
+ current = replacement
+ expect(selectedLease?.()).toBe(false)
+ releaseMutation.resolve(undefined)
+ await fullPass
+ })
+
it('deletes orphaned Context policies in all three namespaces through the canonical contextId effect key', async () => {
const effectKeys: string[] = []
mockApi.listNamespacedNetworkPolicy.mockImplementation(
@@ -1601,7 +1862,9 @@ describe('NetworkPolicyReconciler', () => {
contextInventoryAuthoritative,
})
- expect(reconcileContext).toHaveBeenCalledWith(desiredContext)
+ expect(reconcileContext).toHaveBeenCalledWith(desiredContext, {
+ isCurrent: expect.any(Function),
+ })
expect(contextInventoryAuthoritative).toHaveBeenCalledTimes(2)
expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({
name: 'ctx-deleted-context-old-server',
@@ -1658,7 +1921,9 @@ describe('NetworkPolicyReconciler', () => {
serverInventoryAuthoritative,
})
- expect(reconcileExternalEgress).toHaveBeenCalledWith(desiredServer)
+ expect(reconcileExternalEgress).toHaveBeenCalledWith(desiredServer, {
+ isCurrent: expect.any(Function),
+ })
expect(serverInventoryAuthoritative).toHaveBeenCalledTimes(2)
expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith({
name: 'ext-egress-deleted-server-api-example-com-443',
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index 8c96b5fdc..adebb6629 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -25,7 +25,10 @@ import {
MCPSERVER_LABEL,
POLICY_TYPE_LABEL,
} from './constants'
-import { confirmAuthoritativeMcpServerAbsence } from './mcpServerSafety'
+import {
+ confirmAuthoritativeMcpServerAbsence,
+ sameMcpServerDesiredRevision,
+} from './mcpServerSafety'
import {
ContextCRD,
EgressBinding,
@@ -42,6 +45,10 @@ type JsonPatchOperation = {
value?: unknown
}
+type NetworkPolicyMutationOptions = {
+ isCurrent?: () => boolean
+}
+
const GROUP = 'clerum.io'
const VERSION = 'v1alpha1'
const PLURAL_MCPSERVERS = 'mcpservers'
@@ -451,9 +458,23 @@ export class NetworkPolicyReconciler {
* Reconcile NetworkPolicies for a Context CRD.
* Creates one policy per allowed MCP server.
*/
- async reconcileContext(context: ContextCRD): Promise<void> {
+ async reconcileContext(
+ context: ContextCRD,
+ options: NetworkPolicyMutationOptions = {}
+ ): Promise<void> {
+ const callerIsCurrent = options.isCurrent ?? (() => true)
+ if (!callerIsCurrent()) return
const contextId = context.spec.contextId
const allowedServers = context.spec.mcpServers || []
+ const selectedServers = new Map(
+ allowedServers.map(serverName => [serverName, this.serverCache.get(serverName)])
+ )
+ const isCurrent = (): boolean =>
+ callerIsCurrent() &&
+ allowedServers.every(
+ serverName => this.serverCache.get(serverName) === selectedServers.get(serverName)
+ )
+ if (!isCurrent()) return
console.log(
`[NetPol] Reconciling context "${contextId}" — allowed servers: [${allowedServers.join(', ')}]`
@@ -466,9 +487,11 @@ export class NetworkPolicyReconciler {
// Get existing policies for this context
const existingPolicies = await this.listPoliciesForContext(contextId)
+ if (!isCurrent()) return
// Create or update policies for each allowed server
for (const serverName of allowedServers) {
+ if (!isCurrent()) return
const server = this.serverCache.get(serverName)
if (!server) {
console.warn(
@@ -549,7 +572,8 @@ export class NetworkPolicyReconciler {
},
}
- await this.applyPolicy(name, ingressPolicy)
+ await this.applyPolicy(name, ingressPolicy, isCurrent)
+ if (!isCurrent()) return
// L2 egress counterpart: allow traffic FROM mcp-host pods TO this MCP server
// Without this, L0 egress deny-all blocks agents from reaching MCP servers.
@@ -602,46 +626,53 @@ export class NetworkPolicyReconciler {
egressName,
config.hostNamespace,
egressPolicy,
- '[NetPol]'
+ '[NetPol]',
+ isCurrent
)
+ if (!isCurrent()) return
// L2 rpc-proxy egress: allow rpc-proxy pods to reach this MCP server
- await this.ensureRpcProxyEgress(contextId, serverName, port)
+ await this.ensureRpcProxyEgress(contextId, serverName, port, isCurrent)
}
// Delete policies for servers no longer in the context
for (const existing of existingPolicies) {
+ if (!isCurrent()) return
const existingName = existing.metadata?.name || ''
if (!desiredNames.has(existingName)) {
console.log(`[NetPol] Deleting orphaned policy "${existingName}"`)
- await this.deletePolicy(existingName)
+ await this.deletePolicy(existingName, isCurrent)
}
}
// Delete orphaned L2 egress counterparts in mcp-host namespace
const existingEgressPolicies = await this.listEgressPoliciesForContext(contextId)
+ if (!isCurrent()) return
const desiredEgressNames = new Set(
allowedServers.map(serverName => `${this.policyName(contextId, serverName)}-egress`)
)
for (const existing of existingEgressPolicies) {
+ if (!isCurrent()) return
const existingName = existing.metadata?.name || ''
if (!desiredEgressNames.has(existingName)) {
console.log(`[NetPol] Deleting orphaned L2 egress policy "${existingName}"`)
- await this.deleteEgressPolicy(existingName)
+ await this.deleteEgressPolicy(existingName, isCurrent)
}
}
// Delete orphaned rpc-proxy egress counterparts. Keeping these after a
// server is removed from a Context would preserve an old in-cluster route.
const existingRpcProxyPolicies = await this.listRpcProxyEgressPoliciesForContext(contextId)
+ if (!isCurrent()) return
const desiredRpcProxyNames = new Set(
allowedServers.map(serverName => `rpc-egress-${contextId}-${serverName}`)
)
for (const existing of existingRpcProxyPolicies) {
+ if (!isCurrent()) return
const existingName = existing.metadata?.name || ''
if (!desiredRpcProxyNames.has(existingName)) {
console.log(`[NetPol] Deleting orphaned rpc-proxy egress policy "${existingName}"`)
- await this.deletePolicyInNamespace(config.rpcProxyNamespace, existingName)
+ await this.deletePolicyInNamespace(config.rpcProxyNamespace, existingName, isCurrent)
}
}
}
@@ -692,6 +723,9 @@ export class NetworkPolicyReconciler {
options.runContextEffect ?? ((_contextId: string, work: () => Promise<void>) => work())
const runServerEffect =
options.runServerEffect ?? ((_serverName: string, work: () => Promise<void>) => work())
+ const contextInventoryIsCurrent = (): boolean =>
+ (options.contextInventoryAuthoritative?.() ?? true) &&
+ (options.serverInventoryAuthoritative?.() ?? true)
// Reconcile each context
for (const context of contexts) {
@@ -701,7 +735,11 @@ export class NetworkPolicyReconciler {
? options.resolveCurrentContext(context.name)
: context
if (!current || current.spec.contextId !== contextId) return
- await this.reconcileContext(current)
+ const contextEffectIsCurrent = (): boolean =>
+ contextInventoryIsCurrent() &&
+ (!options.resolveCurrentContext ||
+ options.resolveCurrentContext(current.name) === current)
+ await this.reconcileContext(current, { isCurrent: contextEffectIsCurrent })
})
}
@@ -713,7 +751,13 @@ export class NetworkPolicyReconciler {
? options.resolveCurrentServer(server.name)
: server
if (!current) return
- await this.reconcileExternalEgress(current)
+ const serverEffectIsCurrent = (): boolean => {
+ if (!(options.serverInventoryAuthoritative?.() ?? true)) return false
+ if (!options.resolveCurrentServer) return true
+ const latest = options.resolveCurrentServer(current.name)
+ return latest !== undefined && sameMcpServerDesiredRevision(current, latest)
+ }
+ await this.reconcileExternalEgress(current, { isCurrent: serverEffectIsCurrent })
})
}
@@ -871,7 +915,12 @@ export class NetworkPolicyReconciler {
* For DNS bindings, resolves hostnames to IPs and creates ipBlock rules.
* For CIDR bindings, creates ipBlock rules directly.
*/
- async reconcileExternalEgress(server: McpServerCRD): Promise<void> {
+ async reconcileExternalEgress(
+ server: McpServerCRD,
+ options: NetworkPolicyMutationOptions = {}
+ ): Promise<void> {
+ const isCurrent = options.isCurrent ?? (() => true)
+ if (!isCurrent()) return
let existingPolicies: k8s.V1NetworkPolicy[]
try {
existingPolicies = await this.listExternalEgressPoliciesForServer(
@@ -879,36 +928,48 @@ export class NetworkPolicyReconciler {
server.namespace
)
} catch (error) {
+ if (!isCurrent()) return
await this.writeExternalEgressStatus(
server,
[],
'False',
'InventoryListFailed',
- `Failed to list existing external egress policies: ${this.errorMessage(error)}`
+ `Failed to list existing external egress policies: ${this.errorMessage(error)}`,
+ isCurrent
)
throw error
}
+ if (!isCurrent()) return
const bindings = server.spec.egressBindings
if (!bindings || bindings.length === 0) {
try {
- await this.cleanupExternalEgress(server.name, server.namespace, existingPolicies)
+ await this.cleanupExternalEgress(
+ server.name,
+ server.namespace,
+ existingPolicies,
+ async () => isCurrent()
+ )
} catch (error) {
+ if (!isCurrent()) return
await this.writeExternalEgressStatus(
server,
[],
'False',
'CleanupFailed',
- `Failed to delete stale external egress policies: ${this.errorMessage(error)}`
+ `Failed to delete stale external egress policies: ${this.errorMessage(error)}`,
+ isCurrent
)
throw error
}
+ if (!isCurrent()) return
await this.writeExternalEgressStatus(
server,
[],
'True',
'NoEgressBindings',
- 'No external egress bindings declared'
+ 'No external egress bindings declared',
+ isCurrent
)
return
}
@@ -923,6 +984,7 @@ export class NetworkPolicyReconciler {
const resolvedAt = new Date().toISOString()
for (const binding of bindings) {
+ if (!isCurrent()) return
const egressClass = binding.egressClass ?? 'exact-host'
if (egressClass !== 'exact-host' && egressClass !== 'public-web') {
failures.push(`egressClass "${String(binding.egressClass)}" is not supported`)
@@ -988,7 +1050,14 @@ export class NetworkPolicyReconciler {
},
}
- await applyNetworkPolicy(this.networkingApi, name, server.namespace, policy, '[NetPol]')
+ await applyNetworkPolicy(
+ this.networkingApi,
+ name,
+ server.namespace,
+ policy,
+ '[NetPol]',
+ isCurrent
+ )
continue
}
@@ -1022,6 +1091,7 @@ export class NetworkPolicyReconciler {
}
try {
const ips = await dns.resolve4(binding.dns)
+ if (!isCurrent()) return
const uniqueIps = [...new Set(ips)].sort()
if (uniqueIps.length === 0) {
failures.push(`hostname "${binding.dns}" resolved to no IPv4 addresses`)
@@ -1079,7 +1149,14 @@ export class NetworkPolicyReconciler {
},
}
- await applyNetworkPolicy(this.networkingApi, name, server.namespace, policy, '[NetPol]')
+ await applyNetworkPolicy(
+ this.networkingApi,
+ name,
+ server.namespace,
+ policy,
+ '[NetPol]',
+ isCurrent
+ )
}
try {
@@ -1089,18 +1166,22 @@ export class NetworkPolicyReconciler {
existingPolicies.filter(policy => {
const name = policy.metadata?.name
return Boolean(name) && !desiredPolicyNames.has(name!)
- })
+ }),
+ async () => isCurrent()
)
} catch (error) {
+ if (!isCurrent()) return
await this.writeExternalEgressStatus(
server,
resolvedEgressIPs,
'False',
'CleanupFailed',
- `Failed to delete stale external egress policies: ${this.errorMessage(error)}`
+ `Failed to delete stale external egress policies: ${this.errorMessage(error)}`,
+ isCurrent
)
throw error
}
+ if (!isCurrent()) return
if (failures.length > 0) {
const message = failures.join('; ')
@@ -1109,7 +1190,8 @@ export class NetworkPolicyReconciler {
resolvedEgressIPs,
'False',
'ExternalEgressRejected',
- message
+ message,
+ isCurrent
)
throw new Error(`External egress reconciliation failed for "${server.name}": ${message}`)
}
@@ -1121,7 +1203,8 @@ export class NetworkPolicyReconciler {
'Reconciled',
bindings.some(binding => binding.egressClass === 'public-web')
? 'External egress policies reconciled; public-web allows public TCP 80/443 with private and special ranges excluded'
- : 'External egress policies reconciled'
+ : 'External egress policies reconciled',
+ isCurrent
)
}
@@ -1230,8 +1313,10 @@ export class NetworkPolicyReconciler {
resolvedEgressIPs: McpServerResolvedEgressIP[],
status: 'True' | 'False' | 'Unknown',
reason: string,
- message: string
+ message: string,
+ isCurrent: () => boolean = () => true
): Promise<void> {
+ if (!isCurrent()) return
let currentStatus: McpServerCrdStatus = {}
let hasStatusObject = false
let currentMetadata:
@@ -1273,6 +1358,7 @@ export class NetworkPolicyReconciler {
)
throw error
}
+ if (!isCurrent()) return
if (
(server.uid !== undefined && currentMetadata?.uid !== server.uid) ||
@@ -1339,6 +1425,7 @@ export class NetworkPolicyReconciler {
const statusPatch = [...identityFence, ...statusMutation]
try {
+ if (!isCurrent()) return
await this.customApi.patchNamespacedCustomObjectStatus({
group: GROUP,
version: VERSION,
@@ -1432,13 +1519,25 @@ export class NetworkPolicyReconciler {
}
/** Create or update a NetworkPolicy. */
- private async applyPolicy(name: string, policy: k8s.V1NetworkPolicy): Promise<void> {
- await applyNetworkPolicy(this.networkingApi, name, config.namespace, policy, '[NetPol]')
+ private async applyPolicy(
+ name: string,
+ policy: k8s.V1NetworkPolicy,
+ isCurrent?: () => boolean
+ ): Promise<void> {
+ await applyNetworkPolicy(
+ this.networkingApi,
+ name,
+ config.namespace,
+ policy,
+ '[NetPol]',
+ isCurrent
+ )
}
/** Delete a NetworkPolicy in mcp-server namespace. */
- private async deletePolicy(name: string): Promise<void> {
+ private async deletePolicy(name: string, isCurrent?: () => boolean): Promise<void> {
try {
+ if (isCurrent && !isCurrent()) return
await this.networkingApi.deleteNamespacedNetworkPolicy({
name,
namespace: config.namespace,
@@ -1469,8 +1568,9 @@ export class NetworkPolicyReconciler {
}
/** Delete a NetworkPolicy in mcp-host namespace (L2 egress counterpart). */
- private async deleteEgressPolicy(name: string): Promise<void> {
+ private async deleteEgressPolicy(name: string, isCurrent?: () => boolean): Promise<void> {
try {
+ if (isCurrent && !isCurrent()) return
await this.networkingApi.deleteNamespacedNetworkPolicy({
name,
namespace: config.hostNamespace,
@@ -1495,7 +1595,8 @@ export class NetworkPolicyReconciler {
private async ensureRpcProxyEgress(
contextId: string,
serverName: string,
- port: number
+ port: number,
+ isCurrent?: () => boolean
): Promise<void> {
const name = `rpc-egress-${contextId}-${serverName}`
const policy: k8s.V1NetworkPolicy = {
@@ -1529,7 +1630,14 @@ export class NetworkPolicyReconciler {
],
},
}
- await applyNetworkPolicy(this.networkingApi, name, config.rpcProxyNamespace, policy, '[NetPol]')
+ await applyNetworkPolicy(
+ this.networkingApi,
+ name,
+ config.rpcProxyNamespace,
+ policy,
+ '[NetPol]',
+ isCurrent
+ )
}
/** Delete all rpc-proxy egress policies for a given context. */
@@ -1587,8 +1695,13 @@ export class NetworkPolicyReconciler {
}
/** Delete a NetworkPolicy in an arbitrary namespace. */
- private async deletePolicyInNamespace(namespace: string, name: string): Promise<void> {
+ private async deletePolicyInNamespace(
+ namespace: string,
+ name: string,
+ isCurrent?: () => boolean
+ ): Promise<void> {
try {
+ if (isCurrent && !isCurrent()) return
await this.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace })
console.log(`[NetPol] Deleted rpc-proxy egress policy "${name}"`)
} catch (error: unknown) {
diff --git a/host-context-controller/src/reconciler.test.ts b/host-context-controller/src/reconciler.test.ts
index dbaaf79e9..4cc083410 100644
--- a/host-context-controller/src/reconciler.test.ts
+++ b/host-context-controller/src/reconciler.test.ts
@@ -14,6 +14,17 @@ import { MANAGED_BY_LABEL, MCPSERVER_LABEL, WRC_MANAGED_BY_VALUE } from './const
import { McpServerReconciler } from './reconciler'
import { McpServerCRD } from './types'
+function deferred<T = void>(): {
+ promise: Promise<T>
+ resolve: (value: T | PromiseLike<T>) => void
+} {
+ let resolve!: (value: T | PromiseLike<T>) => void
+ const promise = new Promise<T>(res => {
+ resolve = res
+ })
+ return { promise, resolve }
+}
+
/**
* Tests for the managed:false guard in the reconciler (Risk 1.7).
*
@@ -1164,7 +1175,9 @@ describe('full reconciliation inventory authority', () => {
await reconciler.fullReconcile([desired])
expect(reconcile).toHaveBeenCalledOnce()
- expect(reconcile).toHaveBeenCalledWith(desired)
+ expect(reconcile).toHaveBeenCalledWith(desired, {
+ isCurrent: expect.any(Function),
+ })
expect(appsApi.deleteNamespacedDeployment).not.toHaveBeenCalled()
expect(coreApi.deleteNamespacedService).not.toHaveBeenCalled()
expect(warn).toHaveBeenCalledWith(expect.stringContaining('inventory authority'))
@@ -1251,6 +1264,104 @@ describe('full reconciliation inventory authority', () => {
expect(reconcile).not.toHaveBeenCalled()
})
+ it('does not mutate runtime or status after startup authority retires during Secret validation', async () => {
+ let authority = { known: true, generation: 51 }
+ const server = {
+ ...makeServer({
+ name: 'secret-authority-race',
+ envSecret: {
+ name: 'runtime-secret',
+ keys: [{ secretKey: 'token', envVar: 'TOKEN' }],
+ },
+ }),
+ uid: 'secret-authority-race-uid',
+ generation: 4,
+ }
+ reconciler.setInventoryAuthority(() => authority)
+ reconciler.setResolveCurrentServer(name => (name === server.name ? server : undefined))
+ const secretReadStarted = deferred()
+ const releaseSecretRead = deferred<{ data: Record<string, string> }>()
+ coreApi.readNamespacedSecret.mockImplementationOnce(async () => {
+ secretReadStarted.resolve(undefined)
+ return releaseSecretRead.promise
+ })
+
+ const convergence = reconciler.fullReconcile([server])
+ await secretReadStarted.promise
+
+ authority = { known: true, generation: 53 }
+ releaseSecretRead.resolve({ data: { token: 'encoded-token' } })
+ await convergence
+
+ expect(coreApi.createNamespacedService).not.toHaveBeenCalled()
+ expect(appsApi.createNamespacedDeployment).not.toHaveBeenCalled()
+ expect(customApi.patchNamespacedCustomObject).not.toHaveBeenCalled()
+ expect(customApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()
+ })
+
+ it('retires a same-watch runtime revision superseded during Secret validation', async () => {
+ let current: McpServerCRD
+ const original: McpServerCRD = {
+ ...makeServer({
+ name: 'same-watch-runtime',
+ image: 'clerum/same-watch-runtime:v1',
+ envSecret: {
+ name: 'runtime-secret',
+ keys: [{ secretKey: 'token', envVar: 'TOKEN' }],
+ },
+ }),
+ uid: 'same-watch-runtime-uid',
+ generation: 1,
+ }
+ const replacement: McpServerCRD = {
+ ...original,
+ generation: 2,
+ spec: {
+ ...original.spec,
+ image: 'clerum/same-watch-runtime:v2',
+ },
+ }
+ current = original
+ reconciler.setInventoryAuthority(() => ({ known: true, generation: 61 }))
+ reconciler.setResolveCurrentServer(name => (name === original.name ? current : undefined))
+
+ const originalSecretReadStarted = deferred()
+ const releaseOriginalSecretRead = deferred<{ data: Record<string, string> }>()
+ coreApi.readNamespacedSecret
+ .mockImplementationOnce(async () => {
+ originalSecretReadStarted.resolve(undefined)
+ return releaseOriginalSecretRead.promise
+ })
+ .mockResolvedValueOnce({ data: { token: 'encoded-token' } })
+
+ const originalReconcile = reconciler.reconcile(original)
+ await originalSecretReadStarted.promise
+ current = replacement
+ const replacementReconcile = reconciler.reconcile(replacement)
+ releaseOriginalSecretRead.resolve({ data: { token: 'encoded-token' } })
+
+ await Promise.all([originalReconcile, replacementReconcile])
+
+ expect(coreApi.createNamespacedService).toHaveBeenCalledTimes(1)
+ expect(appsApi.createNamespacedDeployment).toHaveBeenCalledTimes(1)
+ expect(appsApi.createNamespacedDeployment).toHaveBeenCalledWith({
+ namespace: replacement.namespace,
+ body: expect.objectContaining({
+ spec: expect.objectContaining({
+ template: expect.objectContaining({
+ spec: expect.objectContaining({
+ containers: expect.arrayContaining([
+ expect.objectContaining({
+ image: 'clerum/same-watch-runtime:v2',
+ }),
+ ]),
+ }),
+ }),
+ }),
+ }),
+ })
+ })
+
it('admits independent desired effects while another server effect is blocked', async () => {
const blocked = makeServer({ name: 'blocked-server' })
const independent = makeServer({ name: 'independent-server' })
@@ -1276,13 +1387,17 @@ describe('full reconciliation inventory authority', () => {
await blockedStarted
await Promise.resolve()
- expect(reconcile).toHaveBeenCalledWith(independent)
- expect(reconcile).not.toHaveBeenCalledWith(blocked)
+ expect(reconcile).toHaveBeenCalledWith(independent, {
+ isCurrent: expect.any(Function),
+ })
+ expect(reconcile.mock.calls.some(([server]) => server === blocked)).toBe(false)
releaseBlocked()
await fullReconcile
- expect(reconcile).toHaveBeenCalledWith(blocked)
+ expect(reconcile).toHaveBeenCalledWith(blocked, {
+ isCurrent: expect.any(Function),
+ })
})
it('bounds desired-effect admission without serializing independent siblings', async () => {
@@ -1371,7 +1486,9 @@ describe('full reconciliation inventory authority', () => {
expect(error).toMatchObject({
message: 'Failed to reconcile desired McpServers',
})
- expect(reconcile).toHaveBeenCalledWith(slow)
+ expect(reconcile).toHaveBeenCalledWith(slow, {
+ isCurrent: expect.any(Function),
+ })
})
it('aggregates every desired-effect failure after all bounded workers settle', async () => {
diff --git a/host-context-controller/src/reconciler.ts b/host-context-controller/src/reconciler.ts
index 0d2e59caf..b54c4069e 100644
--- a/host-context-controller/src/reconciler.ts
+++ b/host-context-controller/src/reconciler.ts
@@ -71,6 +71,10 @@ export type McpServerFullReconcileOptions = {
maxConcurrency?: number
}
+export type McpServerMutationOptions = {
+ isCurrent?: () => boolean
+}
+
// G2: Pre-deploy handshake constants
const PRE_DEPLOY_ANNOTATION = 'clerum.io/pre-deploy'
const NETWORK_READY_ANNOTATION = 'clerum.io/network-ready'
@@ -142,6 +146,7 @@ export class McpServerReconciler {
known: false,
generation: 0,
})
+ private inventoryAuthorityConfigured = false
private resolveCurrentServer?: (name: string) => McpServerCRD | undefined
/** Tracks the deployment status of each managed McpServer. */
@@ -180,6 +185,7 @@ export class McpServerReconciler {
*/
setInventoryAuthority(fn: () => McpServerInventoryAuthoritySnapshot): void {
this.inventoryAuthority = fn
+ this.inventoryAuthorityConfigured = true
}
/**
@@ -297,7 +303,12 @@ export class McpServerReconciler {
* Poll deployment readiness until ready or maxAttempts reached.
* Cancels any existing poll for the same server name.
*/
- private pollReadiness(server: McpServerCRD, intervalMs = 5000, maxAttempts = 12): void {
+ private pollReadiness(
+ server: McpServerCRD,
+ intervalMs = 5000,
+ maxAttempts = 12,
+ isCurrent: () => boolean = () => true
+ ): void {
const { name, namespace } = server
// Cancel any existing poll for this server
const existing = this.readinessTimers.get(name)
@@ -309,19 +320,24 @@ export class McpServerReconciler {
let attempts = 0
const poll = async () => {
+ if (!isCurrent()) return
attempts++
const ready = await this.checkDeploymentReady(name, namespace)
- if (!this.statusIdentityMatches(server)) return
+ if (!isCurrent() || !this.statusIdentityMatches(server)) return
if (ready) {
this.setStatus(name, { deployed: true, ready: true, message: 'Running' })
this.readinessTimers.delete(name)
- await this.writeStatusCondition(server, {
- type: 'Ready',
- status: 'True',
- reason: 'ReconcileSuccess',
- message: 'Deployment created',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'Ready',
+ status: 'True',
+ reason: 'ReconcileSuccess',
+ message: 'Deployment created',
+ },
+ isCurrent
+ )
console.log(`[Reconciler] McpServer "${name}" is now ready (after ${attempts} poll(s))`)
return
}
@@ -591,8 +607,12 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
/**
* Ensure ConfigMap exists and is up to date (create or replace).
*/
- private async ensureConfigMap(server: McpServerCRD): Promise<void> {
+ private async ensureConfigMap(
+ server: McpServerCRD,
+ isCurrent: () => boolean = () => true
+ ): Promise<void> {
const cm = this.buildNginxConfigMap(server)
+ if (!isCurrent()) return
try {
await this.coreApi.createNamespacedConfigMap({
namespace: server.namespace,
@@ -605,6 +625,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
name: `${server.name}-nginx-conf`,
namespace: server.namespace,
})
+ if (!isCurrent()) return
const next = preserveObjectAnnotations(
{
...cm,
@@ -615,6 +636,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
},
existing
)
+ if (!isCurrent()) return
await this.coreApi.replaceNamespacedConfigMap({
name: `${server.name}-nginx-conf`,
namespace: server.namespace,
@@ -1108,9 +1130,13 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
/**
* Ensure a Deployment exists and is up to date.
*/
- private async ensureDeployment(server: McpServerCRD): Promise<void> {
+ private async ensureDeployment(
+ server: McpServerCRD,
+ isCurrent: () => boolean = () => true
+ ): Promise<void> {
const deployment = this.buildDeployment(server)
+ if (!isCurrent()) return
try {
await this.appsApi.createNamespacedDeployment({
namespace: server.namespace,
@@ -1145,6 +1171,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
namespace: server.namespace,
body,
}),
+ mutationAllowed: isCurrent,
})
}
}
@@ -1152,9 +1179,13 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
/**
* Ensure a Service exists and is up to date.
*/
- private async ensureService(server: McpServerCRD): Promise<void> {
+ private async ensureService(
+ server: McpServerCRD,
+ isCurrent: () => boolean = () => true
+ ): Promise<void> {
const service = this.buildService(server)
+ if (!isCurrent()) return
try {
await this.coreApi.createNamespacedService({
namespace: server.namespace,
@@ -1178,6 +1209,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
namespace: server.namespace,
body,
}),
+ mutationAllowed: isCurrent,
})
} else {
throw error
@@ -1408,13 +1440,17 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
* G2: Set `clerum.io/network-ready: "true"` annotation on McpServer CRD.
* Completes the pre-deploy handshake so WRC knows NetworkPolicies are applied.
*/
- private async setNetworkReadyAnnotation(server: McpServerCRD): Promise<void> {
+ private async setNetworkReadyAnnotation(
+ server: McpServerCRD,
+ isCurrent: () => boolean = () => true
+ ): Promise<void> {
// Use merge-patch (plain object body) instead of JSON Patch (array body).
// JSON Patch op:"add" on /metadata/annotations/<key> requires /metadata/annotations
// to already exist — it fails with 422 when the CRD was created without annotations.
// Merge-patch creates the map if absent. Errors are re-thrown so the caller (reconcile)
// knows the handshake was not completed — WRC will time out and fail rather than proceed
// silently without NetworkPolicies in place.
+ if (!isCurrent()) return
await this.customApi.patchNamespacedCustomObject(
{
group: 'clerum.io',
@@ -1448,21 +1484,30 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
* best-effort cleanup; a failed CRD patch must not block ConfigMap,
* Service, or Deployment reconciliation for the actual proxy runtime.
*/
- private async canonicalizeRemoteEgressProxyImage(server: McpServerCRD): Promise<void> {
+ private async canonicalizeRemoteEgressProxyImage(
+ server: McpServerCRD,
+ isCurrent: () => boolean = () => true
+ ): Promise<void> {
+ if (!isCurrent()) return
if (!this.isRemote(server)) {
return
}
if (server.spec.image === config.egressProxyImage) {
- await this.writeStatusCondition(server, {
- type: 'ImageCanonicalized',
- status: 'True',
- reason: 'RemoteEgressProxyImageMatches',
- message: 'Remote McpServer spec.image matches the platform egress proxy image',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'ImageCanonicalized',
+ status: 'True',
+ reason: 'RemoteEgressProxyImageMatches',
+ message: 'Remote McpServer spec.image matches the platform egress proxy image',
+ },
+ isCurrent
+ )
return
}
try {
+ if (!isCurrent()) return
await this.customApi.patchNamespacedCustomObject(
{
group: 'clerum.io',
@@ -1480,27 +1525,37 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')],
}
)
+ if (!isCurrent()) return
server.spec.image = config.egressProxyImage
console.log(
`[Reconciler] Canonicalized remote McpServer "${server.name}" image to ${config.egressProxyImage}`
)
- await this.writeStatusCondition(server, {
- type: 'ImageCanonicalized',
- status: 'True',
- reason: 'RemoteEgressProxyImageMatches',
- message: 'Remote McpServer spec.image matches the platform egress proxy image',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'ImageCanonicalized',
+ status: 'True',
+ reason: 'RemoteEgressProxyImageMatches',
+ message: 'Remote McpServer spec.image matches the platform egress proxy image',
+ },
+ isCurrent
+ )
} catch (err) {
+ if (!isCurrent()) return
console.warn(
`[Reconciler] Failed to canonicalize remote McpServer "${server.name}" image to ${config.egressProxyImage}:`,
err
)
- await this.writeStatusCondition(server, {
- type: 'ImageCanonicalized',
- status: 'False',
- reason: 'RemoteEgressProxyImagePatchFailed',
- message: 'Failed to patch remote McpServer spec.image to the platform egress proxy image',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'ImageCanonicalized',
+ status: 'False',
+ reason: 'RemoteEgressProxyImagePatchFailed',
+ message: 'Failed to patch remote McpServer spec.image to the platform egress proxy image',
+ },
+ isCurrent
+ )
}
}
@@ -1511,23 +1566,32 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
*/
private async updateStatusConditions(
server: McpServerCRD,
- deploymentReady: boolean
+ deploymentReady: boolean,
+ isCurrent: () => boolean = () => true
): Promise<void> {
try {
- await this.writeStatusCondition(server, {
- type: 'NetworkReady',
- status: 'True',
- reason: 'NetworkPoliciesApplied',
- message: 'NetworkPolicies and Service created',
- })
- await this.writeStatusCondition(server, {
- type: 'DeploymentReady',
- status: deploymentReady ? 'True' : 'False',
- reason: deploymentReady ? 'ReplicasAvailable' : 'WaitingForReplicas',
- message: deploymentReady
- ? 'Deployment has ready replicas'
- : 'Waiting for pods to become ready',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'NetworkReady',
+ status: 'True',
+ reason: 'NetworkPoliciesApplied',
+ message: 'NetworkPolicies and Service created',
+ },
+ isCurrent
+ )
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'DeploymentReady',
+ status: deploymentReady ? 'True' : 'False',
+ reason: deploymentReady ? 'ReplicasAvailable' : 'WaitingForReplicas',
+ message: deploymentReady
+ ? 'Deployment has ready replicas'
+ : 'Waiting for pods to become ready',
+ },
+ isCurrent
+ )
console.log(
`[Reconciler] Updated status conditions on "${server.name}" (DeploymentReady=${deploymentReady})`
)
@@ -1557,8 +1621,10 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
*/
async writeStatusCondition(
server: McpServerCRD,
- condition: Omit<McpServerCondition, 'lastTransitionTime'>
+ condition: Omit<McpServerCondition, 'lastTransitionTime'>,
+ isCurrent: () => boolean = () => true
): Promise<void> {
+ if (!isCurrent()) return
const now = new Date().toISOString()
// Update the missing-secret gauge for SecretResolved conditions.
@@ -1574,6 +1640,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
}
for (let attempt = 1; attempt <= STATUS_CONDITION_WRITE_MAX_ATTEMPTS; attempt += 1) {
+ if (!isCurrent()) return
// Re-read on every optimistic-conflict retry. Merging against the
// latest resourceVersion preserves conditions written by peer
// controllers between our read and patch.
@@ -1607,6 +1674,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
)
return
}
+ if (!isCurrent()) return
const prior = existingConditions.find(c => c.type === condition.type)
const observedGeneration = condition.observedGeneration ?? server.generation
@@ -1677,6 +1745,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
// The generated client prefers JSON Patch for this endpoint. Send an
// actual patch document so status writes keep working across client
// upgrades instead of relying on merge-patch object bodies.
+ if (!isCurrent()) return
await this.customApi.patchNamespacedCustomObjectStatus({
group: 'clerum.io',
version: 'v1alpha1',
@@ -1719,10 +1788,24 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
* A prior failure does not block the next call; the chain absorbs it so
* the next reconcile still runs.
*/
- async reconcile(server: McpServerCRD): Promise<void> {
+ async reconcile(server: McpServerCRD, options: McpServerMutationOptions = {}): Promise<void> {
+ const capturedAuthority = this.inventoryAuthority()
+ const callerIsCurrent = options.isCurrent ?? (() => true)
+ const isCurrent = () => {
+ if (!callerIsCurrent()) return false
+ if (!this.inventoryAuthorityConfigured) return true
+ if (!this.authorityMatches(capturedAuthority)) return false
+ const current = this.resolveCurrentServer?.(server.name)
+ return current !== undefined && sameMcpServerDesiredRevision(server, current)
+ }
const key = server.name
const prev = this.inFlight.get(key) ?? Promise.resolve()
- const next = prev.catch(() => undefined).then(() => this.performReconcile(server))
+ const next = prev
+ .catch(() => undefined)
+ .then(async () => {
+ if (!isCurrent()) return
+ await this.performReconcile(server, isCurrent)
+ })
this.inFlight.set(key, next)
try {
await next
@@ -1733,10 +1816,12 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
}
}
- private async performReconcile(server: McpServerCRD): Promise<void> {
+ private async performReconcile(server: McpServerCRD, isCurrent: () => boolean): Promise<void> {
+ if (!isCurrent()) return
this.beginStatusTracking(server)
// G7: Enforce managed field immutability — once set, cannot change
+ if (!isCurrent()) return
const currentManaged = server.spec.managed ?? true
const previousManaged = this.managedSnapshot.get(server.name)
if (previousManaged !== undefined && previousManaged !== currentManaged) {
@@ -1744,6 +1829,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
`[Reconciler] McpServer "${server.name}": managed field changed from ${previousManaged} to ${currentManaged}. ` +
`This is not allowed — delete and recreate the McpServer to change ownership.`
)
+ if (!isCurrent()) return
this.setStatus(server.name, {
deployed: false,
ready: false,
@@ -1751,6 +1837,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
})
return
}
+ if (!isCurrent()) return
this.managedSnapshot.set(server.name, currentManaged)
// If disabled, respect ownership before any cleanup. managed:false means
@@ -1760,57 +1847,72 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
console.log(
`[Reconciler] McpServer "${server.name}" is disabled — removing HCC-owned resources`
)
- await this.deleteRuntimeResources(server.name, server.namespace)
+ await this.deleteRuntimeResources(server.name, server.namespace, async () => isCurrent())
} else {
console.log(
`[Reconciler] McpServer "${server.name}" is disabled but WRC-owned; skipping runtime cleanup`
)
}
+ if (!isCurrent()) return
this.setStatus(server.name, { deployed: false, ready: false, message: 'Disabled' })
- await this.writeStatusCondition(server, {
- type: 'Ready',
- status: 'False',
- reason: 'Disabled',
- message: 'McpServer is disabled',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'Ready',
+ status: 'False',
+ reason: 'Disabled',
+ message: 'McpServer is disabled',
+ },
+ isCurrent
+ )
return
}
if (!currentManaged) {
- await this.reconcileWrcOwnedServer(server)
+ await this.reconcileWrcOwnedServer(server, isCurrent)
return
}
// Validate secret before creating/updating
const secretResult = await this.validateSecret(server)
+ if (!isCurrent()) return
if (!secretResult.ok) {
console.error(
`[Reconciler] Skipping deployment of "${server.name}" — secret validation failed`
)
if (this.shouldFailClosedForSecretFailure(secretResult)) {
- await this.deleteRuntimeResources(server.name, server.namespace)
+ await this.deleteRuntimeResources(server.name, server.namespace, async () => isCurrent())
} else {
console.warn(
`[Reconciler] Preserving existing runtime for "${server.name}" after transient Secret read failure`
)
}
+ if (!isCurrent()) return
this.setStatus(server.name, {
deployed: false,
ready: false,
message: secretResult.message,
})
- await this.writeStatusCondition(server, {
- type: 'SecretResolved',
- status: 'False',
- reason: secretResult.reason,
- message: secretResult.message,
- })
- await this.writeStatusCondition(server, {
- type: 'Ready',
- status: 'False',
- reason: 'SecretValidationFailed',
- message: secretResult.message,
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'SecretResolved',
+ status: 'False',
+ reason: secretResult.reason,
+ message: secretResult.message,
+ },
+ isCurrent
+ )
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'Ready',
+ status: 'False',
+ reason: 'SecretValidationFailed',
+ message: secretResult.message,
+ },
+ isCurrent
+ )
return
}
@@ -1818,8 +1920,9 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
try {
// Remote egress proxy: create nginx ConfigMap before Deployment
if (this.isRemote(server)) {
- await this.canonicalizeRemoteEgressProxyImage(server)
- await this.ensureConfigMap(server)
+ await this.canonicalizeRemoteEgressProxyImage(server, isCurrent)
+ if (!isCurrent()) return
+ await this.ensureConfigMap(server, isCurrent)
} else {
// Phase 2.3: plugin image-host allowlist. Audit mode (default) logs a
// would-be denial and still builds; enforce mode blocks the workload.
@@ -1831,12 +1934,17 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
const message = `Image "${server.spec.image}" is not permitted by the plugin image allowlist (${decision.reason})`
if (config.enforcePluginImageAllowlist) {
console.warn(`[Reconciler] ${message} — blocking "${server.name}" (enforce mode)`)
- await this.writeStatusCondition(server, {
- type: 'Ready',
- status: 'False',
- reason: 'ImageNotAllowed',
- message,
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'Ready',
+ status: 'False',
+ reason: 'ImageNotAllowed',
+ message,
+ },
+ isCurrent
+ )
+ if (!isCurrent()) return
this.setStatus(server.name, { deployed: false, ready: false, message })
return
}
@@ -1845,9 +1953,12 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
)
}
}
- await this.ensureService(server)
- await this.ensureDeployment(server)
+ if (!isCurrent()) return
+ await this.ensureService(server, isCurrent)
+ if (!isCurrent()) return
+ await this.ensureDeployment(server, isCurrent)
} catch (err) {
+ if (!isCurrent()) return
this.setStatus(server.name, {
deployed: false,
ready: false,
@@ -1864,8 +1975,9 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
server.annotations?.[NETWORK_READY_ANNOTATION] !== 'true'
) {
try {
- await this.setNetworkReadyAnnotation(server)
+ await this.setNetworkReadyAnnotation(server, isCurrent)
} catch (err) {
+ if (!isCurrent()) return
this.setStatus(server.name, {
deployed: false,
ready: false,
@@ -1877,6 +1989,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
// Check readiness after reconciliation
const ready = await this.checkDeploymentReady(server.name, server.namespace)
+ if (!isCurrent()) return
this.setStatus(server.name, {
deployed: true,
ready,
@@ -1884,32 +1997,40 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
})
// G11: Update status conditions on McpServer CRD
- await this.updateStatusConditions(server, ready)
+ await this.updateStatusConditions(server, ready, isCurrent)
// PR-B B1: record SecretResolved=True + Ready=True after a successful
// reconcile. This is additive to updateStatusConditions (NetworkReady /
// DeploymentReady); the merge logic in writeStatusCondition preserves
// the existing conditions by type.
if (server.spec.envSecret) {
- await this.writeStatusCondition(server, {
- type: 'SecretResolved',
- status: 'True',
- reason: 'SecretFound',
- message: 'Secret resolved and validated',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'SecretResolved',
+ status: 'True',
+ reason: 'SecretFound',
+ message: 'Secret resolved and validated',
+ },
+ isCurrent
+ )
}
- await this.writeStatusCondition(server, {
- type: 'Ready',
- status: ready ? 'True' : 'Unknown',
- reason: ready ? 'ReconcileSuccess' : 'WaitingForReplicas',
- message: ready
- ? 'Deployment created'
- : 'Deployment created, waiting for pods to become ready',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'Ready',
+ status: ready ? 'True' : 'Unknown',
+ reason: ready ? 'ReconcileSuccess' : 'WaitingForReplicas',
+ message: ready
+ ? 'Deployment created'
+ : 'Deployment created, waiting for pods to become ready',
+ },
+ isCurrent
+ )
// If not ready yet, poll until it becomes ready
- if (!ready) {
- this.pollReadiness(server)
+ if (!ready && isCurrent()) {
+ this.pollReadiness(server, 5000, 12, isCurrent)
}
}
@@ -1923,13 +2044,18 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
)
}
- private async reconcileWrcOwnedServer(server: McpServerCRD): Promise<void> {
+ private async reconcileWrcOwnedServer(
+ server: McpServerCRD,
+ isCurrent: () => boolean
+ ): Promise<void> {
+ if (!isCurrent()) return
console.log(
`[Reconciler] McpServer "${server.name}" is WRC-owned (managed:false); ` +
'skipping HCC runtime creation/deletion and updating discovery status.'
)
const secretResult = await this.validateSecret(server)
+ if (!isCurrent()) return
if (!secretResult.ok) {
this.setStatus(server.name, {
deployed: true,
@@ -1937,41 +2063,58 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
message: secretResult.message,
})
if (server.spec.envSecret) {
- await this.writeStatusCondition(server, {
- type: 'SecretResolved',
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'SecretResolved',
+ status: 'False',
+ reason: secretResult.reason,
+ message: secretResult.message,
+ },
+ isCurrent
+ )
+ }
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'Ready',
status: 'False',
- reason: secretResult.reason,
+ reason: 'SecretValidationFailed',
message: secretResult.message,
- })
- }
- await this.writeStatusCondition(server, {
- type: 'Ready',
- status: 'False',
- reason: 'SecretValidationFailed',
- message: secretResult.message,
- })
+ },
+ isCurrent
+ )
return
}
+ if (!isCurrent()) return
this.setStatus(server.name, {
deployed: true,
ready: true,
message: 'WRC-owned runtime registered',
})
if (server.spec.envSecret) {
- await this.writeStatusCondition(server, {
- type: 'SecretResolved',
- status: 'True',
- reason: 'SecretFound',
- message: 'Secret resolved and validated',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'SecretResolved',
+ status: 'True',
+ reason: 'SecretFound',
+ message: 'Secret resolved and validated',
+ },
+ isCurrent
+ )
}
- await this.writeStatusCondition(server, {
- type: 'Ready',
- status: 'True',
- reason: WRC_OWNED_RUNTIME_READY_REASON,
- message: 'WRC-owned runtime registered for HCC discovery',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'Ready',
+ status: 'True',
+ reason: WRC_OWNED_RUNTIME_READY_REASON,
+ message: 'WRC-owned runtime registered for HCC discovery',
+ },
+ isCurrent
+ )
}
/**
@@ -2055,7 +2198,16 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
// own spec; reconciling the newer runtime here could otherwise race
// ahead of that safety policy.
if (!current || !sameMcpServerDesiredRevision(server, current)) return
- await this.reconcile(current)
+ const isCurrent = () => {
+ if (this.inventoryAuthorityConfigured && !this.authorityMatches(capturedAuthority)) {
+ return false
+ }
+ const latest = this.resolveCurrentServer?.(current.name)
+ return latest
+ ? sameMcpServerDesiredRevision(current, latest)
+ : this.resolveCurrentServer === undefined
+ }
+ await this.reconcile(current, { isCurrent })
})
)
throwCleanupFailures(
diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.ts
index d405c97ae..3fe113c70 100644
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@ -36,6 +36,8 @@ export async function replaceWithConflictRetry<
* when a meaningful change is still required.
*/
isUpToDate?: (body: T, existing: T) => boolean
+ /** Rechecked immediately before every Kubernetes write attempt. */
+ mutationAllowed?: () => boolean
maxAttempts?: number
}): Promise<void> {
const {
@@ -47,6 +49,7 @@ export async function replaceWithConflictRetry<
replace,
mergeExisting,
isUpToDate,
+ mutationAllowed,
maxAttempts = 3,
} = opts
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
@@ -58,6 +61,7 @@ export async function replaceWithConflictRetry<
}
const next = mergeExisting ? mergeExisting(base, existing) : base
if (isUpToDate?.(next, existing)) return
+ if (mutationAllowed && !mutationAllowed()) return
try {
await replace(next)
const suffix = attempt > 1 ? ` (after ${attempt} attempts)` : ''
@@ -171,8 +175,10 @@ export async function applyNetworkPolicy(
name: string,
namespace: string,
policy: k8s.V1NetworkPolicy,
- logPrefix = '[NetPol]'
+ logPrefix = '[NetPol]',
+ mutationAllowed?: () => boolean
): Promise<void> {
+ if (mutationAllowed && !mutationAllowed()) return
try {
await api.createNamespacedNetworkPolicy({ namespace, body: policy })
console.log(`${logPrefix} Created policy "${name}" in ${namespace}`)
@@ -188,5 +194,6 @@ export async function applyNetworkPolicy(
body: policy,
read: () => api.readNamespacedNetworkPolicy({ name, namespace }),
replace: body => api.replaceNamespacedNetworkPolicy({ name, namespace, body }),
+ mutationAllowed,
})
}