Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): reflect lifecycle outcomes onto the cache under a uid guard [R3-H2]
Alfredo Lopez5108b1bb2f90
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 5a60bed07..0c6745506 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.209",+ "version": "0.1.210","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.209",+ "version": "0.1.210","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 651fb0321..4ae07648f 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.209",+ "version": "0.1.210","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex ac4410e15..072d2b911 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -44,7 +44,7 @@ import {resolveStatelessImagePullPolicy,} from './statelessDeployment'import { EffectiveHostLifecycle, SuspendFromHeartbeatOutcome } from './statelessLifecycle.types'-import { StatelessLifecycleExecutor } from './statelessLifecycleExecutor'+import { ReflectHostOutcomeFn, StatelessLifecycleExecutor } from './statelessLifecycleExecutor'import {CommunicationChannelCRD,HostCRD,@@ -427,6 +427,12 @@ export class HostReconciler {* snapshot for reconcile, and cleanup stays fail-closed (authority unknown).*/private resolveCurrentHost: ((name: string) => HostCRD | undefined) | null = null+ /**+ * H2: late-bound cache reflector. Wired by McpServerWatcher next to+ * setResolveCurrentHost; null (standalone) means lifecycle outcomes reflect+ * only onto the caller's own object (legacy contract).+ */+ private reflectHostOutcome: ReflectHostOutcomeFn | null = null/*** Snapshot the current Host watch authority + generation. Wired by* McpServerWatcher. Default is fail-closed (unknown) so orphan cleanup never@@ -493,6 +499,7 @@ export class HostReconciler {reconcileCore: (host, revalidate) => this.reconcileCore(host, revalidate),prepareHostMutationAdmission: (action, host) =>this.prepareHostMutationAdmission(action, host),+ reflectHostOutcome: (name, uid, apply) => this.reflectHostOutcome?.(name, uid, apply),onLifecycleStatusCommitted: (host, lifecycle) => {const occurredAt = this.now().toISOString()this.infrastructureTelemetryReporter?.enqueueHealthTransition({@@ -558,6 +565,15 @@ export class HostReconciler {this.resolveCurrentHost = fn}+ /**+ * H2: late-bound setter for the guarded cache reflector. Wired by+ * McpServerWatcher from its `hosts` cache (uid-guarded apply). Pattern+ * mirrors setResolveCurrentHost.+ */+ setReflectHostOutcome(fn: ReflectHostOutcomeFn): void {+ this.reflectHostOutcome = fn+ }+/*** Late-bound setter for the Host watch authority/generation snapshot. Wired by* McpServerWatcher so orphan cleanup can require known authority and a stablediff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 4520b4c3d..bc038029e 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -266,6 +266,20 @@ vi.mock('./hostReconciler', () => ({setResolveCurrentHost = vi.fn()setHostWatchAuthority = vi.fn()setHostMutationAuthority = vi.fn()+ // H2: capture the injected uid-guarded cache reflector so Test C can invoke it.+ _reflectHostOutcomeFn:+ | ((name: string, uid: string | undefined, apply: (target: HostCRD) => void) => void)+ | null = null+ setReflectHostOutcome = vi.fn().mockImplementation(function (+ this: {+ _reflectHostOutcomeFn:+ | ((name: string, uid: string | undefined, apply: (target: HostCRD) => void) => void)+ | null+ },+ fn: (name: string, uid: string | undefined, apply: (target: HostCRD) => void) => void+ ) {+ this._reflectHostOutcomeFn = fn+ })_hostMutationDependenciesFn: ((host: HostCRD) => readonly unknown[]) | null = nullsetResolveHostMutationDependencies = vi.fn().mockImplementation(function (this: { _hostMutationDependenciesFn: ((host: HostCRD) => readonly unknown[]) | null },@@ -5532,6 +5546,38 @@ describe('McpServerWatcher wires CC counter into HostReconciler', () => {})describe('McpServerWatcher Host mutation dependency wiring', () => {+ it('H2: wires a uid-guarded cache reflector into HostReconciler', () => {+ const watcher = new McpServerWatcher()+ const reflect = (+ watcher.getHostReconciler() as unknown as {+ _reflectHostOutcomeFn:+ | ((name: string, uid: string | undefined, apply: (target: HostCRD) => void) => void)+ | null+ }+ )._reflectHostOutcomeFn+ if (!reflect) {+ throw new Error('setReflectHostOutcome was never wired by the McpServerWatcher constructor')+ }+ const entry = {+ name: 'h2-host',+ namespace: 'mcp-host',+ uid: 'uid-1',+ spec: { host: 'h2-host', contextRef: 'c', secretRef: 's' },+ } as unknown as HostCRD+ ;(watcher as unknown as { hosts: Map<string, HostCRD> }).hosts.set('h2-host', entry)+ const apply = vi.fn()+ reflect('h2-host', 'uid-1', apply) // positive: current entry, matching uid+ expect(apply).toHaveBeenCalledTimes(1)+ expect(apply).toHaveBeenCalledWith(entry)+ apply.mockClear()+ reflect('h2-host', 'uid-2', apply) // recreation: same name, different uid → skip+ expect(apply).not.toHaveBeenCalled()+ reflect('h2-host', undefined, apply) // fail-closed on missing uid+ expect(apply).not.toHaveBeenCalled()+ reflect('absent-host', 'uid-1', apply) // absent entry → skip+ expect(apply).not.toHaveBeenCalled()+ })+it('tracks only the selected Context, referenced SFS state, and Host-scoped channels', () => {const watcher = new McpServerWatcher()const host = {diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex 64006b508..38210e404 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -819,6 +819,14 @@ export class McpServerWatcher implements McpServerProvider {// entries a delete/newer event has since removed), and orphan cleanup// compares candidates with the CURRENT inventory rather than a pass snapshot.this.hostReconciler.setResolveCurrentHost(name => this.hosts.get(name))+ // H2: reflect committed lifecycle outcomes onto the CURRENT cache entry —+ // but never onto a same-name recreation. uid === undefined fails closed+ // (production watch objects always carry uid).+ this.hostReconciler.setReflectHostOutcome((name, uid, apply) => {+ const cached = this.hosts.get(name)+ if (!cached || uid === undefined || cached.uid !== uid) return+ apply(cached)+ })// Orphan cleanup requires known watch authority and a stable watch// generation; expose both so cleanup fail-closes while authority is unknown// or the watch has been retired mid-pass.diff --git a/host-context-controller/src/statelessLifecycleExecutor.ts b/host-context-controller/src/statelessLifecycleExecutor.tsindex 01d4fda77..f731391ca 100644--- a/host-context-controller/src/statelessLifecycleExecutor.ts+++ b/host-context-controller/src/statelessLifecycleExecutor.ts@@ -42,6 +42,21 @@ const ACTIVE_COMMUNICATION_CHANNELS_REASON = 'ActiveCommunicationChannels'*/const WAKE_REQUESTED_ANNOTATION = 'clerum.io/wake-requested'+/**+ * H2: reflect a committed lifecycle outcome onto the CURRENT canonical cache+ * entry for `name` — but only if that entry still has the admitted `uid`.+ * The receiver (McpServerWatcher) owns the lookup and the uid guard; the+ * executor never touches the cache directly. A same-name recreation with a+ * different uid MUST be skipped silently (the mutation already committed+ * server-side under the old uid; corrupting the new object would be worse+ * than staleness, which the watch/resync repairs).+ */+export type ReflectHostOutcomeFn = (+ name: string,+ uid: string | undefined,+ apply: (target: HostCRD) => void+) => void+/** Constructor-injected seams from HostReconciler (late-bound where needed). */export interface StatelessLifecycleExecutorDeps {appsApi: k8s.AppsV1Api@@ -80,6 +95,7 @@ export interface StatelessLifecycleExecutorDeps {* an authority generation change that happened while the work was waiting.*/prepareHostMutationAdmission?: (action: string, host: HostCRD) => () => HostCRD+ reflectHostOutcome?: ReflectHostOutcomeFnonLifecycleStatusCommitted?: (host: HostCRD, lifecycle: HostLifecycleStatus) => void}@@ -92,6 +108,7 @@ export class StatelessLifecycleExecutor {private readonly isCommunicationChannelCacheSynced: () => booleanprivate readonly reconcileCore: (host: HostCRD, revalidate?: () => HostCRD) => Promise<void>private readonly prepareHostMutationAdmission: (action: string, host: HostCRD) => () => HostCRD+ private readonly reflectHostOutcome: ReflectHostOutcomeFnprivate readonly onLifecycleStatusCommitted: (host: HostCRD,lifecycle: HostLifecycleStatus@@ -143,6 +160,7 @@ export class StatelessLifecycleExecutor {this.reconcileCore = deps.reconcileCorethis.prepareHostMutationAdmission =deps.prepareHostMutationAdmission ?? ((_action, host) => () => host)+ this.reflectHostOutcome = deps.reflectHostOutcome ?? (() => {})this.onLifecycleStatusCommitted = deps.onLifecycleStatusCommitted ?? (() => {})StatelessLifecycleExecutor.warnSingleReplicaInvariantOnce()}@@ -852,7 +870,9 @@ export class StatelessLifecycleExecutor {// legitimately trail either one.const currentAtFollowOn = revalidate?.()if (currentAtFollowOn) this.requireSameHostIdentity(host, currentAtFollowOn)- host.status = writtenStatus+ this.reflectOutcome(host, target => {+ target.status = writtenStatus+ })const reconcileHost = await this.readFreshHost(result.fresh)if (!this.sameHostSpecRevision(host, reconcileHost)) {const error = new Error(@@ -879,12 +899,14 @@ export class StatelessLifecycleExecutor {// the originally admitted instance until the watch delivers the next// MODIFIED event; reflect the final authoritative outcome immediately so// it cannot make a second decision from the pre-follow-on status.- host.uid = reconcileHost.uid- host.generation = reconcileHost.generation- host.resourceVersion = reconcileHost.resourceVersion- host.annotations = reconcileHost.annotations- host.spec = reconcileHost.spec- host.status = reconcileHost.status+ this.reflectOutcome(host, target => {+ target.uid = reconcileHost.uid+ target.generation = reconcileHost.generation+ target.resourceVersion = reconcileHost.resourceVersion+ target.annotations = reconcileHost.annotations+ target.spec = reconcileHost.spec+ target.status = reconcileHost.status+ })// The wake fast-path / drained-pre-scale guard inside reconcile() may// have flipped the host back to active (a wake raced the suspension) —// in that case no scale-down happened, so no phase/metric is emitted.@@ -977,7 +999,10 @@ export class StatelessLifecycleExecutor {if ('skipped' in result || writtenLifecycle === undefined) {return}- host.status = { ...(host.status ?? {}), lifecycle: writtenLifecycle }+ const reflectedStatus = { ...(host.status ?? {}), lifecycle: writtenLifecycle }+ this.reflectOutcome(host, target => {+ target.status = reflectedStatus+ })this.lastWrittenLifecycleStatus.delete(host.name)}@@ -1079,7 +1104,9 @@ export class StatelessLifecycleExecutor {if ('skipped' in result || writtenStatus === undefined) {return}- host.status = writtenStatus+ this.reflectOutcome(host, target => {+ target.status = writtenStatus+ })this.lastWrittenLifecycleStatus.delete(host.name)console.log(`[HostReconciler] Marked stateless Host "${host.name}" draining — control-api now answers {drain:true} from Host.status`@@ -1151,7 +1178,9 @@ export class StatelessLifecycleExecutor {)return}- host.status = writtenStatus+ this.reflectOutcome(host, target => {+ target.status = writtenStatus+ })this.lastWrittenLifecycleStatus.delete(host.name)console.log(`[StatelessLifecycle] host=${host.name} cancel-drain: activity evidence while draining — reverting status to active`@@ -1267,8 +1296,10 @@ export class StatelessLifecycleExecutor {// Reflect the fresh truth on the in-memory object so the heavy// reconcile body derives replicas from the current durable state// instead of the stale event payload.- host.annotations = initialFresh.annotations- host.status = initialFresh.status+ this.reflectOutcome(host, target => {+ target.annotations = initialFresh.annotations+ target.status = initialFresh.status+ })return false}@@ -1327,8 +1358,10 @@ export class StatelessLifecycleExecutor {initialFresh)if ('skipped' in result || writtenLifecycle === undefined) {- host.annotations = latestFresh.annotations- host.status = latestFresh.status+ this.reflectOutcome(host, target => {+ target.annotations = latestFresh.annotations+ target.status = latestFresh.status+ })return false}} catch (err) {@@ -1347,8 +1380,11 @@ export class StatelessLifecycleExecutor {// (assessLifecycle reads host.status) derives replicas from the woken// state instead of re-suspending from the stale event payload. The base// is the FRESH status the write committed over, never the cached spread.- host.annotations = latestFresh.annotations- host.status = { ...(latestFresh.status ?? {}), lifecycle: writtenLifecycle }+ const reflectedStatus = { ...(latestFresh.status ?? {}), lifecycle: writtenLifecycle }+ this.reflectOutcome(host, target => {+ target.annotations = latestFresh.annotations+ target.status = reflectedStatus+ })console.log(`[StatelessWake] host=${host.name} generation=${writtenLifecycle.wakeHandledGeneration} phase=status_flipped ts=${this.now().getTime()}`)@@ -1635,6 +1671,27 @@ export class StatelessLifecycleExecutor {* identity fence. Production watch snapshots always carry UID; if only one* side carries it, fail closed rather than guessing.*/+ /**+ * H2: apply a committed outcome to BOTH visible surfaces:+ * 1. the local working object (`host`) — with a resolver wired this is the+ * admitted CLONE (serializeHeartbeatMutation), so this keeps same-pass+ * logic (assessLifecycle, drained-pre-scale guard, follow-on reconcile)+ * reading the outcome exactly as before; standalone callers (no resolver)+ * get the legacy caller-visible reflection unchanged;+ * 2. the CURRENT cache entry, via the uid-guarded reflector (no-op unless+ * McpServerWatcher wired it).+ * `host.uid` is the admitted identity (admission proved requested.uid ===+ * current.uid; readFreshHost re-proves it), so passing it after mutate() ran+ * is equivalent to passing it before.+ *+ * `mutate` closures MUST only ASSIGN precomputed values — never derive from+ * `target` — so both surfaces receive the identical outcome.+ */+ private reflectOutcome(host: HostCRD, mutate: (target: HostCRD) => void): void {+ mutate(host)+ this.reflectHostOutcome(host.name, host.uid, mutate)+ }+private requireSameHostIdentity(expected: HostCRD, current: HostCRD): void {if (expected.uid === undefined && current.uid === undefined) returnif (expected.uid === undefined || current.uid === undefined || expected.uid !== current.uid) {@@ -1745,8 +1802,10 @@ export class StatelessLifecycleExecutor {// A wake is pending in the fresh read — run the wake transition// instead of the scale-down. Reflect the fresh wake generation on the// in-memory object so downstream writes preserve it.- host.annotations = fresh.annotations- host.status = fresh.status+ this.reflectOutcome(host, target => {+ target.annotations = fresh.annotations+ target.status = fresh.status+ })return {effective: { stateless: true, state: 'active' },lifecycle: { state: 'active', wakeHandledGeneration: freshWakeRequested },@@ -1772,8 +1831,10 @@ export class StatelessLifecycleExecutor {// Reflect fresh onto the in-memory host (mirroring the wake fast-path's// epoch guard) so every downstream write derives from the current// server-side truth instead of the stale event payload.- host.annotations = fresh.annotations- host.status = fresh.status+ this.reflectOutcome(host, target => {+ target.annotations = fresh.annotations+ target.status = fresh.status+ })const freshReason = fresh.status?.lifecycle?.reasonconst preservedReason = isHeartbeatManagedLifecycleReason(freshReason) ? freshReason : undefinedreturn {diff --git a/host-context-controller/test/hostReconciler.heartbeat.test.ts b/host-context-controller/test/hostReconciler.heartbeat.test.tsindex 5ab73f48f..17ac53f0f 100644--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts@@ -2075,3 +2075,89 @@ describe('HostReconciler reconcile — stateless replicas derive from FRESH stat}})})++describe('H2: guarded cache reflection', () => {+ it('reflects a committed lifecycle outcome onto the current cache entry without a watch event', async () => {+ const { reconciler, customApi } = createReconciler()+ const entry = {+ ...makeStatelessHost({+ status: { lifecycle: { state: 'active', wakeHandledGeneration: 0 } },+ }),+ uid: 'uid-1',+ generation: 1,+ resourceVersion: 'rv-1',+ }+ const hosts = new Map<string, HostCRD>([[entry.name, entry]])+ reconciler.setResolveCurrentHost(name => hosts.get(name))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 17 }))+ // Exactly the k8sClient.ts wiring shape (uid-guarded apply onto the cache).+ reconciler.setReflectHostOutcome((name, uid, apply) => {+ const cached = hosts.get(name)+ if (!cached || uid === undefined || cached.uid !== uid) return+ apply(cached)+ })+ customApi.getNamespacedCustomObject.mockResolvedValue({+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: {+ name: entry.name,+ namespace: entry.namespace,+ uid: 'uid-1',+ generation: 1,+ resourceVersion: 'fresh-rv',+ },+ })++ await reconciler.markHostDrainingFromHeartbeat(entry, 0)++ // The status write committed to the API…+ expect(lifecycleStatusWrites(customApi).at(-1)?.lifecycle?.state).toBe('draining')+ // …and — the H2 fix — the committed outcome is visible on the CANONICAL cache+ // entry without waiting for a watch MODIFIED. With the resolver wired, the+ // heartbeat core mutates the admitted clone (Shape A), so this can ONLY be+ // true if the guarded reflector routed the outcome onto the cache entry.+ expect(hosts.get(entry.name)?.status?.lifecycle?.state).toBe('draining')+ })++ it('never reflects a committed outcome onto a same-name recreation with a different uid', async () => {+ const { reconciler, customApi } = createReconciler()+ const entry = {+ ...makeStatelessHost({+ status: { lifecycle: { state: 'active', wakeHandledGeneration: 0 } },+ }),+ uid: 'uid-1',+ generation: 1,+ resourceVersion: 'rv-1',+ }+ const hosts = new Map<string, HostCRD>([[entry.name, entry]])+ const replacement = { ...makeStatelessHost({ name: entry.name }), uid: 'uid-2' }+ reconciler.setResolveCurrentHost(name => hosts.get(name))+ reconciler.setHostWatchAuthority(() => ({ known: true, generation: 17 }))+ reconciler.setReflectHostOutcome((name, uid, apply) => {+ const cached = hosts.get(name)+ if (!cached || uid === undefined || cached.uid !== uid) return+ apply(cached)+ })+ customApi.getNamespacedCustomObject.mockResolvedValue({+ ...freshHostRead({ state: 'active', wakeHandledGeneration: 0 }),+ metadata: {+ name: entry.name,+ namespace: entry.namespace,+ uid: 'uid-1',+ generation: 1,+ resourceVersion: 'fresh-rv',+ },+ })+ // A watch DELETE+ADD recreates the entry (new uid) mid-commit.+ customApi.patchNamespacedCustomObjectStatus.mockImplementation(async () => {+ hosts.set(entry.name, replacement)+ return {}+ })++ await reconciler.markHostDrainingFromHeartbeat(entry, 0)++ // The write committed…+ expect(lifecycleStatusWrites(customApi).at(-1)?.lifecycle?.state).toBe('draining')+ // …but the recreation (uid-2) was NOT corrupted by the stale reflection.+ expect(replacement.status?.lifecycle).toBeUndefined()+ })+})