Skip to content

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

TypeScript

Merge origin/dev into claude/pr-205-fixes [R3-sync]

Alfredo Lopez39bb4e81e6af
diff --cc .github/workflows/ci-public.yml
index 7162b0e4f,f1bbc4a40..1623f9475
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@@ -349,18 -342,18 +354,30 @@@ jobs
- name: Test minikube detect-k8s-api-ip template rendering
run: bash scripts/tests/test-minikube-detect-k8s-api-ip.sh
+ - name: Validate single-writer rollout invariant on rendered overlays
+ run: |
+ # The k8s-api-ip patch is rendered from a gitignored template at setup
+ # time; render it with a dummy IP so `kubectl kustomize` can build the
+ # minikube overlay here. The gcp-* overlays live in evenfire-infra, so
+ # this repo validates only the minikube overlay it actually ships.
+ sed 's#__K8S_API_IP__#10.96.0.1#g' \
+ deploy/overlays/minikube/patches/k8s-api-ip.yaml.template \
+ > deploy/overlays/minikube/patches/k8s-api-ip.yaml
+ SINGLE_WRITER_OVERLAYS="deploy/overlays/minikube" \
+ bash deploy/scripts/validate-postgres-single-writer-strategy.sh
+
+ - name: Test release coordinates (writer, checker, floor decoupling)
+ run: bash scripts/tests/test-release-coordinates.sh
+
+ - name: Test precommit release-manifest exemption
+ run: bash scripts/tests/test-precommit-release-manifest-ignore.sh
+
+ - name: Validate release manifest matches package versions
+ run: node scripts/release/update-desktop-release-manifest.mjs --validate-only
+
+ - name: Validate service version bumps
+ run: node scripts/release/validate-release-version-bumps.mjs --previous "${{ github.event.pull_request.base.sha || github.event.before }}"
+
# ─── Platform NGINX image guard (CVE baseline) ────────────────────────────
nginx-image-guard:
name: Validate platform NGINX images
diff --cc control-ui/components/CreateMcpServerForm/index.tsx
index e2212e918,89329fa10..494ec17dc
--- a/control-ui/components/CreateMcpServerForm/index.tsx
+++ b/control-ui/components/CreateMcpServerForm/index.tsx
@@@ -448,97 -438,101 +438,103 @@@ export function CreateMcpServerForm(
value={description}
/>
</Field>
- </div>
- ) : null}
- {step === 1 ? (
- <div className="cu-form-stack cu-agent-form-stack">
- <div className="cu-form-grid cu-form-grid--2">
- <Field label="Transport Type">
- <SelectInput
- onChange={event => setTransportType(event.target.value as TransportType)}
- disabled={submitting}
- value={transportType}
+ <details className="cu-advanced-details">
+ <summary>Advanced options</summary>
+ <p className="cu-advanced-details__hint">
+ Runtime, container overrides, and network egress. The defaults work for most
+ connectors.
+ </p>
+ <div className="cu-form-stack cu-agent-form-stack">
+ <div className="cu-form-grid cu-form-grid--2">
+ <Field label="Transport Type">
+ <SelectInput
+ onChange={event => setTransportType(event.target.value as TransportType)}
+ disabled={submitting}
+ value={transportType}
+ >
+ {TRANSPORT_TYPES.map(option => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </SelectInput>
+ </Field>
+
+ {transportType !== 'stdio' ? (
+ <Field description="Port the connector listens on." label="Port">
+ <TextInput
+ narrow
+ onChange={event => setPort(parseInt(event.target.value, 10) || 3000)}
+ type="number"
+ disabled={submitting}
+ value={port}
+ />
+ </Field>
+ ) : null}
+ </div>
+
+ <Field
+ description={
+ <>
+ <strong>Managed:</strong> Evenfire creates the Deployment, Service, and
+ NetworkPolicies. <strong>Not managed:</strong> you deploy the pod yourself
+ and Evenfire only registers it for discovery.
+ </>
+ }
+ label="Managed"
>
- {TRANSPORT_TYPES.map(option => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </SelectInput>
- </Field>
-
- {transportType !== 'stdio' ? (
- <Field description="Port the connector listens on." label="Port">
- <TextInput
- narrow
- onChange={event => setPort(parseInt(event.target.value, 10) || 3000)}
- type="number"
+ <SelectInput
+ onChange={event => setManaged(event.target.value === 'true')}
disabled={submitting}
- value={port}
- />
+ value={managed ? 'true' : 'false'}
+ >
+ <option value="true">
+ Yes — Evenfire creates and manages the Deployment, Service, and
+ NetworkPolicies
+ </option>
- <option value="false">No — I will deploy the pod myself (discovery only)</option>
++ <option value="false">
++ No — I will deploy the pod myself (discovery only)
++ </option>
+ </SelectInput>
</Field>
- ) : null}
- </div>
- <Field
- description={
- <>
- <strong>Managed:</strong> Evenfire creates the Deployment, Service, and
- NetworkPolicies. <strong>Not managed:</strong> you deploy the pod yourself and
- Evenfire only registers it for discovery.
- </>
- }
- label="Managed"
- >
- <SelectInput
- onChange={event => setManaged(event.target.value === 'true')}
- disabled={submitting}
- value={managed ? 'true' : 'false'}
- >
- <option value="true">
- Yes — Evenfire creates and manages the Deployment, Service, and NetworkPolicies
- </option>
- <option value="false">No — I will deploy the pod myself (discovery only)</option>
- </SelectInput>
- </Field>
-
- <FormSection
- description="Optional container entrypoint and command overrides."
- title="Container Overrides"
- >
- <Field
- description='Comma-separated values, for example "node, server.js".'
- label="Command"
- >
- <TextInput
- monospace
- onChange={event => setCommand(event.target.value)}
- placeholder="node, server.js"
- disabled={submitting}
- value={command}
- />
- </Field>
-
- <Field
- description='Comma-separated values, for example "--port, 3000, --headless".'
- label="Args"
- >
- <TextInput
- monospace
- onChange={event => setArgs(event.target.value)}
- placeholder="--port, 3000, --headless"
- disabled={submitting}
- value={args}
- />
- </Field>
- </FormSection>
- </div>
- ) : null}
-
- {step === 2 ? (
- <div className="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide">
- <EgressEditor allowCidr onChange={handleEgressChange} />
+ <FormSection
+ description="Optional container entrypoint and command overrides."
+ title="Container Overrides"
+ >
+ <Field
+ description='Comma-separated values, for example "node, server.js".'
+ label="Command"
+ >
+ <TextInput
+ monospace
+ onChange={event => setCommand(event.target.value)}
+ placeholder="node, server.js"
+ disabled={submitting}
+ value={command}
+ />
+ </Field>
+
+ <Field
+ description='Comma-separated values, for example "--port, 3000, --headless".'
+ label="Args"
+ >
+ <TextInput
+ monospace
+ onChange={event => setArgs(event.target.value)}
+ placeholder="--port, 3000, --headless"
+ disabled={submitting}
+ value={args}
+ />
+ </Field>
+ </FormSection>
+
+ <div className="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide">
+ <EgressEditor allowCidr onChange={handleEgressChange} />
+ </div>
+ </div>
+ </details>
</div>
) : null}
diff --cc control-ui/components/RegistryInstallForm/index.tsx
index 5e4d827cd,17a9606f6..ddb3a44d4
--- a/control-ui/components/RegistryInstallForm/index.tsx
+++ b/control-ui/components/RegistryInstallForm/index.tsx
@@@ -300,106 -274,104 +274,106 @@@ export function RegistryInstallForm({ e
}}
className="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide"
>
- {step === 1 ? (
- <>
- <div className="cu-field cu-field--compact">
- <label htmlFor="ri-name">Server name</label>
- <input
- id="ri-name"
- className="cu-input"
- value={serverName}
- onChange={event =>
- setServerName(event.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
- }
- placeholder="my-mcp-server"
- />
- {serverName && !nameValid ? (
- <p className="cu-field__error">
- Must be a valid K8s name (lowercase, alphanumeric, hyphens, max 63 chars).
- </p>
- ) : null}
- </div>
-
- <div className="cu-field cu-field--compact">
- <label htmlFor="ri-context">Context</label>
- <select
- id="ri-context"
- className="cu-input"
- value={contextRef}
- onChange={event => setContextRef(event.target.value)}
- >
- <option value="">Select a context...</option>
- {contexts.map(context => (
- <option key={context.name} value={context.name}>
- {context.name}
- </option>
- ))}
- </select>
- </div>
-
- {credHasKeys ? (
- <fieldset className="cu-form-section">
- <legend className="cu-section-title">
- Credentials ({credSchema!.authType}
- {credRequired ? '' : ' - optional'})
- </legend>
- {credSchema!.keys.map(key => (
- <div className="cu-field cu-field--compact" key={key.name}>
- <label htmlFor={`ri-cred-${key.name}`}>{key.label}</label>
- <input
- id={`ri-cred-${key.name}`}
- className="cu-input"
- type={
- key.kind === 'api-key' || key.kind === 'password' ? 'password' : 'text'
- }
- value={credValues[key.name] ?? ''}
- onChange={event =>
- setCredValues(previous => ({
- ...previous,
- [key.name]: event.target.value,
- }))
- }
- onPaste={event => pasteCredentialValue(key.name, event)}
- autoComplete="new-password"
- placeholder={key.description}
- />
- </div>
- ))}
- {credRequired ? (
- <div
- className={`cu-banner ${credStarted && !credComplete ? 'cu-banner--error' : 'cu-banner--info'}`}
- >
- {credStarted && !credComplete
- ? `Complete all credential fields or clear them all to install pending. Missing: ${missingCredentialKeys.join(', ')}.`
- : 'Leave all credential fields empty to install now and add this connector secret later from Secrets, or fill every field to create it during install.'}
- </div>
+ {step === 0 ? (
+ <details className="cu-registry-install-configuration">
+ <summary>Configuration</summary>
+ <div className="cu-registry-install-configuration__body">
- <div className="cu-field cu-field--compact">
- <label htmlFor="ri-name">Server name</label>
- <input
- id="ri-name"
- className="cu-input"
- value={serverName}
- onChange={event =>
- setServerName(event.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
- }
- placeholder="my-mcp-server"
- />
- {serverName && !nameValid ? (
- <p className="cu-field__error">
- Must be a valid K8s name (lowercase, alphanumeric, hyphens, max 63 chars).
- </p>
- ) : null}
- </div>
-
- <div className="cu-field cu-field--compact">
- <label htmlFor="ri-context">Context</label>
- <select
- id="ri-context"
- className="cu-input"
- value={contextRef}
- onChange={event => setContextRef(event.target.value)}
- >
- <option value="">Select a context...</option>
- {contexts.map(context => (
- <option key={context.name} value={context.name}>
- {context.name}
- </option>
- ))}
- </select>
- </div>
-
- {credHasKeys ? (
- <fieldset className="cu-form-section">
- <legend className="cu-section-title">
- Credentials ({credSchema!.authType}
- {credRequired ? '' : ' - optional'})
- </legend>
- {credSchema!.keys.map(key => (
- <div className="cu-field cu-field--compact" key={key.name}>
- <label htmlFor={`ri-cred-${key.name}`}>{key.label}</label>
- <input
- id={`ri-cred-${key.name}`}
- className="cu-input"
- type={
- key.kind === 'api-key' || key.kind === 'password' ? 'password' : 'text'
- }
- value={credValues[key.name] ?? ''}
- onChange={event =>
- setCredValues(previous => ({
- ...previous,
- [key.name]: event.target.value,
- }))
- }
- onPaste={event => pasteCredentialValue(key.name, event)}
- autoComplete="new-password"
- placeholder={key.description}
- />
- </div>
- ))}
- {credRequired ? (
- <div
- className={`cu-banner ${credStarted && !credComplete ? 'cu-banner--error' : 'cu-banner--info'}`}
- >
- {credStarted && !credComplete
- ? `Complete all credential fields or clear them all to install pending. Missing: ${missingCredentialKeys.join(', ')}.`
- : 'Leave all credential fields empty to install now and add this connector secret later from Secrets, or fill every field to create it during install.'}
- </div>
++ <div className="cu-field cu-field--compact">
++ <label htmlFor="ri-name">Server name</label>
++ <input
++ id="ri-name"
++ className="cu-input"
++ value={serverName}
++ onChange={event =>
++ setServerName(event.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))
++ }
++ placeholder="my-mcp-server"
++ />
++ {serverName && !nameValid ? (
++ <p className="cu-field__error">
++ Must be a valid K8s name (lowercase, alphanumeric, hyphens, max 63 chars).
++ </p>
) : null}
-- </fieldset>
-- ) : null}
- </>
- ) : null}
- <EgressEditor
- allowCidr
- description="Review and adjust the egress contract that will be installed from this Marketplace entry. The final CRD is created from this selection, not from the Marketplace warning alone."
- initialBindings={registryInitialEgressBindings}
- key={`${entry.name}-${entry.version}-${JSON.stringify(registryInitialEgressBindings ?? [])}`}
- onChange={(nextBindings, status) => {
- setEgressBindings(nextBindings)
- setEgressStatus(status)
- }}
- />
- {remoteRequiresEgress && egressStatus?.mode === 'none' ? (
- <div className="cu-banner cu-banner--error" role="alert">
- Remote connectors must keep exact-host egress to the selected vendor endpoint.
+ </div>
- ) : null}
+
- {step === 2 ? (
- <>
- <EgressEditor
- allowCidr
- description="Review and adjust the egress contract that will be installed from this Marketplace entry. The final CRD is created from this selection, not from the Marketplace warning alone."
- initialBindings={registryInitialEgressBindings}
- key={`${entry.name}-${entry.version}-${JSON.stringify(registryInitialEgressBindings ?? [])}`}
- onChange={(nextBindings, status) => {
- setEgressBindings(nextBindings)
- setEgressStatus(status)
- }}
- />
- {remoteRequiresEgress && egressStatus?.mode === 'none' ? (
- <div className="cu-banner cu-banner--error" role="alert">
- Remote connectors must keep exact-host egress to the selected vendor endpoint.
++ <div className="cu-field cu-field--compact">
++ <label htmlFor="ri-context">Context</label>
++ <select
++ id="ri-context"
++ className="cu-input"
++ value={contextRef}
++ onChange={event => setContextRef(event.target.value)}
++ >
++ <option value="">Select a context...</option>
++ {contexts.map(context => (
++ <option key={context.name} value={context.name}>
++ {context.name}
++ </option>
++ ))}
++ </select>
+ </div>
- ) : null}
- </>
++
++ {credHasKeys ? (
++ <fieldset className="cu-form-section">
++ <legend className="cu-section-title">
++ Credentials ({credSchema!.authType}
++ {credRequired ? '' : ' - optional'})
++ </legend>
++ {credSchema!.keys.map(key => (
++ <div className="cu-field cu-field--compact" key={key.name}>
++ <label htmlFor={`ri-cred-${key.name}`}>{key.label}</label>
++ <input
++ id={`ri-cred-${key.name}`}
++ className="cu-input"
++ type={
++ key.kind === 'api-key' || key.kind === 'password'
++ ? 'password'
++ : 'text'
++ }
++ value={credValues[key.name] ?? ''}
++ onChange={event =>
++ setCredValues(previous => ({
++ ...previous,
++ [key.name]: event.target.value,
++ }))
++ }
++ onPaste={event => pasteCredentialValue(key.name, event)}
++ autoComplete="new-password"
++ placeholder={key.description}
++ />
++ </div>
++ ))}
++ {credRequired ? (
++ <div
++ className={`cu-banner ${credStarted && !credComplete ? 'cu-banner--error' : 'cu-banner--info'}`}
++ >
++ {credStarted && !credComplete
++ ? `Complete all credential fields or clear them all to install pending. Missing: ${missingCredentialKeys.join(', ')}.`
++ : 'Leave all credential fields empty to install now and add this connector secret later from Secrets, or fill every field to create it during install.'}
++ </div>
++ ) : null}
++ </fieldset>
++ ) : null}
++ <EgressEditor
++ allowCidr
++ description="Review and adjust the egress contract that will be installed from this Marketplace entry. The final CRD is created from this selection, not from the Marketplace warning alone."
++ initialBindings={registryInitialEgressBindings}
++ key={`${entry.name}-${entry.version}-${JSON.stringify(registryInitialEgressBindings ?? [])}`}
++ onChange={(nextBindings, status) => {
++ setEgressBindings(nextBindings)
++ setEgressStatus(status)
++ }}
++ />
++ {remoteRequiresEgress && egressStatus?.mode === 'none' ? (
++ <div className="cu-banner cu-banner--error" role="alert">
++ Remote connectors must keep exact-host egress to the selected vendor endpoint.
++ </div>
++ ) : null}
+ </div>
+ </details>
) : null}
- {step === 3 ? (
+ {step === 1 ? (
<div className="cu-agent-review">
Connector <b>{serverName || '-'}</b> will be installed into context{' '}
<b>{contextRef || '-'}</b> from <b>{entry.name}</b> v{entry.version}.
diff --cc deploy/base/control-plane/host-context-controller.yaml
index 36c6ab8be,396cd5e2f..782697b37
--- a/deploy/base/control-plane/host-context-controller.yaml
+++ b/deploy/base/control-plane/host-context-controller.yaml
@@@ -13,25 -13,22 +13,34 @@@ metadata
app: host-context-controller
spec:
replicas: 1
- # HCC's /ready stays 503 until its initial fleet reconciliation finishes, so time-to-Ready
- # scales with the McpServer/Context fleet rather than with process start. clerum-dev took
- # 651s on 2026-08-05 at 108 McpServers / 22 Contexts.
+ # HCC's safety model assumes a single NetworkPolicy writer: replicas:1 with no
+ # leader election (see statelessLifecycleExecutor.ts). RollingUpdate (the
+ # default) starts the new pod before terminating the old one, so every rollout
+ # would overlap two writers — during which the outgoing replica can win a
+ # conflict-retry replace and land its wider spec back over a policy the new
+ # replica just hardened and certified, with no NetworkPolicy resync to heal it
+ # and /ready still 200. Recreate terminates the old pod first, honouring the
+ # single-writer assumption through the rollout too.
+ strategy:
+ type: Recreate
+ # Recreate + replicas:1 means a botched rollout (new pod never Ready) leaves
+ # the control plane down until a manual `kubectl rollout undo` — the single-
+ # writer invariant forbids any overlap-based auto-recovery. This deadline is
+ # DETECTION ONLY: it flips Progressing=False (ProgressDeadlineExceeded) and
+ # fails `kubectl rollout status` for callers without their own --timeout; it
- # does not roll back. 300s > worst legitimate startup (imagePullPolicy: Always
- # pull + startupProbe budget 3s*40=120s + initial safety-inventory pass), so a
- # slow pull never trips a false positive.
- progressDeadlineSeconds: 300
++ # does not roll back.
+ #
- # Unset, this defaults to 600s, and that default is what actually governed the deploy:
- # `kubectl rollout status` aborts the instant the controller sets ProgressDeadlineExceeded,
- # so provision-gfs-runtime.sh's --timeout could never exceed the deadline remaining. The
- # clock also starts several steps earlier, at apply-inter-service-tokens.sh's `rollout
- # restart` of HCC, so the wait inherits only what is left. On 2026-08-05 that was 600-160
- # = 440s against a 480s timeout: the timeout raised in #202 never bound, and the deploy
- # failed 50s before HCC came Ready.
- #
- # 1200s covers the 900s wait plus a 300s head-start allowance. This is a mitigation, not
- # the fix — evenfire-ai/evenfire#205 decouples readiness from fleet convergence, after
- # which both numbers should come back down.
++ # Value (origin/dev, 2026-08-05): HCC's /ready stays 503 until its initial fleet
++ # reconciliation finishes, so time-to-Ready scales with the McpServer/Context
++ # fleet — clerum-dev took 651s at 108 McpServers / 22 Contexts. The unset default
++ # (600s) governed the deploy because `kubectl rollout status` aborts the instant
++ # the deadline is exceeded, and the clock starts at apply-inter-service-tokens.sh's
++ # `rollout restart`, so the wait inherits only the remaining budget (600-160=440s
++ # vs a 480s timeout on 2026-08-05: #202's timeout never bound, deploy failed 50s
++ # short). 1200s covers the 900s wait plus a 300s head-start. Mitigation, not the
++ # fix — #205 decouples readiness from fleet convergence, after which this should
++ # come back down.
+ progressDeadlineSeconds: 1200
selector:
matchLabels:
app: host-context-controller
diff --cc desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
index 08568c095,0b1007986..ff8667aa0
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
@@@ -51,10 -51,10 +51,8 @@@ function createDeferred<T>(): Deferred<
return { promise, resolve }
}
- function createSessionState(authenticated: boolean) {
- return authenticated
- ? { authenticated: true, me: HARNESS_ME }
- : { authenticated: false, me: null }
+ function createSessionState(authenticated: boolean, me = HARNESS_ME) {
- return authenticated
- ? { authenticated: true, me }
- : { authenticated: false, me: null }
++ return authenticated ? { authenticated: true, me } : { authenticated: false, me: null }
}
function createCatalog(agentNames: string[]) {
diff --cc host-context-controller/package-lock.json
index d5d339954,9a3aff834..a6d30af44
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-host-context-controller",
- "version": "0.1.212",
- "version": "0.1.160",
++ "version": "0.1.213",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.212",
- "version": "0.1.160",
++ "version": "0.1.213",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --cc host-context-controller/package.json
index 1539613da,51dc2ded1..e0b03ef61
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-host-context-controller",
- "version": "0.1.212",
- "version": "0.1.160",
++ "version": "0.1.213",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --cc host-context-controller/src/deploymentStrategy.test.ts
index 77048f231,000000000..7a9258139
mode 100644,000000..100644
--- a/host-context-controller/src/deploymentStrategy.test.ts
+++ b/host-context-controller/src/deploymentStrategy.test.ts
@@@ -1,63 -1,0 +1,66 @@@
+import { describe, expect, it } from 'vitest'
+import { loadAll } from 'js-yaml'
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+
+/**
+ * HCC's safety model assumes a single writer: replicas:1 with NO leader
+ * election (see statelessLifecycleExecutor.ts — "Running >1 replica risks two
+ * controllers racing"). The default Deployment strategy is RollingUpdate with
+ * maxSurge>0, which starts the new pod before the old one exits — a guaranteed
+ * two-replica overlap on every rollout. During that window the outgoing replica
+ * can win a conflict-retry replace (applyNetworkPolicy → replaceWithConflictRetry)
+ * and land its wider spec back over a policy the new replica just hardened and
+ * certified. There is no NetworkPolicy watch or periodic resync to heal it, and
+ * the new replica's safety fence only sees failures in its own process — so
+ * /ready stays 200 over a stale allow. Recreate closes the overlap, which is the
+ * only way to honour the documented single-writer assumption during a rollout.
+ */
+describe('host-context-controller Deployment strategy', () => {
+ const docs = loadAll(
+ readFileSync(
+ path.join(__dirname, '../../deploy/base/control-plane/host-context-controller.yaml'),
+ 'utf8'
+ )
+ ) as Array<{ kind?: string; metadata?: { name?: string }; spec?: Record<string, unknown> }>
+
+ const deployment = docs.find(
+ d => d?.kind === 'Deployment' && d?.metadata?.name === 'host-context-controller'
+ )
+
+ it('defines the host-context-controller Deployment', () => {
+ expect(deployment).toBeDefined()
+ })
+
+ it('runs a single replica', () => {
+ expect(deployment?.spec?.replicas).toBe(1)
+ })
+
+ it('uses Recreate so a rollout never overlaps two writers', () => {
+ // RollingUpdate (the default) would start the new pod before terminating the
+ // old one; with no leader election that races two NetworkPolicy writers.
+ const strategy = deployment?.spec?.strategy as { type?: string } | undefined
+ expect(strategy?.type).toBe('Recreate')
+ })
+
+ it('carries no rollingUpdate block under Recreate', () => {
+ // A leftover spec.strategy.rollingUpdate is invalid under Recreate and, if a
+ // future edit flipped only `type` back, would quietly reintroduce surge.
+ const strategy = deployment?.spec?.strategy as { rollingUpdate?: unknown } | undefined
+ expect(strategy?.rollingUpdate).toBeUndefined()
+ })
+
+ it('bounds rollout-stall detection above the worst legitimate startup', () => {
+ // Detection only, not recovery: Recreate + replicas:1 means a botched
+ // rollout is healed operationally (kubectl rollout undo), never by K8s.
+ // This deadline just flips Progressing=False / fails `kubectl rollout
+ // status` deterministically for observers without their own --timeout. It
- // must exceed the worst legitimate startup — imagePullPolicy: Always pull +
- // startupProbe budget (3s*40=120s) + the initial safety-inventory pass — so
- // a slow pull never trips a false ProgressDeadlineExceeded.
- expect(deployment?.spec?.progressDeadlineSeconds).toBe(300)
++ // must exceed the worst legitimate startup, which — until #205 fully
++ // decouples readiness from fleet convergence — scales with the McpServer/
++ // Context fleet: origin/dev observed 651s on clerum-dev (108 McpServers /
++ // 22 Contexts) on 2026-08-05, so 1200s (900s wait + 300s head-start) is the
++ // merged mitigation. Comes back down once readiness no longer waits on the
++ // fleet.
++ expect(deployment?.spec?.progressDeadlineSeconds).toBe(1200)
+ })
+})
diff --cc host-context-controller/src/reconciler.test.ts
index bef186be2,92e74d6e8..095983845
--- a/host-context-controller/src/reconciler.test.ts
+++ b/host-context-controller/src/reconciler.test.ts
@@@ -881,164 -608,51 +884,214 @@@ describe('PR-B B1 — writeStatusCondit
)
expect(sample?.value).toBe(0)
})
+
+ it('fences the patch with resourceVersion and retries on a 422 conflict (M2)', async () => {
+ const existing = {
+ type: 'DeploymentReady',
+ status: 'False',
+ reason: 'WaitingForReplicas',
+ message: 'waiting',
+ lastTransitionTime: '2020-01-01T00:00:00.000Z',
+ }
+ // First read at rv=v1; after the conflict, the re-read observes rv=v2 (a
+ // concurrent writer bumped it).
+ customApi.getNamespacedCustomObjectStatus
+ .mockResolvedValueOnce({
+ metadata: { resourceVersion: 'v1' },
+ status: { conditions: [existing] },
+ })
+ .mockResolvedValueOnce({
+ metadata: { resourceVersion: 'v2' },
+ status: { conditions: [existing] },
+ })
+ // First patch loses the race (the resourceVersion `test` op fails → 422);
+ // the retry succeeds.
+ customApi.patchNamespacedCustomObjectStatus
+ .mockRejectedValueOnce(Object.assign(new Error('the test operation failed'), { code: 422 }))
+ .mockResolvedValueOnce({})
+
+ const server = makeServer({ name: 'pg' })
+ await reconciler.writeStatusCondition(server, {
+ type: 'DeploymentReady',
+ status: 'True',
+ reason: 'ReplicasAvailable',
+ message: 'ready',
+ })
+
+ // Re-read and re-patched instead of losing the write.
+ expect(customApi.getNamespacedCustomObjectStatus).toHaveBeenCalledTimes(2)
+ expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(2)
+ // Both patches are fenced; the successful retry uses the RE-READ version.
+ const firstBody = customApi.patchNamespacedCustomObjectStatus.mock.calls[0][0].body
+ const secondBody = customApi.patchNamespacedCustomObjectStatus.mock.calls[1][0].body
+ expect(firstBody[0]).toEqual({ op: 'test', path: '/metadata/resourceVersion', value: 'v1' })
+ expect(secondBody[0]).toEqual({ op: 'test', path: '/metadata/resourceVersion', value: 'v2' })
+ })
})
+describe('restart-safe discovery status', () => {
+ const appsApi = createMockAppsApi()
+ const coreApi = createMockCoreApi()
+ const customApi = createMockCustomApi()
+ let reconciler: McpServerReconciler
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ reconciler = new McpServerReconciler({} as k8s.KubeConfig, {
+ appsApi: asAppsApi(appsApi),
+ coreApi: asCoreApi(coreApi),
+ customApi: asCustomApi(customApi),
+ })
+ })
+
+ it('uses a persisted Ready condition only when it observes the current generation', () => {
+ const server: McpServerCRD = {
+ ...makeServer({ name: 'restart-safe' }),
+ generation: 7,
+ status: {
+ conditions: [
+ {
+ type: 'Ready',
+ status: 'True',
+ reason: 'ReconcileSuccess',
+ message: 'Deployment created',
+ observedGeneration: 7,
+ },
+ ],
+ },
+ }
+
+ expect(reconciler.getStatus(server)).toEqual({
+ deployed: true,
+ ready: true,
+ message: 'Deployment created',
+ authoritative: true,
+ })
+ })
+
+ it.each([
+ ['stale', 6],
+ ['unversioned', undefined],
+ ])('fails closed for a %s persisted Ready condition', (_label, observedGeneration) => {
+ const server: McpServerCRD = {
+ ...makeServer({ name: 'restart-unsafe' }),
+ generation: 7,
+ status: {
+ conditions: [
+ {
+ type: 'Ready',
+ status: 'True',
+ reason: 'ReconcileSuccess',
+ message: 'Deployment created',
+ observedGeneration,
+ },
+ ],
+ },
+ }
+
+ expect(reconciler.getStatus(server)).toEqual({
+ deployed: false,
+ ready: false,
+ message: 'Not reconciled yet',
+ authoritative: false,
+ })
+ })
+
+ it('fails closed when persisted Ready conditions conflict for the current generation', () => {
+ const server: McpServerCRD = {
+ ...makeServer({ name: 'restart-conflict' }),
+ generation: 7,
+ status: {
+ conditions: [
+ {
+ type: 'Ready',
+ status: 'True',
+ reason: 'ReconcileSuccess',
+ observedGeneration: 7,
+ },
+ {
+ type: 'Ready',
+ status: 'False',
+ reason: 'SecretValidationFailed',
+ observedGeneration: 7,
+ },
+ ],
+ },
+ }
+
+ expect(reconciler.getStatus(server)).toEqual({
+ deployed: false,
+ ready: false,
+ message: 'Not reconciled yet',
+ authoritative: false,
+ })
+ })
+
+ it('prefers fresh in-memory status over persisted status from the same generation', async () => {
+ const server: McpServerCRD = {
+ ...makeServer({ name: 'live-status' }),
+ generation: 3,
+ status: {
+ conditions: [
+ {
+ type: 'Ready',
+ status: 'True',
+ reason: 'ReconcileSuccess',
+ observedGeneration: 3,
+ },
+ ],
+ },
+ }
+ appsApi.readNamespacedDeployment.mockResolvedValueOnce({
+ status: { readyReplicas: 0 },
+ })
+
+ await reconciler.reconcile(server)
+
+ expect(reconciler.getStatus(server)).toEqual(
+ expect.objectContaining({
+ deployed: true,
+ ready: false,
+ authoritative: true,
+ })
+ )
+ })
+
+ it.each([
+ ['generation changes', 'stable-uid', 4],
+ ['the same name is recreated', 'replacement-uid', 3],
+ ])('does not reuse in-memory status when %s', async (_case, uid, generation) => {
+ const original: McpServerCRD = {
+ ...makeServer({ name: 'identity-fenced' }),
+ uid: 'original-uid',
+ generation: 3,
+ }
+ await reconciler.reconcile(original)
- expect(reconciler.getStatus(original).ready).toBe(true)
++ // #223 (credential rotation) makes readiness immediately False until the poll
++ // upgrades it, so the original caches deployed/authoritative here — not ready.
++ // This test's subject is the identity fencing asserted below, not readiness
++ // timing; it only needs a real (non-default) cached status to prove it is not
++ // reused across an identity change.
++ expect(reconciler.getStatus(original)).toEqual(
++ expect.objectContaining({ deployed: true, ready: false, authoritative: true })
++ )
+
+ const current: McpServerCRD = {
+ ...original,
+ uid,
+ generation,
+ status: undefined,
+ }
+
+ expect(reconciler.getStatus(current)).toEqual({
+ deployed: false,
+ ready: false,
+ message: 'Not reconciled yet',
+ authoritative: false,
+ })
+ })
+})
+
describe('ownership-safe fail-closed cleanup', () => {
const appsApi = createMockAppsApi()
const coreApi = createMockCoreApi()
diff --cc host-context-controller/src/reconciler.ts
index 99ffc1a25,caba6be91..a44b18cfd
--- a/host-context-controller/src/reconciler.ts
+++ b/host-context-controller/src/reconciler.ts
@@@ -100,37 -95,59 +121,90 @@@ function throwCleanupFailures(failures
}
}
+async function mapSettledWithConcurrency<T, TResult>(
+ items: readonly T[],
+ maxConcurrency: number,
+ work: (item: T, index: number) => Promise<TResult>
+): Promise<Array<PromiseSettledResult<TResult>>> {
+ if (!Number.isInteger(maxConcurrency) || maxConcurrency < 1) {
+ throw new RangeError('maxConcurrency must be a positive integer')
+ }
+
+ const results = new Array<PromiseSettledResult<TResult>>(items.length)
+ let nextIndex = 0
+ const worker = async (): Promise<void> => {
+ while (nextIndex < items.length) {
+ const index = nextIndex
+ nextIndex += 1
+ try {
+ results[index] = {
+ status: 'fulfilled',
+ value: await work(items[index], index),
+ }
+ } catch (reason) {
+ results[index] = { status: 'rejected', reason }
+ }
+ }
+ }
+
+ const workerCount = Math.min(maxConcurrency, items.length)
+ await Promise.all(Array.from({ length: workerCount }, () => worker()))
+ return results
+}
+
+ /**
+ * State of the readiness poll window for one McpServer (issue #223).
+ *
+ * A "window" is one bounded observation of a single Deployment rollout:
+ * maxAttempts ticks of intervalMs each. The window survives repeated
+ * reconciles — see `readinessPolls` below for why that is load-bearing.
+ */
+ interface ReadinessPollState {
+ /**
+ * Timer for the next tick; undefined while a tick is executing its awaits
+ * (the handle is consumed the moment the callback fires) and once the
+ * window reached a terminal verdict.
+ */
+ timer: ReturnType<typeof setTimeout> | undefined
+ /**
+ * True while a tick is executing. `timer` alone cannot distinguish "tick
+ * running RIGHT NOW" from "window ended", and the difference is
+ * load-bearing for pollReadiness() re-entrancy (see `recheckRequested`).
+ */
+ ticking: boolean
+ /**
+ * Set by pollReadiness() when it is called while a tick is in flight. The
+ * caller (a reconcile) may have JUST rewritten the Deployment — e.g. a
+ * corrected credential rotation bumping the generation — and the in-flight
+ * tick's read, started earlier, cannot have seen that write. While this
+ * flag is set the tick must NOT commit a terminal verdict (ready or
+ * exhausted): it defers one interval so the next read, which starts after
+ * that Deployment write, observes the new generation and resets the
+ * window. Without this, the exhausting tick could publish RolloutIncomplete
+ * with the SUPERSEDED generation's numbers and — since McpServer has no
+ * periodic resync or Deployment watch — nothing would ever re-arm the poll
+ * for the new rollout (issue #223).
+ */
+ recheckRequested: boolean
+ /**
+ * Deployment generation the current window is watching; null until the
+ * first tick reads it. A change means a NEW rollout (e.g. another
+ * credential rotation), which resets the window so the new rollout gets
+ * its own full budget.
+ */
+ generation: number | null
+ /** Ticks consumed by the current window. */
+ attempts: number
+ /** True once the terminal RolloutIncomplete verdict was written for `generation`. */
+ exhausted: boolean
+ /**
+ * Rollout numbers from the exhausting tick. reconcile() re-writes them so
+ * the terminal condition stays sticky instead of being downgraded to
+ * WaitingForReplicas by the very reconcile the terminal write triggers.
+ */
+ detail: string
+ }
+
export class McpServerReconciler {
private readonly appsApi: k8s.AppsV1Api
private readonly coreApi: k8s.CoreV1Api
@@@ -250,21 -204,6 +336,25 @@@
)
}
+ private beginStatusTracking(server: McpServerCRD): void {
+ if (!this.statusIdentityMatches(server)) {
+ this.statusMap.delete(server.name)
- const timer = this.readinessTimers.get(server.name)
- if (timer) {
- clearTimeout(timer)
- this.readinessTimers.delete(server.name)
++ // A new CRD identity (uid/generation) retires any poll window armed for
++ // the previous desired revision: its verdicts would describe a rollout
++ // that no longer represents the desired state. The reconcile for the
++ // new identity arms its own window after its Deployment write.
++ const poll = this.readinessPolls.get(server.name)
++ if (poll) {
++ if (poll.timer !== undefined) clearTimeout(poll.timer)
++ this.readinessPolls.delete(server.name)
+ }
+ }
+ this.statusIdentities.set(server.name, {
+ uid: server.uid,
+ generation: server.generation,
+ })
+ }
+
/**
* Update the status of an McpServer after reconciliation.
*/
@@@ -277,12 -216,11 +367,12 @@@
*/
private clearStatus(name: string): void {
this.statusMap.delete(name)
+ this.statusIdentities.delete(name)
this.managedSnapshot.delete(name)
- const timer = this.readinessTimers.get(name)
- if (timer) {
- clearTimeout(timer)
- this.readinessTimers.delete(name)
+ const poll = this.readinessPolls.get(name)
+ if (poll) {
+ if (poll.timer !== undefined) clearTimeout(poll.timer)
+ this.readinessPolls.delete(name)
}
}
@@@ -301,52 -289,133 +441,165 @@@
/**
* Poll deployment readiness until ready or maxAttempts reached.
- * Cancels any existing poll for the same server name.
+ *
+ * Re-entrancy is the whole point (issue #223, E2 status-update-loop):
+ * reconcile() runs after every MODIFIED watch event — including the events
+ * caused by our OWN status writes — and calls this on every pass where the
+ * Deployment is not ready yet. A live window is therefore NEVER cancelled
+ * or re-armed here; it keeps counting toward its budget so a rollout that
+ * never converges reaches the terminal RolloutIncomplete verdict after
+ * maxAttempts × intervalMs. A NEW rollout (bumped Deployment generation,
+ * e.g. another credential rotation) is detected inside the poll tick
+ * itself, which resets the window so the new rollout gets its own budget.
+ *
+ * A call that lands while a tick is EXECUTING (mid-await) is not silently
+ * dropped either: it flags `recheckRequested` so the tick defers any
+ * terminal verdict until a read taken AFTER the caller's Deployment write
+ * confirms the generation — otherwise the exhausting tick could seal the
+ * window with a superseded generation's numbers and the new rollout would
+ * never be observed (see ReadinessPollState.recheckRequested).
*/
- private pollReadiness(server: McpServerCRD, intervalMs = 5000, maxAttempts = 24): void {
+ private pollReadiness(
+ server: McpServerCRD,
+ intervalMs = 5000,
- maxAttempts = 12,
++ maxAttempts = 24,
+ isCurrent: () => boolean = () => true
+ ): void {
const { name, namespace } = server
- // Cancel any existing poll for this server
- const existing = this.readinessTimers.get(name)
- if (existing) {
- clearTimeout(existing)
- this.readinessTimers.delete(name)
+
+ const previous = this.readinessPolls.get(name)
+ if (previous !== undefined && (previous.timer !== undefined || previous.ticking)) {
+ // A window is already running for this server — leave it alone
+ // (re-arming would reset the attempt budget: the E2 status-update-loop).
+ // But if its tick is executing RIGHT NOW, the tick's Deployment read may
+ // predate the Deployment write that triggered THIS call (a new
+ // generation), so a silent no-op could let the tick end the window on
+ // stale data. Record that a re-check is owed; the tick honors it before
+ // committing any terminal verdict.
+ if (previous.ticking) {
+ previous.recheckRequested = true
+ }
+ return
}
- let attempts = 0
+ // Fresh window. Carry over the generation and terminal verdict of a
+ // previous exhausted window: if the Deployment has NOT changed since,
+ // the new window must not mistake it for a new rollout, and reconcile()
+ // keeps reporting the sticky RolloutIncomplete meanwhile.
+ const state: ReadinessPollState = {
+ timer: undefined,
+ ticking: false,
+ recheckRequested: false,
+ generation: previous?.generation ?? null,
+ attempts: 0,
+ exhausted: previous?.exhausted ?? false,
+ detail: previous?.detail ?? '',
+ }
+ this.readinessPolls.set(name, state)
+
+ const poll = async (): Promise<void> => {
+ // The timer handle was consumed the moment this callback fired; reflect
+ // that, and mark the tick as in flight so a concurrent pollReadiness()
+ // can tell "tick running" apart from "window ended" during our awaits.
+ state.timer = undefined
+ state.ticking = true
++ // Mutation fencing: a superseded reconcile (desired-revision or
++ // inventory-authority change) must not keep observing — or writing
++ // status — on behalf of a stale desired state. End the window quietly;
++ // the current reconcile arms its own window after its Deployment write.
++ if (!isCurrent()) {
++ state.ticking = false
++ if (this.readinessPolls.get(name) === state) this.readinessPolls.delete(name)
++ return
++ }
+ const rollout = await this.readDeploymentRollout(name, namespace)
++ if (!isCurrent() || !this.statusIdentityMatches(server)) {
++ state.ticking = false
++ if (this.readinessPolls.get(name) === state) this.readinessPolls.delete(name)
++ return
++ }
- const poll = async () => {
- if (!isCurrent()) return
- attempts++
- const ready = await this.checkDeploymentReady(name, namespace)
- if (!isCurrent() || !this.statusIdentityMatches(server)) return
+ // The McpServer may have been deleted (clearStatus) while we were
+ // reading. A cancelled window must not keep ticking or write status
+ // for a CRD that is gone.
+ if (this.readinessPolls.get(name) !== state) return
+
+ // Generation change ⇒ a NEW rollout: it deserves its own full budget,
+ // and any terminal verdict for the old generation no longer applies.
+ // A failed read (generation null) never resets the window — otherwise
+ // a flapping API server would grant infinite budget.
+ if (rollout.generation !== null && rollout.generation !== state.generation) {
+ state.generation = rollout.generation
+ state.attempts = 0
+ state.exhausted = false
+ state.detail = ''
+ }
+ state.attempts++
+
+ // A pollReadiness() call landed while this tick was mid-await: the
+ // Deployment may have been rewritten AFTER our read (that reconcile
+ // writes the Deployment BEFORE calling pollReadiness()), so a terminal
+ // verdict from this tick's data could blame a superseded generation —
+ // and nothing else would ever re-arm the poll for the new one. Defer
+ // the verdict one interval: the next read starts after that Deployment
+ // write, so it MUST observe the new generation and reset the window
+ // above. A same-generation echo merely delays the verdict by one tick;
+ // the budget is NOT reset, so the E2 status-update-loop stays fixed.
+ if (state.recheckRequested) {
+ state.recheckRequested = false
+ if (rollout.ready || state.attempts >= maxAttempts) {
+ state.ticking = false
+ state.timer = setTimeout(poll, intervalMs)
+ return
+ }
+ }
- if (ready) {
+ if (rollout.ready) {
+ state.ticking = false
this.setStatus(name, { deployed: true, ready: true, message: 'Running' })
- this.readinessTimers.delete(name)
+ this.readinessPolls.delete(name)
+ console.log(
+ `[Reconciler] McpServer "${name}" is now ready (after ${state.attempts} poll(s))`
+ )
+ // The poll MUST write the CRD, not just in-memory status (issue #223).
+ // With generation-aware readiness the check right after a replace is
+ // always false, so this is the ONLY place a converged rollout is ever
+ // recorded — without it every successful credential rotation would sit
+ // at DeploymentReady=False forever and the UI would report a timeout.
- await this.updateStatusConditions(server, true)
++ await this.updateStatusConditions(server, true, undefined, isCurrent)
++ // Readiness is decoupled from fleet convergence: the poll also
++ // upgrades the persisted, generation-matched Ready condition so a
++ // controller restart can trust the recorded readiness (see getStatus).
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'Ready',
+ status: 'True',
+ reason: 'ReconcileSuccess',
+ message: 'Deployment created',
+ },
+ isCurrent
+ )
- console.log(`[Reconciler] McpServer "${name}" is now ready (after ${attempts} poll(s))`)
return
}
- if (attempts >= maxAttempts) {
- this.readinessTimers.delete(name)
+ if (state.attempts >= maxAttempts) {
+ // Terminal verdict for THIS generation. The entry stays in the map
+ // (timer undefined since tick start, ticking cleared here — BEFORE
+ // the status write below, so a reconcile arriving during that await
+ // opens a fresh observation window instead of flagging a re-check
+ // this dying tick would never honor) so reconcile() keeps the verdict
+ // sticky and a later pollReadiness() call may re-observe.
+ state.ticking = false
+ state.exhausted = true
+ state.detail = rollout.detail
console.warn(
- `[Reconciler] McpServer "${name}" not ready after ${maxAttempts} polls — giving up`
+ `[Reconciler] McpServer "${name}" not ready after ${maxAttempts} polls — giving up (${rollout.detail})`
)
+ // Give up loudly, on the CRD: a stuck rollout must be visible to the
+ // operator with the numbers that prove it, never left as a stale
+ // condition or a silent Unknown.
- await this.updateStatusConditions(server, false, rollout.detail)
++ await this.updateStatusConditions(server, false, rollout.detail, isCurrent)
return
}
@@@ -743,14 -809,8 +999,14 @@@ ${authHeaderLines ? '\n # ─�
}
}
- private buildDeployment(server: McpServerCRD): k8s.V1Deployment {
+ private buildDeployment(server: McpServerCRD, credentialsRevision = ''): k8s.V1Deployment {
- // ── Platform hardening: sanitize CRD before building PodSpec ──
+ // ── Platform hardening: sanitize an ephemeral copy before building PodSpec ──
+ // The caller retains this object as the LIST -> WATCH desired-state cache.
+ // Mutating it here makes a later status-only watch event look like a
+ // user-driven spec revision, which invalidates the authoritative policy
+ // revocation marker during startup. Sanitization remains mandatory for the
+ // generated PodSpec, but must never rewrite the observed CRD inventory.
+ server = structuredClone(server)
this.sanitizeCrdSpec(server)
const transportPort = server.spec.transport.port || 3000
@@@ -1136,13 -1206,9 +1402,14 @@@
/**
* Ensure a Deployment exists and is up to date.
*/
- private async ensureDeployment(server: McpServerCRD, credentialsRevision = ''): Promise<void> {
+ private async ensureDeployment(
+ server: McpServerCRD,
++ credentialsRevision = '',
+ isCurrent: () => boolean = () => true
+ ): Promise<void> {
- const deployment = this.buildDeployment(server)
+ const deployment = this.buildDeployment(server, credentialsRevision)
+ if (!isCurrent()) return
try {
await this.appsApi.createNamespacedDeployment({
namespace: server.namespace,
@@@ -1486,31 -1585,34 +1753,43 @@@
private async updateStatusConditions(
server: McpServerCRD,
deploymentReady: boolean,
+ /**
+ * Rollout numbers from readDeploymentRollout, appended to the failure
+ * message so a stuck rollout reports WHAT is stuck (issue #223). Callers
+ * that only know the verdict omit it.
+ */
- rolloutDetail?: string
++ rolloutDetail?: string,
+ isCurrent: () => boolean = () => true
): Promise<void> {
try {
- await this.writeStatusCondition(server, {
- type: 'NetworkReady',
- status: 'True',
- reason: 'NetworkPoliciesApplied',
- message: 'NetworkPolicies and Service created',
- })
- await this.writeStatusCondition(server, {
- type: 'DeploymentReady',
- status: deploymentReady ? 'True' : 'False',
- reason: deploymentReady
- ? 'ReplicasAvailable'
- : rolloutDetail
- ? 'RolloutIncomplete'
- : 'WaitingForReplicas',
- message: rolloutDetail
- ? `Rollout did not converge — ${rolloutDetail}`
- : deploymentReady
- ? 'Deployment has ready replicas'
- : 'Waiting for pods to become ready',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'NetworkReady',
+ status: 'True',
+ reason: 'NetworkPoliciesApplied',
+ message: 'NetworkPolicies and Service created',
+ },
+ isCurrent
+ )
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'DeploymentReady',
+ status: deploymentReady ? 'True' : 'False',
- reason: deploymentReady ? 'ReplicasAvailable' : 'WaitingForReplicas',
- message: deploymentReady
- ? 'Deployment has ready replicas'
- : 'Waiting for pods to become ready',
++ reason: deploymentReady
++ ? 'ReplicasAvailable'
++ : rolloutDetail
++ ? 'RolloutIncomplete'
++ : 'WaitingForReplicas',
++ message: rolloutDetail
++ ? `Rollout did not converge — ${rolloutDetail}`
++ : deploymentReady
++ ? 'Deployment has ready replicas'
++ : 'Waiting for pods to become ready',
+ },
+ isCurrent
+ )
console.log(
`[Reconciler] Updated status conditions on "${server.name}" (DeploymentReady=${deploymentReady})`
)
@@@ -1540,29 -1641,23 +1819,38 @@@
*/
async writeStatusCondition(
server: McpServerCRD,
- condition: Omit<McpServerCondition, 'lastTransitionTime'>
+ condition: Omit<McpServerCondition, 'lastTransitionTime'>,
+ isCurrent: () => boolean = () => true
): Promise<void> {
+ if (!isCurrent()) return
+ const now = new Date().toISOString()
+
+ // Update the missing-secret gauge for SecretResolved conditions.
+ // Do this before any no-op short-circuit so the gauge stays current
+ // across reconciles even when we skip the API patch.
+ if (condition.type === 'SecretResolved' && server.spec.envSecret) {
+ const labels = {
+ namespace: server.namespace,
+ name: server.name,
+ secret_name: server.spec.envSecret.name,
+ }
+ mcpserverMissingSecret.set(labels, condition.status === 'False' ? 1 : 0)
+ }
+
+ // Optimistic-concurrency loop (M2). The patch REPLACES the whole
+ // /status/conditions array with a value built from a snapshot read just
+ // before. Without a version guard, a concurrent writer — the readiness poll
+ // and a reconcile can both write status for the same server, and the poll
+ // timer is NOT serialized through `inFlight` — would be silently clobbered
+ // by whichever patch lands second, dropping the other's condition. A `test`
+ // op on metadata.resourceVersion makes the API server reject the patch (422)
+ // if anything changed since our read; we then re-read and retry, so no
+ // writer's condition is lost.
- const MAX_ATTEMPTS = 4
- for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
- const now = new Date().toISOString()
-
- // Fetch current status (and its resourceVersion) to preserve existing
- // conditions and to fence the write below.
+ for (let attempt = 1; attempt <= STATUS_CONDITION_WRITE_MAX_ATTEMPTS; attempt += 1) {
+ if (!isCurrent()) return
+ // Re-read on every optimistic-conflict retry. Merging against the
+ // latest resourceVersion preserves conditions written by peer
+ // controllers between our read and patch.
let existingConditions: McpServerCondition[] = []
let hasStatusObject = false
let resourceVersion: string | undefined
@@@ -1682,14 -1763,16 +1970,18 @@@
)
return
}
- // 409 (Conflict) or 422 (the resourceVersion `test` op failed) mean a
- // concurrent writer won the race. Re-read and retry rather than lose
- // our condition. Any other error, or the last attempt, falls through to
- // the best-effort log-and-swallow below.
- const code = getErrorCode(error)
- if ((code === 409 || code === 422) && attempt < MAX_ATTEMPTS) {
++ // 409 (Conflict) or 422 (a `test` op failed) mean a concurrent writer
++ // won the race. Re-read and retry rather than lose our condition. Any
++ // other error, or the last attempt, falls through to the best-effort
++ // log-and-swallow below.
+ if (
+ (errorCode === 409 || errorCode === 422) &&
+ attempt < STATUS_CONDITION_WRITE_MAX_ATTEMPTS
+ ) {
continue
}
console.warn(
- `[Reconciler] Failed to write status condition ${condition.type}=${condition.status} on "${server.name}":`,
- `[Reconciler] Failed to write status condition ${condition.type}=${condition.status} on "${server.name}" (attempt ${attempt}/${MAX_ATTEMPTS}):`,
++ `[Reconciler] Failed to write status condition ${condition.type}=${condition.status} on "${server.name}" (attempt ${attempt}/${STATUS_CONDITION_WRITE_MAX_ATTEMPTS}):`,
error
)
return
@@@ -1874,12 -1914,9 +2166,12 @@@
)
}
}
- await this.ensureService(server)
- await this.ensureDeployment(server, secretResult.revision)
+ if (!isCurrent()) return
+ await this.ensureService(server, isCurrent)
+ if (!isCurrent()) return
- await this.ensureDeployment(server, isCurrent)
++ await this.ensureDeployment(server, secretResult.revision, isCurrent)
} catch (err) {
+ if (!isCurrent()) return
this.setStatus(server.name, {
deployed: false,
ready: false,
@@@ -1909,49 -1945,71 +2201,80 @@@
}
// Check readiness after reconciliation
- const ready = await this.checkDeploymentReady(server.name, server.namespace)
+ const rollout = await this.readDeploymentRollout(server.name, server.namespace)
+ if (!isCurrent()) return
+ const ready = rollout.ready
this.setStatus(server.name, {
deployed: true,
ready,
message: ready ? 'Running' : 'Deployment created, waiting for pods to become ready',
})
- // G11: Update status conditions on McpServer CRD
- await this.updateStatusConditions(server, ready, isCurrent)
+ // G11: Update status conditions on McpServer CRD. If the readiness poll
+ // already exhausted its budget for THIS Deployment generation, keep the
+ // terminal RolloutIncomplete verdict sticky: the terminal status write
+ // itself fires a MODIFIED watch event and thus this very code path, and
+ // writing a bare "waiting" condition here would downgrade the verdict
+ // milliseconds after it was published — the operator (and the E2
+ // scenario) would never observe the rollout failure. A NEW rollout
+ // (different generation) drops the stickiness and reports fresh.
+ const pollState = this.readinessPolls.get(server.name)
+ const exhaustedDetail =
+ !ready &&
+ pollState !== undefined &&
+ pollState.exhausted &&
+ rollout.generation !== null &&
+ pollState.generation === rollout.generation
+ ? pollState.detail
+ : undefined
- await this.updateStatusConditions(server, ready, exhaustedDetail)
++ await this.updateStatusConditions(server, ready, exhaustedDetail, isCurrent)
// PR-B B1: record SecretResolved=True + Ready=True after a successful
// reconcile. This is additive to updateStatusConditions (NetworkReady /
// DeploymentReady); the merge logic in writeStatusCondition preserves
// the existing conditions by type.
if (server.spec.envSecret) {
- await this.writeStatusCondition(server, {
- type: 'SecretResolved',
- status: 'True',
- reason: 'SecretFound',
- message: 'Secret resolved and validated',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'SecretResolved',
+ status: 'True',
+ reason: 'SecretFound',
+ message: 'Secret resolved and validated',
+ },
+ isCurrent
+ )
}
- await this.writeStatusCondition(server, {
- type: 'Ready',
- status: ready ? 'True' : 'Unknown',
- reason: ready ? 'ReconcileSuccess' : 'WaitingForReplicas',
- message: ready
- ? 'Deployment created'
- : 'Deployment created, waiting for pods to become ready',
- })
+ await this.writeStatusCondition(
+ server,
+ {
+ type: 'Ready',
+ status: ready ? 'True' : 'Unknown',
+ reason: ready ? 'ReconcileSuccess' : 'WaitingForReplicas',
+ message: ready
+ ? 'Deployment created'
+ : 'Deployment created, waiting for pods to become ready',
+ },
+ isCurrent
+ )
- // If not ready yet, poll until it becomes ready
+ // If not ready yet, poll until it becomes ready. With generation-aware
+ // readiness this is the normal path right after any Deployment write —
+ // including a credential rotation — so the poll owns the terminal verdict
+ // on the CRD.
+ //
+ // Post-terminal re-observation (intentional, self-terminating): after a
+ // terminal RolloutIncomplete, the status write that recorded it fires a
+ // MODIFIED watch → performReconcile → here again with !ready, arming ONE more
+ // poll window. For a genuinely stuck deployment the terminal condition re-write
+ // is byte-identical (the detail is a pure function of the replica tuple, no
+ // timestamps), so writeStatusCondition's `unchanged` short-circuit skips the
+ // patch → no watch event → no further re-arm. The only thing that re-arms again
+ // is a deployment whose replica tuple perpetually OSCILLATES, and that is
+ // bounded to one reconcile per poll window (~120s) — not a tight loop, and (per
+ // pollReadiness's atomic check-then-set) not a timer leak.
- if (!ready) {
- this.pollReadiness(server)
+ if (!ready && isCurrent()) {
- this.pollReadiness(server, 5000, 12, isCurrent)
++ this.pollReadiness(server, 5000, 24, isCurrent)
}
}
diff --cc host-context-controller/src/utils.ts
index 72967b99e,22d63b8b2..a6992eeb8
--- a/host-context-controller/src/utils.ts
+++ b/host-context-controller/src/utils.ts
@@@ -199,7 -188,20 +199,22 @@@ export async function applyNetworkPolic
body: policy,
read: () => api.readNamespacedNetworkPolicy({ name, namespace }),
replace: body => api.replaceNamespacedNetworkPolicy({ name, namespace, body }),
+ mutationAllowed,
+ validateExisting,
})
}
+
+ /**
+ * Stable JSON for hashing: object keys are emitted in sorted order, so the
+ * digest of a Secret's data depends on its content and not on the order the
+ * API server happened to return the keys in.
+ *
+ * Shared by the Host channel-reader credentials revision and the McpServer
+ * connector credentials revision (issue #223): both hash Secret content into a
+ * pod-template annotation, and a divergence between the two canonical forms
+ * would be invisible until a rollout silently stopped happening.
+ */
+ export function canonicalStringify(obj: Record<string, unknown>): string {
+ const sorted = Object.keys(obj).sort()
+ return JSON.stringify(sorted.map(k => [k, obj[k]]))
+ }