Skip to content

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

TypeScript

test(hcc): cover reader no-op with producer defaulting

Alfredo Lopez7e74884f665f
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index b2905694f..8e2309e28 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.340",
+ "version": "0.1.341",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.340",
+ "version": "0.1.341",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index 81dfb1b9c..543c8b462 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.340",
+ "version": "0.1.341",
"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__/applyResultAccounting.test.ts b/host-context-controller/src/__tests__/applyResultAccounting.test.ts
new file mode 100644
index 000000000..8cdf331fb
--- /dev/null
+++ b/host-context-controller/src/__tests__/applyResultAccounting.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest'
+import {
+ type ApplyCountStats,
+ type ResourceApplyResult,
+ accumulateApplyResult,
+ applyResultIsWrite,
+} from '../utils'
+
+const ALL_RESULTS: readonly ResourceApplyResult[] = [
+ 'created',
+ 'replaced',
+ 'up_to_date',
+ 'missing',
+ 'not_allowed',
+]
+
+describe('applyResultIsWrite / accumulateApplyResult', () => {
+ it('treats only created and replaced as writes', () => {
+ expect(ALL_RESULTS.filter(applyResultIsWrite)).toEqual(['created', 'replaced'])
+ })
+
+ it('keeps writes + skips === objects for every ResourceApplyResult', () => {
+ const stats: ApplyCountStats = { objects: 0, writes: 0, skips: 0 }
+ for (const result of ALL_RESULTS) accumulateApplyResult(stats, result)
+ expect(stats.writes + stats.skips).toBe(stats.objects)
+ expect(stats.objects).toBe(ALL_RESULTS.length)
+ expect(stats.writes).toBe(2)
+ expect(stats.skips).toBe(3)
+ })
+
+ it('keeps the invariant for an arbitrary mixed sequence', () => {
+ const sequence: ResourceApplyResult[] = [
+ 'up_to_date',
+ 'replaced',
+ 'missing',
+ 'created',
+ 'not_allowed',
+ 'up_to_date',
+ ]
+ const stats: ApplyCountStats = { objects: 0, writes: 0, skips: 0 }
+ for (const result of sequence) accumulateApplyResult(stats, result)
+ expect(stats.objects).toBe(sequence.length)
+ expect(stats.writes + stats.skips).toBe(stats.objects)
+ expect(stats.writes).toBe(2)
+ expect(stats.skips).toBe(4)
+ })
+})
diff --git a/host-context-controller/src/gfsReconciler.ts b/host-context-controller/src/gfsReconciler.ts
index b91e16291..522bf0ddc 100644
--- a/host-context-controller/src/gfsReconciler.ts
+++ b/host-context-controller/src/gfsReconciler.ts
@@ -38,12 +38,19 @@ import {
} from './k8s/gfsFactory'
import { hccLogger } from './logger'
import type { GlobalFileSystemCRD, GlobalFileSystemStatus } from './types'
-import type { ResourceApplyResult } from './utils'
+import { type ResourceApplyResult, accumulateApplyResult } from './utils'
/**
* Minimal Kubernetes surface the reconciler needs. PVCs are create-if-absent
* (their spec is immutable post-bind); everything else is create-or-replace.
*/
+/**
+ * Per-GFS apply outcomes for one reconcile. `objects` counts every apply op,
+ * including the synthetic `writer_hash_skip` and optional `scaleDeployment`
+ * calls. The reader apply is omitted when the writer never went Ready.
+ * `writes + skips === objects` holds, but `objects` is not comparable to the
+ * LlmHook per-resource count.
+ */
export interface GfsResyncStats {
objects: number
writes: number
@@ -58,23 +65,12 @@ function recordGfsApply(
stats: GfsResyncStats,
result: ResourceApplyResult | 'writer_hash_skip'
): void {
- stats.objects += 1
- switch (result) {
- case 'created':
- case 'replaced':
- stats.writes += 1
- return
- case 'up_to_date':
- case 'writer_hash_skip':
- case 'missing':
- case 'not_allowed':
- stats.skips += 1
- return
- default: {
- const exhaustive: never = result
- throw new Error(`unhandled GFS apply result: ${String(exhaustive)}`)
- }
+ if (result === 'writer_hash_skip') {
+ stats.objects += 1
+ stats.skips += 1
+ return
}
+ accumulateApplyResult(stats, result)
}
export interface GfsK8sApi {
diff --git a/host-context-controller/src/k8s/gfsK8sApi.readFirst.test.ts b/host-context-controller/src/k8s/gfsK8sApi.readFirst.test.ts
index f41b46db3..2686ec995 100644
--- a/host-context-controller/src/k8s/gfsK8sApi.readFirst.test.ts
+++ b/host-context-controller/src/k8s/gfsK8sApi.readFirst.test.ts
@@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as k8s from '@kubernetes/client-node'
+import { asApiserverDeployment } from '../__tests__/asApiserverDeployment'
import liveReaderFixture from '../__tests__/fixtures/629/gfsc-reader.deployment.json'
import livePdbFixture from '../__tests__/fixtures/629/gfsc-writer-pdb.json'
import { createsTotal, existenceReadsTotal, writeSkipsTotal } from '../metrics'
-import { podDisruptionBudgetMatchesDesired } from '../utils'
+import { deploymentMatchesDesired, podDisruptionBudgetMatchesDesired } from '../utils'
+import { type GfsFactoryConfig, buildDeployment } from './gfsFactory'
import { K8sGfsApi } from './gfsK8sApi'
const namespace = 'mcp-host'
@@ -350,6 +352,42 @@ describe('K8sGfsApi PodDisruptionBudget no-op gate (T4)', () => {
const REVISION_ANNOTATION = 'deployment.kubernetes.io/revision'
const RESTARTED_AT = 'kubectl.kubernetes.io/restartedAt'
+const readerProducerConfig: GfsFactoryConfig = {
+ gfsNamespace: 'gfs',
+ controlPlaneNamespace: 'control-plane',
+ postgresPodLabels: { app: 'control-postgres' },
+ postgresPort: 5432,
+ gfscImage: 'clerum-gfs-controller:test',
+ gfscImagePullPolicy: 'IfNotPresent',
+ gfscPort: 8087,
+ gfscInitImage: 'busybox:1.36',
+ gfscResources: {
+ requests: { memory: '128Mi', cpu: '100m' },
+ limits: { memory: '256Mi', cpu: '500m' },
+ },
+ jwtPublicKeyConfigMapName: 'gfs-config',
+ jwtPublicKeyConfigMapKey: 'jwt-public-key',
+ pgSecretName: 'gfs-controller-db',
+ pgSecretKey: 'connection-string',
+ readerPgSecretName: 'gfs-controller-reader-db',
+ readerPgSecretKey: 'connection-string',
+ driveName: 'main',
+ tokenAudience: 'gfs-controller',
+}
+
+function producedReader(): k8s.V1Deployment {
+ return buildDeployment(
+ { name: 'gfs', namespace: 'gfs', spec: {} },
+ readerProducerConfig,
+ 'reader'
+ )
+}
+
+/**
+ * Synthetic twin of the captured fixture (revision stripped). These cases
+ * prove annotation merge and fail-open replica drift. They do not put
+ * `buildDeployment` on the desired side — see the producer+defaulting cases.
+ */
function desiredReaderFromFixture(): k8s.V1Deployment {
const desired = structuredClone(liveReaderFixture) as k8s.V1Deployment
if (desired.metadata?.annotations) {
@@ -394,6 +432,48 @@ describe('K8sGfsApi Deployment no-op gate (T3, T8)', () => {
)
}
+ it('T3: the captured fixture is synthetic and does not match buildDeployment', () => {
+ expect(deploymentMatchesDesired(producedReader(), liveReaderFixture as k8s.V1Deployment)).toBe(
+ false
+ )
+ })
+
+ it('T3: skips replace when live is buildDeployment after apiserver defaulting', async () => {
+ const desired = producedReader()
+ const live = asApiserverDeployment(desired)
+ const templateMeta = live.spec?.template?.metadata
+ if (!templateMeta) throw new Error('expected pod template metadata')
+ templateMeta.annotations = {
+ ...templateMeta.annotations,
+ [RESTARTED_AT]: '2026-09-16T20:33:45Z',
+ }
+ const equal = harness('Deployment')
+ equal.read.mockImplementation(async () => {
+ equal.events.push('GET')
+ return live
+ })
+ await equal.api.applyDeployment(desired, namespace)
+ expect(equal.read).toHaveBeenCalledTimes(1)
+ expect(equal.replace).toHaveBeenCalledTimes(0)
+ expect(await deploymentSkipCount()).toBe(1)
+ })
+
+ it('T3: writes when live has a default-filled field the normalizer does not strip', async () => {
+ const desired = producedReader()
+ const live = asApiserverDeployment(desired)
+ if (!live.spec) throw new Error('expected live spec')
+ live.spec.minReadySeconds = 7
+ const drifted = harness('Deployment')
+ drifted.read.mockImplementation(async () => {
+ drifted.events.push('GET')
+ return live
+ })
+ await drifted.api.applyDeployment(desired, namespace)
+ expect(drifted.read).toHaveBeenCalledTimes(1)
+ expect(drifted.replace).toHaveBeenCalledTimes(1)
+ expect(await deploymentSkipCount()).toBe(0)
+ })
+
it('T3: skips replace when the live reader matches after revision merge', async () => {
const desired = desiredReaderFromFixture()
const equal = harness('Deployment')
diff --git a/host-context-controller/src/llmHookReconciler.ts b/host-context-controller/src/llmHookReconciler.ts
index 303239214..22b6adb4d 100644
--- a/host-context-controller/src/llmHookReconciler.ts
+++ b/host-context-controller/src/llmHookReconciler.ts
@@ -42,6 +42,7 @@ import { isAllowedExternalEgressCidr, isPublicDnsHostname } from './networkPolic
import { HostCRD, LlmHookCRD, LlmHookCondition, LlmHookImageTarget, LlmHookStatus } from './types'
import {
type ResourceApplyResult,
+ accumulateApplyResult,
deploymentMatchesDesired,
ensureResource,
getErrorCode,
@@ -55,6 +56,7 @@ import {
serviceMatchesDesired,
} from './utils'
+/** One apply per LlmHook-owned resource. Not comparable to GFS `objects`. */
type LlmHookResyncCounters = { objects: number; writes: number; skips: number }
const llmHookResyncPass = new AsyncLocalStorage<LlmHookResyncCounters>()
@@ -62,22 +64,7 @@ const llmHookResyncPass = new AsyncLocalStorage<LlmHookResyncCounters>()
function recordLlmHookApply(result: ResourceApplyResult): void {
const acc = llmHookResyncPass.getStore()
if (!acc) return
- acc.objects += 1
- switch (result) {
- case 'created':
- case 'replaced':
- acc.writes += 1
- return
- case 'up_to_date':
- case 'missing':
- case 'not_allowed':
- acc.skips += 1
- return
- default: {
- const exhaustive: never = result
- throw new Error(`unhandled LlmHook apply result: ${String(exhaustive)}`)
- }
- }
+ accumulateApplyResult(acc, result)
}
const GROUP = 'clerum.io'
diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.ts
index 7fcb2aacb..035db37f0 100644
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@ -30,6 +30,33 @@ export async function observeCreate<T>(kind: CreateKind, create: () => Promise<T
/** Outcome of a read-first create-or-replace. Callers may ignore this value. */
export type ResourceApplyResult = 'created' | 'replaced' | 'up_to_date' | 'missing' | 'not_allowed'
+/** Counters for one reconciler apply pass. `writes + skips === objects` is the invariant. */
+export type ApplyCountStats = { objects: number; writes: number; skips: number }
+
+/** True when the apply mutated the cluster (create or replace). */
+export function applyResultIsWrite(result: ResourceApplyResult): boolean {
+ switch (result) {
+ case 'created':
+ case 'replaced':
+ return true
+ case 'up_to_date':
+ case 'missing':
+ case 'not_allowed':
+ return false
+ default: {
+ const exhaustive: never = result
+ throw new Error(`unhandled apply result: ${String(exhaustive)}`)
+ }
+ }
+}
+
+/** Bucket one apply outcome. Both GFS and LlmHook must use this mapping. */
+export function accumulateApplyResult(stats: ApplyCountStats, result: ResourceApplyResult): void {
+ stats.objects += 1
+ if (applyResultIsWrite(result)) stats.writes += 1
+ else stats.skips += 1
+}
+
/** Observe one existence GET without changing its value or error handling. */
export async function observeExistenceRead<T>(
kind: CreateKind,
@@ -264,6 +291,12 @@ export function preserveObjectAnnotations<
* Preserve Deployment annotations at both object and pod-template level.
* Pod-template annotations include operational restart markers such as
* kubectl.kubernetes.io/restartedAt.
+ *
+ * This merges every live annotation, not only operational keys. Narrowing
+ * the merge to an allowlist is a separate design (#698): object-level keys
+ * such as last-applied-configuration must keep merging or the gate churns,
+ * while pod-template security annotations are the injection surface. Do not
+ * allowlist here without a churn tripwire.
*/
export function preserveDeploymentAnnotations<
T extends {