Skip to content

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

TypeScript

feat(hcc): complete read-first RBAC and storage convergence

Alfredo Lopez1ec1b7aa852f
diff --git a/control-ui/e2e/qa-recorder-shared-fs-folders.spec.ts b/control-ui/e2e/qa-recorder-shared-fs-folders.spec.ts
index 7ae14ca05..f9236aca6 100644
--- a/control-ui/e2e/qa-recorder-shared-fs-folders.spec.ts
+++ b/control-ui/e2e/qa-recorder-shared-fs-folders.spec.ts
@@ -97,6 +97,10 @@ test.describe('optional QA recorder: Control UI SharedFileSystem folders', () =>
expect(resource.metadata?.uid).toEqual(expect.any(String))
createdUid = resource.metadata!.uid
expect(createdUid).not.toBe('')
+ testInfo.annotations.push({
+ type: 'owned-shared-filesystem',
+ description: JSON.stringify({ name, uid: createdUid, retainOnDelete: false }),
+ })
expect(resource.spec).toMatchObject({
size: '5Gi',
accessModes: ['ReadWriteOnce'],
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 72a2f6ee1..6a1b59c5a 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.565",
+ "version": "0.1.566",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.565",
+ "version": "0.1.566",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --git a/control-ui/package.json b/control-ui/package.json
index 82f1c7427..cc76bae98 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.565",
+ "version": "0.1.566",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/host-context-controller/CREATE_OBSERVABILITY.md b/host-context-controller/CREATE_OBSERVABILITY.md
index bf0001a29..25e0cd29e 100644
--- a/host-context-controller/CREATE_OBSERVABILITY.md
+++ b/host-context-controller/CREATE_OBSERVABILITY.md
@@ -1,8 +1,10 @@
# HCC create and existence-read metrics
-This instrumentation supports [issue #598](https://github.com/evenfire-ai/evenfire/issues/598). It observes the existing reconciliation
-paths; it does not introduce read-before-create, extra Kubernetes requests,
-ownership rules, retries, or updates to resources currently left unchanged.
+The read-first stage of [issue #598](https://github.com/evenfire-ai/evenfire/issues/598)
+uses `ensureResource` at 22 create expressions. Existing resources retain their
+convergence or preservation policies. The runtime Secret and safety-inventory
+NetworkPolicy writer remain exempt; all 24 create expressions are instrumented.
+Only an observed absence permits a new POST.
## Counters
@@ -17,7 +19,7 @@ request bodies, or exception messages become metric labels.
| `clerum_hcc_creates_total` | `created` | The create callback resolved successfully. |
| | `conflict` | The create callback rejected with HTTP 409. |
| | `error` | The create callback rejected for any other reason, including 403, 5xx, network errors, or synchronous client failure. |
-| | `skipped` | Reserved for presence-based suppression in the read-first stage; remains zero in this PR. |
+| | `skipped` | One successful presence-based suppression of POST; excludes errors, cancellation, retries and attempted POST409. |
| `clerum_hcc_existence_reads_total` | `found` | An instrumented existence read resolved successfully; its result is not validated or altered. |
| | `absent` | An instrumented read rejected with HTTP 404; the original error still reaches the caller. |
| | `error` | An instrumented read rejected for any other reason, including HTTP 409. |
@@ -67,19 +69,19 @@ count as `error` when the wrapper catches them; the original rejection is retain
All 24 production `createNamespaced*` expressions are observed, including the
already-read-first Secret and the safety-inventory NetworkPolicy writer. Their
-exemption from future conversion does not exempt them from measurement.
+exemption from conversion does not exempt them from measurement.
-The 21 instrumented existence-read expressions are:
+The 26 instrumented existence-read expressions are:
-| File | Read paths | Expressions |
-| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ----------: |
-| `src/utils.ts` | Shared NetworkPolicy conflict convergence | 1 |
-| `src/hostReconciler.ts` | Role; runtime Secret; channel-reader Service; channel-reader Deployment outer read and retry; PVC; Host Service and Deployment | 8 |
-| `src/reconciler.ts` | ConfigMap, Deployment, Service conflict convergence | 3 |
-| `src/llmHookReconciler.ts` | Deployment, Service, NetworkPolicy conflict convergence | 3 |
-| `src/sharedFileSystemReconciler.ts` | Deployment conflict convergence | 1 |
-| `src/k8s/gfsK8sApi.ts` | Deployment update check and conflict convergence; PDB conflict convergence | 3 |
-| `src/networkPolicyReconciler.ts` | Fresh external-egress observation; safety-create conflict convergence | 2 |
+| File | Read paths | Expressions |
+| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ----------: |
+| `src/utils.ts` | Shared NetworkPolicy conflict convergence | 1 |
+| `src/hostReconciler.ts` | ServiceAccount, Role, RoleBinding; runtime Secret; channel-reader Service/Deployment; PVC; Host Service and Deployment | 9 |
+| `src/reconciler.ts` | ConfigMap, Deployment, Service conflict convergence | 3 |
+| `src/llmHookReconciler.ts` | Deployment, Service, NetworkPolicy conflict convergence | 3 |
+| `src/sharedFileSystemReconciler.ts` | PVC, Deployment and Service presence/convergence | 3 |
+| `src/k8s/gfsK8sApi.ts` | PVC/Service presence; Deployment update check/convergence; PDB convergence | 5 |
+| `src/networkPolicyReconciler.ts` | Fresh external-egress observation; safety-create conflict convergence | 2 |
Counts refer to source expressions, not requests per reconciliation. Retry paths
can execute more than once. The fresh external-egress helper has several callers;
@@ -94,13 +96,47 @@ or its read path changes; do not instrument both the API call and its retry wrap
The read-inventory test scans all production TypeScript under `src` for direct
dot-property `readNamespaced*`/`readCluster*` calls. Each must be observed or match an explicit
exclusion keyed by file, enclosing operation and SDK method, with an expected
-expression count and reason. It currently accounts for 21 observed expressions
+expression count and reason. It currently accounts for 26 observed expressions
and 43 excluded ones. New unclassified reads and stale exclusions fail the test.
This is structural coverage, not execution evidence: changed purpose inside an
excluded operation still needs review, and computed-property or indirect/aliased calls are outside this
static-analysis guarantee. The behavioral tests and deployed validation
remain separate; an AST pass does not prove all those paths ran.
+## Read-first contract
+
+`existing === undefined` requires an instrumented GET; `existing === null` is a
+caller-observed absence. A present snapshot is consumed once and is not another
+GET. A read resolving without `metadata.name` is a contract error, never absence.
+POST409 discards the absence and converges through real reads. The existing
+replace loop owns validation, desired-body resolution, merge, no-op, mutation
+fences and the original retry budget. Its 404 disappearance policy is distinct
+from the initial GET404 that permits creation.
+
+SDK callbacks remain instrumented at their sites. `onSkipped` retains the
+literal kind there and increments once only after successful presence-based
+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.
+
+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
+create/update catches stay inside those callbacks, outside the initial GET;
+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.
+
+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;
+an `ext-egress-` name alone cannot attribute or excuse a residual conflict.
+
+For stable, already-present resources, verify that POST is suppressed while
+convergence and business state still occur. Separate legitimate new resources,
+races and cold start. A lower create count alone does not establish causality;
+`absent` does not guarantee a POST if the mutation fence expires afterward.
+
## Historical evidence and attribution limits
The historical aggregate `regimen-2026-09-09-agregado.csv` and its companion
@@ -154,10 +190,11 @@ data did not contain GET records; no API-server read rate is inferred from that
absence. The read counter only covers the explicit inventory above.
No fixed GET-to-POST ratio is required: an existing POST409→GET path already
-reads, whereas a create-and-ignore-conflict path does not. Future read-first
-work must preserve that distinction. This change does not demonstrate savings
+reads, whereas a create-and-ignore-conflict path does not. Read-first preserves
+that distinction. This change does not demonstrate savings
in CPU, latency, admission cost, APF, or request volume.
-The next read-first PR remains dependent on deployment and validated measurement
-of this instrumentation. T0, T1, T2, CI, and browser E2E are separate evidence
-lanes; see [the local runtime runbook](../docs/testing/minikube-t2-runbook.md).
+The instrumentation prerequisite was delivered in [PR #599](https://github.com/evenfire-ai/evenfire/pull/599).
+Its deployed observation is a baseline, not validation of the read-first
+candidate. T0, T1, T2, CI, browser E2E and deployed measurements are separate
+evidence lanes; see [the local runtime runbook](../docs/testing/minikube-t2-runbook.md).
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index f6e93875e..dba82bee6 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.306",
+ "version": "0.1.307",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.306",
+ "version": "0.1.307",
"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 d95e80a36..7360143fa 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.306",
+ "version": "0.1.307",
"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__/hostReconciler.mounts.test.ts b/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
index 9c11b2753..7f6f24ed4 100644
--- a/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
+++ b/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts
@@ -1259,7 +1259,19 @@ describe('HostReconciler.reconcile — uses resolveContextMounts', () => {
// Stub APIs to capture the Deployment body and ack everything.
coreApi: {
readNamespacedSecret: readSecretWithChannelReaderRuntimeAuthLabels(),
- createNamespacedServiceAccount: vi.fn(async () => ({})),
+ createNamespacedServiceAccount: vi.fn(),
+ readNamespacedServiceAccount: vi.fn(async ({ name, namespace }) => ({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: {
+ 'clerum.io/host': 'team-mission',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ })),
createNamespacedService: vi.fn(),
readNamespacedService: vi.fn(async ({ name, namespace }) => ({
metadata: {
@@ -1279,11 +1291,48 @@ describe('HostReconciler.reconcile — uses resolveContextMounts', () => {
replaceNamespacedSecret: vi.fn(async () => ({})),
deleteNamespacedPersistentVolumeClaim: vi.fn(),
createNamespacedPersistentVolumeClaim: vi.fn(async () => ({})),
- readNamespacedPersistentVolumeClaim: vi.fn(),
+ readNamespacedPersistentVolumeClaim: vi.fn(async ({ name, namespace }) => ({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: {
+ 'clerum.io/host': 'team-mission',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ spec: { volumeName: 'bound-context-volume' },
+ })),
} as unknown as k8s.CoreV1Api,
rbacApi: {
- createNamespacedRole: vi.fn(async () => ({})),
- createNamespacedRoleBinding: vi.fn(async () => ({})),
+ createNamespacedRole: vi.fn(),
+ readNamespacedRole: vi.fn(async ({ name, namespace }) => ({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: {
+ 'clerum.io/host': 'team-mission',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ })),
+ replaceNamespacedRole: vi.fn(async ({ body }) => body),
+ createNamespacedRoleBinding: vi.fn(),
+ readNamespacedRoleBinding: vi.fn(async ({ name, namespace }) => ({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: {
+ 'clerum.io/host': 'team-mission',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ })),
} as unknown as k8s.RbacAuthorizationV1Api,
networkingApi: {
createNamespacedNetworkPolicy: vi.fn(async () => ({})),
@@ -1356,7 +1405,19 @@ describe('HostReconciler.reconcile — uses resolveContextMounts', () => {
const reconciler = new HostReconciler(makeStubKc(), {
coreApi: {
readNamespacedSecret: readSecretWithChannelReaderRuntimeAuthLabels(desktopHost),
- createNamespacedServiceAccount: vi.fn(async () => ({})),
+ createNamespacedServiceAccount: vi.fn(),
+ readNamespacedServiceAccount: vi.fn(async ({ name, namespace }) => ({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: {
+ 'clerum.io/host': 'team-mission',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ })),
createNamespacedService: vi.fn(),
readNamespacedService: vi.fn(async ({ name, namespace }) => ({
metadata: {
@@ -1376,11 +1437,48 @@ describe('HostReconciler.reconcile — uses resolveContextMounts', () => {
replaceNamespacedSecret: vi.fn(async () => ({})),
deleteNamespacedPersistentVolumeClaim: vi.fn(),
createNamespacedPersistentVolumeClaim: vi.fn(async () => ({})),
- readNamespacedPersistentVolumeClaim: vi.fn(),
+ readNamespacedPersistentVolumeClaim: vi.fn(async ({ name, namespace }) => ({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: {
+ 'clerum.io/host': 'team-mission',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ spec: { volumeName: 'bound-context-volume' },
+ })),
} as unknown as k8s.CoreV1Api,
rbacApi: {
- createNamespacedRole: vi.fn(async () => ({})),
- createNamespacedRoleBinding: vi.fn(async () => ({})),
+ createNamespacedRole: vi.fn(),
+ readNamespacedRole: vi.fn(async ({ name, namespace }) => ({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: {
+ 'clerum.io/host': 'team-mission',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ })),
+ replaceNamespacedRole: vi.fn(async ({ body }) => body),
+ createNamespacedRoleBinding: vi.fn(),
+ readNamespacedRoleBinding: vi.fn(async ({ name, namespace }) => ({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: {
+ 'clerum.io/host': 'team-mission',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ },
+ })),
} as unknown as k8s.RbacAuthorizationV1Api,
networkingApi: networkingApi as unknown as k8s.NetworkingV1Api,
appsApi: {
diff --git a/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
index 4eb9082b6..daa84119b 100644
--- a/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
+++ b/host-context-controller/src/__tests__/hostRoleNoopGate.test.ts
@@ -18,7 +18,7 @@ import {
import { HOST_LABEL } from '../constants'
import { HostReconciler } from '../hostReconciler'
import type { HostCRD } from '../types'
-import { asApiserverPolicyRule, asApiserverRole, updatedRoleLogs } from './asApiserverRole'
+import { asApiserverPolicyRule, asApiserverRole } from './asApiserverRole'
function makeHost(secretRef = 'secret'): HostCRD {
return {
@@ -33,8 +33,14 @@ function makeHost(secretRef = 'secret'): HostCRD {
}
}
-function desiredFromCreate(rbacApi: MockRbacApi): k8s.V1Role {
- return rbacApi.createNamespacedRole.mock.calls[0][0].body as k8s.V1Role
+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 }]
+ : []
+ })
}
function secretGetRule(role: k8s.V1Role): k8s.V1PolicyRule {
@@ -49,8 +55,9 @@ describe('Host ensureHostRole no-op gate', () => {
let rbacApi: MockRbacApi
let reconciler: HostReconciler
const host = makeHost()
+ let desired: k8s.V1Role
- beforeEach(() => {
+ beforeEach(async () => {
rbacApi = createMockRbacApi()
reconciler = new HostReconciler(makeStubKc(), {
coreApi: asCoreApi(createMockCoreApi()),
@@ -59,12 +66,21 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi: asRbacApi(rbacApi),
customApi: asCustomApi(createMockCustomApi()),
})
+ // Capture the real authored Role once through an explicit absent-resource
+ // setup. The measured reconcile below must operate on a present snapshot.
+ rbacApi.readNamespacedRole.mockRejectedValueOnce({ code: 404 })
+ await (reconciler as any).ensureHostRole(host)
+ expect(rbacApi.createNamespacedRole).toHaveBeenCalledOnce()
+ desired = structuredClone(rbacApi.createNamespacedRole.mock.calls[0][0].body)
+ rbacApi.createNamespacedRole.mockClear()
+ rbacApi.readNamespacedRole.mockClear()
})
- it('CREATE-ROLE-1: successful create never reads or replaces', async () => {
+ it('CREATE-ROLE-1: absent Role is read then created without replacement', async () => {
+ rbacApi.readNamespacedRole.mockRejectedValueOnce({ code: 404 })
await (reconciler as any).ensureHostRole(host)
expect(rbacApi.createNamespacedRole).toHaveBeenCalledOnce()
- expect(rbacApi.readNamespacedRole).not.toHaveBeenCalled()
+ expect(rbacApi.readNamespacedRole).toHaveBeenCalledOnce()
expect(rbacApi.replaceNamespacedRole).not.toHaveBeenCalled()
})
@@ -72,7 +88,7 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
let existing: k8s.V1Role | undefined
rbacApi.readNamespacedRole.mockImplementation(() => {
- existing = asApiserverRole(desiredFromCreate(rbacApi))
+ existing = asApiserverRole(desired)
return Promise.resolve(existing)
})
const log = vi.spyOn(console, 'log')
@@ -80,18 +96,18 @@ describe('Host ensureHostRole no-op gate', () => {
await (reconciler as any).ensureHostRole(host)
expect(rbacApi.readNamespacedRole).toHaveBeenCalledOnce()
expect(existing?.rules?.length).toBeGreaterThan(0)
- const authoredKeys = Object.keys(desiredFromCreate(rbacApi).rules![0] ?? {})
+ const authoredKeys = Object.keys(desired.rules![0] ?? {})
const liveKeys = Object.keys(existing!.rules![0] ?? {})
// Author order vs client-node attributeTypeMap — canonicalize must run.
expect(authoredKeys).toEqual(['apiGroups', 'resources', 'resourceNames', 'verbs'])
expect(liveKeys).toEqual(['apiGroups', 'resourceNames', 'resources', 'verbs'])
expect(authoredKeys).not.toEqual(liveKeys)
- const authoredLabelKeys = Object.keys(desiredFromCreate(rbacApi).metadata?.labels ?? {})
+ const authoredLabelKeys = Object.keys(desired.metadata?.labels ?? {})
const liveLabelKeys = Object.keys(existing!.metadata?.labels ?? {})
expect(authoredLabelKeys).not.toEqual(liveLabelKeys)
- expect(desiredFromCreate(rbacApi).rules?.length).toBeGreaterThan(0)
+ expect(desired.rules?.length).toBeGreaterThan(0)
expect(rbacApi.replaceNamespacedRole).not.toHaveBeenCalled()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([])
+ expect(updatedRoleLogs(log)).toEqual([])
} finally {
log.mockRestore()
}
@@ -101,7 +117,7 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
let existing: k8s.V1Role | undefined
rbacApi.readNamespacedRole.mockImplementation(() => {
- const live = structuredClone(desiredFromCreate(rbacApi))
+ const live = structuredClone(desired)
const currentSecretRef = host.spec.secretRef
if (!currentSecretRef) {
throw new Error('test host is missing secretRef')
@@ -115,8 +131,8 @@ describe('Host ensureHostRole no-op gate', () => {
await (reconciler as any).ensureHostRole(makeHost('rotated-secret'))
expect(existing?.rules?.length).toBeGreaterThan(0)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
- '[HostReconciler] Updated Role "host-chatllm-config-reader"',
+ expect(updatedRoleLogs(log)).toEqual([
+ { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
])
} finally {
log.mockRestore()
@@ -127,7 +143,7 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
let existing: k8s.V1Role | undefined
rbacApi.readNamespacedRole.mockImplementation(() => {
- const live = structuredClone(desiredFromCreate(rbacApi))
+ const live = structuredClone(desired)
live.rules = [...(live.rules ?? []), { apiGroups: [''], resources: ['pods'], verbs: ['get'] }]
existing = asApiserverRole(live)
return Promise.resolve(existing)
@@ -135,10 +151,10 @@ describe('Host ensureHostRole no-op gate', () => {
const log = vi.spyOn(console, 'log')
try {
await (reconciler as any).ensureHostRole(host)
- expect(existing?.rules?.length).toBe((desiredFromCreate(rbacApi).rules?.length ?? 0) + 1)
+ expect(existing?.rules?.length).toBe((desired.rules?.length ?? 0) + 1)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
- '[HostReconciler] Updated Role "host-chatllm-config-reader"',
+ expect(updatedRoleLogs(log)).toEqual([
+ { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
])
} finally {
log.mockRestore()
@@ -149,7 +165,7 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
let existing: k8s.V1Role | undefined
rbacApi.readNamespacedRole.mockImplementation(() => {
- const live = structuredClone(desiredFromCreate(rbacApi))
+ const live = structuredClone(desired)
const secretRule = secretGetRule(live)
secretRule.verbs = [...(secretRule.verbs ?? []), 'update']
existing = asApiserverRole(live)
@@ -160,8 +176,8 @@ describe('Host ensureHostRole no-op gate', () => {
await (reconciler as any).ensureHostRole(host)
expect(existing?.rules?.some(rule => rule.verbs?.includes('update'))).toBe(true)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
- '[HostReconciler] Updated Role "host-chatllm-config-reader"',
+ expect(updatedRoleLogs(log)).toEqual([
+ { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
])
} finally {
log.mockRestore()
@@ -175,7 +191,7 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi.readNamespacedRole.mockImplementation(() => {
readPass += 1
if (readPass === 1) {
- const live = structuredClone(desiredFromCreate(rbacApi))
+ const live = structuredClone(desired)
secretGetRule(live).verbs = ['watch', 'get', 'list']
existing = asApiserverRole(live)
return Promise.resolve(existing)
@@ -192,15 +208,15 @@ describe('Host ensureHostRole no-op gate', () => {
await (reconciler as any).ensureHostRole(host)
expect(secretGetRule(existing!).verbs).toEqual(['watch', 'get', 'list'])
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
- '[HostReconciler] Updated Role "host-chatllm-config-reader"',
+ expect(updatedRoleLogs(log)).toEqual([
+ { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
])
await (reconciler as any).ensureHostRole(host)
expect(secretGetRule(existing!).verbs).toEqual(['get', 'watch', 'list'])
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
- '[HostReconciler] Updated Role "host-chatllm-config-reader"',
+ expect(updatedRoleLogs(log)).toEqual([
+ { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
])
} finally {
log.mockRestore()
@@ -211,7 +227,7 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
let existing: k8s.V1Role | undefined
rbacApi.readNamespacedRole.mockImplementation(() => {
- existing = asApiserverRole(desiredFromCreate(rbacApi))
+ existing = asApiserverRole(desired)
existing.metadata!.labels![HOST_LABEL] = 'other-host'
return Promise.resolve(existing)
})
@@ -220,8 +236,8 @@ describe('Host ensureHostRole no-op gate', () => {
await (reconciler as any).ensureHostRole(host)
expect(existing?.metadata?.labels?.[HOST_LABEL]).toBe('other-host')
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
- '[HostReconciler] Updated Role "host-chatllm-config-reader"',
+ expect(updatedRoleLogs(log)).toEqual([
+ { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
])
} finally {
log.mockRestore()
@@ -232,7 +248,7 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
let existing: k8s.V1Role | undefined
rbacApi.readNamespacedRole.mockImplementation(() => {
- const live = structuredClone(desiredFromCreate(rbacApi))
+ const live = structuredClone(desired)
live.rules = (live.rules ?? []).filter(rule => rule.resources?.[0] !== 'configmaps')
existing = asApiserverRole(live)
return Promise.resolve(existing)
@@ -242,8 +258,8 @@ describe('Host ensureHostRole no-op gate', () => {
await (reconciler as any).ensureHostRole(host)
expect(existing?.rules?.some(rule => rule.resources?.[0] === 'configmaps')).toBe(false)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
- '[HostReconciler] Updated Role "host-chatllm-config-reader"',
+ expect(updatedRoleLogs(log)).toEqual([
+ { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
])
} finally {
log.mockRestore()
@@ -254,7 +270,7 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
let existing: k8s.V1Role | undefined
rbacApi.readNamespacedRole.mockImplementation(() => {
- const live = structuredClone(desiredFromCreate(rbacApi))
+ const live = structuredClone(desired)
const secretRule = secretGetRule(live)
secretRule.resourceNames = (secretRule.resourceNames ?? []).filter((_, index) => index !== 1)
existing = asApiserverRole(live)
@@ -264,11 +280,11 @@ describe('Host ensureHostRole no-op gate', () => {
try {
await (reconciler as any).ensureHostRole(host)
expect(secretGetRule(existing!).resourceNames).toHaveLength(
- (secretGetRule(desiredFromCreate(rbacApi)).resourceNames?.length ?? 0) - 1
+ (secretGetRule(desired).resourceNames?.length ?? 0) - 1
)
expect(rbacApi.replaceNamespacedRole).toHaveBeenCalledOnce()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([
- '[HostReconciler] Updated Role "host-chatllm-config-reader"',
+ expect(updatedRoleLogs(log)).toEqual([
+ { msg: 'Updated Host Role', host: 'chatllm', level: 'info' },
])
} finally {
log.mockRestore()
@@ -279,7 +295,7 @@ describe('Host ensureHostRole no-op gate', () => {
rbacApi.createNamespacedRole.mockRejectedValue({ code: 409 })
let existing: k8s.V1Role | undefined
rbacApi.readNamespacedRole.mockImplementation(() => {
- existing = asApiserverRole(desiredFromCreate(rbacApi))
+ existing = asApiserverRole(desired)
existing.metadata!.labels!['argocd.argoproj.io/instance'] = 'clerum-dev'
return Promise.resolve(existing)
})
@@ -288,7 +304,7 @@ describe('Host ensureHostRole no-op gate', () => {
await (reconciler as any).ensureHostRole(host)
expect(existing?.metadata?.labels?.['argocd.argoproj.io/instance']).toBe('clerum-dev')
expect(rbacApi.replaceNamespacedRole).not.toHaveBeenCalled()
- expect(updatedRoleLogs(log, '"host-chatllm-config-reader"')).toEqual([])
+ expect(updatedRoleLogs(log)).toEqual([])
} finally {
log.mockRestore()
}
diff --git a/host-context-controller/src/__tests__/reconciler.pod-hardening.test.ts b/host-context-controller/src/__tests__/reconciler.pod-hardening.test.ts
index 675ac83ad..a8f1d7efc 100644
--- a/host-context-controller/src/__tests__/reconciler.pod-hardening.test.ts
+++ b/host-context-controller/src/__tests__/reconciler.pod-hardening.test.ts
@@ -110,6 +110,8 @@ describe('McpServer generated pod hardening', () => {
})
it('applies the same token and seccomp boundary to remote egress proxy pods', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
await reconciler.reconcile(
makeServer({
name: 'remote-mcp',
diff --git a/host-context-controller/src/__tests__/reconciler.remote.test.ts b/host-context-controller/src/__tests__/reconciler.remote.test.ts
index 833e78037..a14c0a17a 100644
--- a/host-context-controller/src/__tests__/reconciler.remote.test.ts
+++ b/host-context-controller/src/__tests__/reconciler.remote.test.ts
@@ -12,6 +12,7 @@ import {
createMockCustomApi,
} from '../../test/__fixtures__/testMocks'
import { MANAGED_BY_LABEL, MANAGED_BY_VALUE, MCPSERVER_LABEL } from '../constants'
+import { createsTotal } from '../metrics'
import { McpServerReconciler } from '../reconciler'
import { McpServerCRD } from '../types'
@@ -719,6 +720,8 @@ describe('McpServerReconciler remote egress proxy', () => {
describe('reconcile call order for remote servers', () => {
it('should create ConfigMap before Deployment', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
// First materialization is absent; subsequent reads still use the live-state fixture.
appsApi.readNamespacedDeployment.mockRejectedValueOnce({ code: 404 })
coreApi.readNamespacedService.mockRejectedValueOnce({ code: 404 })
@@ -748,6 +751,8 @@ describe('McpServerReconciler remote egress proxy', () => {
})
it('should use the platform image without rewriting a divergent remote desired image', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
// First materialization is absent; subsequent reads still use the live-state fixture.
appsApi.readNamespacedDeployment.mockRejectedValueOnce({ code: 404 })
coreApi.readNamespacedService.mockRejectedValueOnce({ code: 404 })
@@ -798,6 +803,8 @@ describe('McpServerReconciler remote egress proxy', () => {
})
it('should call createNamespacedConfigMap with correct namespace', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
await reconciler.reconcile(REMOTE_SERVER)
expect(coreApi.createNamespacedConfigMap).toHaveBeenCalledWith(
@@ -813,6 +820,8 @@ describe('McpServerReconciler remote egress proxy', () => {
})
it('should also create Deployment and Service', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
// First materialization is absent; subsequent reads still use the live-state fixture.
appsApi.readNamespacedDeployment.mockRejectedValueOnce({ code: 404 })
coreApi.readNamespacedService.mockRejectedValueOnce({ code: 404 })
@@ -961,10 +970,115 @@ describe('McpServerReconciler remote egress proxy', () => {
// ─── Test 8: ensureConfigMap handles 409 conflict ──────────────────────
describe('ensureConfigMap conflict handling', () => {
+ async function skippedConfigMaps() {
+ const samples = await createsTotal.get()
+ const sample = samples.values.find(
+ value => value.labels.kind === 'ConfigMap' && value.labels.outcome === 'skipped'
+ )
+ expect(sample, 'initialized ConfigMap skipped series').toBeDefined()
+ return sample!.value
+ }
+
+ it('propagates a ConfigMap GET 403 without writing', async () => {
+ const forbidden = { code: 403 }
+ coreApi.readNamespacedConfigMap.mockRejectedValue(forbidden)
+ await expect((reconciler as any).ensureConfigMap(REMOTE_SERVER)).rejects.toBe(forbidden)
+ expect(coreApi.readNamespacedConfigMap).toHaveBeenCalledTimes(1)
+ expect(coreApi.createNamespacedConfigMap).not.toHaveBeenCalled()
+ expect(coreApi.replaceNamespacedConfigMap).not.toHaveBeenCalled()
+ })
+
+ it('orders the cold ConfigMap request as GET then POST', async () => {
+ const events: string[] = []
+ coreApi.readNamespacedConfigMap.mockImplementation(async () => {
+ events.push('GET')
+ throw { code: 404 }
+ })
+ coreApi.createNamespacedConfigMap.mockImplementation(async () => {
+ events.push('POST')
+ return {}
+ })
+ await (reconciler as any).ensureConfigMap(REMOTE_SERVER)
+ expect(events).toEqual(['GET', 'POST'])
+ expect(coreApi.replaceNamespacedConfigMap).not.toHaveBeenCalled()
+ })
+
+ it('counts one skipped POST for an unchanged present ConfigMap', async () => {
+ const desired = (reconciler as any).buildNginxConfigMap(REMOTE_SERVER) as k8s.V1ConfigMap
+ const existing = {
+ ...desired,
+ metadata: {
+ ...desired.metadata,
+ resourceVersion: '7',
+ annotations: { 'example.com/operator': 'retained' },
+ },
+ }
+ coreApi.readNamespacedConfigMap.mockResolvedValue(existing)
+ const before = await skippedConfigMaps()
+ await (reconciler as any).ensureConfigMap(REMOTE_SERVER)
+ expect(coreApi.readNamespacedConfigMap).toHaveBeenCalledTimes(1)
+ expect(coreApi.createNamespacedConfigMap).not.toHaveBeenCalled()
+ expect(coreApi.replaceNamespacedConfigMap).not.toHaveBeenCalled()
+ expect(await skippedConfigMaps()).toBe(before + 1)
+ })
+
+ it('rereads after a ConfigMap PUT conflict and preserves the fresh annotations', async () => {
+ const desired = (reconciler as any).buildNginxConfigMap(REMOTE_SERVER) as k8s.V1ConfigMap
+ const events: string[] = []
+ let reads = 0
+ coreApi.readNamespacedConfigMap.mockImplementation(async () => {
+ const revision = String(++reads)
+ events.push(`GET:${revision}`)
+ return {
+ ...desired,
+ metadata: {
+ ...desired.metadata,
+ resourceVersion: revision,
+ annotations: { 'example.com/operator': revision },
+ },
+ data: { 'default.conf.template': 'old-config' },
+ }
+ })
+ coreApi.replaceNamespacedConfigMap.mockImplementation(async ({ body }) => {
+ events.push(`PUT:${body.metadata.resourceVersion}`)
+ if (body.metadata.resourceVersion === '1') throw { code: 409 }
+ return body
+ })
+ const before = await skippedConfigMaps()
+ await (reconciler as any).ensureConfigMap(REMOTE_SERVER)
+ expect(events).toEqual(['GET:1', 'PUT:1', 'GET:2', 'PUT:2'])
+ expect(coreApi.createNamespacedConfigMap).not.toHaveBeenCalled()
+ const final = coreApi.replaceNamespacedConfigMap.mock.calls[1][0].body
+ expect(final.metadata.annotations['example.com/operator']).toBe('2')
+ expect(final.data).toEqual(desired.data)
+ expect(await skippedConfigMaps()).toBe(before + 1)
+ })
+
+ it('does not create after the ConfigMap GET retires authority', async () => {
+ let active = true
+ coreApi.readNamespacedConfigMap.mockImplementation(async () => {
+ active = false
+ throw { code: 404 }
+ })
+ const before = await skippedConfigMaps()
+ await (reconciler as any).ensureConfigMap(REMOTE_SERVER, () => active)
+ expect(coreApi.readNamespacedConfigMap).toHaveBeenCalledTimes(1)
+ expect(coreApi.createNamespacedConfigMap).not.toHaveBeenCalled()
+ expect(coreApi.replaceNamespacedConfigMap).not.toHaveBeenCalled()
+ expect(await skippedConfigMaps()).toBe(before)
+ })
+
it('should call replaceNamespacedConfigMap on 409 conflict', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
coreApi.createNamespacedConfigMap.mockRejectedValue(make409Error())
coreApi.readNamespacedConfigMap.mockResolvedValue({
- metadata: { resourceVersion: '42' },
+ metadata: {
+ name: 'mcp-sentry-remote-nginx-conf',
+ namespace: REMOTE_SERVER.namespace,
+ resourceVersion: '42',
+ labels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE, [MCPSERVER_LABEL]: REMOTE_SERVER.name },
+ },
data: { 'default.conf.template': 'old-config' },
})
@@ -991,7 +1105,12 @@ describe('McpServerReconciler remote egress proxy', () => {
it('should preserve the resourceVersion from the existing ConfigMap on replace', async () => {
coreApi.createNamespacedConfigMap.mockRejectedValue(make409Error())
coreApi.readNamespacedConfigMap.mockResolvedValue({
- metadata: { resourceVersion: '99' },
+ metadata: {
+ name: 'mcp-sentry-remote-nginx-conf',
+ namespace: REMOTE_SERVER.namespace,
+ resourceVersion: '99',
+ labels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE, [MCPSERVER_LABEL]: REMOTE_SERVER.name },
+ },
data: {},
})
@@ -1002,6 +1121,8 @@ describe('McpServerReconciler remote egress proxy', () => {
})
it('should rethrow non-409 errors from createNamespacedConfigMap', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
const err = new Error('Forbidden') as Error & { code?: number }
err.code = 403
coreApi.createNamespacedConfigMap.mockRejectedValue(err)
@@ -1012,11 +1133,17 @@ describe('McpServerReconciler remote egress proxy', () => {
})
it('should succeed on first create when no conflict', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
coreApi.createNamespacedConfigMap.mockResolvedValue({})
await expect((reconciler as any).ensureConfigMap(REMOTE_SERVER)).resolves.not.toThrow()
- expect(coreApi.readNamespacedConfigMap).not.toHaveBeenCalled()
+ expect(coreApi.readNamespacedConfigMap).toHaveBeenCalledExactlyOnceWith({
+ name: 'mcp-sentry-remote-nginx-conf',
+ namespace: REMOTE_SERVER.namespace,
+ })
+ expect(coreApi.createNamespacedConfigMap).toHaveBeenCalledTimes(1)
expect(coreApi.replaceNamespacedConfigMap).not.toHaveBeenCalled()
})
})
@@ -1069,6 +1196,8 @@ describe('McpServerReconciler remote egress proxy', () => {
})
it('should clear status tracking after delete', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
// First materialization is absent; subsequent reads still use the live-state fixture.
appsApi.readNamespacedDeployment.mockRejectedValueOnce({ code: 404 })
coreApi.readNamespacedService.mockRejectedValueOnce({ code: 404 })
@@ -1206,12 +1335,14 @@ describe('McpServerReconciler remote egress proxy', () => {
describe('reconcile failure modes for remote servers', () => {
it('should set status deployed:false when ConfigMap creation fails', async () => {
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
const err = new Error('Quota exceeded') as Error & { code?: number }
err.code = 403
coreApi.createNamespacedConfigMap.mockRejectedValue(err)
await reconciler.reconcile(REMOTE_SERVER)
+ expect(coreApi.createNamespacedConfigMap).toHaveBeenCalledTimes(1)
const status = reconciler.getStatus('mcp-sentry-remote')
expect(status.deployed).toBe(false)
expect(status.ready).toBe(false)
diff --git a/host-context-controller/src/__tests__/sharedFileSystemReconciler.test.ts b/host-context-controller/src/__tests__/sharedFileSystemReconciler.test.ts
index 6c82c70fb..2bc51b207 100644
--- a/host-context-controller/src/__tests__/sharedFileSystemReconciler.test.ts
+++ b/host-context-controller/src/__tests__/sharedFileSystemReconciler.test.ts
@@ -6,6 +6,7 @@ import {
buildDeployment,
buildEgressNetworkPolicy,
buildIngressNetworkPolicy,
+ buildPvc,
buildService,
pvcName,
wfcDeploymentName,
@@ -64,6 +65,14 @@ function liveDeployment(
return { ...desired, metadata: { ...desired.metadata, resourceVersion: '1' }, status }
}
+function livePvc(
+ sfs = makeSfs(),
+ status: k8s.V1PersistentVolumeClaimStatus = { phase: 'Bound', capacity: { storage: '5Gi' } }
+): k8s.V1PersistentVolumeClaim {
+ const desired = buildPvc(sfs, factoryConfig)
+ return { ...desired, metadata: { ...desired.metadata, resourceVersion: '1' }, status }
+}
+
function makeMocks(systems: SharedFileSystemCRD[] = [makeSfs()]) {
// Status/cleanup tests use already-converged policies with real identity and
// ownership. Cold-start tests explicitly arrange absence for their own reads.
@@ -104,9 +113,14 @@ function makeMocks(systems: SharedFileSystemCRD[] = [makeSfs()]) {
// Truthful status (#592): assessReadiness reads the PVC bind state, and
// detectWfcWedge lists the wfc Pod. Defaults = happy path (PVC Bound, no
// wedged pod) so existing tests reach phase=Ready.
- readNamespacedPersistentVolumeClaim: vi
- .fn()
- .mockResolvedValue({ status: { phase: 'Bound', capacity: { storage: '5Gi' } } }),
+ readNamespacedPersistentVolumeClaim: vi.fn(
+ async ({ name }: { name: string }): Promise<k8s.V1PersistentVolumeClaim> => {
+ const sfs = systems.find(item => pvcName(item) === name)
+ if (!sfs) throw new Error(`Missing PVC fixture for ${name}`)
+ return livePvc(sfs)
+ }
+ ),
+ replaceNamespacedPersistentVolumeClaim: vi.fn(),
listNamespacedPod: vi.fn().mockResolvedValue({ items: [] }),
}
const batchApi = {
@@ -175,9 +189,9 @@ describe('SharedFileSystemReconciler — monotonic status on re-reconcile (#592
// not-Ready SFS and deferred the mount forever. ensurePvc + ensureService run
// before assessReadiness restores the truthful phase, so they are the probes.
const phasesSeenMidReconcile: Array<string | undefined> = []
- mocks.coreApi.createNamespacedPersistentVolumeClaim.mockImplementation(async () => {
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockImplementation(async () => {
phasesSeenMidReconcile.push(reconciler.getStatus(sfs).phase)
- return {}
+ return livePvc(sfs)
})
mocks.coreApi.readNamespacedService.mockImplementation(async () => {
phasesSeenMidReconcile.push(reconciler.getStatus(sfs).phase)
@@ -188,7 +202,7 @@ describe('SharedFileSystemReconciler — monotonic status on re-reconcile (#592
await reconciler.reconcile(sfs)
expect(reconciler.getStatus(sfs).phase).toBe('Ready')
- expect(phasesSeenMidReconcile).toHaveLength(2)
+ expect(phasesSeenMidReconcile).toHaveLength(3) // PVC existence + Service existence + PVC readiness
for (const phase of phasesSeenMidReconcile) {
expect(phase).toBe('Ready')
}
@@ -206,6 +220,7 @@ describe('SharedFileSystemReconciler — happy path', () => {
it('creates PVC, Service, Deployment, and both NetworkPolicies — and NEVER an init Job', async () => {
const sfs = makeSfs()
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockRejectedValueOnce(notFound())
mocks.appsApi.readNamespacedDeployment.mockRejectedValueOnce(notFound())
mocks.coreApi.readNamespacedService.mockRejectedValueOnce(notFound())
mocks.networkingApi.readNamespacedNetworkPolicy
@@ -358,12 +373,16 @@ describe('SharedFileSystemReconciler — idempotence', () => {
expect(mocks.networkingApi.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()
})
- it('PVC 409 (already exists) is treated as success — no replace attempt', async () => {
+ it('PVC GET404/create409 rereads the concurrent object without replacing it', async () => {
const mocks = makeMocks()
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockRejectedValueOnce(notFound())
mocks.coreApi.createNamespacedPersistentVolumeClaim.mockRejectedValueOnce(alreadyExists())
const reconciler = makeReconciler(mocks)
await expect(reconciler.reconcile(makeSfs())).resolves.toBeUndefined()
expect(reconciler.getStatus(makeSfs()).phase).toBe('Ready')
+ expect(mocks.coreApi.createNamespacedPersistentVolumeClaim).toHaveBeenCalledTimes(1)
+ expect(mocks.coreApi.readNamespacedPersistentVolumeClaim).toHaveBeenCalledTimes(3) // existence, conflict, readiness
+ expect(mocks.coreApi.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
})
it('Deployment 409 (already exists) triggers a replace via the conflict-retry helper', async () => {
@@ -453,6 +472,7 @@ describe('SharedFileSystemReconciler — idempotence', () => {
describe('SharedFileSystemReconciler — failure handling', () => {
it('writes phase=Failed with a Reconciled=False condition when PVC create errors (non-409)', async () => {
const mocks = makeMocks()
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockRejectedValueOnce(notFound())
mocks.coreApi.createNamespacedPersistentVolumeClaim.mockRejectedValueOnce(
err(500, 'cluster down')
)
@@ -557,13 +577,20 @@ describe('SharedFileSystemReconciler — fullReconcile', () => {
makeSfs({ name: 'sfs-c' }),
]
const mocks = makeMocks(desired)
- mocks.coreApi.createNamespacedPersistentVolumeClaim
- .mockResolvedValueOnce({})
- .mockRejectedValueOnce(err(500, 'cluster down'))
- .mockResolvedValueOnce({})
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockImplementation(async ({ name }) => {
+ const sfs = desired.find(item => pvcName(item) === name)
+ if (!sfs) throw new Error(`Missing PVC fixture for ${name}`)
+ if (sfs.name === 'sfs-b') throw err(500, 'cluster down')
+ return livePvc(sfs)
+ })
const reconciler = makeReconciler(mocks)
await expect(reconciler.fullReconcile(desired)).resolves.toBeUndefined()
- expect(mocks.coreApi.createNamespacedPersistentVolumeClaim).toHaveBeenCalledTimes(3)
+ expect(
+ new Set(
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mock.calls.map(([{ name }]) => name)
+ )
+ ).toEqual(new Set(desired.map(pvcName)))
+ expect(mocks.coreApi.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
expect(reconciler.getStatus(desired[0]).phase).toBe('Ready')
expect(reconciler.getStatus(desired[1]).phase).toBe('Failed')
expect(reconciler.getStatus(desired[2]).phase).toBe('Ready')
@@ -597,9 +624,9 @@ describe('SharedFileSystemReconciler — truthful status (#592)', () => {
// PVC Pending under WaitForFirstConsumer while the wfc pod is still scheduling
// is the NORMAL warm-up path — must report Initializing, never a false Degraded.
it('reports Initializing (not Degraded) while the PVC is Pending and no pod is wedged', async () => {
- mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue({
- status: { phase: 'Pending' },
- })
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue(
+ livePvc(makeSfs(), { phase: 'Pending' })
+ )
mocks.appsApi.readNamespacedDeployment.mockResolvedValue(
liveDeployment(makeSfs(), { readyReplicas: 0 })
)
@@ -610,9 +637,9 @@ describe('SharedFileSystemReconciler — truthful status (#592)', () => {
})
it('reports Degraded (PVCUnbound) when the wfc Pod is Unschedulable', async () => {
- mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue({
- status: { phase: 'Pending' },
- })
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue(
+ livePvc(makeSfs(), { phase: 'Pending' })
+ )
mocks.appsApi.readNamespacedDeployment.mockResolvedValue(
liveDeployment(makeSfs(), { readyReplicas: 0 })
)
@@ -647,9 +674,9 @@ describe('SharedFileSystemReconciler — truthful status (#592)', () => {
// must NOT be mislabeled PVCUnbound, and must NOT carry the "check the PVC
// accessModes" hint that would misdirect the operator. (Review fix #592.)
it('reports Degraded (Unschedulable, NOT PVCUnbound) for a non-volume scheduling failure', async () => {
- mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue({
- status: { phase: 'Pending' },
- })
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue(
+ livePvc(makeSfs(), { phase: 'Pending' })
+ )
mocks.appsApi.readNamespacedDeployment.mockResolvedValue(
liveDeployment(makeSfs(), { readyReplicas: 0 })
)
@@ -679,9 +706,9 @@ describe('SharedFileSystemReconciler — truthful status (#592)', () => {
})
it('reports Degraded (WfcNotReady) when the wfc container is CrashLoopBackOff', async () => {
- mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue({
- status: { phase: 'Bound' },
- })
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue(
+ livePvc(makeSfs(), { phase: 'Bound' })
+ )
mocks.appsApi.readNamespacedDeployment.mockResolvedValue(
liveDeployment(makeSfs(), { readyReplicas: 0 })
)
@@ -710,9 +737,9 @@ describe('SharedFileSystemReconciler — truthful status (#592)', () => {
// to Ready once the PVC binds and the wfc pod serves — no manual intervention.
it('auto-recovers to Ready on a later reconcile once the PVC binds and the wfc is ready', async () => {
const sfs = makeSfs()
- mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValueOnce({
- status: { phase: 'Pending' },
- })
+ mocks.coreApi.readNamespacedPersistentVolumeClaim
+ .mockResolvedValueOnce(livePvc(makeSfs(), { phase: 'Pending' }))
+ .mockResolvedValueOnce(livePvc(makeSfs(), { phase: 'Pending' }))
mocks.appsApi.readNamespacedDeployment
.mockResolvedValueOnce(liveDeployment(makeSfs(), { readyReplicas: 0 }))
.mockResolvedValueOnce(liveDeployment(makeSfs(), { readyReplicas: 0 }))
@@ -785,9 +812,9 @@ describe('SharedFileSystemReconciler — status-write dirty check + lastTransiti
const sfs = makeSfs()
// First reconcile: PVC still Pending, no wedged pod → Initializing.
- mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValueOnce({
- status: { phase: 'Pending' },
- })
+ mocks.coreApi.readNamespacedPersistentVolumeClaim
+ .mockResolvedValueOnce(livePvc(makeSfs(), { phase: 'Pending' }))
+ .mockResolvedValueOnce(livePvc(makeSfs(), { phase: 'Pending' }))
mocks.appsApi.readNamespacedDeployment
.mockResolvedValueOnce(liveDeployment(makeSfs(), { readyReplicas: 0 }))
.mockResolvedValueOnce(liveDeployment(makeSfs(), { readyReplicas: 0 }))
@@ -830,9 +857,7 @@ describe('SharedFileSystemReconciler — mountability decoupled from wfc readine
// drops the SFS out of Ready, but the PVC stays Bound — so the RO mount MUST
// remain mountable and never be ripped out of a running consumer pod.
it('isMountable STAYS TRUE when the wfc is not serving but the PVC is Bound (Initializing)', async () => {
- mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue({
- status: { phase: 'Bound', capacity: { storage: '5Gi' } },
- })
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue(livePvc())
mocks.appsApi.readNamespacedDeployment.mockResolvedValue(
liveDeployment(makeSfs(), { readyReplicas: 0 })
)
@@ -844,9 +869,7 @@ describe('SharedFileSystemReconciler — mountability decoupled from wfc readine
})
it('isMountable STAYS TRUE on a Bound PVC even when the wfc container is CrashLoopBackOff (Degraded)', async () => {
- mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue({
- status: { phase: 'Bound', capacity: { storage: '5Gi' } },
- })
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue(livePvc())
mocks.appsApi.readNamespacedDeployment.mockResolvedValue(
liveDeployment(makeSfs(), { readyReplicas: 0 })
)
@@ -871,9 +894,9 @@ describe('SharedFileSystemReconciler — mountability decoupled from wfc readine
})
it('isMountable is FALSE while the PVC is not Bound (Pending) — nothing to mount', async () => {
- mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue({
- status: { phase: 'Pending' },
- })
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue(
+ livePvc(makeSfs(), { phase: 'Pending' })
+ )
mocks.appsApi.readNamespacedDeployment.mockResolvedValue(
liveDeployment(makeSfs(), { readyReplicas: 0 })
)
@@ -898,111 +921,158 @@ describe('SharedFileSystemReconciler — mountability decoupled from wfc readine
// Exercise the actual resource adapters without readiness reads masking their
// physical GET counts. Integration status and recovery remain covered above.
-describe.each(['Deployment', 'Service'] as const)('SFS %s read-first contract', kind => {
- beforeEach(() => {
- createsTotal.reset()
- existenceReadsTotal.reset()
- })
- function setup() {
- const mocks = makeMocks()
- const reconciler = makeReconciler(mocks) as unknown as {
- ensureDeployment(sfs: SharedFileSystemCRD): Promise<string>
- ensureService(sfs: SharedFileSystemCRD): Promise<string>
+describe.each(['Deployment', 'Service', 'PersistentVolumeClaim'] as const)(
+ 'SFS %s read-first contract',
+ kind => {
+ beforeEach(() => {
+ createsTotal.reset()
+ existenceReadsTotal.reset()
+ })
+ function setup() {
+ const mocks = makeMocks()
+ const reconciler = makeReconciler(mocks) as unknown as {
+ ensureDeployment(sfs: SharedFileSystemCRD): Promise<string>
+ ensureService(sfs: SharedFileSystemCRD): Promise<string>
+ ensurePvc(sfs: SharedFileSystemCRD): Promise<string>
+ }
+ const sfs = makeSfs()
+ const selected = {
+ Deployment: {
+ name: wfcDeploymentName(sfs),
+ read: mocks.appsApi.readNamespacedDeployment,
+ create: mocks.appsApi.createNamespacedDeployment,
+ replace: mocks.appsApi.replaceNamespacedDeployment,
+ run: () => reconciler.ensureDeployment(sfs),
+ },
+ Service: {
+ name: wfcServiceName(sfs),
+ read: mocks.coreApi.readNamespacedService,
+ create: mocks.coreApi.createNamespacedService,
+ replace: mocks.coreApi.replaceNamespacedService,
+ run: () => reconciler.ensureService(sfs),
+ },
+ PersistentVolumeClaim: {
+ name: pvcName(sfs),
+ read: mocks.coreApi.readNamespacedPersistentVolumeClaim,
+ create: mocks.coreApi.createNamespacedPersistentVolumeClaim,
+ replace: mocks.coreApi.replaceNamespacedPersistentVolumeClaim,
+ run: () => reconciler.ensurePvc(sfs),
+ },
+ }[kind]
+ const { name, read, create, replace, run } = selected
+ return { mocks, sfs, name, read, create, replace, run }
+ }
+ async function count(metric: typeof createsTotal, outcome: string) {
+ return (
+ (await metric.get()).values.find(
+ row => row.labels.kind === kind && row.labels.outcome === outcome
+ )?.value ?? 0
+ )
}
- const sfs = makeSfs()
- const name = kind === 'Deployment' ? wfcDeploymentName(sfs) : wfcServiceName(sfs)
- const read =
- kind === 'Deployment'
- ? mocks.appsApi.readNamespacedDeployment
- : mocks.coreApi.readNamespacedService
- const create =
- kind === 'Deployment'
- ? mocks.appsApi.createNamespacedDeployment
- : mocks.coreApi.createNamespacedService
- const replace =
- kind === 'Deployment'
- ? mocks.appsApi.replaceNamespacedDeployment
- : mocks.coreApi.replaceNamespacedService
- const run = () =>
- kind === 'Deployment' ? reconciler.ensureDeployment(sfs) : reconciler.ensureService(sfs)
- return { mocks, sfs, name, read, create, replace, run }
- }
- async function count(metric: typeof createsTotal, outcome: string) {
- return (
- (await metric.get()).values.find(
- row => row.labels.kind === kind && row.labels.outcome === outcome
- )?.value ?? 0
- )
- }
- it('returns the existing name with one GET and no POST or PUT', async () => {
- const h = setup()
- await expect(h.run()).resolves.toBe(h.name)
- expect(h.read).toHaveBeenCalledExactlyOnceWith({ name: h.name, namespace: 'mcp-host' })
- expect(h.create).not.toHaveBeenCalled()
- expect(h.replace).not.toHaveBeenCalled()
- expect(await count(createsTotal, 'skipped')).toBe(1)
- expect(await count(existenceReadsTotal, 'found')).toBe(1)
- })
+ it('returns the existing name with one GET and no POST or PUT', async () => {
+ const h = setup()
+ await expect(h.run()).resolves.toBe(h.name)
+ expect(h.read).toHaveBeenCalledExactlyOnceWith({ name: h.name, namespace: 'mcp-host' })
+ expect(h.create).not.toHaveBeenCalled()
+ expect(h.replace).not.toHaveBeenCalled()
+ expect(await count(createsTotal, 'skipped')).toBe(1)
+ expect(await count(existenceReadsTotal, 'found')).toBe(1)
+ })
- it('creates only after GET404 and returns the created name', async () => {
- const h = setup()
- h.read.mockRejectedValueOnce(notFound())
- await expect(h.run()).resolves.toBe(h.name)
- expect(h.read).toHaveBeenCalledTimes(1)
- expect(h.create).toHaveBeenCalledExactlyOnceWith({
- namespace: 'mcp-host',
- body:
- kind === 'Deployment'
- ? buildDeployment(h.sfs, factoryConfig)
- : buildService(h.sfs, factoryConfig),
+ it('creates only after GET404 and returns the created name', async () => {
+ const h = setup()
+ h.read.mockRejectedValueOnce(notFound())
+ await expect(h.run()).resolves.toBe(h.name)
+ expect(h.read).toHaveBeenCalledTimes(1)
+ expect(h.create).toHaveBeenCalledExactlyOnceWith({
+ namespace: 'mcp-host',
+ body:
+ kind === 'Deployment'
+ ? buildDeployment(h.sfs, factoryConfig)
+ : kind === 'Service'
+ ? buildService(h.sfs, factoryConfig)
+ : buildPvc(h.sfs, factoryConfig),
+ })
+ expect(h.read.mock.invocationCallOrder[0]).toBeLessThan(h.create.mock.invocationCallOrder[0])
+ expect(h.replace).not.toHaveBeenCalled()
+ expect(await count(createsTotal, 'created')).toBe(1)
+ expect(await count(createsTotal, 'skipped')).toBe(0)
})
- expect(h.read.mock.invocationCallOrder[0]).toBeLessThan(h.create.mock.invocationCallOrder[0])
- expect(h.replace).not.toHaveBeenCalled()
- expect(await count(createsTotal, 'created')).toBe(1)
- expect(await count(createsTotal, 'skipped')).toBe(0)
- })
- it('consumes a fresh GET after POST409 rather than reusing absence', async () => {
- const h = setup()
- h.read.mockRejectedValueOnce(notFound())
- h.create.mockRejectedValueOnce(alreadyExists())
- await expect(h.run()).resolves.toBe(h.name)
- expect(h.read).toHaveBeenCalledTimes(2)
- expect(h.create).toHaveBeenCalledTimes(1)
- expect(h.read.mock.invocationCallOrder[0]).toBeLessThan(h.create.mock.invocationCallOrder[0])
- expect(h.create.mock.invocationCallOrder[0]).toBeLessThan(h.read.mock.invocationCallOrder[1])
- expect(h.replace).not.toHaveBeenCalled()
- expect(await count(createsTotal, 'conflict')).toBe(1)
- expect(await count(createsTotal, 'skipped')).toBe(0)
- })
+ it('consumes a fresh GET after POST409 rather than reusing absence', async () => {
+ const h = setup()
+ h.read.mockRejectedValueOnce(notFound())
+ h.create.mockRejectedValueOnce(alreadyExists())
+ await expect(h.run()).resolves.toBe(h.name)
+ expect(h.read).toHaveBeenCalledTimes(2)
+ expect(h.create).toHaveBeenCalledTimes(1)
+ expect(h.read.mock.invocationCallOrder[0]).toBeLessThan(h.create.mock.invocationCallOrder[0])
+ expect(h.create.mock.invocationCallOrder[0]).toBeLessThan(h.read.mock.invocationCallOrder[1])
+ expect(h.replace).not.toHaveBeenCalled()
+ expect(await count(createsTotal, 'conflict')).toBe(1)
+ expect(await count(createsTotal, 'skipped')).toBe(0)
+ })
- it.each([403, 500])('propagates GET%s without any writes or skip', async code => {
- const h = setup()
- const failure = err(code)
- h.read.mockRejectedValueOnce(failure)
- await expect(h.run()).rejects.toBe(failure)
- expect(h.read).toHaveBeenCalledTimes(1)
- expect(h.create).not.toHaveBeenCalled()
- expect(h.replace).not.toHaveBeenCalled()
- expect(await count(createsTotal, 'skipped')).toBe(0)
- expect(await count(existenceReadsTotal, 'error')).toBe(1)
- })
+ it.each([403, 500])('propagates GET%s without any writes or skip', async code => {
+ const h = setup()
+ const failure = err(code)
+ h.read.mockRejectedValueOnce(failure)
+ await expect(h.run()).rejects.toBe(failure)
+ expect(h.read).toHaveBeenCalledTimes(1)
+ expect(h.create).not.toHaveBeenCalled()
+ expect(h.replace).not.toHaveBeenCalled()
+ expect(await count(createsTotal, 'skipped')).toBe(0)
+ expect(await count(existenceReadsTotal, 'error')).toBe(1)
+ })
- it('propagates fresh GET403 after POST409', async () => {
- const h = setup()
- const failure = err(403)
- h.read.mockRejectedValueOnce(notFound()).mockRejectedValueOnce(failure)
- h.create.mockRejectedValueOnce(alreadyExists())
- await expect(h.run()).rejects.toBe(failure)
- expect(h.read).toHaveBeenCalledTimes(2)
- expect(h.create).toHaveBeenCalledTimes(1)
- expect(h.replace).not.toHaveBeenCalled()
- expect(await count(createsTotal, 'skipped')).toBe(0)
- })
-})
+ it('preserves benign disappearance after POST409 without another create or skip', async () => {
+ const h = setup()
+ h.read.mockRejectedValueOnce(notFound()).mockRejectedValueOnce(notFound())
+ h.create.mockRejectedValueOnce(alreadyExists())
+ await expect(h.run()).resolves.toBe(h.name)
+ expect(h.read).toHaveBeenCalledTimes(2)
+ expect(h.create).toHaveBeenCalledTimes(1)
+ expect(h.replace).not.toHaveBeenCalled()
+ expect(await count(createsTotal, 'skipped')).toBe(0)
+ })
+
+ it('propagates fresh GET403 after POST409', async () => {
+ const h = setup()
+ const failure = err(403)
+ h.read.mockRejectedValueOnce(notFound()).mockRejectedValueOnce(failure)
+ h.create.mockRejectedValueOnce(alreadyExists())
+ await expect(h.run()).rejects.toBe(failure)
+ expect(h.read).toHaveBeenCalledTimes(2)
+ expect(h.create).toHaveBeenCalledTimes(1)
+ expect(h.replace).not.toHaveBeenCalled()
+ expect(await count(createsTotal, 'skipped')).toBe(0)
+ })
+ }
+)
describe('SFS preserve and retry contracts', () => {
+ it('keeps an existing PVC unchanged even when desired size or access modes differ', async () => {
+ const mocks = makeMocks()
+ const sfs = makeSfs()
+ const pvc = livePvc(sfs)
+ pvc.spec = {
+ ...pvc.spec,
+ accessModes: ['ReadOnlyMany'],
+ resources: { requests: { storage: '9Gi' } },
+ }
+ mocks.coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValueOnce(pvc)
+ const reconciler = makeReconciler(mocks) as unknown as {
+ ensurePvc(sfs: SharedFileSystemCRD): Promise<string>
+ }
+ await expect(reconciler.ensurePvc(sfs)).resolves.toBe(pvcName(sfs))
+ expect(mocks.coreApi.readNamespacedPersistentVolumeClaim).toHaveBeenCalledTimes(1)
+ expect(mocks.coreApi.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(mocks.coreApi.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(pvc.spec.accessModes).toEqual(['ReadOnlyMany'])
+ expect(pvc.spec.resources?.requests?.storage).toBe('9Gi')
+ })
+
it('keeps an existing Service unchanged even when its fields differ from desired', async () => {
const mocks = makeMocks()
const sfs = makeSfs()
diff --git a/host-context-controller/src/existenceReadMetrics.test.ts b/host-context-controller/src/existenceReadMetrics.test.ts
index 381ad4c23..ac29e683c 100644
--- a/host-context-controller/src/existenceReadMetrics.test.ts
+++ b/host-context-controller/src/existenceReadMetrics.test.ts
@@ -182,10 +182,10 @@ function readProductionSources(): Record<string, string> {
function assertReadInventory(sources: Record<string, string>): void {
const expectedWrapped: Record<string, number> = {
'utils.ts': 1,
- 'hostReconciler.ts': 7,
+ 'hostReconciler.ts': 9,
'reconciler.ts': 3,
'llmHookReconciler.ts': 3,
- 'sharedFileSystemReconciler.ts': 2,
+ 'sharedFileSystemReconciler.ts': 3,
'k8s/gfsK8sApi.ts': 5,
'networkPolicyReconciler.ts': 2,
}
@@ -250,7 +250,7 @@ function assertReadInventory(sources: Record<string, string>): void {
expect(reason.length, id).toBeGreaterThan(0)
expect(excluded[id], `Stale or changed read exclusion: ${id}`).toBe(count)
}
- expect(Object.values(wrapped).reduce((sum, count) => sum + count, 0)).toBe(23)
+ expect(Object.values(wrapped).reduce((sum, count) => sum + count, 0)).toBe(26)
expect(Object.values(excluded).reduce((sum, count) => sum + count, 0)).toBe(43)
}
diff --git a/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.ts b/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.ts
new file mode 100644
index 000000000..f61989ea6
--- /dev/null
+++ b/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.ts
@@ -0,0 +1,299 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ asAppsApi,
+ asCoreApi,
+ asCustomApi,
+ asNetworkingApi,
+ asRbacApi,
+ createMockAppsApi,
+ createMockCoreApi,
+ createMockCustomApi,
+ createMockNetworkingApi,
+ createMockRbacApi,
+ makeStubKc,
+} from '../test/__fixtures__/testMocks'
+import { HostReconciler } from './hostReconciler'
+import { CREATE_KINDS, createsTotal } from './metrics'
+import type { HostCRD } from './types'
+
+const host: HostCRD = {
+ name: 'rbac-host',
+ namespace: 'mcp-host',
+ uid: 'host-uid',
+ generation: 1,
+ spec: { host: 'rbac-host', contextRef: 'context', secretRef: 'host-secret' },
+}
+
+function fixture() {
+ const core = createMockCoreApi()
+ const rbac = createMockRbacApi()
+ const apps = createMockAppsApi()
+ const reconciler = new HostReconciler(makeStubKc(), {
+ coreApi: asCoreApi(core),
+ appsApi: asAppsApi(apps),
+ rbacApi: asRbacApi(rbac),
+ customApi: asCustomApi(createMockCustomApi()),
+ networkingApi: asNetworkingApi(createMockNetworkingApi()),
+ })
+ // A failing RBAC reconcile must not reach credential issuance. This canary
+ // also keeps the negative-control mutation entirely local.
+ const provision = vi
+ .spyOn(reconciler as any, 'provisionRuntimeTokenRevision')
+ .mockImplementation(() => {
+ throw new Error('Downstream provisioning must not execute after an RBAC failure')
+ })
+ return { core, rbac, apps, reconciler, provision }
+}
+
+const rbacCases = ['ServiceAccount', 'Role', 'RoleBinding'] as const
+type RbacKind = (typeof rbacCases)[number]
+function operations(f: ReturnType<typeof fixture>, kind: RbacKind) {
+ if (kind === 'ServiceAccount')
+ return {
+ read: f.core.readNamespacedServiceAccount,
+ create: f.core.createNamespacedServiceAccount,
+ method: 'ensureHostServiceAccount',
+ }
+ if (kind === 'Role')
+ return {
+ read: f.rbac.readNamespacedRole,
+ create: f.rbac.createNamespacedRole,
+ method: 'ensureHostRole',
+ }
+ return {
+ read: f.rbac.readNamespacedRoleBinding,
+ create: f.rbac.createNamespacedRoleBinding,
+ method: 'ensureHostRoleBinding',
+ }
+}
+
+async function count(kind: string, outcome: string) {
+ const sample = (await createsTotal.get()).values.find(
+ v => v.labels.kind === kind && v.labels.outcome === outcome
+ )
+ expect(sample).toBeDefined()
+ return sample!.value
+}
+
+describe('Host read-first RBAC and PVC contracts', () => {
+ beforeEach(() => {
+ createsTotal.reset()
+ for (const kind of CREATE_KINDS)
+ for (const outcome of ['created', 'conflict', 'error', 'skipped'])
+ createsTotal.inc({ kind, outcome }, 0)
+ })
+
+ it.each(rbacCases)('%s propagates initial GET403 without attempting a write', async kind => {
+ const f = fixture()
+ const { read, create, method } = operations(f, kind)
+ const denied = { code: 403 }
+ read.mockRejectedValueOnce(denied)
+ await expect((f.reconciler as any)[method](host)).rejects.toBe(denied)
+ expect(read).toHaveBeenCalledOnce()
+ expect(create).not.toHaveBeenCalled()
+ expect(f.rbac.replaceNamespacedRole).not.toHaveBeenCalled()
+ expect(await count(kind, 'skipped')).toBe(0)
+ })
+
+ it.each(rbacCases)(
+ '%s propagates an unexpected POST failure after observed absence',
+ async kind => {
+ const f = fixture()
+ const { read, create, method } = operations(f, kind)
+ const failure = { code: 503 }
+ read.mockRejectedValueOnce({ code: 404 })
+ create.mockRejectedValueOnce(failure)
+ await expect((f.reconciler as any)[method](host)).rejects.toBe(failure)
+ expect(read).toHaveBeenCalledOnce()
+ expect(create).toHaveBeenCalledOnce()
+ expect(f.rbac.replaceNamespacedRole).not.toHaveBeenCalled()
+ expect(await count(kind, 'error')).toBe(1)
+ expect(await count(kind, 'skipped')).toBe(0)
+ }
+ )
+
+ it.each(rbacCases)('%s rereads after POST409 and propagates raced GET403', async kind => {
+ const f = fixture()
+ const { read, create, method } = operations(f, kind)
+ const denied = { code: 403 }
+ read.mockRejectedValueOnce({ code: 404 }).mockRejectedValueOnce(denied)
+ create.mockRejectedValueOnce({ code: 409 })
+ await expect((f.reconciler as any)[method](host)).rejects.toBe(denied)
+ expect(read).toHaveBeenCalledTimes(2)
+ expect(create).toHaveBeenCalledOnce()
+ expect(f.rbac.replaceNamespacedRole).not.toHaveBeenCalled()
+ expect(await count(kind, 'conflict')).toBe(1)
+ expect(await count(kind, 'skipped')).toBe(0)
+ })
+
+ it.each(rbacCases)(
+ '%s retains the benign POST409 then GET404 disappearance without a skip',
+ async kind => {
+ const f = fixture()
+ const { read, create, method } = operations(f, kind)
+ read.mockRejectedValueOnce({ code: 404 }).mockRejectedValueOnce({ code: 404 })
+ create.mockRejectedValueOnce({ code: 409 })
+ await expect((f.reconciler as any)[method](host)).resolves.toBeUndefined()
+ expect(read).toHaveBeenCalledTimes(2)
+ expect(create).toHaveBeenCalledOnce()
+ expect(f.rbac.replaceNamespacedRole).not.toHaveBeenCalled()
+ expect(await count(kind, 'conflict')).toBe(1)
+ expect(await count(kind, 'skipped')).toBe(0)
+ }
+ )
+
+ it.each(rbacCases)(
+ '%s aborts the Host reconcile before downstream resources on failure',
+ async kind => {
+ const f = fixture()
+ const { read, create } = operations(f, kind)
+ const denied = { code: 403 }
+ read.mockRejectedValueOnce(denied)
+ const reportError = vi.spyOn(f.reconciler as any, 'enqueueControllerError')
+ await expect(f.reconciler.reconcile(host)).rejects.toBe(denied)
+ expect(read).toHaveBeenCalledOnce()
+ expect(create).not.toHaveBeenCalled()
+ expect(f.core.readNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(f.core.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(f.core.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(f.core.readNamespacedService).not.toHaveBeenCalled()
+ expect(f.apps.createNamespacedDeployment).not.toHaveBeenCalled()
+ expect(f.apps.replaceNamespacedDeployment).not.toHaveBeenCalled()
+ expect(f.provision).not.toHaveBeenCalled()
+ expect(reportError).toHaveBeenCalledWith(
+ expect.objectContaining({ name: host.name }),
+ 'reconcile_exception',
+ denied
+ )
+ }
+ )
+
+ it.each(['ServiceAccount', 'RoleBinding'] as const)(
+ '%s preserves present state with one read and no PUT',
+ async kind => {
+ const f = fixture()
+ const { read, create, method } = operations(f, kind)
+ create.mockRejectedValue({ code: 409 })
+ await (f.reconciler as any)[method](host)
+ expect(read).toHaveBeenCalledOnce()
+ expect(create).not.toHaveBeenCalled()
+ expect(f.rbac.replaceNamespacedRole).not.toHaveBeenCalled()
+ expect(await count(kind, 'skipped')).toBe(1)
+ }
+ )
+
+ it.each(['ServiceAccount', 'Role', 'RoleBinding', 'PersistentVolumeClaim'] as const)(
+ '%s rechecks admission after GET404',
+ async kind => {
+ const f = fixture()
+ const op =
+ kind === 'PersistentVolumeClaim'
+ ? {
+ read: f.core.readNamespacedPersistentVolumeClaim,
+ create: f.core.createNamespacedPersistentVolumeClaim,
+ method: 'ensurePvc',
+ }
+ : operations(f, kind)
+ let current = true
+ const retired = new Error('admission retired during existence read')
+ const revalidate = vi.fn(() => {
+ if (!current) throw retired
+ })
+ op.read.mockImplementationOnce(async () => {
+ current = false
+ throw { code: 404 }
+ })
+ await expect((f.reconciler as any)[op.method](host, revalidate)).rejects.toBe(retired)
+ expect(op.read).toHaveBeenCalledOnce()
+ expect(revalidate).toHaveBeenCalledTimes(2)
+ expect(op.create).not.toHaveBeenCalled()
+ expect(f.rbac.replaceNamespacedRole).not.toHaveBeenCalled()
+ expect(f.core.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(await count(kind, 'skipped')).toBe(0)
+ }
+ )
+
+ it('keeps Role PUT404 disappearance benign without counting a successful skip', async () => {
+ const f = fixture()
+ f.rbac.replaceNamespacedRole.mockRejectedValueOnce({ code: 404 })
+ await expect((f.reconciler as any).ensureHostRole(host)).resolves.toBeUndefined()
+ expect(f.rbac.readNamespacedRole).toHaveBeenCalledOnce()
+ expect(f.rbac.replaceNamespacedRole).toHaveBeenCalledOnce()
+ expect(f.rbac.createNamespacedRole).not.toHaveBeenCalled()
+ expect(await count('Role', 'skipped')).toBe(0)
+ })
+
+ it.each([403, 409, 500])('propagates Role PUT%d without introducing a retry', async code => {
+ const f = fixture()
+ const failure = { code }
+ f.rbac.replaceNamespacedRole.mockRejectedValueOnce(failure)
+ await expect((f.reconciler as any).ensureHostRole(host)).rejects.toBe(failure)
+ expect(f.rbac.readNamespacedRole).toHaveBeenCalledOnce()
+ 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({
+ metadata: {
+ name: 'rbac-host-workspace',
+ namespace: host.namespace,
+ uid: 'pvc-uid',
+ resourceVersion: '17',
+ },
+ spec: { volumeName: 'bound-volume' },
+ })
+ await (f.reconciler as any).ensurePvc(host)
+ expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(f.core.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(f.core.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(await count('PersistentVolumeClaim', 'skipped')).toBe(1)
+ })
+
+ it('updates an unbound Host PVC once with its observed resourceVersion', async () => {
+ const f = fixture()
+ await (f.reconciler as any).ensurePvc(host)
+ expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(f.core.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(f.core.replaceNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(
+ f.core.replaceNamespacedPersistentVolumeClaim.mock.calls[0][0].body.metadata.resourceVersion
+ ).toBe('1')
+ expect(await count('PersistentVolumeClaim', 'skipped')).toBe(1)
+ })
+
+ it('propagates a Host PVC initial GET failure outside retained write catches', async () => {
+ const f = fixture()
+ const failure = { code: 403 }
+ f.core.readNamespacedPersistentVolumeClaim.mockRejectedValueOnce(failure)
+ await expect((f.reconciler as any).ensurePvc(host)).rejects.toBe(failure)
+ expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(f.core.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(f.core.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(await count('PersistentVolumeClaim', 'skipped')).toBe(0)
+ })
+
+ it('retains the Host PVC POST failure without recording a skip', async () => {
+ const f = fixture()
+ f.core.readNamespacedPersistentVolumeClaim.mockRejectedValueOnce({ code: 404 })
+ f.core.createNamespacedPersistentVolumeClaim.mockRejectedValueOnce({ code: 503 })
+ await expect((f.reconciler as any).ensurePvc(host)).resolves.toBeUndefined()
+ expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(f.core.createNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(f.core.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(await count('PersistentVolumeClaim', 'error')).toBe(1)
+ expect(await count('PersistentVolumeClaim', 'skipped')).toBe(0)
+ })
+
+ it.each([409, 503])('retains Host PVC PUT%d without retrying or recording a skip', async code => {
+ const f = fixture()
+ f.core.replaceNamespacedPersistentVolumeClaim.mockRejectedValueOnce({ code })
+ await expect((f.reconciler as any).ensurePvc(host)).resolves.toBeUndefined()
+ expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(f.core.replaceNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(f.core.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(await count('PersistentVolumeClaim', 'skipped')).toBe(0)
+ })
+})
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 5f3f542a9..45c941abc 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -1023,22 +1023,38 @@ export class HostReconciler {
/**
* Ensure a per-Host ServiceAccount exists. Idempotent.
*/
- private async ensureHostServiceAccount(host: HostCRD): Promise<void> {
+ private async ensureHostServiceAccount(host: HostCRD, revalidate?: () => void): Promise<void> {
const name = this.hostSaName(host)
const body: k8s.V1ServiceAccount = {
apiVersion: 'v1',
kind: 'ServiceAccount',
metadata: { name, namespace: host.namespace, labels: this.rbacLabels(host) },
}
- try {
- await observeCreate('ServiceAccount', () =>
- this.coreApi.createNamespacedServiceAccount({ namespace: host.namespace, body })
- )
- console.log(`[HostReconciler] Created ServiceAccount "${name}"`)
- } catch (err) {
- if (getErrorCode(err) === 409) return // already exists; SA itself has no spec to update
- console.error(`[HostReconciler] Failed to ensure ServiceAccount "${name}":`, err)
+ const mutationAllowed = () => {
+ revalidate?.()
+ return true
}
+ await ensureResource({
+ mutationAllowed,
+ read: () =>
+ observeExistenceRead('ServiceAccount', () =>
+ this.coreApi.readNamespacedServiceAccount({ name, namespace: host.namespace })
+ ),
+ create: () =>
+ observeCreate('ServiceAccount', () =>
+ this.coreApi.createNamespacedServiceAccount({ namespace: host.namespace, body })
+ ),
+ // Existing ServiceAccounts have always been retained without an update.
+ converge: async read => {
+ try {
+ await read()
+ } catch (error) {
+ if (error != null && getErrorCode(error) === 404) return false
+ throw error
+ }
+ },
+ onSkipped: () => createsTotal.inc({ kind: 'ServiceAccount', outcome: 'skipped' }),
+ })
}
/**
@@ -1047,7 +1063,7 @@ export class HostReconciler {
* On secretRef change the resourceNames are rewritten so Host A can never
* read Host B's Secret.
*/
- private async ensureHostRole(host: HostCRD): Promise<void> {
+ private async ensureHostRole(host: HostCRD, revalidate?: () => void): Promise<void> {
const name = this.hostRoleName(host)
const body: k8s.V1Role = {
apiVersion: 'rbac.authorization.k8s.io/v1',
@@ -1085,36 +1101,43 @@ export class HostReconciler {
},
],
}
- try {
- await observeCreate('Role', () =>
- this.rbacApi.createNamespacedRole({ namespace: host.namespace, body })
- )
- console.log(`[HostReconciler] Created Role "${name}"`)
- return
- } catch (err) {
- if (getErrorCode(err) !== 409) {
- console.error(`[HostReconciler] Failed to create Role "${name}":`, err)
- return
- }
- }
- // Already exists — replace to pick up rotated secretRef / new resourceNames.
- try {
- const existing = await observeExistenceRead('Role', () =>
- this.rbacApi.readNamespacedRole({ name, namespace: host.namespace })
- )
- if (roleMatchesDesired(body, existing)) return
- body.metadata!.resourceVersion = existing.metadata?.resourceVersion
- await this.rbacApi.replaceNamespacedRole({ name, namespace: host.namespace, body })
- console.log(`[HostReconciler] Updated Role "${name}"`)
- } catch (err) {
- console.error(`[HostReconciler] Failed to update Role "${name}":`, err)
+ const mutationAllowed = () => {
+ revalidate?.()
+ return true
}
+ await ensureResource({
+ mutationAllowed,
+ read: () =>
+ observeExistenceRead('Role', () =>
+ this.rbacApi.readNamespacedRole({ name, namespace: host.namespace })
+ ),
+ create: () =>
+ observeCreate('Role', () =>
+ this.rbacApi.createNamespacedRole({ namespace: host.namespace, body })
+ ),
+ 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 })
+ } catch (error) {
+ // Preserve the existing disappearance policy, without swallowing
+ // authorization, transport, or terminal conflict failures.
+ if (error != null && getErrorCode(error) === 404) return false
+ throw error
+ }
+ },
+ onSkipped: () => createsTotal.inc({ kind: 'Role', outcome: 'skipped' }),
+ })
}
/**
* Ensure a per-Host RoleBinding binding the per-Host Role to the per-Host SA.
*/
- private async ensureHostRoleBinding(host: HostCRD): Promise<void> {
+ private async ensureHostRoleBinding(host: HostCRD, revalidate?: () => void): Promise<void> {
const name = this.hostRoleName(host)
const body: k8s.V1RoleBinding = {
apiVersion: 'rbac.authorization.k8s.io/v1',
@@ -1133,15 +1156,31 @@ export class HostReconciler {
name,
},
}
- try {
- await observeCreate('RoleBinding', () =>
- this.rbacApi.createNamespacedRoleBinding({ namespace: host.namespace, body })
- )
- console.log(`[HostReconciler] Created RoleBinding "${name}"`)
- } catch (err) {
- if (getErrorCode(err) === 409) return
- console.error(`[HostReconciler] Failed to ensure RoleBinding "${name}":`, err)
+ const mutationAllowed = () => {
+ revalidate?.()
+ return true
}
+ await ensureResource({
+ mutationAllowed,
+ read: () =>
+ observeExistenceRead('RoleBinding', () =>
+ this.rbacApi.readNamespacedRoleBinding({ name, namespace: host.namespace })
+ ),
+ create: () =>
+ observeCreate('RoleBinding', () =>
+ this.rbacApi.createNamespacedRoleBinding({ namespace: host.namespace, body })
+ ),
+ // Preserve the existing binding; this path does not update subjects/roleRef.
+ converge: async read => {
+ try {
+ await read()
+ } catch (error) {
+ if (error != null && getErrorCode(error) === 404) return false
+ throw error
+ }
+ },
+ onSkipped: () => createsTotal.inc({ kind: 'RoleBinding', outcome: 'skipped' }),
+ })
}
/**
@@ -3311,43 +3350,54 @@ export class HostReconciler {
this.readinessTimers.set(name, timer)
}
- private async ensurePvc(host: HostCRD): Promise<void> {
+ private async ensurePvc(host: HostCRD, revalidate?: () => void): Promise<void> {
const pvc = this.buildPvc(host)
const name = this.pvcName(host)
- try {
- await observeCreate('PersistentVolumeClaim', () =>
- this.coreApi.createNamespacedPersistentVolumeClaim({
- namespace: host.namespace,
- body: pvc,
- })
- )
- console.log(`[HostReconciler] Created PVC "${name}"`)
- } catch (error) {
- if (getErrorCode(error) === 409) {
+ const mutationAllowed = () => {
+ revalidate?.()
+ return true
+ }
+ // Initial GET errors must propagate; retain only the established
+ // non-throwing POST and convergence failures of this PVC writer.
+ await ensureResource({
+ mutationAllowed,
+ read: () =>
+ observeExistenceRead('PersistentVolumeClaim', () =>
+ this.coreApi.readNamespacedPersistentVolumeClaim({ namespace: host.namespace, name })
+ ),
+ create: async () => {
try {
- const existing = await observeExistenceRead('PersistentVolumeClaim', () =>
- this.coreApi.readNamespacedPersistentVolumeClaim({
+ await observeCreate('PersistentVolumeClaim', () =>
+ this.coreApi.createNamespacedPersistentVolumeClaim({
namespace: host.namespace,
- name,
+ body: pvc,
})
)
- if (existing.spec?.volumeName) {
- return
- }
+ } catch (error) {
+ if (isBenignSupersessionError(error) || (error != null && getErrorCode(error) === 409))
+ throw error
+ log.error('Failed to create Host PVC', { host: host.name, err: error })
+ }
+ },
+ converge: async read => {
+ try {
+ const existing = await read()
+ revalidate?.()
+ if (existing.spec?.volumeName) return
pvc.metadata!.resourceVersion = existing.metadata?.resourceVersion
await this.coreApi.replaceNamespacedPersistentVolumeClaim({
namespace: host.namespace,
name,
body: pvc,
})
- console.log(`[HostReconciler] Updated PVC "${name}"`)
- } catch (updateError) {
- console.error(`[HostReconciler] Failed to update PVC "${name}":`, updateError)
+ } catch (error) {
+ if (isBenignSupersessionError(error)) throw error
+ log.error('Failed to update Host PVC', { host: host.name, err: error })
+ return false
}
- } else {
- console.error(`[HostReconciler] Failed to create PVC "${name}":`, error)
- }
- }
+ },
+ onSkipped: () => createsTotal.inc({ kind: 'PersistentVolumeClaim', outcome: 'skipped' }),
+ })
}
private async ensureService(host: HostCRD, revalidate?: () => void): Promise<void> {
@@ -4355,11 +4405,11 @@ export class HostReconciler {
// otherwise the kubelet can't mount the SA token and the pod will
// crash-loop until RBAC is created.
revalidateHostMutationBoundary()
- await this.ensureHostServiceAccount(host)
+ await this.ensureHostServiceAccount(host, revalidateHostMutationBoundary)
revalidateHostMutationBoundary()
- await this.ensureHostRole(host)
+ await this.ensureHostRole(host, revalidateHostMutationBoundary)
revalidateHostMutationBoundary()
- await this.ensureHostRoleBinding(host)
+ await this.ensureHostRoleBinding(host, revalidateHostMutationBoundary)
let mounts: ResolvedSfsMount[] = []
try {
@@ -4406,7 +4456,7 @@ export class HostReconciler {
}
revalidateHostMutationBoundary()
- await this.ensurePvc(host)
+ await this.ensurePvc(host, revalidateHostMutationBoundary)
revalidateHostMutationBoundary()
await this.ensureService(host, revalidateHostMutationBoundary)
diff --git a/host-context-controller/src/reconciler.test.ts b/host-context-controller/src/reconciler.test.ts
index 87796c7f1..13992b5ec 100644
--- a/host-context-controller/src/reconciler.test.ts
+++ b/host-context-controller/src/reconciler.test.ts
@@ -373,6 +373,8 @@ describe('Reconciler managed:false guard (Risk 1.7)', () => {
})
it('completes a remote proxy reconcile without rewriting the desired image', async () => {
+ // This case starts without the nginx ConfigMap.
+ coreApi.readNamespacedConfigMap.mockRejectedValueOnce({ code: 404 })
// First materialization is absent; subsequent reads still use the live-state fixture.
appsApi.readNamespacedDeployment.mockRejectedValueOnce({ code: 404 })
coreApi.readNamespacedService.mockRejectedValueOnce({ code: 404 })
diff --git a/host-context-controller/src/reconciler.ts b/host-context-controller/src/reconciler.ts
index b5330f871..6be983991 100644
--- a/host-context-controller/src/reconciler.ts
+++ b/host-context-controller/src/reconciler.ts
@@ -951,35 +951,37 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolv
isCurrent: () => boolean = () => true
): Promise<void> {
const cm = this.buildNginxConfigMap(server)
- if (!isCurrent()) return
const name = `${server.name}-nginx-conf`
const namespace = server.namespace
- try {
- await observeCreate('ConfigMap', () =>
- this.coreApi.createNamespacedConfigMap({
+ await ensureResource({
+ mutationAllowed: isCurrent,
+ read: () =>
+ observeExistenceRead('ConfigMap', () =>
+ this.coreApi.readNamespacedConfigMap({ name, namespace })
+ ),
+ create: async () => {
+ await observeCreate('ConfigMap', () =>
+ this.coreApi.createNamespacedConfigMap({ namespace, body: cm })
+ )
+ hccLogger.info('nginx ConfigMap created', {
+ scope: '[Reconciler]',
+ configMap: name,
namespace,
- body: cm,
})
- )
- console.log(`[Reconciler] Created nginx ConfigMap "${name}"`)
- } catch (error: unknown) {
- if (getErrorCode(error) !== 409) {
- throw error
- }
- await replaceWithConflictRetry({
- description: `nginx ConfigMap "${name}"`,
- logPrefix: '[Reconciler]',
- body: cm,
- mergeExisting: preserveObjectAnnotations,
- isUpToDate: configMapMatchesDesired,
- mutationAllowed: isCurrent,
- read: () =>
- observeExistenceRead('ConfigMap', () =>
- this.coreApi.readNamespacedConfigMap({ name, namespace })
- ),
- replace: body => this.coreApi.replaceNamespacedConfigMap({ name, namespace, body }),
- })
- }
+ },
+ converge: read =>
+ replaceWithConflictRetry({
+ description: `nginx ConfigMap "${name}"`,
+ logPrefix: '[Reconciler]',
+ body: cm,
+ mergeExisting: preserveObjectAnnotations,
+ isUpToDate: configMapMatchesDesired,
+ mutationAllowed: isCurrent,
+ read,
+ replace: body => this.coreApi.replaceNamespacedConfigMap({ name, namespace, body }),
+ }),
+ onSkipped: () => createsTotal.inc({ kind: 'ConfigMap', outcome: 'skipped' }),
+ })
}
/**
diff --git a/host-context-controller/src/sharedFileSystemReconciler.ts b/host-context-controller/src/sharedFileSystemReconciler.ts
index f34e8b7ee..61b9349a1 100644
--- a/host-context-controller/src/sharedFileSystemReconciler.ts
+++ b/host-context-controller/src/sharedFileSystemReconciler.ts
@@ -275,22 +275,31 @@ export class SharedFileSystemReconciler {
private async ensurePvc(sfs: SharedFileSystemCRD): Promise<string> {
const pvc = buildPvc(sfs, this.factoryConfig)
const name = pvcName(sfs)
- try {
- await observeCreate('PersistentVolumeClaim', () =>
- this.coreApi.createNamespacedPersistentVolumeClaim({
- namespace: this.factoryConfig.hostNamespace,
- body: pvc,
- })
- )
- console.log(`${LOG} Created PVC "${name}"`)
- } catch (err) {
- if (getErrorCode(err) !== 409) {
- throw err
- }
- // PVC spec is largely immutable post-create (size can grow, accessModes
- // can't change). We don't attempt to replace — just log and continue.
- console.log(`${LOG} PVC "${name}" already exists`)
- }
+ const namespace = this.factoryConfig.hostNamespace
+ await ensureResource<k8s.V1PersistentVolumeClaim>({
+ read: () =>
+ observeExistenceRead('PersistentVolumeClaim', () =>
+ this.coreApi.readNamespacedPersistentVolumeClaim({ namespace, name })
+ ),
+ create: async () => {
+ await observeCreate('PersistentVolumeClaim', () =>
+ this.coreApi.createNamespacedPersistentVolumeClaim({ namespace, body: pvc })
+ )
+ hccLogger.info('SharedFileSystem PVC created', { scope: LOG, name, namespace })
+ },
+ onSkipped: () => createsTotal.inc({ kind: 'PersistentVolumeClaim', outcome: 'skipped' }),
+ converge: async read => {
+ // Preserve the existing PVC without resizing or changing accessModes.
+ // After POST409, consume a fresh read; only disappearance is benign.
+ try {
+ await read()
+ } catch (err) {
+ if (err == null || getErrorCode(err) !== 404) throw err
+ return
+ }
+ hccLogger.info('SharedFileSystem PVC already exists', { scope: LOG, name, namespace })
+ },
+ })
return name
}
diff --git a/host-context-controller/test/__fixtures__/testMocks.ts b/host-context-controller/test/__fixtures__/testMocks.ts
index 6c5ddcc0c..48a40291b 100644
--- a/host-context-controller/test/__fixtures__/testMocks.ts
+++ b/host-context-controller/test/__fixtures__/testMocks.ts
@@ -184,10 +184,17 @@ export function createMockCoreApi(): MockCoreApi {
patchNamespacedSecret: vi.fn().mockResolvedValue({}),
deleteNamespacedSecret: vi.fn().mockResolvedValue({}),
createNamespacedPersistentVolumeClaim: vi.fn().mockResolvedValue({}),
- readNamespacedPersistentVolumeClaim: vi.fn(({ name }: { name?: string } = {}) =>
- Promise.resolve({
- metadata: { resourceVersion: '1', labels: hccOwnedLabels(name) },
- } as MockK8sResource)
+ readNamespacedPersistentVolumeClaim: vi.fn(
+ ({ name, namespace }: { name?: string; namespace?: string } = {}) =>
+ Promise.resolve({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: hccOwnedLabels(name),
+ },
+ } as MockK8sResource)
),
replaceNamespacedPersistentVolumeClaim: vi.fn().mockResolvedValue({}),
deleteNamespacedPersistentVolumeClaim: vi.fn().mockResolvedValue({}),
@@ -199,10 +206,17 @@ export function createMockCoreApi(): MockCoreApi {
deleteNamespacedConfigMap: vi.fn().mockResolvedValue({}),
// Per-Host ServiceAccount (lives on CoreV1Api)
createNamespacedServiceAccount: vi.fn().mockResolvedValue({}),
- readNamespacedServiceAccount: vi.fn(({ name }: { name?: string } = {}) =>
- Promise.resolve({
- metadata: { resourceVersion: '1', labels: hccOwnedLabels(name) },
- } as MockK8sResource)
+ readNamespacedServiceAccount: vi.fn(
+ ({ name, namespace }: { name?: string; namespace?: string } = {}) =>
+ Promise.resolve({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: hccOwnedLabels(name),
+ },
+ } as MockK8sResource)
),
deleteNamespacedServiceAccount: vi.fn().mockResolvedValue({}),
// #827 partial-leftover discovery lists these owned kinds by ownership label.
@@ -268,18 +282,31 @@ export function createMockNetworkingApi(): MockNetworkingApi {
export function createMockRbacApi(): MockRbacApi {
return {
createNamespacedRole: vi.fn().mockResolvedValue({}),
- readNamespacedRole: vi.fn(({ name }: { name?: string } = {}) =>
+ readNamespacedRole: vi.fn(({ name, namespace }: { name?: string; namespace?: string } = {}) =>
Promise.resolve({
- metadata: { resourceVersion: '1', labels: hccOwnedLabels(name) },
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: hccOwnedLabels(name),
+ },
} as MockK8sResource)
),
replaceNamespacedRole: vi.fn().mockResolvedValue({}),
deleteNamespacedRole: vi.fn().mockResolvedValue({}),
createNamespacedRoleBinding: vi.fn().mockResolvedValue({}),
- readNamespacedRoleBinding: vi.fn(({ name }: { name?: string } = {}) =>
- Promise.resolve({
- metadata: { resourceVersion: '1', labels: hccOwnedLabels(name) },
- } as MockK8sResource)
+ readNamespacedRoleBinding: vi.fn(
+ ({ name, namespace }: { name?: string; namespace?: string } = {}) =>
+ Promise.resolve({
+ metadata: {
+ name,
+ namespace,
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: hccOwnedLabels(name),
+ },
+ } as MockK8sResource)
),
deleteNamespacedRoleBinding: vi.fn().mockResolvedValue({}),
// #827 partial-leftover discovery lists RBAC by ownership label.
diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.ts
index 93d43ebda..6e71c845f 100644
--- a/host-context-controller/test/hostReconciler.test.ts
+++ b/host-context-controller/test/hostReconciler.test.ts
@@ -289,7 +289,7 @@ describe('HostReconciler', () => {
).toBe(true)
})
- it('converges existing deployment and service and creates pvc for valid host', async () => {
+ it('converges existing deployment, service, and unbound pvc for valid host', async () => {
const { reconciler, appsApi, coreApi } = createReconciler()
const host = makeHost()
@@ -299,7 +299,9 @@ describe('HostReconciler', () => {
namespace: 'mcp-host',
name: 'host-secret',
})
- expect(coreApi.createNamespacedPersistentVolumeClaim).toHaveBeenCalledTimes(1)
+ expect(coreApi.readNamespacedPersistentVolumeClaim).toHaveBeenCalledTimes(1)
+ expect(coreApi.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
+ expect(coreApi.replaceNamespacedPersistentVolumeClaim).toHaveBeenCalledTimes(1)
// Reconcile updates two existing Services: the host (mcp-host ns) and its
// channel-reader handoff Service (channels ns).
expect(coreApi.readNamespacedService).toHaveBeenCalledTimes(2)
@@ -671,7 +673,16 @@ describe('HostReconciler', () => {
const { reconciler, coreApi } = createReconciler()
coreApi.createNamespacedPersistentVolumeClaim.mockRejectedValue({ code: 409 })
coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue({
- metadata: { resourceVersion: '42' },
+ metadata: {
+ name: 'alpha-host-workspace',
+ namespace: 'mcp-host',
+ uid: 'pvc-uid',
+ labels: {
+ 'clerum.io/host': 'alpha-host',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ resourceVersion: '42',
+ },
spec: {
volumeName: 'pvc-aaaa-bbbb-cccc-dddd',
storageClassName: 'standard',
@@ -681,6 +692,8 @@ describe('HostReconciler', () => {
})
await reconciler.reconcile(makeHost())
+ expect(coreApi.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(coreApi.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
expect(coreApi.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
})
@@ -689,7 +702,16 @@ describe('HostReconciler', () => {
const { reconciler, coreApi } = createReconciler()
coreApi.createNamespacedPersistentVolumeClaim.mockRejectedValue({ code: 409 })
coreApi.readNamespacedPersistentVolumeClaim.mockResolvedValue({
- metadata: { resourceVersion: '7' },
+ metadata: {
+ name: 'alpha-host-workspace',
+ namespace: 'mcp-host',
+ uid: 'pvc-uid',
+ labels: {
+ 'clerum.io/host': 'alpha-host',
+ 'clerum.io/managed-by': 'host-context-controller',
+ },
+ resourceVersion: '7',
+ },
spec: {
storageClassName: 'standard',
accessModes: ['ReadWriteOnce'],
@@ -698,6 +720,8 @@ describe('HostReconciler', () => {
})
await reconciler.reconcile(makeHost())
+ expect(coreApi.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()
+ expect(coreApi.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()
expect(coreApi.replaceNamespacedPersistentVolumeClaim).toHaveBeenCalledTimes(1)
})
@@ -975,6 +999,10 @@ describe('HostReconciler — desktop support', () => {
describe('HostReconciler — per-Host RBAC scaffolding', () => {
it('provisions per-Host SA + Role + RoleBinding before the Deployment', async () => {
const { reconciler, coreApi, rbacApi } = createReconciler()
+ // Initial provisioning explicitly starts without these three RBAC objects.
+ coreApi.readNamespacedServiceAccount.mockRejectedValueOnce({ code: 404 })
+ rbacApi.readNamespacedRole.mockRejectedValueOnce({ code: 404 })
+ rbacApi.readNamespacedRoleBinding.mockRejectedValueOnce({ code: 404 })
await reconciler.reconcile(makeHost())
expect(coreApi.createNamespacedServiceAccount).toHaveBeenCalledTimes(1)
@@ -1046,6 +1074,8 @@ describe('HostReconciler — per-Host RBAC scaffolding', () => {
it('rewrites Role resourceNames when spec.secretRef changes (replace path)', async () => {
const { reconciler, rbacApi } = createReconciler()
rbacApi.createNamespacedRole.mockRejectedValueOnce({ code: 409 })
+ // Race: the first absence is superseded by a conflicting creator.
+ rbacApi.readNamespacedRole.mockRejectedValueOnce({ code: 404 })
rbacApi.readNamespacedRole.mockImplementation(async () => {
const desired = rbacApi.createNamespacedRole.mock.calls[0][0].body as {
metadata?: { labels?: Record<string, string> }
@@ -1086,7 +1116,14 @@ describe('HostReconciler — per-Host RBAC scaffolding', () => {
it('replaces a live Role that has no rules (fail-open-to-write)', async () => {
const { reconciler, rbacApi } = createReconciler()
rbacApi.createNamespacedRole.mockRejectedValueOnce({ code: 409 })
- rbacApi.readNamespacedRole.mockResolvedValue({ metadata: { resourceVersion: '7' } })
+ rbacApi.readNamespacedRole.mockResolvedValue({
+ metadata: {
+ name: 'host-alpha-host-config-reader',
+ namespace: 'mcp-host',
+ uid: 'role-uid',
+ resourceVersion: '7',
+ },
+ })
await reconciler.reconcile(makeHost({ spec: { secretRef: 'rotated-secret' } } as never))