Skip to content

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

TypeScript

refactor(hcc): isolate readiness convergence schedulers

Alfredo Lopez7c1f6e4e417c
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 52c68406d..949683f89 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.166",
+ "version": "0.1.167",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.166",
+ "version": "0.1.167",
"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 bb5b441d4..44a681873 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.166",
+ "version": "0.1.167",
"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/externalEgressConvergenceCoordinator.test.ts b/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
new file mode 100644
index 000000000..52f2bbc5b
--- /dev/null
+++ b/host-context-controller/src/externalEgressConvergenceCoordinator.test.ts
@@ -0,0 +1,637 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ ExternalEgressConvergenceCoordinator,
+ type ExternalEgressRetryHandle,
+ type ExternalEgressWatchEventType,
+} from './externalEgressConvergenceCoordinator'
+import type { McpServerCRD } from './types'
+
+function deferred<T = void>() {
+ let resolve!: (value: T | PromiseLike<T>) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+function server(
+ name: string,
+ generation = 1,
+ options: { bindings?: boolean; namespace?: string } = {}
+): McpServerCRD {
+ return {
+ name,
+ namespace: options.namespace ?? 'mcp-server',
+ uid: `${name}-uid`,
+ generation,
+ spec: {
+ contextRef: 'default',
+ image: `clerum/${name}:v${generation}`,
+ transport: { type: 'streamableHttp', port: 3000 },
+ egressBindings:
+ options.bindings === false ? undefined : [{ dns: `${name}.example`, port: 443 }],
+ },
+ }
+}
+
+type CoordinatorOverrides = Partial<
+ ConstructorParameters<typeof ExternalEgressConvergenceCoordinator>[0]
+>
+
+function coordinator(overrides: CoordinatorOverrides = {}) {
+ const servers = new Map<string, McpServerCRD>()
+ const mutate = vi.fn(async () => undefined)
+ const replay = vi.fn(async () => undefined)
+ const instance = new ExternalEgressConvergenceCoordinator({
+ listServers: () => [...servers.values()],
+ getCurrentServer: name => servers.get(name),
+ sameDesiredRevision: (left, right) =>
+ left.uid === right.uid &&
+ left.generation === right.generation &&
+ JSON.stringify(left.spec) === JSON.stringify(right.spec),
+ enqueue: async (_selected, work) => work(),
+ mutate,
+ replay,
+ ...overrides,
+ })
+ return { instance, mutate, replay, servers }
+}
+
+async function flushMicrotasks(): Promise<void> {
+ await Promise.resolve()
+ await Promise.resolve()
+ await Promise.resolve()
+}
+
+describe('ExternalEgressConvergenceCoordinator', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ })
+
+ it.each([
+ ['presence', 'DELETED' as const, undefined],
+ ['revision', 'MODIFIED' as const, server('redis-tools', 2)],
+ ])(
+ 'lets an existing timer consume the latest %s intent and resets its attempt ladder',
+ async (_change, nextType, nextServer) => {
+ vi.useFakeTimers()
+ const initial = server('redis-tools', 1)
+ const state = new Map<string, McpServerCRD>([[initial.name, initial]])
+ const replayed: Array<{ type: ExternalEgressWatchEventType; server: McpServerCRD }> = []
+ let instance!: ExternalEgressConvergenceCoordinator
+ instance = coordinator({
+ getCurrentServer: name => state.get(name),
+ replay: async (type, selected) => {
+ replayed.push({ type, server: selected })
+ instance.scheduleRetry(type, selected)
+ },
+ }).instance
+
+ instance.scheduleRetry('ADDED', initial)
+ if (nextServer) state.set(nextServer.name, nextServer)
+ else state.delete(initial.name)
+ instance.scheduleRetry(nextType, nextServer ?? initial)
+
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(replayed).toEqual([
+ {
+ type: nextType,
+ server: expect.objectContaining({
+ generation: nextServer?.generation ?? initial.generation,
+ }),
+ },
+ ])
+
+ await vi.advanceTimersByTimeAsync(4999)
+ expect(replayed).toHaveLength(1)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(replayed).toHaveLength(2)
+ instance.stop()
+ }
+ )
+
+ it('continues retrying at the capped delay until the replay succeeds', async () => {
+ vi.useFakeTimers()
+ const selected = server('web-search')
+ let instance!: ExternalEgressConvergenceCoordinator
+ let attempts = 0
+ instance = coordinator({
+ getCurrentServer: () => selected,
+ replay: async (type, current, retry) => {
+ attempts += 1
+ if (attempts < 5) {
+ instance.scheduleRetry(type, current)
+ return
+ }
+ retry.complete()
+ },
+ }).instance
+
+ instance.scheduleRetry('ADDED', selected)
+ for (const delay of [5000, 15000, 30000, 30000, 30000]) {
+ await vi.advanceTimersByTimeAsync(delay)
+ }
+
+ expect(attempts).toBe(5)
+ await vi.advanceTimersByTimeAsync(30000)
+ expect(attempts).toBe(5)
+ instance.stop()
+ })
+
+ it('never clears a pending full replay after an egress-only success', async () => {
+ vi.useFakeTimers()
+ const selected = server('web-search')
+ const { instance, replay, servers } = coordinator()
+ servers.set(selected.name, selected)
+
+ instance.scheduleRetry('ADDED', selected)
+ const retry = await instance.reconcile('MODIFIED', selected)
+ expect(retry).toBeDefined()
+
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(replay).toHaveBeenCalledOnce()
+ instance.stop()
+ })
+
+ it('clears a retry only after its complete full-replay handle finishes', async () => {
+ vi.useFakeTimers()
+ const selected = server('web-search')
+ let instance!: ExternalEgressConvergenceCoordinator
+ const replays: ExternalEgressRetryHandle[] = []
+ instance = coordinator({
+ getCurrentServer: () => selected,
+ replay: async (type, current, retry) => {
+ replays.push(retry)
+ const completion = await instance.reconcile(type, current, { retry })
+ expect(completion).toBe(retry)
+ retry.complete()
+ },
+ }).instance
+
+ instance.scheduleRetry('ADDED', selected)
+ await vi.advanceTimersByTimeAsync(5000)
+ await vi.advanceTimersByTimeAsync(30000)
+
+ expect(replays).toHaveLength(1)
+ instance.stop()
+ })
+
+ it('prevents a stale retry handle from clearing a newer intent', async () => {
+ vi.useFakeTimers()
+ const first = server('web-search', 1)
+ const second = server('web-search', 2)
+ const state = new Map<string, McpServerCRD>([[first.name, first]])
+ const handles: ExternalEgressRetryHandle[] = []
+ const replayed: McpServerCRD[] = []
+ const firstReplayStarted = deferred()
+ const releaseFirstReplay = deferred()
+ const { instance } = coordinator({
+ getCurrentServer: name => state.get(name),
+ replay: async (_type, current, retry) => {
+ replayed.push(current)
+ handles.push(retry)
+ if (replayed.length === 1) {
+ firstReplayStarted.resolve()
+ await releaseFirstReplay.promise
+ }
+ },
+ })
+
+ instance.scheduleRetry('ADDED', first)
+ await vi.advanceTimersByTimeAsync(5000)
+ await firstReplayStarted.promise
+ expect(handles).toHaveLength(1)
+
+ state.set(second.name, second)
+ instance.scheduleRetry('MODIFIED', second)
+ handles[0].complete()
+ releaseFirstReplay.resolve()
+ await flushMicrotasks()
+ await vi.advanceTimersByTimeAsync(5000)
+
+ expect(replayed).toEqual([
+ expect.objectContaining({ generation: 1 }),
+ expect.objectContaining({ generation: 2 }),
+ ])
+ instance.stop()
+ })
+
+ it('keeps retry, resync, and startup concurrency lanes independent', async () => {
+ vi.useFakeTimers()
+ vi.spyOn(Math, 'random').mockReturnValue(0)
+ const retryRelease = deferred()
+ const activeRetries = deferred()
+ let retryCount = 0
+ const resyncServer = server('resync-server')
+ const startupServer = server('startup-server')
+ const canonical = new Map<string, McpServerCRD>([
+ [resyncServer.name, resyncServer],
+ [startupServer.name, startupServer],
+ ])
+ const mutations: string[] = []
+ const { instance } = coordinator({
+ listServers: () => [resyncServer],
+ getCurrentServer: name => canonical.get(name),
+ mutate: async (_type, selected) => {
+ mutations.push(selected.name)
+ },
+ replay: async () => {
+ retryCount += 1
+ if (retryCount === 10) activeRetries.resolve()
+ await retryRelease.promise
+ },
+ })
+
+ for (let index = 0; index < 10; index += 1) {
+ const selected = server(`retry-${index}`, 1, { bindings: false })
+ instance.scheduleRetry('ADDED', selected)
+ }
+ await vi.advanceTimersByTimeAsync(5000)
+ await activeRetries.promise
+
+ const resync = instance.runResync()
+ const startup = instance.prepareStartupGates([startupServer])
+ await Promise.all([resync, startup.waitFor(startupServer)])
+
+ expect(mutations).toEqual(expect.arrayContaining(['resync-server', 'startup-server']))
+ retryRelease.resolve()
+ instance.stop()
+ })
+
+ it('queues at most one latest-wins retry job per key behind a saturated limiter', async () => {
+ vi.useFakeTimers()
+ const blockersRelease = deferred()
+ const tenBlockersStarted = deferred()
+ const finalReplayStarted = deferred()
+ const initial = server('churning-server', 1)
+ const second = server('churning-server', 2)
+ const final = server('churning-server', 3)
+ const state = new Map<string, McpServerCRD>([[initial.name, initial]])
+ const targetEnqueues: McpServerCRD[] = []
+ const targetReplays: McpServerCRD[] = []
+ let blockerCount = 0
+ const { instance } = coordinator({
+ getCurrentServer: name => state.get(name),
+ enqueue: async (selected, work) => {
+ if (selected.name === initial.name) targetEnqueues.push(selected)
+ await work()
+ },
+ replay: async (_type, selected, retry) => {
+ if (selected.name.startsWith('limiter-blocker-')) {
+ blockerCount += 1
+ if (blockerCount === 10) tenBlockersStarted.resolve()
+ await blockersRelease.promise
+ return
+ }
+ targetReplays.push(selected)
+ retry.complete()
+ finalReplayStarted.resolve()
+ },
+ })
+
+ for (let index = 0; index < 10; index += 1) {
+ instance.scheduleRetry('DELETED', server(`limiter-blocker-${index}`))
+ }
+ await vi.advanceTimersByTimeAsync(5000)
+ await tenBlockersStarted.promise
+
+ instance.scheduleRetry('ADDED', initial)
+ await vi.advanceTimersByTimeAsync(5000)
+ state.set(second.name, second)
+ instance.scheduleRetry('MODIFIED', second)
+ await vi.advanceTimersByTimeAsync(5000)
+ state.set(final.name, final)
+ instance.scheduleRetry('MODIFIED', final)
+ await vi.advanceTimersByTimeAsync(5000)
+
+ expect(targetEnqueues).toHaveLength(0)
+ blockersRelease.resolve()
+ await finalReplayStarted.promise
+ await flushMicrotasks()
+ await flushMicrotasks()
+
+ expect(targetEnqueues).toHaveLength(1)
+ expect(targetReplays).toEqual([expect.objectContaining({ generation: 3 })])
+ instance.stop()
+ })
+
+ it('re-arms a retry scheduled by an active replay only after that key leaves its slot', async () => {
+ vi.useFakeTimers()
+ const selected = server('slow-retry')
+ const firstReplayStarted = deferred()
+ const releaseFirstReplay = deferred()
+ let instance!: ExternalEgressConvergenceCoordinator
+ let replayCount = 0
+ instance = coordinator({
+ getCurrentServer: () => selected,
+ replay: async (type, current, retry) => {
+ replayCount += 1
+ if (replayCount === 1) {
+ instance.scheduleRetry(type, current)
+ firstReplayStarted.resolve()
+ await releaseFirstReplay.promise
+ return
+ }
+ retry.complete()
+ },
+ }).instance
+
+ instance.scheduleRetry('ADDED', selected)
+ await vi.advanceTimersByTimeAsync(5000)
+ await firstReplayStarted.promise
+
+ await vi.advanceTimersByTimeAsync(15000)
+ expect(replayCount).toBe(1)
+
+ releaseFirstReplay.resolve()
+ await flushMicrotasks()
+ await vi.advanceTimersByTimeAsync(14999)
+ expect(replayCount).toBe(1)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(replayCount).toBe(2)
+ instance.stop()
+ })
+
+ it('cancels a retry waiter on stop before limiter capacity becomes available', async () => {
+ vi.useFakeTimers()
+ const blockersRelease = deferred()
+ const tenBlockersStarted = deferred()
+ const queued = server('queued-before-stop')
+ let blockerCount = 0
+ const enqueuedTargets: string[] = []
+ const { instance } = coordinator({
+ enqueue: async (selected, work) => {
+ if (selected.name === queued.name) enqueuedTargets.push(selected.name)
+ await work()
+ },
+ replay: async (_type, selected) => {
+ if (!selected.name.startsWith('stop-blocker-')) return
+ blockerCount += 1
+ if (blockerCount === 10) tenBlockersStarted.resolve()
+ await blockersRelease.promise
+ },
+ })
+
+ for (let index = 0; index < 10; index += 1) {
+ instance.scheduleRetry('DELETED', server(`stop-blocker-${index}`))
+ }
+ await vi.advanceTimersByTimeAsync(5000)
+ await tenBlockersStarted.promise
+ instance.scheduleRetry('DELETED', queued)
+ await vi.advanceTimersByTimeAsync(5000)
+
+ instance.stop()
+ blockersRelease.resolve()
+ await flushMicrotasks()
+ await flushMicrotasks()
+
+ expect(enqueuedTargets).toEqual([])
+ })
+
+ it('resolves the current canonical server after periodic jitter', async () => {
+ vi.useFakeTimers()
+ vi.spyOn(Math, 'random').mockReturnValue(0.5)
+ const stale = server('web-search', 1)
+ const current = server('web-search', 2)
+ const state = new Map<string, McpServerCRD>([[stale.name, stale]])
+ const reconciled: McpServerCRD[] = []
+ const { instance } = coordinator({
+ listServers: () => [stale],
+ getCurrentServer: name => state.get(name),
+ mutate: async (_type, selected) => {
+ reconciled.push(selected)
+ },
+ })
+
+ const resync = instance.runResync()
+ await flushMicrotasks()
+ state.set(current.name, current)
+ await vi.advanceTimersByTimeAsync(2500)
+ await resync
+
+ expect(reconciled).toEqual([expect.objectContaining({ generation: 2 })])
+ instance.stop()
+ })
+
+ it('returns one global single-flight promise for overlapping resync requests', async () => {
+ vi.spyOn(Math, 'random').mockReturnValue(0)
+ const selected = server('web-search')
+ const release = deferred()
+ const mutationStarted = deferred()
+ const { instance, servers } = coordinator({
+ mutate: async () => {
+ mutationStarted.resolve()
+ await release.promise
+ },
+ })
+ servers.set(selected.name, selected)
+
+ const first = instance.runResync()
+ const overlapping = instance.runResync()
+ expect(overlapping).toBe(first)
+ await mutationStarted.promise
+
+ release.resolve()
+ await first
+ instance.stop()
+ })
+
+ it('skips a resync key whose external-egress mutation is already in flight', async () => {
+ vi.spyOn(Math, 'random').mockReturnValue(0)
+ const selected = server('web-search')
+ const release = deferred()
+ const mutationStarted = deferred()
+ const mutate = vi.fn(async () => {
+ mutationStarted.resolve()
+ await release.promise
+ })
+ const { instance, servers } = coordinator({ mutate })
+ servers.set(selected.name, selected)
+
+ const active = instance.reconcile('MODIFIED', selected)
+ await mutationStarted.promise
+ await instance.runResync()
+
+ expect(mutate).toHaveBeenCalledOnce()
+ release.resolve()
+ await active
+ instance.stop()
+ })
+
+ it('resolves canonical state after entering the keyed resync queue', async () => {
+ vi.spyOn(Math, 'random').mockReturnValue(0)
+ const stale = server('web-search', 1)
+ const current = server('web-search', 2)
+ const state = new Map<string, McpServerCRD>([[stale.name, stale]])
+ const queueEntered = deferred()
+ const releaseQueue = deferred()
+ const reconciled: McpServerCRD[] = []
+ const { instance } = coordinator({
+ listServers: () => [stale],
+ getCurrentServer: name => state.get(name),
+ enqueue: async (_selected, work) => {
+ queueEntered.resolve()
+ await releaseQueue.promise
+ await work()
+ },
+ mutate: async (_type, selected) => {
+ reconciled.push(selected)
+ },
+ })
+
+ const resync = instance.runResync()
+ await queueEntered.promise
+ state.set(current.name, current)
+ releaseQueue.resolve()
+ await resync
+
+ expect(reconciled).toEqual([expect.objectContaining({ generation: 2 })])
+ instance.stop()
+ })
+
+ it('keeps a startup gate false when desired revision changes during egress', async () => {
+ const selected = server('web-search', 1)
+ const current = server('web-search', 2)
+ const state = new Map<string, McpServerCRD>([[selected.name, selected]])
+ const mutationStarted = deferred()
+ const releaseMutation = deferred()
+ const { instance } = coordinator({
+ getCurrentServer: name => state.get(name),
+ mutate: async () => {
+ mutationStarted.resolve()
+ await releaseMutation.promise
+ },
+ })
+
+ const gates = instance.prepareStartupGates([selected])
+ await mutationStarted.promise
+ state.set(current.name, current)
+ releaseMutation.resolve()
+
+ await expect(gates.waitFor(selected)).resolves.toBe(false)
+ 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 first = instance.reconcile('MODIFIED', selected)
+ await vi.waitFor(() => expect(mutate).toHaveBeenCalledOnce())
+ const waiting = instance.reconcile('MODIFIED', selected)
+ instance.stop()
+ firstMutation.resolve()
+ await Promise.all([first, waiting])
+
+ expect(mutate).toHaveBeenCalledOnce()
+ })
+
+ it('rechecks per-key in-flight ownership when multiple waiters resume together', async () => {
+ const selected = server('web-search')
+ const releases = [deferred(), deferred(), deferred()]
+ const starts = [deferred(), deferred(), deferred()]
+ let active = 0
+ let maxActive = 0
+ let call = 0
+ const mutate = vi.fn(async () => {
+ const index = call++
+ active += 1
+ maxActive = Math.max(maxActive, active)
+ starts[index].resolve()
+ await releases[index].promise
+ active -= 1
+ })
+ const { instance } = coordinator({ mutate })
+
+ const first = instance.reconcile('MODIFIED', selected)
+ await starts[0].promise
+ const second = instance.reconcile('MODIFIED', selected)
+ const third = instance.reconcile('MODIFIED', selected)
+
+ try {
+ releases[0].resolve()
+ await starts[1].promise
+ await flushMicrotasks()
+ expect(maxActive).toBe(1)
+ } finally {
+ for (const release of releases) release.resolve()
+ await Promise.all([first, second, third])
+ instance.stop()
+ }
+ })
+
+ it('does not resume periodic work from jitter after stop', async () => {
+ vi.useFakeTimers()
+ vi.spyOn(Math, 'random').mockReturnValue(0.5)
+ const selected = server('web-search')
+ const { instance, mutate, servers } = coordinator()
+ servers.set(selected.name, selected)
+
+ const resync = instance.runResync()
+ await flushMicrotasks()
+ instance.stop()
+ await vi.advanceTimersByTimeAsync(2500)
+ await resync
+
+ expect(mutate).not.toHaveBeenCalled()
+ })
+
+ it('does not start an eleventh startup mutation after stop releases the limiter', async () => {
+ const release = deferred()
+ const tenStarted = deferred()
+ let active = 0
+ const selected = Array.from({ length: 11 }, (_, index) => server(`startup-${index}`))
+ const state = new Map(selected.map(item => [item.name, item]))
+ const mutate = vi.fn(async () => {
+ active += 1
+ if (active === 10) tenStarted.resolve()
+ await release.promise
+ })
+ const { instance } = coordinator({
+ getCurrentServer: name => state.get(name),
+ mutate,
+ })
+
+ const gates = instance.prepareStartupGates(selected)
+ await tenStarted.promise
+ instance.stop()
+ release.resolve()
+ await Promise.all(selected.map(item => gates.waitFor(item)))
+
+ expect(mutate).toHaveBeenCalledTimes(10)
+ })
+
+ it('passes DELETE authority through to the watcher mutation without evaluating it', async () => {
+ const selected = server('web-search')
+ const deleteAllowed = vi.fn(async () => false)
+ const mutate = vi.fn(async () => undefined)
+ const { instance } = coordinator({ mutate })
+
+ await instance.reconcile('DELETED', selected, { deleteAllowed })
+
+ expect(mutate).toHaveBeenCalledWith('DELETED', selected, { deleteAllowed })
+ expect(deleteAllowed).not.toHaveBeenCalled()
+ instance.stop()
+ })
+
+ it('owns periodic resync scheduling and stops it immediately', async () => {
+ vi.useFakeTimers()
+ vi.spyOn(Math, 'random').mockReturnValue(0)
+ const selected = server('web-search')
+ const { instance, mutate, servers } = coordinator()
+ servers.set(selected.name, selected)
+
+ instance.startPeriodicResync(1)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(mutate).toHaveBeenCalledOnce()
+
+ instance.stop()
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(mutate).toHaveBeenCalledOnce()
+ })
+})
diff --git a/host-context-controller/src/externalEgressConvergenceCoordinator.ts b/host-context-controller/src/externalEgressConvergenceCoordinator.ts
new file mode 100644
index 000000000..cfbf90ea0
--- /dev/null
+++ b/host-context-controller/src/externalEgressConvergenceCoordinator.ts
@@ -0,0 +1,462 @@
+import type { McpServerCRD } from './types'
+
+const EXTERNAL_EGRESS_RETRY_DELAYS_MS = [5000, 15000, 30000] as const
+const EXTERNAL_EGRESS_MAX_CONCURRENCY = 10
+const EXTERNAL_EGRESS_RESYNC_JITTER_MS = 5000
+
+export type ExternalEgressWatchEventType = 'ADDED' | 'MODIFIED' | 'DELETED'
+
+export type ExternalEgressRetryHandle = {
+ isCurrent: () => boolean
+ complete: () => void
+}
+
+type ExternalEgressRetryIntent = {
+ sequence: number
+ type: ExternalEgressWatchEventType
+ server: McpServerCRD
+}
+
+type ExternalEgressMutationOptions = {
+ deleteAllowed?: () => Promise<boolean>
+}
+
+type ExternalEgressReconcileOptions = ExternalEgressMutationOptions & {
+ retry?: ExternalEgressRetryHandle
+}
+
+type ExternalEgressCoordinatorDependencies = {
+ listServers: () => McpServerCRD[]
+ getCurrentServer: (name: string) => McpServerCRD | undefined
+ sameDesiredRevision: (left: McpServerCRD, right: McpServerCRD) => boolean
+ enqueue: (server: McpServerCRD, work: () => Promise<void>) => Promise<void>
+ mutate: (
+ type: ExternalEgressWatchEventType,
+ server: McpServerCRD,
+ options: ExternalEgressMutationOptions
+ ) => Promise<void>
+ replay: (
+ type: ExternalEgressWatchEventType,
+ server: McpServerCRD,
+ retry: ExternalEgressRetryHandle
+ ) => Promise<void>
+}
+
+export type ExternalEgressStartupGates = {
+ waitFor: (server: Pick<McpServerCRD, 'name' | 'namespace'>) => Promise<boolean>
+}
+
+class AsyncConcurrencyLimiter {
+ private active = 0
+ private readonly waiters: Array<(admitted: boolean) => void> = []
+ private closed = false
+
+ constructor(private readonly limit: number) {}
+
+ async run<T>(work: () => Promise<T>): Promise<T | undefined> {
+ if (this.closed) return undefined
+ if (this.active >= this.limit) {
+ const admitted = await new Promise<boolean>(resolve => this.waiters.push(resolve))
+ if (!admitted) return undefined
+ } else {
+ this.active += 1
+ }
+ try {
+ return await work()
+ } finally {
+ this.release()
+ }
+ }
+
+ cancelPending(): void {
+ if (this.closed) return
+ this.closed = true
+ for (const resume of this.waiters.splice(0)) {
+ resume(false)
+ }
+ }
+
+ private release(): void {
+ this.active -= 1
+ if (this.closed) return
+ const resume = this.waiters.shift()
+ if (!resume) return
+ // Transfer the released permit before waking the waiter. Reserving it here
+ // prevents a new caller from entering between wake-up and its microtask.
+ this.active += 1
+ resume(true)
+ }
+}
+
+function delay(ms: number): Promise<void> {
+ return new Promise(resolve => setTimeout(resolve, ms))
+}
+
+/**
+ * Owns temporal coordination for external-egress convergence. Kubernetes
+ * authority and mutations remain behind callbacks supplied by the watcher.
+ */
+export class ExternalEgressConvergenceCoordinator {
+ private readonly retryTimers = new Map<string, ReturnType<typeof setTimeout>>()
+ private readonly retryAttempts = new Map<string, number>()
+ private readonly retryIntents = new Map<string, ExternalEgressRetryIntent>()
+ private retrySequence = 0
+ private readonly retryLimiter = new AsyncConcurrencyLimiter(EXTERNAL_EGRESS_MAX_CONCURRENCY)
+ private readonly retrySlots = new Map<string, object>()
+ private readonly inFlight = new Map<string, Promise<void>>()
+ private resyncInFlight: Promise<void> | null = null
+ private resyncTimer: ReturnType<typeof setInterval> | null = null
+ private stopped = false
+
+ constructor(private readonly dependencies: ExternalEgressCoordinatorDependencies) {}
+
+ startPeriodicResync(intervalSec: number): void {
+ if (this.stopped || intervalSec <= 0 || this.resyncTimer) return
+ this.resyncTimer = setInterval(() => {
+ void this.runResync()
+ }, intervalSec * 1000)
+ console.log(`[K8s] External egress periodic DNS resync enabled (every ${intervalSec}s)`)
+ }
+
+ runResync(): Promise<void> {
+ if (this.resyncInFlight) return this.resyncInFlight
+ const run = this.runResyncCore()
+ this.resyncInFlight = run
+ const settle = () => {
+ if (this.resyncInFlight === run) this.resyncInFlight = null
+ }
+ void run.then(settle, settle)
+ return run
+ }
+
+ prepareStartupGates(servers: McpServerCRD[]): ExternalEgressStartupGates {
+ const gates = new Map<string, Promise<boolean>>()
+ const selectedServers = servers
+ .filter(server => (server.spec.egressBindings?.length ?? 0) > 0)
+ .sort((left, right) => this.key(left).localeCompare(this.key(right)))
+
+ if (selectedServers.length > 0) {
+ console.log(
+ `[K8s] Reconciling external egress before startup runtime reconciliation for ` +
+ `${selectedServers.length} McpServer(s)`
+ )
+ }
+
+ // Startup admission is intentionally independent from retry and periodic
+ // resync capacity, so a saturated recovery lane cannot head-of-line block
+ // initial runtime gates for unrelated servers.
+ const limiter = new AsyncConcurrencyLimiter(EXTERNAL_EGRESS_MAX_CONCURRENCY)
+ for (const selected of selectedServers) {
+ const key = this.key(selected)
+ const gate = limiter
+ .run(async () => {
+ if (this.stopped) return false
+ let ready = false
+ await this.dependencies.enqueue(selected, async () => {
+ if (this.stopped) return
+ const current = this.dependencies.getCurrentServer(selected.name)
+ if (
+ !current ||
+ current.namespace !== selected.namespace ||
+ !this.dependencies.sameDesiredRevision(selected, current)
+ ) {
+ return
+ }
+ 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)
+ const latest = this.dependencies.getCurrentServer(selected.name)
+ ready =
+ !this.stopped &&
+ latest !== undefined &&
+ latest.namespace === selected.namespace &&
+ this.dependencies.sameDesiredRevision(selected, latest)
+ } catch (error) {
+ console.error(
+ `[K8s] Initial external egress reconciliation failed for ${key}; ` +
+ 'runtime reconciliation will stay blocked until retry succeeds:',
+ error
+ )
+ this.scheduleRetry('MODIFIED', current)
+ }
+ })
+ return ready
+ })
+ .then(result => result ?? false)
+ gates.set(key, gate)
+ }
+
+ return {
+ waitFor: server => gates.get(this.key(server)) ?? Promise.resolve(true),
+ }
+ }
+
+ async reconcile(
+ type: ExternalEgressWatchEventType,
+ server: McpServerCRD,
+ options: ExternalEgressReconcileOptions = {}
+ ): Promise<ExternalEgressRetryHandle | undefined> {
+ if (this.stopped || (options.retry && !options.retry.isCurrent())) 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
+ existing = this.inFlight.get(key)
+ }
+
+ const completion = options.retry ?? this.currentRetryHandle(key)
+ const run = this.dependencies.mutate(type, server, {
+ deleteAllowed: options.deleteAllowed,
+ })
+ this.inFlight.set(key, run)
+ try {
+ await run
+ return completion
+ } finally {
+ if (this.inFlight.get(key) === run) {
+ this.inFlight.delete(key)
+ }
+ }
+ }
+
+ scheduleRetry(type: string, server: McpServerCRD): void {
+ if (!this.isWatchEventType(type) || this.stopped) return
+
+ const cached = this.dependencies.getCurrentServer(server.name)
+ const retryType: ExternalEgressWatchEventType =
+ cached && cached.namespace === server.namespace
+ ? type === 'ADDED' && this.dependencies.sameDesiredRevision(server, cached)
+ ? 'ADDED'
+ : 'MODIFIED'
+ : 'DELETED'
+ const retryServer = cached && cached.namespace === server.namespace ? cached : server
+ const key = this.key(server)
+ const previousIntent = this.retryIntents.get(key)
+ if (previousIntent && !this.sameRetryTarget(previousIntent, retryType, retryServer)) {
+ this.retryAttempts.delete(key)
+ }
+
+ const intent: ExternalEgressRetryIntent = {
+ sequence: ++this.retrySequence,
+ type: retryType,
+ server: retryServer,
+ }
+ this.retryIntents.set(key, intent)
+ // A timer or queued/active slot already owning the key consumes the newest
+ // intent when it next enters the retry and per-server lanes.
+ if (this.retryTimers.has(key) || this.retrySlots.has(key)) return
+ this.armRetryTimer(key)
+ }
+
+ private armRetryTimer(key: string): void {
+ if (
+ this.stopped ||
+ this.retryTimers.has(key) ||
+ this.retrySlots.has(key) ||
+ !this.retryIntents.has(key)
+ ) {
+ return
+ }
+ const attempt = Math.min(
+ (this.retryAttempts.get(key) ?? 0) + 1,
+ EXTERNAL_EGRESS_RETRY_DELAYS_MS.length
+ )
+ const delayMs = EXTERNAL_EGRESS_RETRY_DELAYS_MS[attempt - 1]
+ this.retryAttempts.set(key, attempt)
+ const capped = attempt === EXTERNAL_EGRESS_RETRY_DELAYS_MS.length
+ console.warn(
+ `[K8s] Scheduling external egress retry ${attempt}/${EXTERNAL_EGRESS_RETRY_DELAYS_MS.length}` +
+ `${capped ? ' (capped)' : ''} ` +
+ `for McpServer "${this.retryIntents.get(key)!.server.name}" in ${delayMs}ms`
+ )
+
+ const timer = setTimeout(() => {
+ if (this.retryTimers.get(key) !== timer) return
+ this.retryTimers.delete(key)
+ this.queueRetry(key)
+ }, delayMs)
+ this.retryTimers.set(key, timer)
+ }
+
+ private queueRetry(key: string): void {
+ if (this.stopped || !this.retryIntents.has(key)) return
+ if (this.retrySlots.has(key)) {
+ // A timer can overlap work admitted through another lane. The durable
+ // slot owns the latest intent and rearms it on exit if it remains live.
+ return
+ }
+
+ const slot = {}
+ this.retrySlots.set(key, slot)
+ void this.retryLimiter
+ .run(async () => {
+ if (this.stopped || this.retrySlots.get(key) !== slot) 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
+ // 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)
+ if (!currentIntent) return
+ await this.replayIntent(currentIntent)
+ })
+ })
+ .catch(error => {
+ if (!this.stopped) {
+ console.error(`[K8s] External egress retry execution failed for ${key}:`, error)
+ }
+ })
+ .finally(() => {
+ if (this.retrySlots.get(key) !== slot) return
+ this.retrySlots.delete(key)
+ // A replay may schedule its successor while still active, or a newer
+ // intent may arrive after this slot selected work. Rearm only after the
+ // key leaves the slot so one key never accumulates limiter backlog.
+ if (!this.stopped && this.retryIntents.has(key) && !this.retryTimers.has(key)) {
+ this.armRetryTimer(key)
+ }
+ })
+ }
+
+ stop(): void {
+ if (this.stopped) return
+ this.stopped = true
+ this.retryLimiter.cancelPending()
+ if (this.resyncTimer) {
+ clearInterval(this.resyncTimer)
+ this.resyncTimer = null
+ }
+ for (const timer of this.retryTimers.values()) {
+ clearTimeout(timer)
+ }
+ this.retryTimers.clear()
+ this.retryAttempts.clear()
+ this.retryIntents.clear()
+ this.retrySlots.clear()
+ this.inFlight.clear()
+ }
+
+ private async runResyncCore(): Promise<void> {
+ if (this.stopped) return
+ const servers = this.dependencies
+ .listServers()
+ .filter(server => (server.spec.egressBindings?.length ?? 0) > 0)
+ .sort((left, right) => this.key(left).localeCompare(this.key(right)))
+ if (servers.length === 0) return
+
+ console.log(`[K8s] Periodic external egress DNS resync: ${servers.length} McpServer(s)`)
+ let index = 0
+ const workers = Array.from(
+ { length: Math.min(EXTERNAL_EGRESS_MAX_CONCURRENCY, servers.length) },
+ async () => {
+ while (!this.stopped) {
+ const server = servers[index++]
+ if (!server) return
+ const key = this.key(server)
+ if (this.inFlight.has(key)) {
+ console.log(`[K8s] Skipping external egress resync for ${key}; reconcile in flight`)
+ continue
+ }
+ const jitterMs = Math.floor(Math.random() * EXTERNAL_EGRESS_RESYNC_JITTER_MS)
+ if (jitterMs > 0) await delay(jitterMs)
+ if (this.stopped) return
+
+ await this.dependencies.enqueue(server, async () => {
+ if (this.stopped) 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)
+ if (
+ !current ||
+ current.namespace !== server.namespace ||
+ (current.spec.egressBindings?.length ?? 0) === 0
+ ) {
+ return
+ }
+ try {
+ const retryIntent = this.retryIntents.get(key)
+ if (retryIntent) {
+ await this.replayIntent(retryIntent)
+ return
+ }
+ // 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)
+ } catch (error) {
+ console.error(`[K8s] External egress periodic resync failed for ${key}:`, error)
+ this.scheduleRetry('MODIFIED', current)
+ }
+ })
+ }
+ }
+ )
+ await Promise.all(workers)
+ }
+
+ private async replayIntent(intent: ExternalEgressRetryIntent): Promise<void> {
+ if (this.stopped) return
+ const handle = this.retryHandle(intent)
+ if (!handle.isCurrent()) return
+
+ const current = this.dependencies.getCurrentServer(intent.server.name)
+ const type: ExternalEgressWatchEventType =
+ current && current.namespace === intent.server.namespace ? 'MODIFIED' : 'DELETED'
+ const server = type === 'DELETED' ? intent.server : current!
+ await this.dependencies.replay(type, server, handle)
+ }
+
+ private currentRetryHandle(key: string): ExternalEgressRetryHandle | undefined {
+ const intent = this.retryIntents.get(key)
+ return intent ? this.retryHandle(intent) : undefined
+ }
+
+ private retryHandle(intent: ExternalEgressRetryIntent): ExternalEgressRetryHandle {
+ return {
+ isCurrent: () =>
+ !this.stopped &&
+ this.retryIntents.get(this.key(intent.server))?.sequence === intent.sequence,
+ complete: () => {
+ if (this.retryIntents.get(this.key(intent.server))?.sequence !== intent.sequence) return
+ this.clearRetry(intent.server)
+ },
+ }
+ }
+
+ private clearRetry(server: Pick<McpServerCRD, 'name' | 'namespace'>): void {
+ const key = this.key(server)
+ const timer = this.retryTimers.get(key)
+ if (timer) {
+ clearTimeout(timer)
+ this.retryTimers.delete(key)
+ }
+ this.retryAttempts.delete(key)
+ this.retryIntents.delete(key)
+ }
+
+ private sameRetryTarget(
+ previous: ExternalEgressRetryIntent,
+ type: ExternalEgressWatchEventType,
+ server: McpServerCRD
+ ): boolean {
+ const previousPresent = previous.type !== 'DELETED'
+ const nextPresent = type !== 'DELETED'
+ return (
+ previousPresent === nextPresent &&
+ this.dependencies.sameDesiredRevision(previous.server, server)
+ )
+ }
+
+ private key(server: Pick<McpServerCRD, 'name' | 'namespace'>): string {
+ return `${server.namespace}/${server.name}`
+ }
+
+ private isWatchEventType(type: string): type is ExternalEgressWatchEventType {
+ return type === 'ADDED' || type === 'MODIFIED' || type === 'DELETED'
+ }
+}
diff --git a/host-context-controller/src/hostFleetScheduler.test.ts b/host-context-controller/src/hostFleetScheduler.test.ts
new file mode 100644
index 000000000..82f29c77c
--- /dev/null
+++ b/host-context-controller/src/hostFleetScheduler.test.ts
@@ -0,0 +1,229 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ type HostFleetReconcileRequest,
+ type HostFleetRequestResult,
+ HostFleetScheduler,
+} from './hostFleetScheduler'
+
+function deferred<T = void>() {
+ let resolve!: (value: T | PromiseLike<T>) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+describe('HostFleetScheduler', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('merges newer work into one trailing pass with full coverage and latest inputs', async () => {
+ const activePass = deferred()
+ const requests: HostFleetReconcileRequest[] = []
+ const results: HostFleetRequestResult[] = []
+ const scheduler = new HostFleetScheduler({
+ perform: async request => {
+ requests.push({ ...request })
+ if (requests.length === 1) await activePass.promise
+ },
+ recordRequest: result => results.push(result),
+ })
+
+ const firstGeneration = scheduler.beginLifecycleTransition()
+ scheduler.bumpInputRevision()
+ const active = scheduler.request('active lifecycle', firstGeneration, 'lifecycle')
+ await vi.waitFor(() => expect(requests).toHaveLength(1))
+
+ scheduler.bumpInputRevision()
+ const pendingFull = scheduler.request('pending full', firstGeneration, 'full')
+ const latestGeneration = scheduler.beginLifecycleTransition()
+ scheduler.bumpInputRevision()
+ const latestLifecycle = scheduler.request('latest lifecycle', latestGeneration, 'lifecycle')
+
+ activePass.resolve()
+ await Promise.all([active, pendingFull, latestLifecycle])
+
+ expect(requests).toEqual([
+ {
+ reason: 'active lifecycle',
+ mode: 'lifecycle',
+ ccLifecycleGeneration: firstGeneration,
+ inputRevision: 1,
+ },
+ {
+ reason: 'latest lifecycle',
+ mode: 'full',
+ ccLifecycleGeneration: latestGeneration,
+ inputRevision: 3,
+ },
+ ])
+ expect(results).toEqual(['started', 'coalesced', 'coalesced', 'trailing'])
+ })
+
+ it('reuses active work only when its mode, revision, and lifecycle generation cover the request', async () => {
+ const activePass = deferred()
+ const requests: HostFleetReconcileRequest[] = []
+ const scheduler = new HostFleetScheduler({
+ perform: async request => {
+ requests.push({ ...request })
+ if (requests.length === 1) await activePass.promise
+ },
+ recordRequest: vi.fn(),
+ })
+ const generation = scheduler.beginLifecycleTransition()
+ scheduler.bumpInputRevision()
+
+ const active = scheduler.request('full', generation, 'full')
+ await vi.waitFor(() => expect(requests).toHaveLength(1))
+ const covered = scheduler.request('covered lifecycle', generation, 'lifecycle')
+
+ activePass.resolve()
+ await Promise.all([active, covered])
+
+ expect(requests).toHaveLength(1)
+ })
+
+ it('rejects stale or already-applied lifecycle work without suppressing a current full pass', async () => {
+ const perform = vi.fn<(request: HostFleetReconcileRequest) => Promise<void>>(
+ async () => undefined
+ )
+ const scheduler = new HostFleetScheduler({
+ perform,
+ recordRequest: vi.fn(),
+ })
+ const firstGeneration = scheduler.beginLifecycleTransition()
+ scheduler.markLifecycleApplied(firstGeneration)
+
+ await scheduler.request('already applied', firstGeneration, 'lifecycle')
+ await scheduler.request('current full', firstGeneration, 'full')
+ scheduler.beginLifecycleTransition()
+ await scheduler.request('stale full', firstGeneration, 'full')
+
+ expect(perform).toHaveBeenCalledOnce()
+ expect(perform).toHaveBeenCalledWith(
+ expect.objectContaining({ reason: 'current full', mode: 'full' })
+ )
+ })
+
+ it('does not let a rejected pass poison later work', async () => {
+ const failure = new Error('transient failure')
+ const perform = vi
+ .fn<(request: HostFleetReconcileRequest) => Promise<void>>()
+ .mockRejectedValueOnce(failure)
+ .mockResolvedValueOnce(undefined)
+ const scheduler = new HostFleetScheduler({
+ perform,
+ recordRequest: vi.fn(),
+ })
+
+ await expect(scheduler.request('fails')).rejects.toThrow(failure)
+ await expect(scheduler.request('recovers')).resolves.toBeUndefined()
+
+ expect(perform).toHaveBeenCalledTimes(2)
+ })
+
+ it('releases active and queued waiters on stop without starting queued work', async () => {
+ const activePass = deferred()
+ const requests: HostFleetReconcileRequest[] = []
+ const scheduler = new HostFleetScheduler({
+ perform: async request => {
+ requests.push({ ...request })
+ await activePass.promise
+ },
+ recordRequest: vi.fn(),
+ })
+
+ const active = scheduler.request('active')
+ await vi.waitFor(() => expect(requests).toHaveLength(1))
+ scheduler.bumpInputRevision()
+ const queued = scheduler.request('queued')
+
+ scheduler.stop()
+ await Promise.all([active, queued, scheduler.request('after stop')])
+ activePass.resolve()
+ await Promise.resolve()
+
+ expect(requests).toHaveLength(1)
+ })
+
+ it('tracks lifecycle state and cancels obsolete retries', async () => {
+ vi.useFakeTimers()
+ const perform = vi.fn<(request: HostFleetReconcileRequest) => Promise<void>>(
+ async () => undefined
+ )
+ const scheduler = new HostFleetScheduler({
+ perform,
+ recordRequest: vi.fn(),
+ })
+ const firstGeneration = scheduler.beginLifecycleTransition()
+
+ expect(scheduler.currentLifecycleGeneration).toBe(firstGeneration)
+ expect(scheduler.appliedLifecycleGeneration).toBe(-1)
+
+ scheduler.scheduleLifecycleRetry({
+ reason: 'failed lifecycle',
+ mode: 'lifecycle',
+ ccLifecycleGeneration: firstGeneration,
+ inputRevision: 0,
+ })
+ await vi.advanceTimersByTimeAsync(4999)
+ expect(perform).not.toHaveBeenCalled()
+
+ const secondGeneration = scheduler.beginLifecycleTransition()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(perform).not.toHaveBeenCalled()
+
+ scheduler.scheduleLifecycleRetry({
+ reason: 'current lifecycle',
+ mode: 'lifecycle',
+ ccLifecycleGeneration: secondGeneration,
+ inputRevision: 0,
+ })
+ scheduler.markLifecycleApplied(secondGeneration)
+ await vi.advanceTimersByTimeAsync(5000)
+
+ expect(scheduler.appliedLifecycleGeneration).toBe(secondGeneration)
+ expect(perform).not.toHaveBeenCalled()
+ })
+
+ it('retries an unapplied current lifecycle generation with bounded backoff', async () => {
+ vi.useFakeTimers()
+ const requests: HostFleetReconcileRequest[] = []
+ const scheduler = new HostFleetScheduler({
+ perform: async request => {
+ requests.push({ ...request })
+ },
+ recordRequest: vi.fn(),
+ })
+ const generation = scheduler.beginLifecycleTransition()
+ const failedRequest: HostFleetReconcileRequest = {
+ reason: 'failed lifecycle',
+ mode: 'lifecycle',
+ ccLifecycleGeneration: generation,
+ inputRevision: 0,
+ }
+
+ scheduler.scheduleLifecycleRetry(failedRequest)
+ await vi.advanceTimersByTimeAsync(5000)
+ scheduler.scheduleLifecycleRetry(failedRequest)
+ await vi.advanceTimersByTimeAsync(14999)
+ expect(requests).toHaveLength(1)
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(requests).toEqual([
+ expect.objectContaining({
+ reason: 'CommunicationChannel lifecycle convergence retry',
+ mode: 'lifecycle',
+ ccLifecycleGeneration: generation,
+ }),
+ expect.objectContaining({
+ reason: 'CommunicationChannel lifecycle convergence retry',
+ mode: 'lifecycle',
+ ccLifecycleGeneration: generation,
+ }),
+ ])
+ })
+})
diff --git a/host-context-controller/src/hostFleetScheduler.ts b/host-context-controller/src/hostFleetScheduler.ts
new file mode 100644
index 000000000..d872d6cad
--- /dev/null
+++ b/host-context-controller/src/hostFleetScheduler.ts
@@ -0,0 +1,246 @@
+const COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 300000] as const
+
+export type HostFleetReconcileMode = 'full' | 'lifecycle'
+
+export type HostFleetReconcileRequest = {
+ reason: string
+ mode: HostFleetReconcileMode
+ ccLifecycleGeneration?: number
+ inputRevision: number
+}
+
+type PendingHostFleetReconcile = HostFleetReconcileRequest & {
+ promise: Promise<void>
+ resolve: () => void
+}
+
+type ActiveHostFleetReconcile = HostFleetReconcileRequest & {
+ promise: Promise<void>
+}
+
+export type HostFleetRequestResult = 'started' | 'coalesced' | 'trailing'
+
+type HostFleetSchedulerDependencies = {
+ perform: (request: HostFleetReconcileRequest) => Promise<void>
+ recordRequest: (result: HostFleetRequestResult) => void
+}
+
+function hostFleetRequestCovers(
+ active: HostFleetReconcileRequest,
+ requested: HostFleetReconcileRequest
+): boolean {
+ const modeCovered = active.mode === 'full' || requested.mode === 'lifecycle'
+ if (!modeCovered) return false
+ if (active.inputRevision !== requested.inputRevision) return false
+ if (requested.ccLifecycleGeneration === undefined) return true
+ return active.ccLifecycleGeneration === requested.ccLifecycleGeneration
+}
+
+function mergeHostFleetRequests(
+ pending: HostFleetReconcileRequest,
+ requested: HostFleetReconcileRequest
+): HostFleetReconcileRequest {
+ const pendingGeneration = pending.ccLifecycleGeneration
+ const requestedGeneration = requested.ccLifecycleGeneration
+ return {
+ reason: requested.reason,
+ mode: pending.mode === 'full' || requested.mode === 'full' ? 'full' : 'lifecycle',
+ inputRevision: Math.max(pending.inputRevision, requested.inputRevision),
+ ccLifecycleGeneration:
+ pendingGeneration === undefined
+ ? requestedGeneration
+ : requestedGeneration === undefined
+ ? pendingGeneration
+ : Math.max(pendingGeneration, requestedGeneration),
+ }
+}
+
+/**
+ * Owns temporal coordination for Host fleet convergence. Kubernetes reads and
+ * mutations stay behind `perform`, so this scheduler only serializes requests,
+ * coalesces a single trailing pass, and manages lifecycle retry/shutdown state.
+ */
+export class HostFleetScheduler {
+ private ccLifecycleGeneration = 0
+ private ccAppliedLifecycleGeneration = -1
+ private ccFleetRetryTimer: ReturnType<typeof setTimeout> | null = null
+ private ccFleetRetryAttempt = 0
+ private hostFleetReconcileInFlight: ActiveHostFleetReconcile | null = null
+ private hostFleetReconcilePending: PendingHostFleetReconcile | null = null
+ private hostFleetInputRevision = 0
+ private resolveHostFleetShutdown: () => void = () => {}
+ private readonly hostFleetShutdown = new Promise<void>(resolve => {
+ this.resolveHostFleetShutdown = resolve
+ })
+ private stopped = false
+
+ constructor(private readonly dependencies: HostFleetSchedulerDependencies) {}
+
+ get currentLifecycleGeneration(): number {
+ return this.ccLifecycleGeneration
+ }
+
+ get appliedLifecycleGeneration(): number {
+ return this.ccAppliedLifecycleGeneration
+ }
+
+ beginLifecycleTransition(): number {
+ this.ccLifecycleGeneration += 1
+ this.ccFleetRetryAttempt = 0
+ this.clearLifecycleRetry()
+ return this.ccLifecycleGeneration
+ }
+
+ bumpInputRevision(): number {
+ this.hostFleetInputRevision += 1
+ return this.hostFleetInputRevision
+ }
+
+ markLifecycleApplied(generation: number): void {
+ if (generation !== this.ccLifecycleGeneration) return
+ this.ccAppliedLifecycleGeneration = generation
+ this.ccFleetRetryAttempt = 0
+ this.clearLifecycleRetry()
+ }
+
+ scheduleLifecycleRetry(request: HostFleetReconcileRequest): void {
+ const generation = request.ccLifecycleGeneration
+ if (generation === undefined) return
+ if (
+ this.stopped ||
+ generation !== this.ccLifecycleGeneration ||
+ generation === this.ccAppliedLifecycleGeneration ||
+ this.ccFleetRetryTimer
+ ) {
+ return
+ }
+
+ const delayIndex = Math.min(
+ this.ccFleetRetryAttempt,
+ COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS.length - 1
+ )
+ const retryDelay = COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS[delayIndex]
+ this.ccFleetRetryAttempt += 1
+ this.ccFleetRetryTimer = setTimeout(() => {
+ this.ccFleetRetryTimer = null
+ if (
+ this.stopped ||
+ generation !== this.ccLifecycleGeneration ||
+ generation === this.ccAppliedLifecycleGeneration
+ ) {
+ return
+ }
+ void this.request(
+ 'CommunicationChannel lifecycle convergence retry',
+ generation,
+ request.mode
+ )
+ }, retryDelay)
+ }
+
+ /**
+ * Cache transitions, periodic resyncs, and retries share one active pass and
+ * at most one merged trailing pass. Each caller waits only for work covering
+ * its request, keeping startup bounded under a sustained retry stream.
+ */
+ request(
+ reason: string,
+ ccLifecycleGeneration?: number,
+ mode?: HostFleetReconcileMode
+ ): Promise<void> {
+ if (this.stopped) return Promise.resolve()
+ const requestMode = mode ?? (ccLifecycleGeneration === undefined ? 'full' : 'lifecycle')
+ if (
+ ccLifecycleGeneration !== undefined &&
+ (ccLifecycleGeneration !== this.ccLifecycleGeneration ||
+ (requestMode === 'lifecycle' &&
+ ccLifecycleGeneration === this.ccAppliedLifecycleGeneration))
+ ) {
+ return Promise.resolve()
+ }
+
+ const request: HostFleetReconcileRequest = {
+ reason,
+ mode: requestMode,
+ ccLifecycleGeneration,
+ inputRevision: this.hostFleetInputRevision,
+ }
+ const active = this.hostFleetReconcileInFlight
+ if (!active) {
+ this.dependencies.recordRequest('started')
+ return this.waitForHostFleetOrShutdown(this.startHostFleetReconcile(request))
+ }
+ if (hostFleetRequestCovers(active, request)) {
+ this.dependencies.recordRequest('coalesced')
+ return this.waitForHostFleetOrShutdown(active.promise)
+ }
+
+ if (!this.hostFleetReconcilePending) {
+ let resolve!: () => void
+ const promise = new Promise<void>(resolvePromise => {
+ resolve = resolvePromise
+ })
+ this.hostFleetReconcilePending = {
+ ...request,
+ promise,
+ resolve,
+ }
+ } else {
+ const merged = mergeHostFleetRequests(this.hostFleetReconcilePending, request)
+ this.hostFleetReconcilePending.reason = merged.reason
+ this.hostFleetReconcilePending.mode = merged.mode
+ this.hostFleetReconcilePending.ccLifecycleGeneration = merged.ccLifecycleGeneration
+ this.hostFleetReconcilePending.inputRevision = merged.inputRevision
+ }
+ this.dependencies.recordRequest('coalesced')
+ return this.waitForHostFleetOrShutdown(this.hostFleetReconcilePending.promise)
+ }
+
+ stop(): void {
+ if (this.stopped) return
+ this.stopped = true
+ this.resolveHostFleetShutdown()
+ this.hostFleetReconcilePending?.resolve()
+ this.hostFleetReconcilePending = null
+ this.clearLifecycleRetry()
+ }
+
+ private clearLifecycleRetry(): void {
+ if (!this.ccFleetRetryTimer) return
+ clearTimeout(this.ccFleetRetryTimer)
+ this.ccFleetRetryTimer = null
+ }
+
+ private waitForHostFleetOrShutdown(coverage: Promise<void>): Promise<void> {
+ return Promise.race([coverage, this.hostFleetShutdown])
+ }
+
+ private startHostFleetReconcile(request: HostFleetReconcileRequest): Promise<void> {
+ const reconcileRequest: HostFleetReconcileRequest = {
+ reason: request.reason,
+ mode: request.mode,
+ ccLifecycleGeneration: request.ccLifecycleGeneration,
+ inputRevision: request.inputRevision,
+ }
+ const promise = this.dependencies.perform(reconcileRequest)
+ const active: ActiveHostFleetReconcile = { ...reconcileRequest, promise }
+ this.hostFleetReconcileInFlight = active
+
+ const settle = () => {
+ if (this.hostFleetReconcileInFlight !== active) return
+ this.hostFleetReconcileInFlight = null
+ const pending = this.hostFleetReconcilePending
+ this.hostFleetReconcilePending = null
+ if (!pending) return
+ if (this.stopped) {
+ pending.resolve()
+ return
+ }
+ this.dependencies.recordRequest('trailing')
+ const trailing = this.startHostFleetReconcile(pending)
+ void trailing.then(pending.resolve, pending.resolve)
+ }
+ void promise.then(settle, settle)
+ return promise
+ }
+}
diff --git a/host-context-controller/src/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.ts
index 944edc7ea..152234ee3 100644
--- a/host-context-controller/src/hostReconciler.test.ts
+++ b/host-context-controller/src/hostReconciler.test.ts
@@ -1368,7 +1368,11 @@ describe('HostReconciler Host inventory mutation authority', () => {
it('does not patch channel-reader after Host authority changes during revision resolution', async () => {
const reconciler = makeBasicReconciler()
- const host = makeHost({ name: 'channel-authority-race' })
+ const host = {
+ ...makeHost({ name: 'channel-authority-race' }),
+ uid: 'channel-authority-race-uid',
+ generation: 3,
+ }
const authority = { current: { known: true, generation: 9 } }
wireAuthoritativeHost(reconciler, host, authority)
const revisionStarted = deferred()
@@ -1392,6 +1396,98 @@ describe('HostReconciler Host inventory mutation authority', () => {
expect(patchDeployment).not.toHaveBeenCalled()
})
+ it.each([
+ ['UID', (host: HostCRD) => ({ ...host, uid: 'replacement-channel-reader-uid' })],
+ [
+ 'spec generation',
+ (host: HostCRD) => ({
+ ...host,
+ generation: (host.generation ?? 0) + 1,
+ spec: { ...host.spec, contextRef: 'replacement-context' },
+ }),
+ ],
+ ] as const)(
+ 'does not patch channel-reader when the Host %s changes during revision resolution',
+ async (_, replaceCurrent) => {
+ const reconciler = makeBasicReconciler()
+ const host = {
+ ...makeHost({ name: 'channel-host-race' }),
+ uid: 'channel-host-race-uid',
+ generation: 3,
+ }
+ let current: HostCRD = host
+ reconciler.setResolveCurrentHost(name => (name === host.name ? current : undefined))
+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 9 }))
+ const revisionStarted = deferred()
+ const releaseRevision = deferred<string>()
+ vi.spyOn(reconciler as any, 'computeChannelReaderRevisionForHost').mockImplementation(
+ async () => {
+ revisionStarted.resolve(undefined)
+ return releaseRevision.promise
+ }
+ )
+ const patchDeployment = vi
+ .spyOn((reconciler as any).appsApi, 'patchNamespacedDeployment')
+ .mockResolvedValue(undefined)
+
+ const pending = reconciler.patchChannelReaderRevisionAnnotation(host.name)
+ await revisionStarted.promise
+ current = replaceCurrent(host)
+ releaseRevision.resolve('resolved-revision')
+ await pending
+
+ expect(patchDeployment).not.toHaveBeenCalled()
+ }
+ )
+
+ it('serializes a fresh channel-reader revision behind an older in-flight Host reconcile', async () => {
+ const reconciler = makeBasicReconciler()
+ const host = {
+ ...makeHost({ name: 'channel-revision-order' }),
+ uid: 'channel-revision-order-uid',
+ generation: 4,
+ }
+ const authority = { current: { known: true, generation: 9 } }
+ wireAuthoritativeHost(reconciler, host, authority)
+ const staleReconcileStarted = deferred()
+ const releaseStaleReconcile = deferred()
+ const order: string[] = []
+ let liveRevision = ''
+
+ vi.spyOn(reconciler as any, 'reconcileCore').mockImplementation(async () => {
+ order.push('reconcile-a:start')
+ staleReconcileStarted.resolve(undefined)
+ await releaseStaleReconcile.promise
+ liveRevision = 'revision-a'
+ order.push('reconcile-a:write')
+ })
+ vi.spyOn(reconciler as any, 'computeChannelReaderRevisionForHost').mockResolvedValue(
+ 'revision-b'
+ )
+ const patchDeployment = vi
+ .spyOn((reconciler as any).appsApi, 'patchNamespacedDeployment')
+ .mockImplementation(async (request: any) => {
+ const { body } = request
+ liveRevision = body.spec.template.metadata.annotations['clerum.io/credentials-revision']
+ order.push('revision-b:patch')
+ })
+
+ const staleReconcile = reconciler.reconcile(host)
+ await staleReconcileStarted.promise
+ const freshRevision = reconciler.patchChannelReaderRevisionAnnotation(host.name)
+
+ // Give B the opportunity to patch before A is released. Without a shared
+ // Host lane, B writes first and A deterministically overwrites it.
+ await Promise.resolve()
+ await Promise.resolve()
+ releaseStaleReconcile.resolve(undefined)
+ await Promise.all([staleReconcile, freshRevision])
+
+ expect(liveRevision).toBe('revision-b')
+ expect(patchDeployment).toHaveBeenCalledOnce()
+ expect(order).toEqual(['reconcile-a:start', 'reconcile-a:write', 'revision-b:patch'])
+ })
+
it('rejects a queued delete when Host authority changes before admission', async () => {
const reconciler = makeBasicReconciler()
const host = makeHost({ name: 'delete-authority-race' })
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 9484c1279..34e321911 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -2185,37 +2185,44 @@ export class HostReconciler {
const capturedAuthority = this.captureHostMutationAuthority()
const depName = `channel-reader-${hostName}`
try {
- this.requireHostMutationAuthority(
- `channel-reader "${hostName}" revision patch`,
- capturedAuthority
- )
- if (this.resolveCurrentHost && !this.resolveCurrentHost(hostName)) return
- const revision = await this.computeChannelReaderRevisionForHost(hostName)
- this.requireHostMutationAuthority(
- `channel-reader "${hostName}" revision patch`,
- capturedAuthority
- )
- if (this.resolveCurrentHost && !this.resolveCurrentHost(hostName)) return
- const patchBody = {
- spec: {
- template: {
- metadata: {
- annotations: { 'clerum.io/credentials-revision': revision },
+ await this.lifecycle.serializeByHost(hostName, async () => {
+ const action = `channel-reader "${hostName}" revision patch`
+ this.requireHostMutationAuthority(action, capturedAuthority)
+
+ const resolveCurrentHost = this.resolveCurrentHost
+ const admittedHost = resolveCurrentHost?.(hostName)
+ if (resolveCurrentHost !== null && admittedHost === undefined) return
+ const revalidate = admittedHost
+ ? this.makeHostMutationAdmission(action, admittedHost, capturedAuthority)
+ : () => this.requireHostMutationAuthority(action, capturedAuthority)
+
+ revalidate()
+ const revision = await this.computeChannelReaderRevisionForHost(hostName)
+ // The revision calculation can await multiple Secret reads. Revalidate
+ // Host LIST/WATCH authority plus UID and generation immediately before
+ // entering the Kubernetes mutation, while still holding this Host lane.
+ revalidate()
+ const patchBody = {
+ spec: {
+ template: {
+ metadata: {
+ annotations: { 'clerum.io/credentials-revision': revision },
+ },
},
},
- },
- }
- await this.appsApi.patchNamespacedDeployment(
- { name: depName, namespace: config.channelsNamespace, body: patchBody },
- {
- middleware: [
- k8s.setHeaderMiddleware('Content-Type', 'application/strategic-merge-patch+json'),
- ],
}
- )
- console.log(
- `[HostReconciler] Patched ${depName} credentials-revision=${revision || '(empty)'}`
- )
+ await this.appsApi.patchNamespacedDeployment(
+ { name: depName, namespace: config.channelsNamespace, body: patchBody },
+ {
+ middleware: [
+ k8s.setHeaderMiddleware('Content-Type', 'application/strategic-merge-patch+json'),
+ ],
+ }
+ )
+ console.log(
+ `[HostReconciler] Patched ${depName} credentials-revision=${revision || '(empty)'}`
+ )
+ })
} catch (err) {
if (getErrorCode(err) === 404) return
console.error(`[HostReconciler] Failed to reconcile ${depName} revision:`, err)
diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.ts
index d3f612e01..507c08976 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -307,6 +307,7 @@ describe('McpServerWatcher startup', () => {
afterEach(() => {
vi.useRealTimers()
+ vi.restoreAllMocks()
mocks.ensureDefaultPolicies.mockReset().mockResolvedValue(undefined)
mocks.netPolFullReconcile.mockReset().mockResolvedValue(undefined)
mocks.serverFullReconcile.mockReset().mockResolvedValue(undefined)
@@ -1256,6 +1257,27 @@ describe('McpServerWatcher startup', () => {
await watcher.stop()
})
+ it('keeps env-Secret reconciliation a no-op after stop', async () => {
+ const selected = {
+ name: 'stopped-secret-server',
+ namespace: 'mcp-server',
+ spec: {
+ contextRef: 'default',
+ image: 'clerum/stopped-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)
+
+ await watcher.stop()
+ await watcher.reconcileByEnvSecret('shared-env', 'mcp-server')
+
+ expect(reconciler.reconcile).not.toHaveBeenCalled()
+ })
+
it('admits an initial server without egress while another initial server waits on DNS', async () => {
const dnsBlockedServer = {
name: 'dns-blocked-server',
@@ -1969,6 +1991,7 @@ describe('McpServerWatcher startup', () => {
await (watcher as any).runInitialNetworkPolicyConvergence()
await vi.advanceTimersByTimeAsync(5000)
+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(2)
expect(mocks.netPolFullReconcile).toHaveBeenLastCalledWith(
[],
[],
@@ -2153,7 +2176,7 @@ describe('McpServerWatcher startup', () => {
})
)
- watcher.stop()
+ await watcher.stop()
errorSpy.mockRestore()
})
@@ -2419,6 +2442,7 @@ describe('McpServerWatcher external egress retries', () => {
}
beforeEach(() => {
+ vi.clearAllMocks()
vi.useFakeTimers()
})
@@ -2689,6 +2713,38 @@ describe('McpServerWatcher external egress retries', () => {
watcher.stop()
})
+ it('replays a retry against the watcher generation current when the timer executes', async () => {
+ const watcher = new McpServerWatcher()
+ const selected = {
+ name: 'generation-fenced-server',
+ namespace: 'mcp-server',
+ spec: {
+ ...serverObject.spec,
+ egressBindings: undefined,
+ },
+ }
+ ;(watcher as any).servers.set(selected.name, selected)
+ ;(watcher as any).mcpWatchGeneration = 41
+ const replay = vi
+ .spyOn(watcher as any, 'reconcileMcpServerWatchEvent')
+ .mockResolvedValue(undefined)
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ ;(watcher as any).scheduleExternalEgressRetry('ADDED', selected)
+ ;(watcher as any).mcpWatchGeneration = 42
+ await vi.advanceTimersByTimeAsync(5000)
+
+ expect(replay).toHaveBeenCalledWith(
+ 'MODIFIED',
+ expect.objectContaining({ name: selected.name }),
+ 42,
+ expect.objectContaining({
+ isCurrent: expect.any(Function),
+ complete: expect.any(Function),
+ })
+ )
+ watcher.stop()
+ })
+
it('reconciles external egress before runtime reconciliation on ADDED events', async () => {
const watcher = new McpServerWatcher()
const netPol = (watcher as any).netPolReconciler
@@ -2756,6 +2812,37 @@ describe('McpServerWatcher external egress retries', () => {
watcher.stop()
})
+ it('retries the full DELETE pipeline when authoritative absence is temporarily unavailable', 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
+ const unavailable = Object.assign(new Error('apiserver temporarily unavailable'), {
+ response: { statusCode: 503 },
+ })
+ mocks.getNamespacedCustomObject.mockRejectedValueOnce(unavailable)
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ const watchCallback = (watcher as any).getMcpServerWatchCallback()
+ await expect(watchCallback('DELETED', serverObject)).resolves.toBeUndefined()
+
+ expect(mocks.getNamespacedCustomObject).toHaveBeenCalledTimes(1)
+ expect(netPol.cleanupExternalEgress).not.toHaveBeenCalled()
+ expect(reconciler.reconcileDelete).not.toHaveBeenCalled()
+ expect(bindingReconciler.cleanupBindings).not.toHaveBeenCalled()
+
+ await vi.advanceTimersByTimeAsync(5000)
+
+ expect(netPol.cleanupExternalEgress).toHaveBeenCalledTimes(1)
+ expect(reconciler.reconcileDelete).toHaveBeenCalledWith('redis-tools', 'mcp-server')
+ expect(bindingReconciler.cleanupBindings).toHaveBeenCalledWith('redis-tools')
+ expect(mocks.getNamespacedCustomObject).toHaveBeenCalledTimes(4)
+
+ watcher.stop()
+ })
+
it('retires queued McpServer work immediately when its watch ends', async () => {
const blockerStarted = deferred()
const releaseBlocker = deferred()
@@ -2993,51 +3080,60 @@ describe('McpServerWatcher external egress retries', () => {
it('does not run parallel external egress reconciles for the same McpServer', async () => {
const watcher = new McpServerWatcher()
const netPol = (watcher as any).netPolReconciler
+ const mutationStarted = deferred()
+ const releaseMutation = deferred()
const server = {
name: 'redis-tools',
namespace: 'mcp-server',
spec: serverObject.spec,
}
;(watcher as any).servers.set('redis-tools', server)
- ;(watcher as any).externalEgressInFlight.set(
- 'mcp-server/redis-tools',
- new Promise(() => undefined)
- )
+ netPol.reconcileExternalEgress.mockImplementationOnce(async () => {
+ mutationStarted.resolve(undefined)
+ await releaseMutation.promise
+ })
vi.spyOn(Math, 'random').mockReturnValue(0)
+ const active = (watcher as any).runExternalEgressOnce('MODIFIED', server)
+ await mutationStarted.promise
await (watcher as any).runExternalEgressResync()
- expect(netPol.reconcileExternalEgress).not.toHaveBeenCalled()
+ expect(netPol.reconcileExternalEgress).toHaveBeenCalledOnce()
+ releaseMutation.resolve(undefined)
+ await active
watcher.stop()
})
it('waits for already in-flight external egress before reconciling the current server', async () => {
const watcher = new McpServerWatcher()
const netPol = (watcher as any).netPolReconciler
+ const mutationStarted = deferred()
+ const releaseMutation = deferred()
const server = {
name: 'redis-tools',
namespace: 'mcp-server',
spec: serverObject.spec,
}
- let releaseExisting!: () => void
- const existing = new Promise<void>(resolve => {
- releaseExisting = resolve
+ netPol.reconcileExternalEgress.mockImplementationOnce(async () => {
+ mutationStarted.resolve(undefined)
+ await releaseMutation.promise
})
- ;(watcher as any).externalEgressInFlight.set('mcp-server/redis-tools', existing)
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const run = (watcher as any).runExternalEgressOnce('MODIFIED', server)
- await Promise.resolve()
+ const active = (watcher as any).runExternalEgressOnce('MODIFIED', server)
+ await mutationStarted.promise
+ const waiting = (watcher as any).runExternalEgressOnce('MODIFIED', server)
+ await flushMicrotasks()
- expect(netPol.reconcileExternalEgress).not.toHaveBeenCalled()
+ expect(netPol.reconcileExternalEgress).toHaveBeenCalledOnce()
expect(warn).toHaveBeenCalledWith(
'[K8s] Waiting for external egress reconcile for mcp-server/redis-tools; already in flight'
)
- releaseExisting()
- await expect(run).resolves.toBeUndefined()
- expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(1)
+ releaseMutation.resolve(undefined)
+ await Promise.all([active, waiting])
+ expect(netPol.reconcileExternalEgress).toHaveBeenCalledTimes(2)
warn.mockRestore()
watcher.stop()
@@ -3046,21 +3142,27 @@ describe('McpServerWatcher external egress retries', () => {
it('does not start another external egress mutation after stop releases an in-flight wait', async () => {
const watcher = new McpServerWatcher()
const netPol = (watcher as any).netPolReconciler
+ const mutationStarted = deferred()
+ const releaseMutation = deferred()
const server = {
name: 'redis-tools',
namespace: 'mcp-server',
spec: serverObject.spec,
}
- const existing = deferred()
- ;(watcher as any).externalEgressInFlight.set('mcp-server/redis-tools', existing.promise)
+ netPol.reconcileExternalEgress.mockImplementationOnce(async () => {
+ mutationStarted.resolve(undefined)
+ await releaseMutation.promise
+ })
- const run = (watcher as any).runExternalEgressOnce('MODIFIED', server)
+ const active = (watcher as any).runExternalEgressOnce('MODIFIED', server)
+ await mutationStarted.promise
+ const waiting = (watcher as any).runExternalEgressOnce('MODIFIED', server)
await flushMicrotasks()
await watcher.stop()
- existing.resolve(undefined)
- await run
+ releaseMutation.resolve(undefined)
+ await Promise.all([active, waiting])
- expect(netPol.reconcileExternalEgress).not.toHaveBeenCalled()
+ expect(netPol.reconcileExternalEgress).toHaveBeenCalledOnce()
})
})
@@ -3571,14 +3673,12 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
lifecycleGeneration
)
expect((watcher as any).ccAppliedLifecycleGeneration).not.toBe(lifecycleGeneration)
- expect((watcher as any).ccFleetRetryTimer).not.toBeNull()
expect(mocks.hostReconcileHosts).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(5000)
await vi.waitFor(() => expect(mocks.hostReconcileHosts).toHaveBeenCalledOnce())
expect(hostListAttempts).toBe(2)
expect((watcher as any).ccAppliedLifecycleGeneration).toBe(lifecycleGeneration)
- expect((watcher as any).ccFleetRetryTimer).toBeNull()
} finally {
errorSpy.mockRestore()
watcher.stop()
@@ -3606,7 +3706,6 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
)
expect((watcher as any).ccAppliedLifecycleGeneration).toBe(lifecycleGeneration)
- expect((watcher as any).ccFleetRetryTimer).toBeNull()
await vi.advanceTimersByTimeAsync(300000)
expect(mocks.hostFullReconcile).toHaveBeenCalledOnce()
} finally {
@@ -3644,7 +3743,6 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
await vi.advanceTimersByTimeAsync(5000)
await vi.waitFor(() => expect(mocks.hostReconcileHosts).toHaveBeenCalledOnce())
expect((watcher as any).ccAppliedLifecycleGeneration).toBe(lifecycleGeneration)
- expect((watcher as any).ccFleetRetryTimer).toBeNull()
await (watcher as any).performHostResync()
expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(2)
@@ -3766,9 +3864,7 @@ describe('McpServerWatcher CommunicationChannel cache recovery', () => {
try {
const staleGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
await (watcher as any).requestHostFleetReconcile('fail-closed', staleGeneration)
- expect((watcher as any).ccFleetRetryTimer).not.toBeNull()
const currentGeneration = (watcher as any).beginCommunicationChannelLifecycleTransition()
- expect((watcher as any).ccFleetRetryTimer).toBeNull()
await (watcher as any).requestHostFleetReconcile('recovered', currentGeneration)
expect(mocks.hostReconcileHosts).toHaveBeenCalledTimes(2)
@@ -4268,7 +4364,9 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
.mockResolvedValue(undefined)
const watcher = new McpServerWatcher()
;(watcher as any).ccCacheSynced = true
- ;(watcher as any).ccAppliedLifecycleGeneration = (watcher as any).ccLifecycleGeneration
+ ;(watcher as any).hostFleetScheduler.markLifecycleApplied(
+ (watcher as any).ccLifecycleGeneration
+ )
const first = (watcher as any).runHostResync() as Promise<void>
await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledTimes(1))
@@ -4361,11 +4459,11 @@ describe('McpServerWatcher Host periodic resync serialization', () => {
if (requests.length === 1) await activePass.promise
}
)
- ;(watcher as any).hostFleetInputRevision = 1
+ ;(watcher as any).hostFleetScheduler.bumpInputRevision()
const first = (watcher as any).requestHostFleetReconcile('active') as Promise<void>
- ;(watcher as any).hostFleetInputRevision = 2
+ ;(watcher as any).hostFleetScheduler.bumpInputRevision()
const second = (watcher as any).requestHostFleetReconcile('pending-v2') as Promise<void>
- ;(watcher as any).hostFleetInputRevision = 3
+ ;(watcher as any).hostFleetScheduler.bumpInputRevision()
const third = (watcher as any).requestHostFleetReconcile('pending-v3') as Promise<void>
activePass.resolve(undefined)
@@ -5550,7 +5648,8 @@ describe('McpServerWatcher Host watch generation', () => {
) as Promise<void>
await vi.waitFor(() => expect(mocks.watch).toHaveBeenCalledOnce())
- const internal = (watcher as any).hostFleetReconcileInFlight.promise as Promise<void>
+ const internal = (watcher as any).hostFleetScheduler.hostFleetReconcileInFlight
+ .promise as Promise<void>
expect((watcher as any).hosts.has('snapshot-host')).toBe(true)
watcher.stop()
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index e58f853aa..815c54b12 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -14,9 +14,19 @@ import {
} from './administrativeOutcomeReporter'
import { BindingDef, BindingPolicyReconciler } from './bindingPolicyReconciler'
import { config } from './config'
+import {
+ ExternalEgressConvergenceCoordinator,
+ type ExternalEgressRetryHandle,
+ type ExternalEgressWatchEventType,
+} from './externalEgressConvergenceCoordinator'
import { gfsDefaultFactoryConfig } from './gfsConfig'
import { GfsReconciler } from './gfsReconciler'
import { ControlApiGfsSeedClient } from './gfsSeedClient'
+import {
+ type HostFleetReconcileMode,
+ type HostFleetReconcileRequest,
+ HostFleetScheduler,
+} from './hostFleetScheduler'
import {
HostFleetReconcileError,
type HostReconcileSource,
@@ -95,16 +105,12 @@ const PLURAL_HOSTS = 'hosts'
const PLURAL_SHAREDFILESYSTEMS = 'sharedfilesystems'
const PLURAL_GLOBALFILESYSTEMS = 'globalfilesystems'
const PLURAL_COMMUNICATIONCHANNELS = 'communicationchannels'
-const EXTERNAL_EGRESS_RETRY_DELAYS_MS = [5000, 15000, 30000]
-const EXTERNAL_EGRESS_RESYNC_MAX_CONCURRENCY = 10
-const EXTERNAL_EGRESS_RESYNC_JITTER_MS = 5000
// Before readiness was decoupled, a failed initial McpServer or NetworkPolicy
// sweep made provider.start() fail and Kubernetes restarted HCC. These retries
// retain that convergence guarantee now that the sweeps run in the background.
const INITIAL_CONVERGENCE_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 300000]
const INVENTORY_CACHE_RECOVERY_RETRY_MS = 5000
const COMMUNICATION_CHANNEL_CACHE_RECOVERY_RETRY_MS = 5000
-const COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS = [5000, 15000, 30000, 60000, 300000]
const HOST_CACHE_RECOVERY_RETRY_MS = 5000
const HOST_WATCH_RECONCILE_RETRY_DELAYS_MS = [5000, 15000, 30000]
// Wake-pending Hosts get immediate per-Host admission after watch recovery
@@ -131,10 +137,8 @@ type HostSnapshot = {
resourceVersion?: string
}
-type HostFleetReconcileMode = 'full' | 'lifecycle'
type HostInventoryRecoveryCause = 'cold-start' | 'watch-recovery'
type HostWatchEventType = 'ADDED' | 'MODIFIED' | 'DELETED'
-type McpServerWatchEventType = 'ADDED' | 'MODIFIED' | 'DELETED'
type InitialConvergenceLane = 'McpServer' | 'NetworkPolicy'
type HostInventoryRecoveryRequest = {
@@ -194,80 +198,6 @@ type KeyedReconciliationQueue = {
references: number
}
-class AsyncConcurrencyLimiter {
- private active = 0
- private readonly waiters: Array<() => void> = []
-
- constructor(private readonly limit: number) {}
-
- async run<T>(work: () => Promise<T>): Promise<T> {
- if (this.active >= this.limit) {
- await new Promise<void>(resolve => this.waiters.push(resolve))
- }
- this.active += 1
- try {
- return await work()
- } finally {
- this.active -= 1
- this.waiters.shift()?.()
- }
- }
-}
-
-type ExternalEgressRetryIntent = {
- sequence: number
- type: McpServerWatchEventType
- server: McpServerCRD
-}
-
-type HostFleetReconcileRequest = {
- reason: string
- mode: HostFleetReconcileMode
- ccLifecycleGeneration?: number
- inputRevision: number
-}
-
-type PendingHostFleetReconcile = HostFleetReconcileRequest & {
- promise: Promise<void>
- resolve: () => void
-}
-
-type ActiveHostFleetReconcile = HostFleetReconcileRequest & { promise: Promise<void> }
-
-function hostFleetRequestCovers(
- active: HostFleetReconcileRequest,
- requested: HostFleetReconcileRequest
-): boolean {
- const modeCovered = active.mode === 'full' || requested.mode === 'lifecycle'
- if (!modeCovered) return false
- if (active.inputRevision !== requested.inputRevision) return false
- if (requested.ccLifecycleGeneration === undefined) return true
- return active.ccLifecycleGeneration === requested.ccLifecycleGeneration
-}
-
-function mergeHostFleetRequests(
- pending: HostFleetReconcileRequest,
- requested: HostFleetReconcileRequest
-): HostFleetReconcileRequest {
- const pendingGeneration = pending.ccLifecycleGeneration
- const requestedGeneration = requested.ccLifecycleGeneration
- return {
- reason: requested.reason,
- mode: pending.mode === 'full' || requested.mode === 'full' ? 'full' : 'lifecycle',
- inputRevision: Math.max(pending.inputRevision, requested.inputRevision),
- ccLifecycleGeneration:
- pendingGeneration === undefined
- ? requestedGeneration
- : requestedGeneration === undefined
- ? pendingGeneration
- : Math.max(pendingGeneration, requestedGeneration),
- }
-}
-
-function delay(ms: number): Promise<void> {
- return new Promise(resolve => setTimeout(resolve, ms))
-}
-
type McpServerWatchObject = {
metadata: {
name: string
@@ -719,17 +649,16 @@ export class McpServerWatcher implements McpServerProvider {
private ccWatchGeneration = 0
private ccCacheRecoveryTimer: ReturnType<typeof setTimeout> | null = null
private ccCacheRecoveryInFlight: Promise<boolean> | null = null
- private ccLifecycleGeneration = 0
- private ccAppliedLifecycleGeneration = -1
- private ccFleetRetryTimer: ReturnType<typeof setTimeout> | null = null
- private ccFleetRetryAttempt = 0
- private hostFleetReconcileInFlight: ActiveHostFleetReconcile | null = null
- private hostFleetReconcilePending: PendingHostFleetReconcile | null = null
- private hostFleetInputRevision = 0
- private resolveHostFleetShutdown: () => void = () => {}
- private readonly hostFleetShutdown = new Promise<void>(resolve => {
- this.resolveHostFleetShutdown = resolve
+ private readonly hostFleetScheduler = new HostFleetScheduler({
+ perform: request => this.performHostFleetReconcile(request),
+ recordRequest: result => hostFleetRequestsTotal.inc({ result }),
})
+ private get ccLifecycleGeneration(): number {
+ return this.hostFleetScheduler.currentLifecycleGeneration
+ }
+ private get ccAppliedLifecycleGeneration(): number {
+ return this.hostFleetScheduler.appliedLifecycleGeneration
+ }
private hostResyncInFlight: Promise<void> | null = null
private changeCallback?: () => void
private stopped = false
@@ -741,15 +670,16 @@ export class McpServerWatcher implements McpServerProvider {
private gfsReconciler: GfsReconciler
private readonly infrastructureTelemetryReporter?: InfrastructureTelemetryReporter
private readonly administrativeOutcomeReporter?: AdministrativeOutcomeReporter
- private readonly externalEgressRetryTimers = new Map<string, ReturnType<typeof setTimeout>>()
- private readonly externalEgressRetryAttempts = new Map<string, number>()
- private readonly externalEgressRetryIntents = new Map<string, ExternalEgressRetryIntent>()
- private externalEgressRetrySequence = 0
- private readonly externalEgressRetryLimiter = new AsyncConcurrencyLimiter(
- EXTERNAL_EGRESS_RESYNC_MAX_CONCURRENCY
- )
- private readonly externalEgressInFlight = new Map<string, Promise<void>>()
- private externalEgressResyncInFlight: Promise<void> | null = null
+ private readonly externalEgressCoordinator = new ExternalEgressConvergenceCoordinator({
+ listServers: () => [...this.servers.values()],
+ getCurrentServer: name => this.servers.get(name),
+ sameDesiredRevision: sameMcpServerDesiredRevision,
+ enqueue: (server, work) => this.enqueueMcpServerReconciliation(server, work),
+ mutate: (type, server, options) =>
+ this.performExternalEgressMutation(type, server, options.deleteAllowed),
+ replay: (type, server, retry) =>
+ this.reconcileMcpServerWatchEvent(type, server, this.mcpWatchGeneration, retry),
+ })
private readonly initialConvergenceRetryTimers = new Map<
InitialConvergenceLane,
ReturnType<typeof setTimeout>
@@ -770,7 +700,6 @@ export class McpServerWatcher implements McpServerProvider {
// rotation eventually catches up even after a missed MODIFIED event.
// Disabled when interval <= 0 (tests).
private resyncTimer: ReturnType<typeof setInterval> | null = null
- private externalEgressResyncTimer: ReturnType<typeof setInterval> | null = null
// Periodic SharedFileSystem resync (#592): the SFS watch fires only on SFS CRD
// changes, not on PVC binding / wfc pod readiness, so a SharedFileSystem that
// reported Initializing/Degraded needs a periodic re-reconcile to converge to a
@@ -1017,6 +946,24 @@ export class McpServerWatcher implements McpServerProvider {
})
}
+ private async authorizeMcpServerDeleteOrRetry(
+ server: McpServerCRD,
+ watchGeneration: number
+ ): Promise<boolean> {
+ try {
+ return await this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration)
+ } catch (error) {
+ console.error(
+ `[K8s] Authoritative absence check failed for deleted McpServer ${server.name}; ` +
+ 'cleanup blocked until retry:',
+ error
+ )
+ this.scheduleExternalEgressRetry('DELETED', server)
+ this.changeCallback?.()
+ return false
+ }
+ }
+
private async contextAbsentForDelete(
name: string,
namespace: string,
@@ -1188,7 +1135,7 @@ export class McpServerWatcher implements McpServerProvider {
if (this.stopped) return false
await this.restartContextWatch(snapshot)
if (this.stopped) return false
- this.hostFleetInputRevision += 1
+ this.hostFleetScheduler.bumpInputRevision()
void this.runInitialNetworkPolicyConvergence()
void this.runInitialSharedFileSystemConvergence()
if (this.hostCacheSynced) {
@@ -1239,57 +1186,15 @@ export class McpServerWatcher implements McpServerProvider {
}
private beginCommunicationChannelLifecycleTransition(): number {
- this.ccLifecycleGeneration += 1
- this.ccFleetRetryAttempt = 0
- if (this.ccFleetRetryTimer) {
- clearTimeout(this.ccFleetRetryTimer)
- this.ccFleetRetryTimer = null
- }
- return this.ccLifecycleGeneration
+ return this.hostFleetScheduler.beginLifecycleTransition()
}
private markCommunicationChannelLifecycleApplied(generation: number): void {
- if (generation !== this.ccLifecycleGeneration) return
- this.ccAppliedLifecycleGeneration = generation
- this.ccFleetRetryAttempt = 0
- if (this.ccFleetRetryTimer) {
- clearTimeout(this.ccFleetRetryTimer)
- this.ccFleetRetryTimer = null
- }
+ this.hostFleetScheduler.markLifecycleApplied(generation)
}
private scheduleCommunicationChannelFleetRetry(request: HostFleetReconcileRequest): void {
- const generation = request.ccLifecycleGeneration
- if (generation === undefined) return
- if (
- this.stopped ||
- generation !== this.ccLifecycleGeneration ||
- generation === this.ccAppliedLifecycleGeneration ||
- this.ccFleetRetryTimer
- ) {
- return
- }
- const delayIndex = Math.min(
- this.ccFleetRetryAttempt,
- COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS.length - 1
- )
- const retryDelay = COMMUNICATION_CHANNEL_FLEET_RETRY_DELAYS_MS[delayIndex]
- this.ccFleetRetryAttempt += 1
- this.ccFleetRetryTimer = setTimeout(() => {
- this.ccFleetRetryTimer = null
- if (
- this.stopped ||
- generation !== this.ccLifecycleGeneration ||
- generation === this.ccAppliedLifecycleGeneration
- ) {
- return
- }
- void this.requestHostFleetReconcile(
- 'CommunicationChannel lifecycle convergence retry',
- generation,
- request.mode
- )
- }, retryDelay)
+ this.hostFleetScheduler.scheduleLifecycleRetry(request)
}
/**
@@ -1843,80 +1748,7 @@ export class McpServerWatcher implements McpServerProvider {
ccLifecycleGeneration?: number,
mode?: HostFleetReconcileMode
): Promise<void> {
- if (this.stopped) return Promise.resolve()
- const requestMode = mode ?? (ccLifecycleGeneration === undefined ? 'full' : 'lifecycle')
- if (
- ccLifecycleGeneration !== undefined &&
- (ccLifecycleGeneration !== this.ccLifecycleGeneration ||
- (requestMode === 'lifecycle' &&
- ccLifecycleGeneration === this.ccAppliedLifecycleGeneration))
- ) {
- return Promise.resolve()
- }
-
- const request: HostFleetReconcileRequest = {
- reason,
- mode: requestMode,
- ccLifecycleGeneration,
- inputRevision: this.hostFleetInputRevision,
- }
- const active = this.hostFleetReconcileInFlight
- if (!active) {
- hostFleetRequestsTotal.inc({ result: 'started' })
- return this.waitForHostFleetOrShutdown(this.startHostFleetReconcile(request))
- }
- if (hostFleetRequestCovers(active, request)) {
- hostFleetRequestsTotal.inc({ result: 'coalesced' })
- return this.waitForHostFleetOrShutdown(active.promise)
- }
-
- if (!this.hostFleetReconcilePending) {
- let resolve!: () => void
- const promise = new Promise<void>(resolvePromise => {
- resolve = resolvePromise
- })
- this.hostFleetReconcilePending = {
- ...request,
- promise,
- resolve,
- }
- } else {
- const merged = mergeHostFleetRequests(this.hostFleetReconcilePending, request)
- this.hostFleetReconcilePending.reason = merged.reason
- this.hostFleetReconcilePending.mode = merged.mode
- this.hostFleetReconcilePending.ccLifecycleGeneration = merged.ccLifecycleGeneration
- this.hostFleetReconcilePending.inputRevision = merged.inputRevision
- }
- // The request did not start its own pass; it is queued behind the active one.
- hostFleetRequestsTotal.inc({ result: 'coalesced' })
- return this.waitForHostFleetOrShutdown(this.hostFleetReconcilePending.promise)
- }
-
- private waitForHostFleetOrShutdown(coverage: Promise<void>): Promise<void> {
- return Promise.race([coverage, this.hostFleetShutdown])
- }
-
- private startHostFleetReconcile(request: HostFleetReconcileRequest): Promise<void> {
- const promise = this.performHostFleetReconcile(request)
- const active: ActiveHostFleetReconcile = { ...request, promise }
- this.hostFleetReconcileInFlight = active
-
- const settle = () => {
- if (this.hostFleetReconcileInFlight !== active) return
- this.hostFleetReconcileInFlight = null
- const pending = this.hostFleetReconcilePending
- this.hostFleetReconcilePending = null
- if (!pending) return
- if (this.stopped) {
- pending.resolve()
- return
- }
- hostFleetRequestsTotal.inc({ result: 'trailing' })
- const trailing = this.startHostFleetReconcile(pending)
- void trailing.then(pending.resolve, pending.resolve)
- }
- void promise.then(settle, settle)
- return promise
+ return this.hostFleetScheduler.request(reason, ccLifecycleGeneration, mode)
}
private contextsReferencingSfs(sfsName: string): Array<{ namespace: string; name: string }> {
@@ -2377,8 +2209,10 @@ export class McpServerWatcher implements McpServerProvider {
}
// SFS/GFS retain their established eventual-resync contract. McpServer,
- // Context, CommunicationChannel and Host use authoritative LIST-to-WATCH
- // handoffs before readiness; full convergence remains outside readiness.
+ // Context and Host require authoritative LIST-to-WATCH handoffs before
+ // readiness. CommunicationChannel recovery instead fails safe by preserving
+ // replicas and disabling stateless suspension; full convergence remains
+ // outside readiness for every inventory.
await this.startSharedFileSystemWatch()
await this.startGlobalFileSystemWatch()
@@ -2444,14 +2278,7 @@ export class McpServerWatcher implements McpServerProvider {
}
const externalEgressResyncSec = config.externalEgressResyncIntervalSec
- if (externalEgressResyncSec > 0) {
- this.externalEgressResyncTimer = setInterval(() => {
- void this.runExternalEgressResync()
- }, externalEgressResyncSec * 1000)
- console.log(
- `[K8s] External egress periodic DNS resync enabled (every ${externalEgressResyncSec}s)`
- )
- }
+ this.externalEgressCoordinator.startPeriodicResync(externalEgressResyncSec)
// Full convergence is observable and retains each lane's existing retry or
// periodic-resync contract, but it no longer extends provider.start() or
@@ -2477,7 +2304,7 @@ export class McpServerWatcher implements McpServerProvider {
try {
const initialServers = [...this.servers.values()]
const initialExternalEgressGates =
- this.reconcileInitialExternalEgressBeforeRuntime(initialServers)
+ this.externalEgressCoordinator.prepareStartupGates(initialServers)
if (this.stopped) return
console.log('[K8s] Running initial McpServer background reconciliation...')
await this.reconciler.fullReconcile(initialServers, {
@@ -2487,10 +2314,7 @@ export class McpServerWatcher implements McpServerProvider {
name: serverName,
namespace: config.namespace,
}
- const externalEgressReady = initialExternalEgressGates.get(
- this.externalEgressRetryKey(laneOwner)
- )
- if (externalEgressReady && !(await externalEgressReady)) return
+ if (!(await initialExternalEgressGates.waitFor(laneOwner))) return
if (this.stopped) return
await this.enqueueMcpServerReconciliation(laneOwner, work)
},
@@ -3031,128 +2855,7 @@ export class McpServerWatcher implements McpServerProvider {
}
private runExternalEgressResync(): Promise<void> {
- if (this.externalEgressResyncInFlight) return this.externalEgressResyncInFlight
- const run = this.runExternalEgressResyncCore().finally(() => {
- if (this.externalEgressResyncInFlight === run) {
- this.externalEgressResyncInFlight = null
- }
- })
- this.externalEgressResyncInFlight = run
- return run
- }
-
- private async runExternalEgressResyncCore(): Promise<void> {
- if (this.stopped) return
- const servers = [...this.servers.values()]
- .filter(server => (server.spec.egressBindings?.length ?? 0) > 0)
- .sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`))
-
- if (servers.length === 0) return
-
- console.log(`[K8s] Periodic external egress DNS resync: ${servers.length} McpServer(s)`)
- let index = 0
- const workers = Array.from(
- { length: Math.min(EXTERNAL_EGRESS_RESYNC_MAX_CONCURRENCY, servers.length) },
- async () => {
- while (!this.stopped) {
- const server = servers[index++]
- if (!server) return
- const key = this.externalEgressRetryKey(server)
- if (this.externalEgressInFlight.has(key)) {
- console.log(`[K8s] Skipping external egress resync for ${key}; reconcile in flight`)
- continue
- }
- const jitterMs = Math.floor(Math.random() * EXTERNAL_EGRESS_RESYNC_JITTER_MS)
- if (jitterMs > 0) await delay(jitterMs)
- if (this.stopped) return
- await this.enqueueMcpServerReconciliation(server, async () => {
- // The fleet snapshot above selects work only. Resolve desired state
- // after entering the same per-server FIFO lane as watch and retry
- // effects, so a newer revision can never be overwritten by stale
- // periodic work.
- const current = this.servers.get(server.name)
- if (
- this.stopped ||
- !current ||
- current.namespace !== server.namespace ||
- (current.spec.egressBindings?.length ?? 0) === 0
- ) {
- return
- }
- try {
- // A pending intent represents the full ordered pipeline, not only
- // DNS state. Continue it in this same per-server FIFO lane so a
- // successful periodic refresh also heals runtime and bindings.
- const retryIntent = this.externalEgressRetryIntents.get(key)
- if (retryIntent) {
- await this.retryExternalEgressCore(retryIntent)
- return
- }
- await this.runExternalEgressOnce('MODIFIED', current, {
- clearRetryOnSuccess: false,
- })
- } catch (error) {
- console.error(`[K8s] External egress periodic resync failed for ${key}:`, error)
- this.scheduleExternalEgressRetry('MODIFIED', current)
- }
- })
- }
- }
- )
- await Promise.all(workers)
- }
-
- private reconcileInitialExternalEgressBeforeRuntime(
- servers: McpServerCRD[]
- ): Map<string, Promise<boolean>> {
- const gates = new Map<string, Promise<boolean>>()
- const serversWithExternalEgress = servers
- .filter(server => (server.spec.egressBindings?.length ?? 0) > 0)
- .sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`))
-
- if (serversWithExternalEgress.length === 0) return gates
-
- console.log(
- `[K8s] Reconciling external egress before startup runtime reconciliation for ` +
- `${serversWithExternalEgress.length} McpServer(s)`
- )
-
- const limiter = new AsyncConcurrencyLimiter(EXTERNAL_EGRESS_RESYNC_MAX_CONCURRENCY)
- for (const selected of serversWithExternalEgress) {
- const key = this.externalEgressRetryKey(selected)
- const gate = limiter.run(async () => {
- let ready = false
- await this.enqueueMcpServerReconciliation(selected, async () => {
- if (this.stopped) return
- const current = this.servers.get(selected.name)
- if (
- !current ||
- current.namespace !== selected.namespace ||
- !sameMcpServerDesiredRevision(selected, current)
- ) {
- return
- }
- try {
- await this.runExternalEgressOnce('MODIFIED', current)
- const latest = this.servers.get(selected.name)
- ready =
- !this.stopped &&
- latest !== undefined &&
- sameMcpServerDesiredRevision(selected, latest)
- } catch (error) {
- console.error(
- `[K8s] Initial external egress reconciliation failed for ${key}; ` +
- 'runtime reconciliation will stay blocked until retry succeeds:',
- error
- )
- this.scheduleExternalEgressRetry('MODIFIED', current)
- }
- })
- return ready
- })
- gates.set(key, gate)
- }
- return gates
+ return this.externalEgressCoordinator.runResync()
}
/**
@@ -3197,25 +2900,23 @@ export class McpServerWatcher implements McpServerProvider {
}
await this.enqueueMcpServerReconciliation(server, () =>
- this.reconcileMcpServerWatchEvent(type, server, watchGeneration)
+ this.reconcileMcpServerWatchEvent(
+ type as ExternalEgressWatchEventType,
+ server,
+ watchGeneration
+ )
)
}
}
private async reconcileMcpServerWatchEvent(
- type: string,
+ type: ExternalEgressWatchEventType,
server: McpServerCRD,
watchGeneration: number,
- retryIntent?: ExternalEgressRetryIntent
+ retry?: ExternalEgressRetryHandle
): Promise<void> {
if (this.stopped || watchGeneration !== this.mcpWatchGeneration) return
- if (
- retryIntent &&
- this.externalEgressRetryIntents.get(this.externalEgressRetryKey(retryIntent.server))
- ?.sequence !== retryIntent.sequence
- ) {
- return
- }
+ if (retry && !retry.isCurrent()) return
const current = this.servers.get(server.name)
if (type === 'DELETED') {
// A same-name recreation may already be accepted while this callback
@@ -3229,11 +2930,10 @@ export class McpServerWatcher implements McpServerProvider {
// External egress is part of the workload's pre-start contract. Reconcile
// it before HCC creates or updates any managed runtime Deployment so a
// stdio MCP with egressBindings cannot start before ExternalEgressReady.
+ let retryCompletion: ExternalEgressRetryHandle | undefined
if (type === 'ADDED' || type === 'MODIFIED') {
try {
- await this.runExternalEgressOnce(type, server, {
- clearRetryOnSuccess: retryIntent === undefined,
- })
+ retryCompletion = await this.runExternalEgressOnce(type, server, { retry })
} catch (error) {
console.error(
`[K8s] External egress reconciliation failed for ${server.name}; runtime reconciliation blocked:`,
@@ -3246,11 +2946,11 @@ export class McpServerWatcher implements McpServerProvider {
} else {
const deleteAllowed = () =>
this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration)
- if (!(await deleteAllowed())) return
+ if (!(await this.authorizeMcpServerDeleteOrRetry(server, watchGeneration))) return
try {
- await this.runExternalEgressOnce(type, server, {
- clearRetryOnSuccess: retryIntent === undefined,
+ retryCompletion = await this.runExternalEgressOnce(type, server, {
deleteAllowed,
+ retry,
})
} catch (error) {
console.error(
@@ -3266,9 +2966,7 @@ export class McpServerWatcher implements McpServerProvider {
if (type === 'ADDED' || type === 'MODIFIED') {
if (!this.mcpServerWatchEffectIsCurrent(server, watchGeneration)) return
server = this.servers.get(server.name)!
- } else if (
- !(await this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration))
- ) {
+ } else if (!(await this.authorizeMcpServerDeleteOrRetry(server, watchGeneration))) {
return
}
@@ -3289,9 +2987,7 @@ export class McpServerWatcher implements McpServerProvider {
if (type === 'ADDED' || type === 'MODIFIED') {
if (!this.mcpServerWatchEffectIsCurrent(server, watchGeneration)) return
server = this.servers.get(server.name)!
- } else if (
- !(await this.mcpServerAbsentForDelete(server.name, server.namespace, watchGeneration))
- ) {
+ } else if (!(await this.authorizeMcpServerDeleteOrRetry(server, watchGeneration))) {
return
}
@@ -3343,7 +3039,7 @@ export class McpServerWatcher implements McpServerProvider {
return
}
- if (retryIntent) this.clearExternalEgressRetryIntent(retryIntent)
+ retryCompletion?.complete()
this.changeCallback?.()
}
@@ -3381,154 +3077,42 @@ export class McpServerWatcher implements McpServerProvider {
return watchGeneration
}
- private externalEgressRetryKey(server: Pick<McpServerCRD, 'name' | 'namespace'>): string {
- return `${server.namespace}/${server.name}`
- }
-
private mcpServerWatchEffectIsCurrent(expected: McpServerCRD, watchGeneration: number): boolean {
if (this.stopped || watchGeneration !== this.mcpWatchGeneration) return false
const current = this.servers.get(expected.name)
return current !== undefined && sameMcpServerDesiredRevision(expected, current)
}
- private async runExternalEgressOnce(
- type: string,
+ private runExternalEgressOnce(
+ type: ExternalEgressWatchEventType,
server: McpServerCRD,
options: {
- clearRetryOnSuccess?: boolean
deleteAllowed?: () => Promise<boolean>
+ retry?: ExternalEgressRetryHandle
} = {}
- ): Promise<void> {
- if (this.stopped) return
- const clearRetryOnSuccess = options.clearRetryOnSuccess ?? true
- const key = this.externalEgressRetryKey(server)
- const existing = this.externalEgressInFlight.get(key)
- if (existing) {
- console.warn(`[K8s] Waiting for external egress reconcile for ${key}; already in flight`)
- await existing
- if (this.stopped) return
- }
-
- const run = (async () => {
- if (type === 'DELETED') {
- await this.netPolReconciler.cleanupExternalEgress(
- server.name,
- server.namespace,
- undefined,
- options.deleteAllowed
- )
- } else {
- await this.netPolReconciler.reconcileExternalEgress(server)
- }
- })()
- this.externalEgressInFlight.set(key, run)
- try {
- await run
- if (clearRetryOnSuccess) {
- this.clearExternalEgressRetry(server)
- }
- } finally {
- if (this.externalEgressInFlight.get(key) === run) {
- this.externalEgressInFlight.delete(key)
- }
- }
- }
-
- private clearExternalEgressRetry(server: Pick<McpServerCRD, 'name' | 'namespace'>): void {
- const key = this.externalEgressRetryKey(server)
- const timer = this.externalEgressRetryTimers.get(key)
- if (timer) {
- clearTimeout(timer)
- this.externalEgressRetryTimers.delete(key)
- }
- this.externalEgressRetryAttempts.delete(key)
- this.externalEgressRetryIntents.delete(key)
- }
-
- private clearExternalEgressRetryIntent(intent: ExternalEgressRetryIntent): void {
- const key = this.externalEgressRetryKey(intent.server)
- if (this.externalEgressRetryIntents.get(key)?.sequence !== intent.sequence) return
- this.clearExternalEgressRetry(intent.server)
- }
-
- private sameExternalEgressRetryTarget(
- previous: ExternalEgressRetryIntent,
- type: McpServerWatchEventType,
- server: McpServerCRD
- ): boolean {
- const previousPresent = previous.type !== 'DELETED'
- const nextPresent = type !== 'DELETED'
- return previousPresent === nextPresent && sameMcpServerDesiredRevision(previous.server, server)
+ ): Promise<ExternalEgressRetryHandle | undefined> {
+ return this.externalEgressCoordinator.reconcile(type, server, options)
}
private scheduleExternalEgressRetry(type: string, server: McpServerCRD): void {
- if (type !== 'ADDED' && type !== 'MODIFIED' && type !== 'DELETED') return
- if (this.stopped) return
-
- const cached = this.servers.get(server.name)
- const retryType: McpServerWatchEventType =
- cached && cached.namespace === server.namespace
- ? type === 'ADDED' && sameMcpServerDesiredRevision(server, cached)
- ? 'ADDED'
- : 'MODIFIED'
- : 'DELETED'
- const retryServer = cached && cached.namespace === server.namespace ? cached : server
- const key = this.externalEgressRetryKey(server)
- const previousIntent = this.externalEgressRetryIntents.get(key)
- if (
- previousIntent &&
- !this.sameExternalEgressRetryTarget(previousIntent, retryType, retryServer)
- ) {
- this.externalEgressRetryAttempts.delete(key)
- }
- const intent: ExternalEgressRetryIntent = {
- sequence: ++this.externalEgressRetrySequence,
- type: retryType,
- server: retryServer,
- }
- this.externalEgressRetryIntents.set(key, intent)
- if (this.externalEgressRetryTimers.has(key)) return
-
- const attempt = Math.min(
- (this.externalEgressRetryAttempts.get(key) ?? 0) + 1,
- EXTERNAL_EGRESS_RETRY_DELAYS_MS.length
- )
- const delayMs = EXTERNAL_EGRESS_RETRY_DELAYS_MS[attempt - 1]
-
- this.externalEgressRetryAttempts.set(key, attempt)
- const capped = attempt === EXTERNAL_EGRESS_RETRY_DELAYS_MS.length
- console.warn(
- `[K8s] Scheduling external egress retry ${attempt}/${EXTERNAL_EGRESS_RETRY_DELAYS_MS.length}` +
- `${capped ? ' (capped)' : ''} ` +
- `for McpServer "${server.name}" in ${delayMs}ms`
- )
-
- const timer = setTimeout(() => {
- this.externalEgressRetryTimers.delete(key)
- const currentIntent = this.externalEgressRetryIntents.get(key)
- if (currentIntent) {
- void this.externalEgressRetryLimiter.run(() => this.retryExternalEgress(currentIntent))
- }
- }, delayMs)
- this.externalEgressRetryTimers.set(key, timer)
- }
-
- private retryExternalEgress(intent: ExternalEgressRetryIntent): Promise<void> {
- return this.enqueueMcpServerReconciliation(intent.server, () =>
- this.retryExternalEgressCore(intent)
- )
+ this.externalEgressCoordinator.scheduleRetry(type, server)
}
- private async retryExternalEgressCore(intent: ExternalEgressRetryIntent): Promise<void> {
- if (this.stopped) return
- const key = this.externalEgressRetryKey(intent.server)
- if (this.externalEgressRetryIntents.get(key)?.sequence !== intent.sequence) return
-
- const current = this.servers.get(intent.server.name)
- const type: McpServerWatchEventType =
- current && current.namespace === intent.server.namespace ? 'MODIFIED' : 'DELETED'
- const server = type === 'DELETED' ? intent.server : current!
- await this.reconcileMcpServerWatchEvent(type, server, this.mcpWatchGeneration, intent)
+ private async performExternalEgressMutation(
+ type: ExternalEgressWatchEventType,
+ server: McpServerCRD,
+ deleteAllowed?: () => Promise<boolean>
+ ): Promise<void> {
+ if (type === 'DELETED') {
+ await this.netPolReconciler.cleanupExternalEgress(
+ server.name,
+ server.namespace,
+ undefined,
+ deleteAllowed
+ )
+ return
+ }
+ await this.netPolReconciler.reconcileExternalEgress(server)
}
/**
@@ -3756,23 +3340,18 @@ export class McpServerWatcher implements McpServerProvider {
*/
async stop(): Promise<void> {
this.stopped = true
+ this.externalEgressCoordinator.stop()
this.retireMcpServerWatch()
this.retireContextWatch()
this.ccCacheSynced = false
this.hostCacheSynced = false
this.hostWatchGeneration += 1
this.ccWatchGeneration += 1
- this.resolveHostFleetShutdown()
- this.hostFleetReconcilePending?.resolve()
- this.hostFleetReconcilePending = null
+ this.hostFleetScheduler.stop()
if (this.ccCacheRecoveryTimer) {
clearTimeout(this.ccCacheRecoveryTimer)
this.ccCacheRecoveryTimer = null
}
- if (this.ccFleetRetryTimer) {
- clearTimeout(this.ccFleetRetryTimer)
- this.ccFleetRetryTimer = null
- }
if (this.hostCacheRecoveryTimer) {
clearTimeout(this.hostCacheRecoveryTimer)
this.hostCacheRecoveryTimer = null
@@ -3799,17 +3378,6 @@ export class McpServerWatcher implements McpServerProvider {
clearInterval(this.gfsResyncTimer)
this.gfsResyncTimer = null
}
- if (this.externalEgressResyncTimer) {
- clearInterval(this.externalEgressResyncTimer)
- this.externalEgressResyncTimer = null
- }
- for (const timer of this.externalEgressRetryTimers.values()) {
- clearTimeout(timer)
- }
- this.externalEgressRetryTimers.clear()
- this.externalEgressRetryAttempts.clear()
- this.externalEgressRetryIntents.clear()
- this.externalEgressInFlight.clear()
for (const timer of this.initialConvergenceRetryTimers.values()) {
clearTimeout(timer)
}