Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): preserve readiness safety certificates
Alfredo Lopez43ad4b78023c
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex d28f9d006..d0353c046 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.180",+ "version": "0.1.181","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.180",+ "version": "0.1.181","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 7fc22a607..97eeb924d 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.180",+ "version": "0.1.181","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/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 9e45c729a..d5e1c7780 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -385,6 +385,71 @@ describe('McpServerWatcher startup', () => {await watcher.stop()})+ it('loads the SharedFileSystem inventory before scheduling the first Host fleet pass', async () => {+ const sharedFileSystemsListed = deferred<{ items: unknown[] }>()+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'sharedfilesystems') return sharedFileSystemsListed.promise+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'sfs-ordering-cc-rv' }, items: [] }+ }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()+ const start = watcher.start()++ try {+ await flushMicrotasks()+ expect(mocks.hostFullReconcile).not.toHaveBeenCalled()++ sharedFileSystemsListed.resolve({+ items: [{ metadata: { name: 'initial-sfs', namespace: 'mcp-host' }, spec: {} }],+ })+ await start+ await vi.waitFor(() => expect(mocks.hostFullReconcile).toHaveBeenCalledOnce())+ expect((watcher as any).sharedFileSystems.get('initial-sfs')).toEqual(+ expect.objectContaining({ name: 'initial-sfs' })+ )+ } finally {+ sharedFileSystemsListed.resolve({ items: [] })+ await start.catch(() => undefined)+ await watcher.stop()+ }+ })++ it('retains Context uid and generation from the authoritative initial snapshot', async () => {+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'contexts') {+ return {+ items: [+ {+ metadata: {+ name: 'identity-context',+ namespace: 'mcp-server',+ uid: 'context-uid-1',+ generation: 7,+ },+ spec: { contextId: 'identity-context', mcpServers: [] },+ },+ ],+ }+ }+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'context-identity-cc-rv' }, items: [] }+ }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()++ try {+ await watcher.start()+ expect((watcher as any).contexts.get('identity-context')).toEqual(+ expect.objectContaining({ uid: 'context-uid-1', generation: 7 })+ )+ } finally {+ await watcher.stop()+ }+ })+it('fails safe bootstrap and keeps readiness unavailable when baseline NetworkPolicies fail', async () => {const policyError = new Error('baseline NetworkPolicies unavailable')mocks.ensureDefaultPolicies.mockRejectedValueOnce(policyError)@@ -1087,7 +1152,7 @@ describe('McpServerWatcher startup', () => {| ((type: string,apiObj: {- metadata: { name: string; namespace: string }+ metadata: { name: string; namespace: string; uid: string }spec: { contextId: string; mcpServers: string[] }}) => Promise<void>)@@ -1150,6 +1215,178 @@ describe('McpServerWatcher startup', () => {}})+ it('does not issue a Context delta certificate before any authoritative safety certificate', async () => {+ const pendingFullSafetyPass = deferred()+ let contextWatchCallback:+ | ((+ type: string,+ apiObj: {+ metadata: { name: string; namespace: string }+ spec: { contextId: string; mcpServers: string[] }+ }+ ) => Promise<void>)+ | undefined+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {+ contextWatchCallback = callback+ return { abort: vi.fn() }+ })+ mocks.netPolFullReconcile.mockImplementationOnce(() => pendingFullSafetyPass.promise)++ const watcher = new McpServerWatcher()+ await (watcher as any).startContextWatch('uncertified-context-delta-rv')+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).hostCacheSynced = true+ ;(watcher as any).mcpWatchGeneration = 1+ ;(watcher as any).contexts.set('uncertified-context', {+ name: 'uncertified-context',+ namespace: 'mcp-server',+ uid: 'uncertified-context-uid',+ spec: { contextId: 'uncertified-context', mcpServers: [] },+ })+ const server = new ContextMapperServer(watcher, 0, undefined, undefined, () =>+ watcher.isReadinessInventoryAuthoritative()+ )+ await server.start()+ server.setReady(true)++ try {+ await contextWatchCallback!('MODIFIED', {+ metadata: {+ name: 'uncertified-context',+ namespace: 'mcp-server',+ uid: 'uncertified-context-uid',+ },+ spec: { contextId: 'uncertified-context', mcpServers: ['delta-server'] },+ })++ expect((await requestReadyOverHttp(server)).statusCode).toBe(503)+ } finally {+ pendingFullSafetyPass.resolve(undefined)+ await watcher.stop()+ await server.stop()+ }+ })++ it('does not let a Context delta certify an outstanding McpServer revision', async () => {+ const pendingFullSafetyPass = deferred()+ let contextWatchCallback:+ | ((+ type: string,+ apiObj: {+ metadata: { name: string; namespace: string; uid: string }+ spec: { contextId: string; mcpServers: string[] }+ }+ ) => Promise<void>)+ | undefined+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {+ contextWatchCallback = callback+ return { abort: vi.fn() }+ })+ mocks.netPolFullReconcile.mockImplementationOnce(() => pendingFullSafetyPass.promise)++ const watcher = new McpServerWatcher()+ await (watcher as any).startContextWatch('server-revision-context-delta-rv')+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).hostCacheSynced = true+ ;(watcher as any).mcpWatchGeneration = 1+ ;(watcher as any).contexts.set('unrelated-context', {+ name: 'unrelated-context',+ namespace: 'mcp-server',+ uid: 'unrelated-context-uid',+ spec: { contextId: 'unrelated-context', mcpServers: [] },+ })+ markNetworkPolicyRevocationAuthoritative(watcher)+ ;(watcher as any).mcpServerDesiredRevision += 1+ const server = new ContextMapperServer(watcher, 0, undefined, undefined, () =>+ watcher.isReadinessInventoryAuthoritative()+ )+ await server.start()+ server.setReady(true)++ try {+ expect((await requestReadyOverHttp(server)).statusCode).toBe(503)+ await contextWatchCallback!('MODIFIED', {+ metadata: {+ name: 'unrelated-context',+ namespace: 'mcp-server',+ uid: 'unrelated-context-uid',+ },+ spec: { contextId: 'unrelated-context', mcpServers: ['delta-server'] },+ })++ expect((await requestReadyOverHttp(server)).statusCode).toBe(503)+ } finally {+ pendingFullSafetyPass.resolve(undefined)+ await watcher.stop()+ await server.stop()+ }+ })++ it('does not let one Context delta certify another Context revision still in flight', async () => {+ const pendingFullSafetyPass = deferred()+ let contextWatchCallback:+ | ((+ type: string,+ apiObj: {+ metadata: { name: string; namespace: string; uid: string }+ spec: { contextId: string; mcpServers: string[] }+ }+ ) => Promise<void>)+ | undefined+ mocks.watch.mockImplementationOnce(async (_path, _options, callback) => {+ contextWatchCallback = callback+ return { abort: vi.fn() }+ })+ mocks.netPolFullReconcile.mockImplementationOnce(() => pendingFullSafetyPass.promise)++ const watcher = new McpServerWatcher()+ await (watcher as any).startContextWatch('parallel-context-delta-rv')+ ;(watcher as any).contextCacheSynced = true+ ;(watcher as any).mcpServerCacheSynced = true+ ;(watcher as any).hostCacheSynced = true+ ;(watcher as any).mcpWatchGeneration = 1+ ;(watcher as any).contexts.set('first-context', {+ name: 'first-context',+ namespace: 'mcp-server',+ uid: 'first-context-uid',+ spec: { contextId: 'first-context', mcpServers: [] },+ })+ ;(watcher as any).contexts.set('second-context', {+ name: 'second-context',+ namespace: 'mcp-server',+ uid: 'second-context-uid',+ spec: { contextId: 'second-context', mcpServers: [] },+ })+ markNetworkPolicyRevocationAuthoritative(watcher)+ // This represents a prior Context change whose global safety sweep is+ // pending. It invalidates the old certificate before the scoped delta.+ ;(watcher as any).contextDesiredRevision += 1+ const server = new ContextMapperServer(watcher, 0, undefined, undefined, () =>+ watcher.isReadinessInventoryAuthoritative()+ )+ await server.start()+ server.setReady(true)++ try {+ await contextWatchCallback!('MODIFIED', {+ metadata: {+ name: 'second-context',+ namespace: 'mcp-server',+ uid: 'second-context-uid',+ },+ spec: { contextId: 'second-context', mcpServers: ['delta-server'] },+ })++ expect((await requestReadyOverHttp(server)).statusCode).toBe(503)+ } finally {+ pendingFullSafetyPass.resolve(undefined)+ await watcher.stop()+ await server.stop()+ }+ })+it.each([['Context', 'contextDesiredRevision'],['McpServer', 'mcpServerDesiredRevision'],diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex 5c4b74f9e..c77458159 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -319,7 +319,12 @@ async function listContextSnapshot(): Promise<ContextSnapshot> {const list = response as {metadata?: { resourceVersion?: string }items: Array<{- metadata: { name: string; namespace?: string }+ metadata: {+ name: string+ namespace?: string+ uid?: string+ generation?: number+ }spec: ContextSpec}>}@@ -327,6 +332,8 @@ async function listContextSnapshot(): Promise<ContextSnapshot> {const contexts = list.items.map(item => ({name: item.metadata.name,namespace: item.metadata.namespace || config.namespace,+ uid: item.metadata.uid,+ generation: item.metadata.generation,spec: item.spec,}))@@ -666,6 +673,10 @@ export class McpServerWatcher implements McpServerProvider {// process-wide convergence tail — they enter the per-Host serializer directly.private hostRecoveryInFlight: ActiveHostInventoryRecovery | null = nullprivate hostCacheRecoveryIntent: HostInventoryRecoveryRequest | null = null+ // Only the cold-start Host fleet pass waits for the initial SFS inventory.+ // The inventory itself remains asynchronous with respect to provider.start+ // and NetworkPolicy readiness certification.+ private initialHostFleetSfsInventory: Promise<boolean> | null = null// B2: tracks whether the CC snapshot is paired with a continuing watch.// Set to true only while a complete snapshot is paired with a live watch;// used by HostReconciler to make fail-closed lifecycle decisions.@@ -1552,12 +1563,26 @@ export class McpServerWatcher implements McpServerProvider {this.enqueueRecoveredHostDeletes(snapshot.hosts, previousNames)}// Request a coalesced background full pass, but do NOT await it before- // declaring watch recovery complete.- void this.requestHostFleetReconcile(- request.convergenceReason,- request.ccLifecycleGeneration,- 'full'- )+ // declaring watch recovery complete. The cold-start pass alone waits for+ // the concurrent SFS LIST: otherwise it can write every Host template+ // without its declared mounts, then immediately roll the fleet again+ // when SFS discovery finishes. NetworkPolicy readiness and start() stay+ // independent from that finite inventory request.+ const requestFleetPass = () => {+ if (this.stopped) return+ void this.requestHostFleetReconcile(+ request.convergenceReason,+ request.ccLifecycleGeneration,+ 'full'+ )+ }+ const initialSfsInventory =+ request.cause === 'cold-start' ? this.initialHostFleetSfsInventory : null+ if (initialSfsInventory) {+ void initialSfsInventory.then(() => requestFleetPass())+ } else {+ requestFleetPass()+ }return snapshot.hosts} catch (error) {// Keep authority unknown, record the failure, and use the existing@@ -2312,6 +2337,14 @@ export class McpServerWatcher implements McpServerProvider {const initialContextSnapshot = await listContextSnapshot()await this.restartContextWatch(initialContextSnapshot)+ // Host templates resolve Context SharedFileSystem references from this+ // cache. Inventory is therefore a fixed startup boundary, not part of the+ // unbounded SFS reconciliation fleet: letting the first Host pass run+ // without it writes mount-less templates and immediately rolls the entire+ // Host fleet a second time once discovery catches up.+ const initialSharedFileSystemInventory = this.startSharedFileSystemInventoryAndWatch()+ this.initialHostFleetSfsInventory = initialSharedFileSystemInventory+// ── CommunicationChannel snapshot + watch — MUST complete before Host fullReconcile ──// A stateless Host may suspend only after this controller has a complete// CommunicationChannel snapshot and a watch continuing from that snapshot's@@ -2429,11 +2462,15 @@ export class McpServerWatcher implements McpServerProvider {// This prevents the startup egress refresh from racing or undoing the safety// pass while keeping readiness independent from both additive fleets.void this.runInitialNetworkPolicyConvergence()- void this.startSharedFileSystemBackgroundLane()+ void initialSharedFileSystemInventory.then(inventoryComplete => {+ if (inventoryComplete && !this.stopped) {+ void this.runInitialSharedFileSystemConvergence()+ }+ })void this.startGlobalFileSystemBackgroundLane()}- private async startSharedFileSystemBackgroundLane(): Promise<void> {+ private async startSharedFileSystemInventoryAndWatch(): Promise<boolean> {let inventoryComplete = falsetry {const initialSfses = await listAllSharedFileSystems()@@ -2452,8 +2489,9 @@ export class McpServerWatcher implements McpServerProvider {this.scheduleSharedFileSystemWatchRestart(5000)}if (inventoryComplete && !this.stopped) {- void this.runInitialSharedFileSystemConvergence()+ return true}+ return false}private async startGlobalFileSystemBackgroundLane(): Promise<void> {@@ -3568,12 +3606,22 @@ export class McpServerWatcher implements McpServerProvider {const watchCallback = async (type: string,- apiObj: { metadata: { name: string; namespace?: string }; spec: ContextSpec }+ apiObj: {+ metadata: {+ name: string+ namespace?: string+ uid?: string+ generation?: number+ }+ spec: ContextSpec+ }) => {if (this.stopped || watchGeneration !== this.contextWatchGeneration) returnconst context: ContextCRD = {name: apiObj.metadata.name,namespace: apiObj.metadata.namespace || config.namespace,+ uid: apiObj.metadata.uid,+ generation: apiObj.metadata.generation,spec: apiObj.spec,}@@ -3582,6 +3630,11 @@ export class McpServerWatcher implements McpServerProvider {// Capture the previous spec before mutating the cache so we can// re-reconcile any SFS that *was* referenced but is no longer.const previous = this.contexts.get(context.name)+ // A scoped Context delta may replace only a prior, fully authoritative+ // safety certificate. Capturing it before this event changes desired+ // state proves there was no outstanding Context or McpServer revocation+ // work that the scoped reconciliation could accidentally certify.+ const previousSafetyCertificate = this.currentNetworkPolicySafetyCertificate()// Cache the context for cross-resource re-reconciliationlet desiredStateChanged = false@@ -3600,12 +3653,17 @@ export class McpServerWatcher implements McpServerProvider {// to restore readiness without waiting for an older pass's additive// fleet. Deletes and identity changes remain fail-closed until the// authoritative full pass certifies their broader cleanup.- if (type === 'MODIFIED' && previous?.spec.contextId === context.spec.contextId) {+ if (+ type === 'MODIFIED' &&+ previous?.uid === context.uid &&+ previous?.spec.contextId === context.spec.contextId &&+ previousSafetyCertificate !== null+ ) {deltaSafetyCertificate = {- contextGeneration: watchGeneration,- serverGeneration: this.mcpWatchGeneration,+ contextGeneration: previousSafetyCertificate.contextGeneration,+ serverGeneration: previousSafetyCertificate.serverGeneration,contextRevision: this.contextDesiredRevision,- serverRevision: this.mcpServerDesiredRevision,+ serverRevision: previousSafetyCertificate.serverRevision,}}void this.runInitialNetworkPolicyConvergence()diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.tsindex 885b1e7ee..9fa4037f9 100644--- a/host-context-controller/src/networkPolicyReconciler.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.test.ts@@ -1265,6 +1265,54 @@ describe('NetworkPolicyReconciler', () => {// ─── L3: External Egress ───────────────────────────────────────────describe('L3 — reconcileExternalEgress', () => {+ it('removes a deterministic safety policy created after its desired-state fence is lost', async () => {+ const server: McpServerCRD = {+ name: 'race-server',+ namespace: 'mcp-server',+ spec: {+ contextRef: 'default',+ image: 'race:latest',+ transport: { type: 'streamableHttp', port: 3000 },+ egressBindings: [{ cidr: '104.18.0.0/16', port: 443 }],+ },+ }+ const createStarted = deferred()+ const releaseCreate = deferred()+ let current = true+ mockApi.createNamespacedNetworkPolicy.mockImplementationOnce(async () => {+ createStarted.resolve(undefined)+ await releaseCreate.promise+ return {+ metadata: {+ name: 'ext-egress-race-server-104-18-0-0-16-443',+ namespace: server.namespace,+ uid: 'created-race-policy',+ resourceVersion: '7',+ },+ }+ })++ const safety = (reconciler as any).reconcileExternalEgressSafety(+ server,+ [{ metadata: { name: 'ext-egress-race-server-stale' } }],+ () => current+ ) as Promise<boolean>++ await createStarted.promise+ current = false+ releaseCreate.resolve(undefined)++ expect(await safety).toBe(false)+ const created = mockApi.createNamespacedNetworkPolicy.mock.calls[0][0].body+ expect(mockApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ name: created.metadata.name,+ namespace: server.namespace,+ body: { preconditions: { uid: 'created-race-policy', resourceVersion: '7' } },+ })+ )+ })+it('refuses to adopt a foreign policy that collides with an external-egress name', async () => {const server: McpServerCRD = {name: 'openai-mcp',diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.tsindex 0235c306c..4ebbb265a 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -2445,11 +2445,18 @@ export class NetworkPolicyReconciler {isCurrent: () => boolean): Promise<boolean> {if (!isCurrent()) return false- await this.networkingApi.createNamespacedNetworkPolicy({+ const created = await this.networkingApi.createNamespacedNetworkPolicy({namespace,body: desired,})- return isCurrent()+ if (isCurrent()) return true++ // The mutation crossed its desired-state fence. Remove exactly the object+ // this request created, even though the old reconciliation is no longer+ // authoritative. The UID/resourceVersion preconditions ensure a+ // replacement or foreign policy with the same name is never deleted.+ await this.deleteSafetyPolicySnapshot(namespace, created)+ return false}/** List L2 egress counterpart policies in mcp-host namespace for a given context. */