Skip to content

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

TypeScript

fix(hcc): strip empty container resources and stop mutating the Deployment fixture

Alfredo Lopez7df1dc1b5530
diff --git a/host-context-controller/README.md b/host-context-controller/README.md
index 85ee15fa6..0997190e1 100644
--- a/host-context-controller/README.md
+++ b/host-context-controller/README.md
@@ -380,7 +380,7 @@ a permissive policy — see the NetworkPolicy and GFS tables:
| `CONTEXT_MAPPER_DESKTOP_RESOURCES_REQUEST_MEMORY` | `256Mi` | Desktop memory request. |
| `CONTEXT_MAPPER_DESKTOP_RESOURCES_REQUEST_CPU` | `250m` | Desktop CPU request. |
| `CONTEXT_MAPPER_DESKTOP_RESOURCES_LIMIT_MEMORY` | `4Gi` | Desktop memory limit. |
-| `CONTEXT_MAPPER_DESKTOP_RESOURCES_LIMIT_CPU` | `1000m` | Desktop CPU limit. |
+| `CONTEXT_MAPPER_DESKTOP_RESOURCES_LIMIT_CPU` | `1` | Desktop CPU limit. Author the apiserver-canonical form (`1`, not `1000m`) so the Deployment no-op gate can match. |
| `CONTEXT_MAPPER_DESKTOP_API_TOKEN` | `` (empty) | Bearer token required by `GET /api/v1/desktop/:hostRef`. **When empty the check is skipped and the endpoint is unauthenticated** — a dev-mode convenience. Set it in any shared cluster. |
### channel-reader provisioning
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 1d372dfaa..2813266c8 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.282",
+ "version": "0.1.283",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.282",
+ "version": "0.1.283",
"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 e0bd1a0ad..3f6fff27a 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.282",
+ "version": "0.1.283",
"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__/asApiserverDeployment.ts b/host-context-controller/src/__tests__/asApiserverDeployment.ts
index 5a2f97d01..b6074070d 100644
--- a/host-context-controller/src/__tests__/asApiserverDeployment.ts
+++ b/host-context-controller/src/__tests__/asApiserverDeployment.ts
@@ -119,13 +119,17 @@ const REPLACE_OBJECT_KEYS = new Set([
/** Defined overlay keys win; omitted keys keep the recorded apiserver default. */
function overlayDefined(base: unknown, overlay: unknown): unknown {
if (overlay === undefined) return base
- if (overlay === null || typeof overlay !== 'object' || Array.isArray(overlay)) return overlay
- if (base === null || typeof base !== 'object' || Array.isArray(base)) return overlay
+ if (overlay === null || typeof overlay !== 'object' || Array.isArray(overlay)) {
+ return structuredClone(overlay)
+ }
+ if (base === null || typeof base !== 'object' || Array.isArray(base)) {
+ return structuredClone(overlay)
+ }
const out: Record<string, unknown> = { ...(base as Record<string, unknown>) }
for (const [key, value] of Object.entries(overlay as Record<string, unknown>)) {
if (value === undefined) continue
if (REPLACE_OBJECT_KEYS.has(key) && typeof value === 'object' && !Array.isArray(value)) {
- out[key] = value
+ out[key] = structuredClone(value)
continue
}
out[key] = overlayDefined((base as Record<string, unknown>)[key], value)
@@ -175,6 +179,7 @@ function applyPodSpecDefaults(podSpec: k8s.V1PodSpec | undefined): void {
}
function applyContainerDefaults(container: k8s.V1Container): void {
+ if (container.resources === undefined) container.resources = {}
if (container.imagePullPolicy === undefined) {
container.imagePullPolicy = defaultImagePullPolicy(container.image)
}
diff --git a/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts b/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts
index 93ac6cff3..f149ac58f 100644
--- a/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts
+++ b/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts
@@ -160,6 +160,13 @@ describe('asApiserverDeployment', () => {
expect(asApiserverDeployment(desired)).not.toEqual(desired)
})
+ it('FIXTURE-1: asApiserverDeployment does not mutate the caller desired object', () => {
+ const desired = sparseDeployment()
+ const before = structuredClone(desired)
+ asApiserverDeployment(desired)
+ expect(desired).toEqual(before)
+ })
+
it('FIXTURE-1: omitted Deployment spec fields come from the recorded blob', () => {
const desired = sparseDeployment()
const existing = asApiserverDeployment(desired)
@@ -196,6 +203,7 @@ describe('asApiserverDeployment', () => {
type CanonicalPodSpec = {
serviceAccountName?: string
containers?: Array<{
+ resources?: unknown
livenessProbe?: { timeoutSeconds?: number; failureThreshold?: number }
}>
}
@@ -276,6 +284,35 @@ describe('safe-strip lemma equality guards', () => {
const existing = asApiserverDeployment(desired)
expect(deploymentMatchesDesired(mergedForCompare(desired, existing), existing)).toBe(true)
})
+
+ it('strips empty resources {} and keeps a non-empty request', () => {
+ const empty = deploymentWithProbe({ periodSeconds: 5 })
+ empty.spec!.template.spec!.containers![0].resources = {}
+ const kept = deploymentWithProbe({ periodSeconds: 5 })
+ kept.spec!.template.spec!.containers![0].resources = { requests: { cpu: '50m' } }
+ expect(
+ canonicalPodSpec(normalizeDeploymentForComparison(empty))?.containers?.[0]?.resources
+ ).toBeUndefined()
+ expect(
+ canonicalPodSpec(normalizeDeploymentForComparison(kept))?.containers?.[0]?.resources
+ ).toEqual({ requests: { cpu: '50m' } })
+ })
+
+ it('omitted container resources match a live empty resources object', () => {
+ const desired = deploymentWithProbe({ periodSeconds: 5 })
+ const existing = asApiserverDeployment(desired)
+ expect(existing.spec?.template?.spec?.containers?.[0]?.resources).toEqual({})
+ expect(desired.spec?.template?.spec?.containers?.[0]?.resources).toBeUndefined()
+ expect(deploymentMatchesDesired(mergedForCompare(desired, existing), existing)).toBe(true)
+ })
+
+ it('does not treat 1000m and 1 as the same cpu quantity', () => {
+ const milli = deploymentWithProbe({ periodSeconds: 5 })
+ milli.spec!.template.spec!.containers![0].resources = { limits: { cpu: '1000m' } }
+ const canonical = deploymentWithProbe({ periodSeconds: 5 })
+ canonical.spec!.template.spec!.containers![0].resources = { limits: { cpu: '1' } }
+ expect(deploymentMatchesDesired(milli, canonical)).toBe(false)
+ })
})
describe('deploymentMatchesDesired', () => {
diff --git a/host-context-controller/src/__tests__/deploymentWriterInventory.test.ts b/host-context-controller/src/__tests__/deploymentWriterInventory.test.ts
index 58eeb1f23..b0242b642 100644
--- a/host-context-controller/src/__tests__/deploymentWriterInventory.test.ts
+++ b/host-context-controller/src/__tests__/deploymentWriterInventory.test.ts
@@ -91,7 +91,20 @@ describe('Deployment writer inventory', () => {
const rel = relative(SRC_ROOT, file).replaceAll('\\', '/')
const source = readFileSync(file, 'utf8')
const sites = callSiteIndexes(source)
- if (sites.length === 0) continue
+ const identCount = [...source.matchAll(/replaceNamespacedDeployment\b/g)].filter(
+ match => match.index !== undefined && !isCommentLine(lineAt(source, match.index))
+ ).length
+ if (sites.length === 0) {
+ expect(
+ identCount,
+ `${rel} mentions replaceNamespacedDeployment but has no call; an alias/bind form is invisible to the call regex`
+ ).toBe(0)
+ continue
+ }
+ expect(
+ identCount,
+ `${rel} has ${identCount} replaceNamespacedDeployment identifier(s) but ${sites.length} call(s); an alias/bind form is invisible to the call regex`
+ ).toBe(sites.length)
const isGated = GATED.has(rel)
const isExempt = EXEMPT.has(rel)
expect(
diff --git a/host-context-controller/src/__tests__/replaceWithConflictRetryOrder.test.ts b/host-context-controller/src/__tests__/replaceWithConflictRetryOrder.test.ts
index f9439e29c..fb195364d 100644
--- a/host-context-controller/src/__tests__/replaceWithConflictRetryOrder.test.ts
+++ b/host-context-controller/src/__tests__/replaceWithConflictRetryOrder.test.ts
@@ -331,6 +331,7 @@ describe('replaceWithConflictRetry order and retry', () => {
it('WRITE-2: isUpToDate skip and read-404 do not increment', async () => {
const replace = vi.fn()
const before = await readWritesTotal('Service')
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
await replaceWithConflictRetry({
description: 'Service "svc"',
@@ -354,6 +355,31 @@ describe('replaceWithConflictRetry order and retry', () => {
expect(replace).not.toHaveBeenCalled()
expect(await readWritesTotal('Service')).toBe(before)
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringMatching(/disappeared \(404\); skipping replace/)
+ )
+ warn.mockRestore()
+ })
+
+ it('SKIP-3: isUpToDate skip with mutationAllowed false does not increment writes or skips', async () => {
+ const replace = vi.fn()
+ const beforeWrites = await readWritesTotal('Service')
+ const beforeSkips = await readWriteSkipsTotal('Service')
+
+ await replaceWithConflictRetry({
+ description: 'Service "svc"',
+ logPrefix: '[Test]',
+ body: desired,
+ mergeExisting: preserveServiceAssignedFields,
+ isUpToDate: () => true,
+ mutationAllowed: () => false,
+ read: async () => existing,
+ replace,
+ })
+
+ expect(replace).not.toHaveBeenCalled()
+ expect(await readWritesTotal('Service')).toBe(beforeWrites)
+ expect(await readWriteSkipsTotal('Service')).toBe(beforeSkips)
})
it('SKIP-1: isUpToDate skip increments clerum_hcc_write_skips_total{kind=Service}', async () => {
diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.ts
index 9006c5088..fd7697a4b 100644
--- a/host-context-controller/src/config.ts
+++ b/host-context-controller/src/config.ts
@@ -716,7 +716,7 @@ export const config: Config = {
},
limits: {
memory: getEnv('CONTEXT_MAPPER_DESKTOP_RESOURCES_LIMIT_MEMORY', '4Gi')!,
- cpu: getEnv('CONTEXT_MAPPER_DESKTOP_RESOURCES_LIMIT_CPU', '1000m')!,
+ cpu: getEnv('CONTEXT_MAPPER_DESKTOP_RESOURCES_LIMIT_CPU', '1')!,
},
},
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 250558b57..730a2c5e6 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -2534,7 +2534,9 @@ export class HostReconciler {
* - On 409 from create, compares a fresh, server-normalized Deployment and
* replaces only meaningful drift. Conflict retries rebuild against the
* latest live replica count. A Deployment owned by a different host is
- * never overwritten.
+ * never overwritten: the initial read skips, and a retry-time ownership
+ * change throws so write_skips_total does not count the refusal as a
+ * healthy no-op.
*/
private async reconcileChannelReaderDeployment(host: HostCRD): Promise<void> {
const name = `channel-reader-${host.name}`
@@ -2601,12 +2603,18 @@ export class HostReconciler {
}
return preserveChannelReaderDeploymentAnnotations(desiredWithLiveReplicas, fresh)
},
- isUpToDate: (next, fresh) => {
+ validateExisting: fresh => {
const freshOwnerHost = fresh.metadata?.labels?.[HOST_LABEL]
// Never replace an object whose ownership changed during a retry.
- if (freshOwnerHost && freshOwnerHost !== host.name) return true
- return deploymentMatchesDesired(next, fresh)
+ // Veto here — not via isUpToDate — so write_skips_total stays a
+ // genuine no-op count.
+ if (freshOwnerHost && freshOwnerHost !== host.name) {
+ throw new Error(
+ `channel-reader Deployment ownership changed to host "${freshOwnerHost}"; refusing replace`
+ )
+ }
},
+ isUpToDate: deploymentMatchesDesired,
})
} catch (replaceErr) {
console.error(`[HostReconciler] Failed to update channel-reader "${name}":`, replaceErr)
diff --git a/host-context-controller/src/reconciler.ts b/host-context-controller/src/reconciler.ts
index db48b0f64..3756104b3 100644
--- a/host-context-controller/src/reconciler.ts
+++ b/host-context-controller/src/reconciler.ts
@@ -1270,8 +1270,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
{
name: 'copy-mcp-app',
image: server.spec.image,
- imagePullPolicy:
- server.spec.imagePullPolicy || config.mcpServerImagePullPolicy,
+ imagePullPolicy: config.mcpServerImagePullPolicy,
command: [
'sh',
'-c',
@@ -1332,8 +1331,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
{
name: 'mcp-server',
image: server.spec.image,
- imagePullPolicy:
- server.spec.imagePullPolicy || config.mcpServerImagePullPolicy,
+ imagePullPolicy: config.mcpServerImagePullPolicy,
command: server.spec.command || undefined,
args: server.spec.args || undefined,
ports,
@@ -1370,8 +1368,7 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
{
name: 'stdio-bridge',
image: config.stdioBridgeImage, // G10: configurable bridge image
- imagePullPolicy:
- server.spec.imagePullPolicy || config.mcpServerImagePullPolicy,
+ imagePullPolicy: config.mcpServerImagePullPolicy,
env: [
{
name: 'STDIO_COMMAND',
diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.ts
index 7f0a5efe9..3ecea9520 100644
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@ -61,7 +61,10 @@ export async function replaceWithConflictRetry<
try {
existing = await read()
} catch (err) {
- if (getErrorCode(err) === 404) return
+ if (getErrorCode(err) === 404) {
+ console.warn(`${logPrefix} ${description} disappeared (404); skipping replace`)
+ return
+ }
throw err
}
validateExisting?.(existing)
@@ -72,6 +75,7 @@ export async function replaceWithConflictRetry<
}
const next = mergeExisting ? mergeExisting(base, existing) : base
if (isUpToDate?.(next, existing)) {
+ if (mutationAllowed && !mutationAllowed()) return
writeSkipsTotal.inc({ kind: next.kind ?? 'unknown' })
return
}
@@ -247,8 +251,10 @@ function normalizeServiceForComparison(service: k8s.V1Service): unknown {
/**
* True when the merged desired ConfigMap is equivalent to the live object.
* ConfigMaps have no apps/v1-style spec defaulting, so comparison is the
- * whole object after stripping server-owned metadata. Doubt or a malformed
- * object returns false (fail-open-to-write).
+ * whole object after stripping server-owned metadata. Labels, finalizers,
+ * and ownerReferences are compared in full (mergeExisting keeps annotations
+ * only), so a foreign stamp there is permanent write churn, not a skip.
+ * Doubt or a malformed object returns false (fail-open-to-write).
*/
export function configMapMatchesDesired(
desired: k8s.V1ConfigMap | undefined,
@@ -330,7 +336,10 @@ function normalizeNetworkPolicyForComparison(policy: k8s.V1NetworkPolicy): unkno
* must compare as drift rather than be silently ignored.
*
* Pod-template annotations are merged by preserveDeploymentAnnotations before
- * this comparison. Doubt or a malformed object returns false
+ * this comparison. Labels, finalizers, and ownerReferences are compared in
+ * full: a third-party stamp on those fields is drift and keeps the gate
+ * writing (fail-open), because mergeExisting does not absorb them.
+ * Doubt or a malformed object returns false
* (fail-open-to-write), matching serviceMatchesDesired / networkPolicyMatchesDesired.
*/
export function deploymentMatchesDesired(
@@ -378,6 +387,9 @@ export function normalizeDeploymentForComparison(deployment: k8s.V1Deployment):
delete podSpec.terminationGracePeriodSeconds
if (podSpec.enableServiceLinks === true) delete podSpec.enableServiceLinks
if (podSpec.preemptionPolicy === 'PreemptLowerPriority') delete podSpec.preemptionPolicy
+ // Cross-field default: kube mirrors serviceAccount from serviceAccountName.
+ // Delete the deprecated alias first; then strip SA === 'default'. Swapping
+ // these two lines would leave a dangling alias and force a write every pass.
if (podSpec.serviceAccount === podSpec.serviceAccountName) delete podSpec.serviceAccount
if (podSpec.serviceAccountName === 'default') delete podSpec.serviceAccountName
if (Object.keys(podSpec.securityContext ?? {}).length === 0) delete podSpec.securityContext
@@ -396,6 +408,7 @@ export function normalizeDeploymentForComparison(deployment: k8s.V1Deployment):
}
export function normalizeContainerDefaults(container: k8s.V1Container): void {
+ if (Object.keys(container.resources ?? {}).length === 0) delete container.resources
if (container.terminationMessagePath === '/dev/termination-log') {
delete container.terminationMessagePath
}
diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.ts
index 5b4100f09..da634e350 100644
--- a/host-context-controller/test/hostReconciler.test.ts
+++ b/host-context-controller/test/hostReconciler.test.ts
@@ -56,7 +56,7 @@ vi.mock('../src/config', () => ({
desktopPort: 3000,
desktopResources: {
requests: { memory: '256Mi', cpu: '250m' },
- limits: { memory: '4Gi', cpu: '1000m' },
+ limits: { memory: '4Gi', cpu: '1' },
},
devMcpServers: [],
devContexts: [],
@@ -814,7 +814,7 @@ describe('HostReconciler — desktop support', () => {
expect(resources.requests.memory).toBe('256Mi')
expect(resources.requests.cpu).toBe('250m')
expect(resources.limits.memory).toBe('4Gi')
- expect(resources.limits.cpu).toBe('1000m')
+ expect(resources.limits.cpu).toBe('1')
})
it('creates desktop NetworkPolicy when desktop enabled', async () => {
@@ -1488,7 +1488,9 @@ describe('reconcileChannelReaderDeployment', () => {
appsApi.replaceNamespacedDeployment.mockRejectedValueOnce({ code: 409 })
coreApi.readNamespacedSecret.mockRejectedValue({ code: 404 })
- await (reconciler as any).reconcileChannelReaderDeployment(host)
+ await expect((reconciler as any).reconcileChannelReaderDeployment(host)).rejects.toThrow(
+ /ownership changed to host "other-host"/
+ )
expect(appsApi.replaceNamespacedDeployment).toHaveBeenCalledOnce()
})