Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(reconciler): rebind the readiness-poll ownership fence on superseding reconciles [R4-F1]
Alfredo Lopez22145f234805
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex a6d30af44..a79b69a2f 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.213",+ "version": "0.1.214","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.213",+ "version": "0.1.214","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/image-policy": "file:../packages/image-policy",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex e0b03ef61..41a7b6711 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.213",+ "version": "0.1.214","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/__tests__/reconciler.credentialsRotation.test.ts b/host-context-controller/src/__tests__/reconciler.credentialsRotation.test.tsindex f8d6857cb..d7c268fd1 100644--- a/host-context-controller/src/__tests__/reconciler.credentialsRotation.test.ts+++ b/host-context-controller/src/__tests__/reconciler.credentialsRotation.test.ts@@ -548,3 +548,110 @@ describe('the readiness poll must publish its verdict on the CRD (issue #223)',expect(writes.some(w => w.reason === 'RolloutIncomplete')).toBe(false)})})++describe('poll-window fence survives a superseding reconcile (F1, watch-recovery race)', () => {+ const appsApi = createMockAppsApi()+ const coreApi = createMockCoreApi()+ const customApi = createMockCustomApi()+ let reconciler: McpServerReconciler+ // The inventory-authority generation IS mcpWatchGeneration in production+ // (k8sClient wiring): a routine McpServer watch recovery bumps it.+ let authorityGeneration: number+ let currentServer: McpServerCRD++ // A rollout mid-flight (total 2 vs updated 1) that never converges on its own.+ const midRollout = {+ metadata: { generation: 2, labels: {} },+ spec: { replicas: 1 },+ status: {+ observedGeneration: 2,+ replicas: 2,+ updatedReplicas: 1,+ readyReplicas: 1,+ availableReplicas: 1,+ unavailableReplicas: 0,+ },+ }++ beforeEach(() => {+ vi.clearAllMocks()+ vi.useFakeTimers()+ authorityGeneration = 1+ currentServer = makeServer()+ coreApi.readNamespacedSecret.mockResolvedValue({ data: { 'api-key': stored('old-key') } })+ reconciler = new McpServerReconciler({} as k8s.KubeConfig, {+ appsApi: asAppsApi(appsApi),+ coreApi: asCoreApi(coreApi),+ customApi: asCustomApi(customApi),+ })+ reconciler.setInventoryAuthority(() => ({ known: true, generation: authorityGeneration }))+ reconciler.setResolveCurrentServer(name => (name === 'linear' ? currentServer : undefined))+ })++ afterEach(() => {+ vi.useRealTimers()+ })++ it('rebinds the fence so a converged rollout is recorded after a watch-generation bump (T1)', async () => {+ appsApi.readNamespacedDeployment.mockResolvedValue(midRollout)+ // R1 arms the window under authority generation 1 (timer pending).+ await reconciler.reconcile(makeServer())+ // A routine McpServer watch recovery bumps the inventory-authority generation.+ authorityGeneration = 2+ // R2, current under generation 2, finds R1's pending window and rebinds it.+ await reconciler.reconcile(makeServer())+ // The rollout converges before the (single) pending tick fires.+ appsApi.readNamespacedDeployment.mockResolvedValue(convergedDeployment('linear'))+ await vi.advanceTimersByTimeAsync(5000)++ // Without the rebind, R1's tick evaluates its stale generation-1 fence,+ // self-deletes, and DeploymentReady=True is never written.+ expect(deploymentReadyWrites(customApi).at(-1)?.status).toBe('True')+ expect(+ (reconciler as unknown as { readinessPolls: Map<string, unknown> }).readinessPolls.size+ ).toBe(0)+ })++ it('control: without the generation bump the rollout converges the same way (T2)', async () => {+ appsApi.readNamespacedDeployment.mockResolvedValue(midRollout)+ await reconciler.reconcile(makeServer())+ await reconciler.reconcile(makeServer()) // no bump+ appsApi.readNamespacedDeployment.mockResolvedValue(convergedDeployment('linear'))+ await vi.advanceTimersByTimeAsync(5000)++ expect(deploymentReadyWrites(customApi).at(-1)?.status).toBe('True')+ })++ it('rebind does NOT reset the attempt budget across the bump (E2 guard, T3)', async () => {+ appsApi.readNamespacedDeployment.mockResolvedValue(midRollout) // never converges+ await reconciler.reconcile(makeServer())+ await vi.advanceTimersByTimeAsync(2 * 5000) // 2 attempts consumed+ authorityGeneration = 2+ await reconciler.reconcile(makeServer()) // rebind — must NOT reset attempts+ await vi.advanceTimersByTimeAsync(21 * 5000) // 2 + 21 = 23 attempts, still short of 24++ expect(deploymentReadyWrites(customApi).some(w => w.reason === 'RolloutIncomplete')).toBe(false)+ await vi.advanceTimersByTimeAsync(5000) // the 24th tick+ expect(deploymentReadyWrites(customApi).some(w => w.reason === 'RolloutIncomplete')).toBe(true)+ })++ it('does NOT adopt a same-name recreate — a new uid gets a fresh window (T4)', async () => {+ appsApi.readNamespacedDeployment.mockResolvedValue(midRollout)+ await reconciler.reconcile(makeServer())+ const polls = (reconciler as unknown as { readinessPolls: Map<string, { attempts: number }> })+ .readinessPolls+ const firstWindow = polls.get('linear')+ await vi.advanceTimersByTimeAsync(12 * 5000)++ // Same name, NEW uid: identity retirement (beginStatusTracking), not a+ // rebind, must own this — a rebind adopting the recreate would carry the+ // old window's spent budget.+ const recreated = { ...makeServer(), uid: 'uid-linear-9999' }+ currentServer = recreated+ await reconciler.reconcile(recreated)++ const secondWindow = polls.get('linear')+ expect(secondWindow).not.toBe(firstWindow)+ expect(secondWindow?.attempts).toBe(0)+ })+})diff --git a/host-context-controller/src/reconciler.ts b/host-context-controller/src/reconciler.tsindex a44b18cfd..96b47fbfe 100644--- a/host-context-controller/src/reconciler.ts+++ b/host-context-controller/src/reconciler.ts@@ -203,6 +203,35 @@ interface ReadinessPollState {* WaitingForReplicas by the very reconcile the terminal write triggers.*/detail: string+ /**+ * Mutation fence and CRD object of the LATEST reconcile that owns this+ * window. pollReadiness() REBINDS both on every call that finds the window+ * live: a superseding reconcile (e.g. the fullReconcile after a routine+ * McpServer watch recovery bumps the inventory-authority generation) becomes+ * the window's owner, so the next tick evaluates the CURRENT fence instead of+ * the arming reconcile's stale closure. Without the rebind the stale fence+ * self-terminates the window with no re-arm and — status-only MODIFIED events+ * being suppressed, with no periodic McpServer resync — DeploymentReady=False+ * sticks forever for a healthy rollout (the #223 rotation-timeout symptom,+ * reintroduced under a routine reconnect).+ *+ * Two ORTHOGONAL supersession guards protect this window; do not assume one+ * covers the other (that assumption is exactly how the F1 race was born):+ * - Identity retirement: beginStatusTracking()/clearStatus() retire the+ * window on any CRD uid or CRD-generation change (spec edit, recreate),+ * so a surviving window always has the caller's status identity — a+ * rebind can never adopt a recreate or a superseded desired revision.+ * - In-tick generation reset + recheckRequested: a credential rotation+ * bumps neither CRD uid nor CRD generation (it changes the Deployment's+ * metadata.generation only), so identity retirement does NOT fire; the+ * rotation is instead guarded by the tick's live Deployment read (a new+ * generation resets attempts/exhausted) and by recheckRequested deferring+ * a mid-flight tick's terminal verdict past the rotation's write.+ * A rebind never touches the budget fields (generation/attempts/exhausted/+ * detail) above.+ */+ isCurrent: () => boolean+ server: McpServerCRD}export class McpServerReconciler {@@ -469,9 +498,16 @@ export class McpServerReconciler {const previous = this.readinessPolls.get(name)if (previous !== undefined && (previous.timer !== undefined || previous.ticking)) {- // A window is already running for this server — leave it alone- // (re-arming would reset the attempt budget: the E2 status-update-loop).- // But if its tick is executing RIGHT NOW, the tick's Deployment read may+ // A window is already running for this server — leave its TIMER and+ // BUDGET alone (re-arming would reset the attempt budget: the E2+ // status-update-loop). But this caller is now the window's owner: rebind+ // the mutation fence (and the same-identity server object) so the next+ // tick evaluates the CURRENT fence instead of the arming reconcile's+ // stale closure, which would otherwise self-terminate the window with no+ // re-arm after a routine watch-generation bump.+ previous.isCurrent = isCurrent+ previous.server = server+ // If its tick is executing RIGHT NOW, the tick's Deployment read may// predate the Deployment write that triggered THIS call (a new// generation), so a silent no-op could let the tick end the window on// stale data. Record that a re-check is owed; the tick honors it before@@ -494,6 +530,8 @@ export class McpServerReconciler {attempts: 0,exhausted: previous?.exhausted ?? false,detail: previous?.detail ?? '',+ isCurrent,+ server,}this.readinessPolls.set(name, state)@@ -507,13 +545,13 @@ export class McpServerReconciler {// inventory-authority change) must not keep observing — or writing// status — on behalf of a stale desired state. End the window quietly;// the current reconcile arms its own window after its Deployment write.- if (!isCurrent()) {+ if (!state.isCurrent()) {state.ticking = falseif (this.readinessPolls.get(name) === state) this.readinessPolls.delete(name)return}const rollout = await this.readDeploymentRollout(name, namespace)- if (!isCurrent() || !this.statusIdentityMatches(server)) {+ if (!state.isCurrent() || !this.statusIdentityMatches(state.server)) {state.ticking = falseif (this.readinessPolls.get(name) === state) this.readinessPolls.delete(name)return@@ -566,19 +604,19 @@ export class McpServerReconciler {// always false, so this is the ONLY place a converged rollout is ever// recorded — without it every successful credential rotation would sit// at DeploymentReady=False forever and the UI would report a timeout.- await this.updateStatusConditions(server, true, undefined, isCurrent)+ await this.updateStatusConditions(state.server, true, undefined, state.isCurrent)// Readiness is decoupled from fleet convergence: the poll also// upgrades the persisted, generation-matched Ready condition so a// controller restart can trust the recorded readiness (see getStatus).await this.writeStatusCondition(- server,+ state.server,{type: 'Ready',status: 'True',reason: 'ReconcileSuccess',message: 'Deployment created',},- isCurrent+ state.isCurrent)return}@@ -599,7 +637,7 @@ export class McpServerReconciler {// Give up loudly, on the CRD: a stuck rollout must be visible to the// operator with the numbers that prove it, never left as a stale// condition or a silent Unknown.- await this.updateStatusConditions(server, false, rollout.detail, isCurrent)+ await this.updateStatusConditions(state.server, false, rollout.detail, state.isCurrent)return}