Skip to content

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

TypeScript

fix(hcc): retry Role conflicts and address PR review findings

Alfredo Lopez2c9897e68bea
diff --git a/host-context-controller/CREATE_OBSERVABILITY.md b/host-context-controller/CREATE_OBSERVABILITY.md
index 25e0cd29e..2882c15a6 100644
--- a/host-context-controller/CREATE_OBSERVABILITY.md
+++ b/host-context-controller/CREATE_OBSERVABILITY.md
@@ -119,6 +119,10 @@ convergence/preservation. Failed or cancelled paths do not count as skipped;
neither do retries or a POST409 already emitted. A caller preserving an existing
non-throwing convergence failure returns `false` to avoid reporting a skip.
+`skipped` means a create was suppressed because the resource was present, not
+that reconciliation was a no-op: convergence may still issue a separately
+instrumented replace. A POST409 race counts as `conflict`, never another `skipped`.
+
Host ServiceAccount, Role and RoleBinding propagate unexpected read, create and
convergence failures to the existing reconciliation error handler. The new GET
never turns 403/transport failures into absence. Historical Host PVC/Service
@@ -127,6 +131,13 @@ supersession retains its separate error path. Preserved existing resources gain
no PUT or synthetic equality comparison. An unbound Host PVC retains its direct
update policy.
+Role convergence retries optimistic-lock conflicts through the shared bounded
+retry helper (three attempts, fresh reads and admission checks). Exhausted
+conflicts and unexpected RBAC errors still propagate; they are not successful
+provisioning. Role replaces and no-op decisions now use the helper's write
+metrics. Operators should expect previously silent RBAC failures to surface in
+reconciliation error telemetry.
+
External-egress passes its fresh object separately from the expected UID/RV
snapshot constraint. A conflict invalidates the consumed snapshot, not the
constraint. The safety exception retains its existing inventory-based behavior;
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index ac64d6908..e75446390 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.308",
+ "version": "0.1.309",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.308",
+ "version": "0.1.309",
"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 e2d883c8e..98c9b543b 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.308",
+ "version": "0.1.309",
"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__/applyNetworkPolicyNoopGate.test.ts b/host-context-controller/src/__tests__/applyNetworkPolicyNoopGate.test.ts
index 37dc2ae3a..19cbc2573 100644
--- a/host-context-controller/src/__tests__/applyNetworkPolicyNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/applyNetworkPolicyNoopGate.test.ts
@@ -186,6 +186,27 @@ describe('applyNetworkPolicy no-op gate', () => {
}
)
+ it('GATE-NP-0: mutation denied at entry skips GET and all writes', async () => {
+ const api = fakeNetworkingApi()
+ const mutationAllowed = vi.fn(() => false)
+
+ await expect(
+ applyNetworkPolicy(
+ api as unknown as k8s.NetworkingV1Api,
+ 'np',
+ 'ns',
+ desiredPolicy(),
+ '[NetPol]',
+ mutationAllowed
+ )
+ ).resolves.toBeUndefined()
+
+ expect(mutationAllowed).toHaveBeenCalledOnce()
+ expect(api.readNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(api.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ expect(api.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
it('GATE-NP-1: expiry during existence GET suppresses POST and drift PUT', async () => {
const desired = desiredPolicy()
const drifted = asApiserverNetworkPolicy(desired, { port: 9090 })
diff --git a/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
index daa84119b..272366b56 100644
--- a/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
@@ -37,8 +37,16 @@ function updatedRoleLogs(log: ReturnType<typeof vi.spyOn>) {
return log.mock.calls.flatMap(([line]: unknown[]) => {
if (typeof line !== 'string' || !line.startsWith('{')) return []
const entry = JSON.parse(line)
- return entry.msg === 'Updated Host Role'
- ? [{ msg: entry.msg, host: entry.host, level: entry.level }]
+ return entry.msg === 'Kubernetes resource updated' && entry.description?.startsWith('Role ')
+ ? [
+ {
+ msg: entry.msg,
+ description: entry.description,
+ scope: entry.scope,
+ attempt: entry.attempt,
+ level: entry.level,
+ },
+ ]
: []
})
}
@@ -132,7 +140,13 @@ describe('Host ensureHostRole no-op gate', () => {
expect(existing?.rules?.length).toBeGreaterThan(0)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
expect(updatedRoleLogs(log)).toEqual([
- { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
+ {
+ msg: 'Kubernetes resource updated',
+ description: `Role "${desired.metadata!.name}"`,
+ scope: '[HostReconciler]',
+ attempt: 1,
+ level: 'info',
+ },
])
} finally {
log.mockRestore()
@@ -154,7 +168,13 @@ describe('Host ensureHostRole no-op gate', () => {
expect(existing?.rules?.length).toBe((desired.rules?.length ?? 0) + 1)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
expect(updatedRoleLogs(log)).toEqual([
- { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
+ {
+ msg: 'Kubernetes resource updated',
+ description: `Role "${desired.metadata!.name}"`,
+ scope: '[HostReconciler]',
+ attempt: 1,
+ level: 'info',
+ },
])
} finally {
log.mockRestore()
@@ -177,7 +197,13 @@ describe('Host ensureHostRole no-op gate', () => {
expect(existing?.rules?.some(rule => rule.verbs?.includes('update'))).toBe(true)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
expect(updatedRoleLogs(log)).toEqual([
- { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
+ {
+ msg: 'Kubernetes resource updated',
+ description: `Role "${desired.metadata!.name}"`,
+ scope: '[HostReconciler]',
+ attempt: 1,
+ level: 'info',
+ },
])
} finally {
log.mockRestore()
@@ -209,14 +235,26 @@ describe('Host ensureHostRole no-op gate', () => {
expect(secretGetRule(existing!).verbs).toEqual(['watch', 'get', 'list'])
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
expect(updatedRoleLogs(log)).toEqual([
- { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
+ {
+ msg: 'Kubernetes resource updated',
+ description: `Role "${desired.metadata!.name}"`,
+ scope: '[HostReconciler]',
+ attempt: 1,
+ level: 'info',
+ },
])
await (reconciler as any).ensureHostRole(host)
expect(secretGetRule(existing!).verbs).toEqual(['get', 'watch', 'list'])
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
expect(updatedRoleLogs(log)).toEqual([
- { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
+ {
+ msg: 'Kubernetes resource updated',
+ description: `Role "${desired.metadata!.name}"`,
+ scope: '[HostReconciler]',
+ attempt: 1,
+ level: 'info',
+ },
])
} finally {
log.mockRestore()
@@ -237,7 +275,13 @@ describe('Host ensureHostRole no-op gate', () => {
expect(existing?.metadata?.labels?.[HOST_LABEL]).toBe('other-host')
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
expect(updatedRoleLogs(log)).toEqual([
- { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
+ {
+ msg: 'Kubernetes resource updated',
+ description: `Role "${desired.metadata!.name}"`,
+ scope: '[HostReconciler]',
+ attempt: 1,
+ level: 'info',
+ },
])
} finally {
log.mockRestore()
@@ -259,7 +303,13 @@ describe('Host ensureHostRole no-op gate', () => {
expect(existing?.rules?.some(rule => rule.resources?.[0] === 'configmaps')).toBe(false)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
expect(updatedRoleLogs(log)).toEqual([
- { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
+ {
+ msg: 'Kubernetes resource updated',
+ description: `Role "${desired.metadata!.name}"`,
+ scope: '[HostReconciler]',
+ attempt: 1,
+ level: 'info',
+ },
])
} finally {
log.mockRestore()
@@ -284,7 +334,13 @@ describe('Host ensureHostRole no-op gate', () => {
)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
expect(updatedRoleLogs(log)).toEqual([
- { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
+ {
+ msg: 'Kubernetes resource updated',
+ description: `Role "${desired.metadata!.name}"`,
+ scope: '[HostReconciler]',
+ attempt: 1,
+ level: 'info',
+ },
])
} finally {
log.mockRestore()
diff --git a/host-context-controller/src/__tests__/llmHookNetworkPolicyNoopGate.test.ts b/host-context-controller/src/__tests__/llmHookNetworkPolicyNoopGate.test.ts
index a51dcc3e7..916a07b2a 100644
--- a/host-context-controller/src/__tests__/llmHookNetworkPolicyNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/llmHookNetworkPolicyNoopGate.test.ts
@@ -13,14 +13,7 @@ import {
createMockNetworkingApi,
} from '../../test/__fixtures__/testMocks'
import { updatedLogs } from '../../test/__fixtures__/updatedLogs'
-import {
- HOST_LABEL,
- LLMHOOK_LABEL,
- MANAGED_BY_LABEL,
- MANAGED_BY_VALUE,
- POLICY_TYPE_LABEL,
-} from '../constants'
-import { LlmHookReconciler, computePodKey, serviceTargetNpName } from '../llmHookReconciler'
+import { LlmHookReconciler, computePodKey } from '../llmHookReconciler'
import type { HostCRD, LlmHookCRD } from '../types'
import { asApiserverNetworkPolicy, updatedPolicyLogs } from './asApiserverNetworkPolicy'
@@ -123,26 +116,22 @@ describe('LlmHook NetworkPolicy no-op gate', () => {
coreApi.readNamespacedService.mockResolvedValue({
spec: { selector: { app: 'hook-svc' } },
})
- const desired: k8s.V1NetworkPolicy = {
- apiVersion: 'networking.k8s.io/v1',
- kind: 'NetworkPolicy',
- metadata: {
- name: serviceTargetNpName(hook.name),
- namespace: 'llm-hooks',
- labels: {
- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
- [POLICY_TYPE_LABEL]: 'service-hook-ingress',
- [LLMHOOK_LABEL]: hook.name,
- },
- },
- spec: {
- podSelector: { matchLabels: { app: 'hook-svc' } },
- policyTypes: ['Ingress'],
- ingress: [],
- },
- }
+ // Capture the policy built by the production caller before simulating its stored form.
+ networkingApi.readNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 404 })
+ networkingApi.createNamespacedNetworkPolicy.mockResolvedValueOnce({})
+ await (reconciler as any).ensureServiceTargetNetworkPolicy(hook)
+ expect(networkingApi.createNamespacedNetworkPolicy).toHaveBeenCalledOnce()
+ const desired = networkingApi.createNamespacedNetworkPolicy.mock.calls[0][0].body
+ networkingApi.readNamespacedNetworkPolicy.mockClear()
+ networkingApi.createNamespacedNetworkPolicy.mockClear()
networkingApi.readNamespacedNetworkPolicy.mockResolvedValue(asApiserverNetworkPolicy(desired))
+
await (reconciler as any).ensureServiceTargetNetworkPolicy(hook)
+ expect(networkingApi.readNamespacedNetworkPolicy).toHaveBeenCalledExactlyOnceWith({
+ name: desired.metadata!.name,
+ namespace: 'llm-hooks',
+ })
+ expect(networkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
expect(networkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
@@ -151,32 +140,22 @@ describe('LlmHook NetworkPolicy no-op gate', () => {
const host = makeHost(hook.name)
hooks.set(hook.name, hook)
hosts.set(host.name, host)
- const rules = (await (reconciler as any).buildHostEgressRules(
- host
- )) as k8s.V1NetworkPolicyEgressRule[]
- expect(rules.length).toBeGreaterThan(0)
- const desired: k8s.V1NetworkPolicy = {
- apiVersion: 'networking.k8s.io/v1',
- kind: 'NetworkPolicy',
- metadata: {
- name: `mcp-host-${host.name}-egress-llm-hooks`,
- namespace: 'mcp-host',
- labels: {
- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
- [HOST_LABEL]: host.name,
- [POLICY_TYPE_LABEL]: 'llm-hooks-egress',
- },
- },
- spec: {
- podSelector: {
- matchLabels: { [HOST_LABEL]: host.name, [MANAGED_BY_LABEL]: MANAGED_BY_VALUE },
- },
- policyTypes: ['Egress'],
- egress: rules,
- },
- }
+ networkingApi.readNamespacedNetworkPolicy.mockRejectedValueOnce({ code: 404 })
+ networkingApi.createNamespacedNetworkPolicy.mockResolvedValueOnce({})
+ await (reconciler as any).ensureHostEgressNetworkPolicy(host)
+ expect(networkingApi.createNamespacedNetworkPolicy).toHaveBeenCalledOnce()
+ const desired = networkingApi.createNamespacedNetworkPolicy.mock.calls[0][0].body
+ expect(desired.spec?.egress?.length).toBeGreaterThan(0)
+ networkingApi.readNamespacedNetworkPolicy.mockClear()
+ networkingApi.createNamespacedNetworkPolicy.mockClear()
networkingApi.readNamespacedNetworkPolicy.mockResolvedValue(asApiserverNetworkPolicy(desired))
+
await (reconciler as any).ensureHostEgressNetworkPolicy(host)
+ expect(networkingApi.readNamespacedNetworkPolicy).toHaveBeenCalledExactlyOnceWith({
+ name: desired.metadata!.name,
+ namespace: 'mcp-host',
+ })
+ expect(networkingApi.createNamespacedNetworkPolicy).not.toHaveBeenCalled()
expect(networkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
diff --git a/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.ts b/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.ts
index f61989ea6..75a2c3d9a 100644
--- a/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.ts
+++ b/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.ts
@@ -223,7 +223,7 @@ describe('Host read-first RBAC and PVC contracts', () => {
expect(await count('Role', 'skipped')).toBe(0)
})
- it.each([403, 409, 500])('propagates Role PUT%d without introducing a retry', async code => {
+ it.each([403, 500])('propagates Role PUT%d without retrying', async code => {
const f = fixture()
const failure = { code }
f.rbac.replaceNamespacedRole.mockRejectedValueOnce(failure)
@@ -234,6 +234,69 @@ describe('Host read-first RBAC and PVC contracts', () => {
expect(await count('Role', 'skipped')).toBe(0)
})
+ it('rereads a conflicted Role and replaces using the fresh resourceVersion', async () => {
+ const f = fixture()
+ f.rbac.readNamespacedRole
+ .mockResolvedValueOnce({ metadata: { name: 'host-rbac-host', resourceVersion: '17' } })
+ .mockResolvedValueOnce({ metadata: { name: 'host-rbac-host', resourceVersion: '18' } })
+ f.rbac.replaceNamespacedRole.mockRejectedValueOnce({ code: 409 })
+ await expect((f.reconciler as any).ensureHostRole(host)).resolves.toBeUndefined()
+ expect(f.rbac.readNamespacedRole).toHaveBeenCalledTimes(2)
+ expect(f.rbac.replaceNamespacedRole).toHaveBeenCalledTimes(2)
+ expect(
+ f.rbac.replaceNamespacedRole.mock.calls.map(
+ ([request]) => request.body.metadata.resourceVersion
+ )
+ ).toEqual(['17', '18'])
+ expect(f.rbac.createNamespacedRole).not.toHaveBeenCalled()
+ expect(await count('Role', 'skipped')).toBe(1)
+ })
+
+ it('accepts a Role already converged by the competing writer after a conflict', async () => {
+ const f = fixture()
+ f.rbac.replaceNamespacedRole.mockImplementationOnce(async ({ body }) => {
+ f.rbac.readNamespacedRole.mockResolvedValue({
+ ...structuredClone(body),
+ metadata: { ...body.metadata, resourceVersion: '18' },
+ })
+ throw { code: 409 }
+ })
+ await expect((f.reconciler as any).ensureHostRole(host)).resolves.toBeUndefined()
+ expect(f.rbac.readNamespacedRole).toHaveBeenCalledTimes(2)
+ expect(f.rbac.replaceNamespacedRole).toHaveBeenCalledOnce()
+ expect(f.rbac.createNamespacedRole).not.toHaveBeenCalled()
+ expect(await count('Role', 'skipped')).toBe(1)
+ })
+
+ it('propagates the final Role conflict after three attempts', async () => {
+ const f = fixture()
+ const failure = { code: 409 }
+ f.rbac.replaceNamespacedRole.mockRejectedValue(failure)
+ await expect((f.reconciler as any).ensureHostRole(host)).rejects.toBe(failure)
+ expect(f.rbac.readNamespacedRole).toHaveBeenCalledTimes(3)
+ expect(f.rbac.replaceNamespacedRole).toHaveBeenCalledTimes(3)
+ expect(f.rbac.createNamespacedRole).not.toHaveBeenCalled()
+ expect(await count('Role', 'skipped')).toBe(0)
+ })
+
+ it('rechecks admission before retrying a conflicted Role write', async () => {
+ const f = fixture()
+ let current = true
+ const retired = new Error('Host spec changed while the Role write was in flight')
+ retired.name = 'HostMutationSpecRevisionChangedError'
+ const revalidate = () => {
+ if (!current) throw retired
+ }
+ f.rbac.replaceNamespacedRole.mockImplementationOnce(async () => {
+ current = false
+ throw { code: 409 }
+ })
+ await expect((f.reconciler as any).ensureHostRole(host, revalidate)).rejects.toBe(retired)
+ expect(f.rbac.replaceNamespacedRole).toHaveBeenCalledOnce()
+ expect(f.rbac.createNamespacedRole).not.toHaveBeenCalled()
+ expect(await count('Role', 'skipped')).toBe(0)
+ })
+
it('preserves a bound Host PVC without attempting an immutable update', async () => {
const f = fixture()
f.core.readNamespacedPersistentVolumeClaim.mockResolvedValueOnce({
diff --git a/host-context-controller/src/hostReconciler.readFirst.test.ts b/host-context-controller/src/hostReconciler.readFirst.test.ts
index e6f443794..5270b45a6 100644
--- a/host-context-controller/src/hostReconciler.readFirst.test.ts
+++ b/host-context-controller/src/hostReconciler.readFirst.test.ts
@@ -168,6 +168,48 @@ describe('Host read-first Service and Deployment contracts', () => {
expect(await count('Deployment', 'skipped')).toBe(0)
})
+ it.each([0, 1])(
+ 'builds a present Host Deployment once per attempt with fresh state (%i conflicts)',
+ async conflicts => {
+ const { apps, reconciler } = fixture()
+ const existing = reconciler.buildDeployment(host, [], 'old-revision')
+ apps.readNamespacedDeployment.mockImplementation(async () => ({
+ ...existing,
+ metadata: {
+ ...existing.metadata,
+ resourceVersion: String(apps.readNamespacedDeployment.mock.calls.length),
+ },
+ }))
+ if (conflicts) apps.replaceNamespacedDeployment.mockRejectedValueOnce({ code: 409 })
+ const build = vi.spyOn(reconciler, 'buildDeployment')
+ const resolveState = vi.fn(async () => {
+ const attempt = apps.readNamespacedDeployment.mock.calls.length
+ return {
+ runtimeTokenRevision: `fresh-revision-${attempt}`,
+ lifecycle: { stateless: true, state: attempt === 1 ? 'active' : 'suspended' },
+ }
+ })
+
+ await (reconciler as any).ensureDeployment(host, [], 'old-revision', undefined, resolveState)
+
+ const attempts = conflicts + 1
+ expect(apps.readNamespacedDeployment).toHaveBeenCalledTimes(attempts)
+ expect(resolveState).toHaveBeenCalledTimes(attempts)
+ expect(build).toHaveBeenCalledTimes(attempts)
+ expect(apps.createNamespacedDeployment).not.toHaveBeenCalled()
+ expect(apps.replaceNamespacedDeployment).toHaveBeenCalledTimes(attempts)
+ for (let attempt = 1; attempt <= attempts; attempt++) {
+ const body = apps.replaceNamespacedDeployment.mock.calls[attempt - 1][0]
+ .body as k8s.V1Deployment
+ expect(body.metadata?.resourceVersion).toBe(String(attempt))
+ expect(
+ body.spec?.template.metadata?.annotations?.['clerum.io/runtime-token-revision']
+ ).toBe(`fresh-revision-${attempt}`)
+ expect(body.spec?.replicas).toBe(attempt === 1 ? 1 : 0)
+ }
+ }
+ )
+
it('retains a Host Service POST failure without recording presence suppression', async () => {
const { core, reconciler } = fixture()
core.readNamespacedService.mockRejectedValueOnce({ code: 404 })
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 45c941abc..d903d7d4a 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -1117,12 +1117,18 @@ export class HostReconciler {
),
converge: async read => {
try {
- const existing = await read()
- revalidate?.()
- if (roleMatchesDesired(body, existing)) return
- body.metadata!.resourceVersion = existing.metadata?.resourceVersion
- await this.rbacApi.replaceNamespacedRole({ name, namespace: host.namespace, body })
- log.info('Updated Host Role', { host: host.name })
+ // Retry optimistic-lock contention, but never continue provisioning
+ // with stale permissions after the bounded retry budget is exhausted.
+ await replaceWithConflictRetry({
+ description: `Role "${name}"`,
+ logPrefix: '[HostReconciler]',
+ body,
+ read,
+ mutationAllowed,
+ isUpToDate: roleMatchesDesired,
+ replace: next =>
+ this.rbacApi.replaceNamespacedRole({ name, namespace: host.namespace, body: next }),
+ })
} catch (error) {
// Preserve the existing disappearance policy, without swallowing
// authorization, transport, or terminal conflict failures.
@@ -3374,8 +3380,7 @@ export class HostReconciler {
})
)
} catch (error) {
- if (isBenignSupersessionError(error) || (error != null && getErrorCode(error) === 409))
- throw error
+ if (error != null && getErrorCode(error) === 409) throw error
log.error('Failed to create Host PVC', { host: host.name, err: error })
}
},
@@ -3420,8 +3425,7 @@ export class HostReconciler {
this.coreApi.createNamespacedService({ namespace: host.namespace, body: service })
)
} catch (error) {
- if (isBenignSupersessionError(error) || (error != null && getErrorCode(error) === 409))
- throw error
+ if (error != null && getErrorCode(error) === 409) throw error
log.error('Failed to create Host Service', { host: host.name, err: error })
}
},
@@ -3492,7 +3496,6 @@ export class HostReconciler {
replaceWithConflictRetry({
description: `Deployment "${host.name}"`,
logPrefix: '[HostReconciler]',
- body: this.buildDeployment(host, mounts, runtimeTokenRevision, lifecycle),
resolveBody: buildDesiredDeployment,
mergeExisting: preserveHostDeploymentAnnotations,
isUpToDate: deploymentMatchesDesired,
diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.ts
index 3a58b7ce6..c4e6790f6 100644
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@ -133,35 +133,36 @@ export async function ensureResource<T extends { metadata?: { name?: string } }>
*/
export async function replaceWithConflictRetry<
T extends { metadata?: { resourceVersion?: string }; kind?: string },
->(opts: {
- description: string
- logPrefix: string
- body: T
- /** Rebuild mutable desired state immediately before each replace attempt. */
- resolveBody?: () => T | Promise<T>
- read: () => Promise<T>
- replace: (body: T) => Promise<unknown>
- mergeExisting?: (body: T, existing: T) => T
- /**
- * Called after the desired object has been merged with server-owned fields.
- * Returning true avoids a no-op replace (and therefore avoids a needless
- * resourceVersion/generation bump) while retaining the conflict-retry path
- * when a meaningful change is still required.
- */
- isUpToDate?: (body: T, existing: T) => boolean
- /** Reject an object whose identity or ownership is unsafe to replace. */
- validateExisting?: (existing: T) => void
- /** Rechecked immediately before every Kubernetes write attempt. */
- mutationAllowed?: () => boolean
- /** Admission-sensitive callers must not treat an absent object as applied. */
- missingIsError?: boolean
- maxAttempts?: number
-}): Promise<void> {
+>(
+ opts: {
+ description: string
+ logPrefix: string
+ read: () => Promise<T>
+ replace: (body: T) => Promise<unknown>
+ mergeExisting?: (body: T, existing: T) => T
+ /**
+ * Called after the desired object has been merged with server-owned fields.
+ * Returning true avoids a no-op replace (and therefore avoids a needless
+ * resourceVersion/generation bump) while retaining the conflict-retry path
+ * when a meaningful change is still required.
+ */
+ isUpToDate?: (body: T, existing: T) => boolean
+ /** Reject an object whose identity or ownership is unsafe to replace. */
+ validateExisting?: (existing: T) => void
+ /** Rechecked immediately before every Kubernetes write attempt. */
+ mutationAllowed?: () => boolean
+ /** Admission-sensitive callers must not treat an absent object as applied. */
+ missingIsError?: boolean
+ maxAttempts?: number
+ } & (
+ | { body: T; resolveBody?: () => T | Promise<T> }
+ /** Rebuild desired state before each attempt without an unused eager body. */
+ | { body?: never; resolveBody: () => T | Promise<T> }
+ )
+): Promise<void> {
const {
description,
logPrefix,
- body,
- resolveBody,
read,
replace,
mergeExisting,
@@ -187,7 +188,8 @@ export async function replaceWithConflictRetry<
throw err
}
validateExisting?.(existing)
- const desired = resolveBody ? await resolveBody() : body
+ // The options union requires body whenever resolveBody is absent.
+ const desired: T = opts.resolveBody ? await opts.resolveBody() : opts.body!
const base: T = {
...desired,
metadata: { ...desired.metadata, resourceVersion: existing.metadata?.resourceVersion },