Skip to content

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

TypeScript

refactor(hcc): move the Deployment no-op predicate to utils

Alfredo Lopez2f9305aa1c13
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 1d8cc6aa0..d8379c43d 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.272",
+ "version": "0.1.273",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.272",
+ "version": "0.1.273",
"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 2e6efbaea..421cc7f34 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.272",
+ "version": "0.1.273",
"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
new file mode 100644
index 000000000..cf8815b10
--- /dev/null
+++ b/host-context-controller/src/__tests__/asApiserverDeployment.ts
@@ -0,0 +1,144 @@
+import type * as k8s from '@kubernetes/client-node'
+
+/**
+ * Apply documented apps/v1 defaulting onto a desired Deployment. Unlike
+ * `asApiserverService`, this is not a recorded-blob overlay: it fills fields
+ * the apiserver would default-fill, leaving every HCC-authored value intact.
+ * Refresh this function when a live `kubectl get deploy -o json` reveals a
+ * default the fixture does not model (PR G §8).
+ */
+const SERVER_TIME = new Date('2026-04-01T00:00:00.000Z')
+const SERVER_UID = '11111111-2222-3333-4444-555555555555'
+const SERVER_RESOURCE_VERSION = '1776125'
+
+export function asApiserverDeployment(desired: k8s.V1Deployment): k8s.V1Deployment {
+ const live = structuredClone(desired)
+ applyServerOwnedMetadata(live)
+ applyDeploymentSpecDefaults(live.spec)
+ return live
+}
+
+function applyServerOwnedMetadata(deployment: k8s.V1Deployment): void {
+ const name = deployment.metadata?.name ?? 'unnamed'
+ const namespace = deployment.metadata?.namespace ?? 'default'
+ deployment.metadata = {
+ ...deployment.metadata,
+ annotations: {
+ ...deployment.metadata?.annotations,
+ 'deployment.kubernetes.io/revision':
+ deployment.metadata?.annotations?.['deployment.kubernetes.io/revision'] ?? '1',
+ },
+ creationTimestamp: SERVER_TIME,
+ generation: 1,
+ managedFields: [
+ {
+ apiVersion: 'apps/v1',
+ fieldsType: 'FieldsV1',
+ fieldsV1: { 'f:spec': { 'f:template': {} } },
+ manager: 'kube-apiserver',
+ operation: 'Update',
+ time: SERVER_TIME,
+ },
+ ],
+ resourceVersion: SERVER_RESOURCE_VERSION,
+ uid: SERVER_UID,
+ selfLink: `/apis/apps/v1/namespaces/${namespace}/deployments/${name}`,
+ }
+ deployment.status = {
+ observedGeneration: 1,
+ replicas: deployment.spec?.replicas ?? 1,
+ readyReplicas: 0,
+ updatedReplicas: 0,
+ unavailableReplicas: deployment.spec?.replicas ?? 1,
+ conditions: [],
+ }
+}
+
+function applyDeploymentSpecDefaults(spec: k8s.V1Deployment['spec']): void {
+ if (!spec) return
+ if (spec.replicas === undefined) spec.replicas = 1
+ if (spec.progressDeadlineSeconds === undefined) spec.progressDeadlineSeconds = 600
+ if (spec.revisionHistoryLimit === undefined) spec.revisionHistoryLimit = 10
+ if (spec.minReadySeconds === undefined) spec.minReadySeconds = 0
+ if (spec.paused === undefined) spec.paused = false
+ if (!spec.strategy) {
+ spec.strategy = {
+ type: 'RollingUpdate',
+ rollingUpdate: { maxSurge: '25%', maxUnavailable: '25%' },
+ }
+ }
+
+ const template = spec.template
+ if (!template) return
+ if (template.metadata && template.metadata.creationTimestamp === undefined) {
+ template.metadata.creationTimestamp = SERVER_TIME
+ }
+ applyPodSpecDefaults(template.spec)
+}
+
+function applyPodSpecDefaults(podSpec: k8s.V1PodSpec | undefined): void {
+ if (!podSpec) return
+ if (podSpec.restartPolicy === undefined) podSpec.restartPolicy = 'Always'
+ if (podSpec.dnsPolicy === undefined) podSpec.dnsPolicy = 'ClusterFirst'
+ if (podSpec.schedulerName === undefined) podSpec.schedulerName = 'default-scheduler'
+ if (podSpec.terminationGracePeriodSeconds === undefined) {
+ podSpec.terminationGracePeriodSeconds = 30
+ }
+ if (podSpec.enableServiceLinks === undefined) podSpec.enableServiceLinks = true
+ if (podSpec.preemptionPolicy === undefined) podSpec.preemptionPolicy = 'PreemptLowerPriority'
+ if (!podSpec.serviceAccountName) podSpec.serviceAccountName = 'default'
+ if (podSpec.serviceAccount === undefined) podSpec.serviceAccount = podSpec.serviceAccountName
+
+ for (const container of [...(podSpec.initContainers ?? []), ...(podSpec.containers ?? [])]) {
+ applyContainerDefaults(container)
+ }
+ for (const volume of podSpec.volumes ?? []) applyVolumeDefaults(volume)
+}
+
+function applyContainerDefaults(container: k8s.V1Container): void {
+ if (container.terminationMessagePath === undefined) {
+ container.terminationMessagePath = '/dev/termination-log'
+ }
+ if (container.terminationMessagePolicy === undefined) {
+ container.terminationMessagePolicy = 'File'
+ }
+ for (const port of container.ports ?? []) {
+ if (port.protocol === undefined) port.protocol = 'TCP'
+ }
+ applyProbeDefaults(container.startupProbe)
+ applyProbeDefaults(container.livenessProbe)
+ applyProbeDefaults(container.readinessProbe)
+ for (const env of container.env ?? []) {
+ if (env.valueFrom?.fieldRef && env.valueFrom.fieldRef.apiVersion === undefined) {
+ env.valueFrom.fieldRef.apiVersion = 'v1'
+ }
+ }
+}
+
+function applyProbeDefaults(probe: k8s.V1Probe | undefined): void {
+ if (!probe) return
+ if (probe.initialDelaySeconds === undefined) probe.initialDelaySeconds = 0
+ if (probe.timeoutSeconds === undefined) probe.timeoutSeconds = 1
+ if (probe.periodSeconds === undefined) probe.periodSeconds = 10
+ if (probe.successThreshold === undefined) probe.successThreshold = 1
+ if (probe.failureThreshold === undefined) probe.failureThreshold = 3
+ if (probe.httpGet && probe.httpGet.scheme === undefined) probe.httpGet.scheme = 'HTTP'
+}
+
+function applyVolumeDefaults(volume: k8s.V1Volume): void {
+ if (volume.secret && volume.secret.defaultMode === undefined) volume.secret.defaultMode = 420
+ if (volume.secret && volume.secret.optional === undefined) volume.secret.optional = false
+ if (volume.configMap && volume.configMap.defaultMode === undefined) {
+ volume.configMap.defaultMode = 420
+ }
+ if (volume.configMap && volume.configMap.optional === undefined) volume.configMap.optional = false
+ if (volume.downwardAPI && volume.downwardAPI.defaultMode === undefined) {
+ volume.downwardAPI.defaultMode = 420
+ }
+ if (volume.projected && volume.projected.defaultMode === undefined) {
+ volume.projected.defaultMode = 420
+ }
+ if (volume.persistentVolumeClaim && volume.persistentVolumeClaim.readOnly === undefined) {
+ volume.persistentVolumeClaim.readOnly = false
+ }
+}
diff --git a/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts b/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts
new file mode 100644
index 000000000..61fb09255
--- /dev/null
+++ b/host-context-controller/src/__tests__/deploymentMatchesDesired.test.ts
@@ -0,0 +1,173 @@
+import { describe, expect, it, vi } from 'vitest'
+import * as k8s from '@kubernetes/client-node'
+import {
+ asAppsApi,
+ asCoreApi,
+ asNetworkingApi,
+ asRbacApi,
+ createMockAppsApi,
+ createMockCoreApi,
+ createMockNetworkingApi,
+ createMockRbacApi,
+} from '../../test/__fixtures__/testMocks'
+import { HostReconciler } from '../hostReconciler'
+import type { HostCRD } from '../types'
+import { deploymentMatchesDesired, preserveDeploymentAnnotations } from '../utils'
+import { asApiserverDeployment } from './asApiserverDeployment'
+import { cloneAndMutateLeaf, collectLeafPaths, formatLeafPath } from './mutateJsonLeaves'
+
+vi.mock('../config', () => ({
+ config: {
+ hostNamespace: 'mcp-host',
+ hostWorkspaceStorageClassName: 'standard',
+ hostWorkspaceStorageSize: '1Gi',
+ hostWorkspacePath: '/workspace',
+ hostImage: 'clerum/mcp-host:test',
+ desktopImage: 'clerum/mcp-host-desktop:test',
+ hostImagePullPolicy: 'IfNotPresent',
+ hostImagePullSecretName: '',
+ hostPort: 8080,
+ hostConfigMapName: 'mcp-host-config',
+ hostServiceAccountName: 'mcp-host',
+ gfsNamespace: 'gfs',
+ gfscPort: 8087,
+ desktopPort: 3000,
+ rpcProxyNamespace: 'rpc-proxy',
+ channelsNamespace: 'channels',
+ channelReaderImage: 'clerum/channel-reader:test',
+ channelReaderImagePullPolicy: 'IfNotPresent',
+ channelReaderHandoffPort: 8091,
+ hostK8sRequestTimeoutMs: 30_000,
+ hostFullReconcileConcurrency: 2,
+ mcpHostGatewayUrl: 'http://mcp-host-gateway',
+ hostResources: {
+ requests: { memory: '128Mi', cpu: '50m' },
+ limits: { memory: '256Mi', cpu: '200m' },
+ },
+ desktopResources: {
+ requests: { memory: '256Mi', cpu: '100m' },
+ limits: { memory: '512Mi', cpu: '500m' },
+ },
+ },
+}))
+
+function sparseDeployment(): k8s.V1Deployment {
+ return {
+ apiVersion: 'apps/v1',
+ kind: 'Deployment',
+ metadata: { name: 'sparse', namespace: 'ns' },
+ spec: {
+ selector: { matchLabels: { app: 'sparse' } },
+ template: {
+ metadata: { labels: { app: 'sparse' } },
+ spec: {
+ containers: [{ name: 'c', image: 'img:1', ports: [{ containerPort: 80 }] }],
+ },
+ },
+ },
+ }
+}
+
+function makeHost(name = 'alpha-host'): HostCRD {
+ return {
+ name,
+ namespace: 'mcp-host',
+ uid: 'uid-alpha-host',
+ spec: {
+ host: name,
+ contextRef: 'ctx1',
+ secretRef: 'llm-secret',
+ },
+ }
+}
+
+function createReconciler(): HostReconciler {
+ return new HostReconciler({} as k8s.KubeConfig, {
+ appsApi: asAppsApi(createMockAppsApi()),
+ coreApi: asCoreApi(createMockCoreApi()),
+ networkingApi: asNetworkingApi(createMockNetworkingApi()),
+ rbacApi: asRbacApi(createMockRbacApi()),
+ countCommunicationChannels: () => 1,
+ isCommunicationChannelCacheSynced: () => true,
+ })
+}
+
+/** Mirror replaceWithConflictRetry: merge after stamping the live resourceVersion. */
+function mergedForCompare(desired: k8s.V1Deployment, existing: k8s.V1Deployment): k8s.V1Deployment {
+ return preserveDeploymentAnnotations(
+ {
+ ...desired,
+ metadata: { ...desired.metadata, resourceVersion: existing.metadata?.resourceVersion },
+ },
+ existing
+ )
+}
+
+function expectSweepDetectsEveryLeaf(desired: k8s.V1Deployment, existing: k8s.V1Deployment): void {
+ const undetectable: string[] = []
+ for (const path of collectLeafPaths(desired)) {
+ const mutated = cloneAndMutateLeaf(desired, path) as k8s.V1Deployment
+ if (deploymentMatchesDesired(mergedForCompare(mutated, existing), existing)) {
+ undetectable.push(formatLeafPath(path))
+ }
+ }
+ expect(undetectable, `undetectable leaf path(s): ${undetectable.join(', ')}`).toEqual([])
+}
+
+describe('asApiserverDeployment', () => {
+ it('FIXTURE-1: default-fills a sparse Deployment so it differs structurally', () => {
+ const desired = sparseDeployment()
+ expect(asApiserverDeployment(desired)).not.toEqual(desired)
+ })
+
+ it('FIXTURE-1: Host builder output differs from the default-filled live object', () => {
+ const desired = createReconciler().buildDeployment(makeHost())
+ expect(asApiserverDeployment(desired)).not.toEqual(desired)
+ })
+
+ it('FIXTURE-1: channel-reader builder output differs from the default-filled live object', () => {
+ const desired = (createReconciler() as any).buildChannelReaderDeployment(
+ makeHost(),
+ 'rev-abc'
+ ) as k8s.V1Deployment
+ expect(asApiserverDeployment(desired)).not.toEqual(desired)
+ })
+})
+
+describe('deploymentMatchesDesired', () => {
+ it('returns false when either spec is missing (fail-open-to-write)', () => {
+ const desired = sparseDeployment()
+ expect(deploymentMatchesDesired(undefined, desired)).toBe(false)
+ expect(deploymentMatchesDesired(desired, undefined)).toBe(false)
+ expect(deploymentMatchesDesired({ metadata: { name: 'x' } }, desired)).toBe(false)
+ expect(deploymentMatchesDesired(desired, { metadata: { name: 'x' } })).toBe(false)
+ })
+
+ it('Host builder vs fixture is a no-op after merge', () => {
+ const desired = createReconciler().buildDeployment(makeHost())
+ const existing = asApiserverDeployment(desired)
+ expect(deploymentMatchesDesired(mergedForCompare(desired, existing), existing)).toBe(true)
+ })
+
+ it('channel-reader builder vs fixture is a no-op after merge', () => {
+ const desired = (createReconciler() as any).buildChannelReaderDeployment(
+ makeHost(),
+ 'rev-abc'
+ ) as k8s.V1Deployment
+ const existing = asApiserverDeployment(desired)
+ expect(deploymentMatchesDesired(mergedForCompare(desired, existing), existing)).toBe(true)
+ })
+
+ it('Host mutation sweep: every desired leaf is detectable', () => {
+ const desired = createReconciler().buildDeployment(makeHost())
+ expectSweepDetectsEveryLeaf(desired, asApiserverDeployment(desired))
+ })
+
+ it('channel-reader mutation sweep: every desired leaf is detectable', () => {
+ const desired = (createReconciler() as any).buildChannelReaderDeployment(
+ makeHost(),
+ 'rev-abc'
+ ) as k8s.V1Deployment
+ expectSweepDetectsEveryLeaf(desired, asApiserverDeployment(desired))
+ })
+})
diff --git a/host-context-controller/src/__tests__/mutateJsonLeaves.ts b/host-context-controller/src/__tests__/mutateJsonLeaves.ts
new file mode 100644
index 000000000..7e23f1359
--- /dev/null
+++ b/host-context-controller/src/__tests__/mutateJsonLeaves.ts
@@ -0,0 +1,53 @@
+/** Collect every JSON leaf path: primitives and arrays (arrays also recurse). */
+export function collectLeafPaths(value: unknown, prefix: string[] = []): string[][] {
+ if (value === undefined || value === null) return []
+ if (Array.isArray(value)) {
+ const nested = value.flatMap((item, index) =>
+ collectLeafPaths(item, [...prefix, String(index)])
+ )
+ return [prefix, ...nested]
+ }
+ if (typeof value === 'object') {
+ return Object.entries(value as Record<string, unknown>).flatMap(([key, entry]) =>
+ collectLeafPaths(entry, [...prefix, key])
+ )
+ }
+ return [prefix]
+}
+
+export function getAtPath(root: unknown, path: string[]): unknown {
+ let cursor: unknown = root
+ for (const key of path) {
+ if (cursor === null || typeof cursor !== 'object') return undefined
+ cursor = (cursor as Record<string, unknown>)[key]
+ }
+ return cursor
+}
+
+export function setAtPath(root: unknown, path: string[], next: unknown): void {
+ if (path.length === 0) return
+ let cursor: Record<string, unknown> = root as Record<string, unknown>
+ for (let i = 0; i < path.length - 1; i++) {
+ cursor = cursor[path[i]] as Record<string, unknown>
+ }
+ cursor[path[path.length - 1]] = next
+}
+
+/** Spec §7.2(a): string +'-x', number +1, boolean flip, array drop one element. */
+export function mutateLeaf(value: unknown): unknown {
+ if (typeof value === 'string') return `${value}-x`
+ if (typeof value === 'number') return value + 1
+ if (typeof value === 'boolean') return !value
+ if (Array.isArray(value)) return value.length === 0 ? ['_sweep'] : value.slice(0, -1)
+ return value
+}
+
+export function cloneAndMutateLeaf(root: unknown, path: string[]): unknown {
+ const clone = structuredClone(root)
+ setAtPath(clone, path, mutateLeaf(getAtPath(clone, path)))
+ return clone
+}
+
+export function formatLeafPath(path: string[]): string {
+ return path.length === 0 ? '(root)' : path.join('.')
+}
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 4eb196e8b..250558b57 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -76,6 +76,7 @@ import {
applyNetworkPolicy,
canonicalStringify,
canonicalizeValue,
+ deploymentMatchesDesired,
getErrorCode,
preserveDeploymentAnnotations,
preserveServiceAssignedFields,
@@ -5067,22 +5068,6 @@ function roleMatchesDesired(desired: k8s.V1Role, existing: k8s.V1Role): boolean
}
}
-/**
- * Kubernetes persists server metadata and defaulted Deployment/PodSpec fields
- * that HCC does not author. Remove only those known fields before comparing
- * the objects; every HCC-authored field stays exact so an intentional removal
- * or change still causes a rollout. Keep this allowlist conservative: an
- * unknown admission mutation must compare as drift rather than be silently
- * ignored. Pod-template annotations are merged by preserveDeploymentAnnotations
- * before this comparison.
- */
-function deploymentMatchesDesired(desired: k8s.V1Deployment, existing: k8s.V1Deployment): boolean {
- return (
- JSON.stringify(normalizeDeploymentForComparison(desired)) ===
- JSON.stringify(normalizeDeploymentForComparison(existing))
- )
-}
-
/**
* Preserve operational pod-template annotations (kubectl restart markers,
* operator edits) while keeping CONTROLLER-OWNED ones authoritative: a key in
@@ -5152,85 +5137,3 @@ function preserveChannelReaderDeploymentAnnotations(
): k8s.V1Deployment {
return preserveDeploymentAnnotationsExcept(desired, existing, ['clerum.io/credentials-revision'])
}
-
-function normalizeDeploymentForComparison(deployment: k8s.V1Deployment): unknown {
- const normalized = structuredClone(deployment)
- delete normalized.status
- delete normalized.metadata?.resourceVersion
- delete normalized.metadata?.uid
- delete normalized.metadata?.generation
- delete normalized.metadata?.creationTimestamp
- delete normalized.metadata?.managedFields
- delete normalized.metadata?.selfLink
-
- const spec = normalized.spec
- if (spec) {
- if (spec.progressDeadlineSeconds === 600) delete spec.progressDeadlineSeconds
- if (spec.revisionHistoryLimit === 10) delete spec.revisionHistoryLimit
- if (spec.minReadySeconds === 0) delete spec.minReadySeconds
- if (spec.paused === false) delete spec.paused
- if (
- spec.strategy?.type === 'RollingUpdate' &&
- spec.strategy.rollingUpdate?.maxSurge === '25%' &&
- spec.strategy.rollingUpdate.maxUnavailable === '25%'
- ) {
- delete spec.strategy
- }
- const template = spec.template
- if (template) {
- delete template.metadata?.creationTimestamp
-
- const podSpec = template.spec
- if (podSpec) {
- if (podSpec.restartPolicy === 'Always') delete podSpec.restartPolicy
- if (podSpec.dnsPolicy === 'ClusterFirst') delete podSpec.dnsPolicy
- if (podSpec.schedulerName === 'default-scheduler') delete podSpec.schedulerName
- if (podSpec.terminationGracePeriodSeconds === 30)
- delete podSpec.terminationGracePeriodSeconds
- if (podSpec.enableServiceLinks === true) delete podSpec.enableServiceLinks
- if (podSpec.preemptionPolicy === 'PreemptLowerPriority') delete podSpec.preemptionPolicy
- if (podSpec.serviceAccount === podSpec.serviceAccountName) delete podSpec.serviceAccount
- if (Object.keys(podSpec.securityContext ?? {}).length === 0) delete podSpec.securityContext
- for (const container of [
- ...(podSpec.initContainers ?? []),
- ...(podSpec.containers ?? []),
- ]) {
- normalizeContainerDefaults(container)
- }
- for (const volume of podSpec.volumes ?? []) normalizeVolumeDefaults(volume)
- }
- }
- }
-
- return canonicalizeValue(normalized)
-}
-
-function normalizeContainerDefaults(container: k8s.V1Container): void {
- if (container.terminationMessagePath === '/dev/termination-log') {
- delete container.terminationMessagePath
- }
- if (container.terminationMessagePolicy === 'File') delete container.terminationMessagePolicy
- for (const probe of [container.startupProbe, container.livenessProbe, container.readinessProbe]) {
- if (!probe) continue
- if (probe.initialDelaySeconds === 0) delete probe.initialDelaySeconds
- if (probe.successThreshold === 1) delete probe.successThreshold
- if (probe.httpGet?.scheme === 'HTTP') delete probe.httpGet.scheme
- }
- for (const env of container.env ?? []) {
- if (env.valueFrom?.fieldRef?.apiVersion === 'v1') {
- delete env.valueFrom.fieldRef.apiVersion
- }
- }
-}
-
-function normalizeVolumeDefaults(volume: k8s.V1Volume): void {
- if (volume.secret?.defaultMode === 420) delete volume.secret.defaultMode
- if (volume.secret?.optional === false) delete volume.secret.optional
- if (volume.configMap?.defaultMode === 420) delete volume.configMap.defaultMode
- if (volume.configMap?.optional === false) delete volume.configMap.optional
- if (volume.downwardAPI?.defaultMode === 420) delete volume.downwardAPI.defaultMode
- if (volume.projected?.defaultMode === 420) delete volume.projected.defaultMode
- if (volume.persistentVolumeClaim?.readOnly === false) {
- delete volume.persistentVolumeClaim.readOnly
- }
-}
diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.ts
index e0d681e4c..864b3f831 100644
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@ -285,6 +285,115 @@ function normalizeNetworkPolicyForComparison(policy: k8s.V1NetworkPolicy): unkno
return canonicalizeValue(normalized)
}
+/**
+ * True when the merged desired Deployment is equivalent to the live object.
+ * Kubernetes persists server metadata and defaulted Deployment/PodSpec fields
+ * that HCC does not author. Remove only those known fields before comparing;
+ * every HCC-authored field stays exact so an intentional removal or change
+ * still causes a rollout.
+ *
+ * Safe-strip lemma: a normalizer mutation of the form "delete field X iff
+ * X === documented-default, applied identically to both sides" cannot hide
+ * any real change for any consumer. Anything outside that form — unconditional
+ * deletes, value normalisation, per-writer branches — can hide changes and is
+ * forbidden. Keep this allowlist conservative: an unknown admission mutation
+ * 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
+ * (fail-open-to-write), matching serviceMatchesDesired / networkPolicyMatchesDesired.
+ */
+export function deploymentMatchesDesired(
+ desired: k8s.V1Deployment | undefined,
+ existing: k8s.V1Deployment | undefined
+): boolean {
+ try {
+ if (!desired?.spec || !existing?.spec) return false
+ return (
+ JSON.stringify(normalizeDeploymentForComparison(desired)) ===
+ JSON.stringify(normalizeDeploymentForComparison(existing))
+ )
+ } catch {
+ return false
+ }
+}
+
+export function normalizeDeploymentForComparison(deployment: k8s.V1Deployment): unknown {
+ const normalized = structuredClone(deployment)
+ stripServerOwnedMetadata(normalized)
+
+ const spec = normalized.spec
+ if (spec) {
+ if (spec.progressDeadlineSeconds === 600) delete spec.progressDeadlineSeconds
+ if (spec.revisionHistoryLimit === 10) delete spec.revisionHistoryLimit
+ if (spec.minReadySeconds === 0) delete spec.minReadySeconds
+ if (spec.paused === false) delete spec.paused
+ if (
+ spec.strategy?.type === 'RollingUpdate' &&
+ spec.strategy.rollingUpdate?.maxSurge === '25%' &&
+ spec.strategy.rollingUpdate.maxUnavailable === '25%'
+ ) {
+ delete spec.strategy
+ }
+ const template = spec.template
+ if (template) {
+ delete template.metadata?.creationTimestamp
+
+ const podSpec = template.spec
+ if (podSpec) {
+ if (podSpec.restartPolicy === 'Always') delete podSpec.restartPolicy
+ if (podSpec.dnsPolicy === 'ClusterFirst') delete podSpec.dnsPolicy
+ if (podSpec.schedulerName === 'default-scheduler') delete podSpec.schedulerName
+ if (podSpec.terminationGracePeriodSeconds === 30)
+ delete podSpec.terminationGracePeriodSeconds
+ if (podSpec.enableServiceLinks === true) delete podSpec.enableServiceLinks
+ if (podSpec.preemptionPolicy === 'PreemptLowerPriority') delete podSpec.preemptionPolicy
+ if (podSpec.serviceAccount === podSpec.serviceAccountName) delete podSpec.serviceAccount
+ if (Object.keys(podSpec.securityContext ?? {}).length === 0) delete podSpec.securityContext
+ for (const container of [
+ ...(podSpec.initContainers ?? []),
+ ...(podSpec.containers ?? []),
+ ]) {
+ normalizeContainerDefaults(container)
+ }
+ for (const volume of podSpec.volumes ?? []) normalizeVolumeDefaults(volume)
+ }
+ }
+ }
+
+ return canonicalizeValue(normalized)
+}
+
+export function normalizeContainerDefaults(container: k8s.V1Container): void {
+ if (container.terminationMessagePath === '/dev/termination-log') {
+ delete container.terminationMessagePath
+ }
+ if (container.terminationMessagePolicy === 'File') delete container.terminationMessagePolicy
+ for (const probe of [container.startupProbe, container.livenessProbe, container.readinessProbe]) {
+ if (!probe) continue
+ if (probe.initialDelaySeconds === 0) delete probe.initialDelaySeconds
+ if (probe.successThreshold === 1) delete probe.successThreshold
+ if (probe.httpGet?.scheme === 'HTTP') delete probe.httpGet.scheme
+ }
+ for (const env of container.env ?? []) {
+ if (env.valueFrom?.fieldRef?.apiVersion === 'v1') {
+ delete env.valueFrom.fieldRef.apiVersion
+ }
+ }
+}
+
+export function normalizeVolumeDefaults(volume: k8s.V1Volume): void {
+ if (volume.secret?.defaultMode === 420) delete volume.secret.defaultMode
+ if (volume.secret?.optional === false) delete volume.secret.optional
+ if (volume.configMap?.defaultMode === 420) delete volume.configMap.defaultMode
+ if (volume.configMap?.optional === false) delete volume.configMap.optional
+ if (volume.downwardAPI?.defaultMode === 420) delete volume.downwardAPI.defaultMode
+ if (volume.projected?.defaultMode === 420) delete volume.projected.defaultMode
+ if (volume.persistentVolumeClaim?.readOnly === false) {
+ delete volume.persistentVolumeClaim.readOnly
+ }
+}
+
/** Create-or-replace a NetworkPolicy (409 catch → conflict-retry replace). */
export async function applyNetworkPolicy(
api: k8s.NetworkingV1Api,