Skip to content

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

TypeScript

fix(hcc): hard-reject stateless lifecycle for channel-bound hosts

Alfredo Lopez8aa6fd98bf1f
diff --git a/control-api/src/routes/admin/__tests__/hostsOverview.lifecyclePassthrough.test.ts b/control-api/src/routes/admin/__tests__/hostsOverview.lifecyclePassthrough.test.ts
new file mode 100644
index 000000000..4331a6579
--- /dev/null
+++ b/control-api/src/routes/admin/__tests__/hostsOverview.lifecyclePassthrough.test.ts
@@ -0,0 +1,130 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+
+// The control-ui host-detail view consumes the Host's lifecycle projection
+// (status.lifecycle.effectiveMode + reason) and the StatelessEnableRejected
+// condition to render the stateless×CommunicationChannel hard-rejection banner
+// (issue #791, plan Addendum 6 item 4). This test proves the admin read surface
+// serves that status subtree UNFILTERED — it is a raw CRD passthrough, so no
+// control-api change is required for the operator-visibility feature.
+//
+// vi.mock specifiers resolve RELATIVE TO THIS TEST FILE (routes/admin/__tests__/).
+// The router imports the same modules via its own relative paths; Vitest matches
+// mocks by canonical path, so both resolve to the same module instance.
+vi.mock('../../../services/directory/index.js', () => ({
+ listUsers: vi.fn().mockResolvedValue([]),
+ listAllTeams: vi.fn().mockResolvedValue([]),
+ listUsersByAgent: vi.fn().mockResolvedValue([]),
+ listTeamsByAgent: vi.fn().mockResolvedValue([]),
+}))
+
+vi.mock('../hostSecrets.js', () => ({
+ listHostSecrets: vi.fn().mockResolvedValue([]),
+}))
+
+// Import AFTER vi.mock so the mocked dependencies wire up.
+const { createAdminHostsOverviewRouter } = await import('../hostsOverview.js')
+
+describe('admin hosts read surface — lifecycle status passthrough (issue #791, Addendum 6)', () => {
+ function buildApp(gateway: unknown) {
+ const app = express()
+ app.use(express.json({ limit: '1mb' }))
+ app.use('/api/v1', createAdminHostsOverviewRouter(gateway as never))
+ return app
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('GET /admin/hosts/:name/detail returns status.lifecycle (effectiveMode + reason) and the StatelessEnableRejected condition unfiltered', async () => {
+ const rejectionMessage =
+ '2 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle'
+ const host = {
+ metadata: { name: 'foo', namespace: 'mcp-host', generation: 9 },
+ spec: { lifecycle: { stateless: true } },
+ status: {
+ lifecycle: {
+ state: 'active',
+ effectiveMode: 'stateful',
+ observedGeneration: 9,
+ wakeHandledGeneration: 0,
+ reason: rejectionMessage,
+ },
+ conditions: [
+ {
+ type: 'StatelessEnableRejected',
+ status: 'True',
+ reason: 'ActiveCommunicationChannels',
+ message: rejectionMessage,
+ },
+ ],
+ },
+ }
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue(host),
+ listResource: vi.fn().mockResolvedValue([]),
+ }
+ const app = buildApp(gateway)
+
+ const res = await request(app).get('/api/v1/admin/hosts/foo/detail')
+
+ expect(res.status).toBe(200)
+ // Raw CRD passthrough: the Host object is returned exactly as read from the
+ // cluster — no DTO projection strips the lifecycle status or conditions.
+ expect(res.body.host).toEqual(host)
+ // The specific fields the operator banner reads survive the read surface.
+ expect(res.body.host.status.lifecycle.effectiveMode).toBe('stateful')
+ expect(res.body.host.status.lifecycle.reason).toBe(rejectionMessage)
+ expect(res.body.host.status.conditions).toEqual([
+ {
+ type: 'StatelessEnableRejected',
+ status: 'True',
+ reason: 'ActiveCommunicationChannels',
+ message: rejectionMessage,
+ },
+ ])
+ expect(gateway.getResource).toHaveBeenCalledWith('hosts', 'foo', expect.any(String))
+ })
+
+ it('GET /admin/hosts/:name/detail returns a StatelessSuspensionBlocked condition unfiltered', async () => {
+ const host = {
+ metadata: { name: 'foo', generation: 7 },
+ spec: { lifecycle: { stateless: true } },
+ status: {
+ lifecycle: {
+ state: 'active',
+ effectiveMode: 'stateless',
+ observedGeneration: 7,
+ wakeHandledGeneration: 0,
+ reason: 'Waiting for the CommunicationChannel cache to synchronize.',
+ },
+ conditions: [
+ {
+ type: 'StatelessSuspensionBlocked',
+ status: 'True',
+ message: 'Communication channel status is reconciling.',
+ },
+ ],
+ },
+ }
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue(host),
+ listResource: vi.fn().mockResolvedValue([]),
+ }
+ const app = buildApp(gateway)
+
+ const res = await request(app).get('/api/v1/admin/hosts/foo/detail')
+
+ expect(res.status).toBe(200)
+ expect(res.body.host.status.lifecycle.effectiveMode).toBe('stateless')
+ expect(res.body.host.status.conditions).toEqual([
+ {
+ type: 'StatelessSuspensionBlocked',
+ status: 'True',
+ message: 'Communication channel status is reconciling.',
+ },
+ ])
+ })
+})
diff --git a/control-ui/components/__tests__/HostDetailsPage.lifecycle.test.tsx b/control-ui/components/__tests__/HostDetailsPage.lifecycle.test.tsx
index 57d211887..22fb2e9ca 100644
--- a/control-ui/components/__tests__/HostDetailsPage.lifecycle.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.lifecycle.test.tsx
@@ -90,6 +90,42 @@ const rejectedHost: TestHost = {
},
}
+// Addendum 6 (issue #791): a CONFIRMED CommunicationChannel association hard-rejects
+// the requested stateless lifecycle. HCC selects the stateful template at replicas 1
+// and writes a StatelessEnableRejected condition whose message names the channel
+// count AND the disassociation recovery action. control-ui renders that condition
+// message verbatim in the warning banner.
+const channelHardRejectedHost: TestHost = {
+ metadata: { name: 'foo' },
+ spec: { ...baseSpec, lifecycle: { stateless: true } },
+ status: {
+ lifecycle: {
+ state: 'active',
+ reason:
+ '2 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
+ },
+ conditions: [
+ {
+ type: 'StatelessEnableRejected',
+ status: 'True',
+ reason: 'ActiveCommunicationChannels',
+ message:
+ '2 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
+ },
+ ],
+ },
+}
+
+// The same Host after the operator disassociates the channels: HCC clears the
+// rejection and activates the requested stateless mode on the next reconcile.
+const disassociatedStatelessHost: TestHost = {
+ metadata: { name: 'foo' },
+ spec: { ...baseSpec, lifecycle: { stateless: true } },
+ status: {
+ lifecycle: { state: 'active' },
+ },
+}
+
function setupApiMocks(host: TestHost) {
;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
host,
@@ -254,6 +290,60 @@ describe('HostDetailsPage stateless lifecycle', () => {
expect(screen.getByText(/Host has active communication channels\./)).toBeInTheDocument()
})
+ it('renders the CommunicationChannel hard-rejection banner with the disassociation recovery action verbatim (Addendum 6)', async () => {
+ setupApiMocks(channelHardRejectedHost)
+ render(<HostDetailsPage />)
+
+ // Prominent warning banner on the (default) details view.
+ const bannerLabel = await screen.findByText('Stateless mode rejected:')
+ const banner = bannerLabel.closest('.cu-banner')
+ expect(banner).not.toBeNull()
+ // The banner surfaces the status condition message VERBATIM: the channel
+ // count (the reason) AND the operator recovery action (disassociate).
+ expect(banner).toHaveTextContent(
+ '2 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle'
+ )
+ })
+
+ it('clears the hard-rejection banner after the operator disassociates the channels and the view reloads', async () => {
+ // First load: hard-rejected (channels still associated). After the operator
+ // removes the channels, the overview save reloads the Host, which now reports
+ // stateless-active with no StatelessEnableRejected condition.
+ ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>)
+ .mockResolvedValueOnce({
+ host: channelHardRejectedHost,
+ contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
+ secrets: [{ name: 'openai-secret' }],
+ users: [],
+ teams: [],
+ agentUsers: [],
+ agentTeams: [],
+ })
+ .mockResolvedValue({
+ host: disassociatedStatelessHost,
+ contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
+ secrets: [{ name: 'openai-secret' }],
+ users: [],
+ teams: [],
+ agentUsers: [],
+ agentTeams: [],
+ })
+ ;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(channelHardRejectedHost)
+ ;(api.apiSend as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({})
+
+ render(<HostDetailsPage />)
+
+ expect(await screen.findByText('Stateless mode rejected:')).toBeInTheDocument()
+
+ await openOverviewEdit()
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+
+ await waitFor(() =>
+ expect(screen.queryByText('Stateless mode rejected:')).not.toBeInTheDocument()
+ )
+ expect(screen.queryByText(/disassociate them to enable/)).not.toBeInTheDocument()
+ })
+
it('does not render the rejection banner when no condition is present', async () => {
setupApiMocks(statelessHost)
render(<HostDetailsPage />)
diff --git a/control-ui/e2e/host-stateless-channel-rejection.spec.ts b/control-ui/e2e/host-stateless-channel-rejection.spec.ts
new file mode 100644
index 000000000..8ddb686a2
--- /dev/null
+++ b/control-ui/e2e/host-stateless-channel-rejection.spec.ts
@@ -0,0 +1,198 @@
+/**
+ * E2E -- Operator visibility: stateless × CommunicationChannel hard-rejection banner
+ *
+ * Validates plan Addendum 6 item 4 (issue #791) on the LIVE control-ui host detail
+ * view: a stateless Host that has a CONFIRMED CommunicationChannel association is
+ * hard-rejected by HCC (effectiveMode=stateful + StatelessEnableRejected condition),
+ * and the operator sees a prominent warning banner carrying the status reason
+ * VERBATIM plus the disassociation recovery action. Removing the channel clears it.
+ *
+ * Why this spec arranges via a direct CRD write (kubectl), not the control-api:
+ * The normal control-api/UI path CANNOT reach this state by design — control-api
+ * rejects associating a CommunicationChannel with a stateless Host, and rejects
+ * flipping a channel-bound Host to stateless, both with 409
+ * `stateless_host_communication_channel_conflict`
+ * (control-api/src/routes/admin/resources.ts). The hard-rejection is HCC's
+ * defensive backstop for direct/racing CRD writes (AP-7,
+ * docs/architecture/stateless-invariants.md). So this spec reproduces exactly that
+ * race: it `kubectl apply`s a CommunicationChannel referencing a dedicated stateless
+ * Host, then asserts the operator-facing banner.
+ *
+ * Opt-in: this spec is skipped unless E2E_STATELESS_CHANNEL_REJECTION=1, because it
+ * requires a dedicated stateless Host, a kubectl context, and the Addendum-6 executor
+ * fix deployed (until it lands, a channel keeps effectiveMode=stateless and the
+ * effectiveMode=stateful assertion below fails).
+ *
+ * Prerequisites (when enabled):
+ * 1. Port-forwards running (control-ui :3000, control-api :8090).
+ * 2. Admin credentials: ADMIN_USER, ADMIN_PASS.
+ * 3. E2E_STATELESS_HOST — a dedicated Host with spec.lifecycle.stateless=true that is
+ * NOT chatllm-stateless (avoids colliding with the transient Test 2d window of
+ * scripts/e2e/e2e-stateless-suspend-wake.sh on a shared profile).
+ * 4. E2E_KUBECONTEXT (or CONTEXT) — an allowed kubectl context (clerum-test /
+ * clerum-codex-* / gke_eventfire-*_clerum-dev). Passed to every kubectl call.
+ */
+import { execFileSync } from 'node:child_process'
+import { type Page, expect, test } from '@playwright/test'
+
+const BASE_UI = process.env.CONTROL_UI_URL || 'http://localhost:3000'
+const ADMIN_USER = process.env.ADMIN_USER || 'admin'
+const ADMIN_PASS = process.env.ADMIN_PASS || 'admin123!'
+
+const ENABLED = process.env.E2E_STATELESS_CHANNEL_REJECTION === '1'
+const HOST = process.env.E2E_STATELESS_HOST || ''
+const KUBECONTEXT = process.env.E2E_KUBECONTEXT || process.env.CONTEXT || ''
+const HOSTS_NS = process.env.E2E_HOSTS_NAMESPACE || 'mcp-host'
+const CHANNELS_NS = process.env.E2E_CHANNELS_NAMESPACE || 'channels'
+const REJECTED_CONDITION = 'StatelessEnableRejected'
+
+// Unique per run so parallel/leftover runs never collide, and cleanup is targeted.
+const CC_NAME = `e2e-vis-stateless-reject-${Date.now()}`
+
+function kubectl(args: string[], input?: string): string {
+ if (!KUBECONTEXT) {
+ throw new Error(
+ 'E2E_KUBECONTEXT (or CONTEXT) must be set to an allowed context; kubectl context is never inferred.'
+ )
+ }
+ return execFileSync('kubectl', ['--context', KUBECONTEXT, ...args], {
+ encoding: 'utf8',
+ ...(input !== undefined ? { input } : {}),
+ })
+}
+
+function getHostJson(): {
+ effectiveMode?: string
+ rejected?: boolean
+ rejectionMessage?: string
+} {
+ const raw = kubectl(['get', 'host', HOST, '-n', HOSTS_NS, '-o', 'json'])
+ const obj = JSON.parse(raw) as {
+ status?: {
+ lifecycle?: { effectiveMode?: string }
+ conditions?: Array<{ type?: string; status?: string; message?: string }>
+ }
+ }
+ const condition = obj.status?.conditions?.find(c => c.type === REJECTED_CONDITION)
+ return {
+ effectiveMode: obj.status?.lifecycle?.effectiveMode,
+ rejected: condition?.status === 'True',
+ rejectionMessage: condition?.message,
+ }
+}
+
+function applyChannel(): void {
+ const manifest = `apiVersion: clerum.io/v1alpha1
+kind: CommunicationChannel
+metadata:
+ name: ${CC_NAME}
+ namespace: ${CHANNELS_NS}
+spec:
+ hostRef: ${HOST}
+ email:
+ - channelId: "INBOX"
+ emails:
+`
+ kubectl(['apply', '-n', CHANNELS_NS, '-f', '-'], manifest)
+}
+
+function deleteChannel(): void {
+ try {
+ kubectl(['delete', 'communicationchannel', CC_NAME, '-n', CHANNELS_NS, '--ignore-not-found'])
+ } catch (err) {
+ // Cleanup is best-effort; surface it but never mask a prior assertion failure.
+ console.warn(`[e2e] failed to delete CommunicationChannel ${CC_NAME}: ${String(err)}`)
+ }
+}
+
+async function login(page: Page) {
+ await page.goto(BASE_UI)
+ await page.waitForSelector('text=Sign in', { timeout: 15_000 })
+ const inputs = page.locator('input')
+ await inputs.nth(0).fill(ADMIN_USER)
+ await inputs.nth(1).fill(ADMIN_PASS)
+ await page.locator('button:has-text("Sign in")').last().click()
+ await page.waitForSelector('text=Marketplace', { timeout: 20_000 })
+}
+
+test.describe('operator sees the stateless × CommunicationChannel hard-rejection banner', () => {
+ test.skip(
+ !ENABLED,
+ 'opt-in: set E2E_STATELESS_CHANNEL_REJECTION=1 (with E2E_STATELESS_HOST, E2E_KUBECONTEXT) and deploy the Addendum-6 executor fix'
+ )
+
+ test.beforeAll(() => {
+ // Fail loud on missing prerequisites rather than skipping silently.
+ if (!HOST) throw new Error('E2E_STATELESS_HOST must name a dedicated stateless Host.')
+ if (!KUBECONTEXT) throw new Error('E2E_KUBECONTEXT (or CONTEXT) must be set to an allowed context.')
+ const host = getHostJson()
+ // Guard: the target must actually be a stateless Host, or the whole scenario is invalid.
+ const statelessRaw = kubectl([
+ 'get',
+ 'host',
+ HOST,
+ '-n',
+ HOSTS_NS,
+ '-o',
+ 'jsonpath={.spec.lifecycle.stateless}',
+ ]).trim()
+ if (statelessRaw !== 'true') {
+ throw new Error(
+ `E2E_STATELESS_HOST "${HOST}" must have spec.lifecycle.stateless=true (got "${statelessRaw}"). Host status: ${JSON.stringify(host)}`
+ )
+ }
+ // Ensure a clean slate from any aborted prior run.
+ deleteChannel()
+ })
+
+ test.afterAll(() => {
+ deleteChannel()
+ })
+
+ test('renders the hard-rejection warning verbatim and clears it after disassociation', async ({
+ page,
+ }) => {
+ // Arrange: the AP-7 racing CRD write — associate a channel with the stateless Host.
+ applyChannel()
+
+ // HCC hard-rejects on the next reconcile: effectiveMode=stateful + rejected condition.
+ // Bounded, fail-loud poll — on timeout the last observed status is reported.
+ await expect
+ .poll(() => JSON.stringify(getHostJson()), {
+ timeout: 120_000,
+ intervals: [2_000],
+ message:
+ 'HCC did not hard-reject the stateless Host after the CommunicationChannel was applied ' +
+ '(requires the Addendum-6 executor fix deployed).',
+ })
+ .toMatch(/"effectiveMode":"stateful".*"rejected":true|"rejected":true.*"effectiveMode":"stateful"/)
+
+ const rejectionMessage = getHostJson().rejectionMessage
+ expect(rejectionMessage, 'StatelessEnableRejected condition must carry a message').toBeTruthy()
+ // Contract (Addendum 6): the message names the channel count AND the recovery action.
+ expect(rejectionMessage).toMatch(/disassociate/i)
+
+ // Assert the operator-facing banner shows the status message VERBATIM.
+ await login(page)
+ await page.goto(`${BASE_UI}/hosts/${encodeURIComponent(HOST)}`)
+ await expect(page.getByText('Stateless mode rejected:')).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByText(rejectionMessage as string, { exact: false })).toBeVisible()
+
+ // Disassociation recovery: remove the channel; HCC clears the rejection.
+ // Strict delete (not the best-effort cleanup helper) so a real failure here
+ // fails the test loudly instead of being swallowed mid-scenario.
+ kubectl(['delete', 'communicationchannel', CC_NAME, '-n', CHANNELS_NS, '--ignore-not-found'])
+ await expect
+ .poll(() => JSON.stringify(getHostJson()), {
+ timeout: 120_000,
+ intervals: [2_000],
+ message: 'HCC did not clear the hard-rejection after the CommunicationChannel was removed.',
+ })
+ .toMatch(/"rejected":false/)
+
+ // The banner must disappear once the Host reports stateless-active again.
+ await page.reload()
+ await expect(page.getByText('Stateless mode rejected:')).toHaveCount(0, { timeout: 20_000 })
+ })
+})
diff --git a/host-context-controller/src/statelessLifecycleExecutor.ts b/host-context-controller/src/statelessLifecycleExecutor.ts
index 807347ed9..81542832a 100644
--- a/host-context-controller/src/statelessLifecycleExecutor.ts
+++ b/host-context-controller/src/statelessLifecycleExecutor.ts
@@ -211,8 +211,15 @@ export class StatelessLifecycleExecutor {
}
const ccCount = this.countCommunicationChannels(hostName)
if (ccCount > 0) {
+ // Addendum 6 (operator visibility): the rejection message names both the
+ // associated channel count AND the recovery action, because control-ui
+ // renders `condition.message` verbatim in the stateless-rejection banner.
+ // The rejection is state-derived, so disassociating the channels
+ // re-enables the requested stateless lifecycle on the next reconcile.
reasons.push(ACTIVE_COMMUNICATION_CHANNELS_REASON)
- messages.push(`${ccCount} CommunicationChannel(s) reference this Host`)
+ messages.push(
+ `${ccCount} CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle`
+ )
}
return { reasons, messages }
}
diff --git a/host-context-controller/test/hostReconciler.heartbeat.test.ts b/host-context-controller/test/hostReconciler.heartbeat.test.ts
index 3c5ce8ece..eb28006b4 100644
--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts
+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts
@@ -439,7 +439,7 @@ describe('HostReconciler.publishSuspendBlockedReason', () => {
lifecycle: {
state: 'active',
wakeHandledGeneration: 0,
- reason: '1 CommunicationChannel(s) reference this Host',
+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
},
},
})
@@ -452,7 +452,7 @@ describe('HostReconciler.publishSuspendBlockedReason', () => {
freshHostRead({
state: 'active',
wakeHandledGeneration: 0,
- reason: '1 CommunicationChannel(s) reference this Host',
+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
)
diff --git a/host-context-controller/test/hostReconciler.lifecycle.test.ts b/host-context-controller/test/hostReconciler.lifecycle.test.ts
index b665f6268..8a937827b 100644
--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts
+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts
@@ -793,7 +793,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
expect(writes[1].lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 5,
- reason: '1 CommunicationChannel(s) reference this Host',
+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
expect(rejectedCondition(writes[1])).toMatchObject({
status: 'True',
@@ -872,7 +872,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
expect(writes[1].lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 6,
- reason: '1 CommunicationChannel(s) reference this Host',
+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
})
@@ -988,7 +988,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
)
const writes = lifecycleStatusWrites(customApi)
expect(writes).toHaveLength(2)
- expect(writes[1].lifecycle?.reason).toBe('1 CommunicationChannel(s) reference this Host')
+ expect(writes[1].lifecycle?.reason).toBe('1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle')
})
it('does not repeat bootstrap provisioning when channel ingress already existed in spec', async () => {
@@ -1306,6 +1306,73 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
expect(writes[0].lifecycle).toEqual({ state: 'suspended', wakeHandledGeneration: 4 })
expect(rejectedCondition(writes[0]).status).toBe('False')
})
+
+ it('hard-rejects on the FIRST stateless reconcile when a channel already exists (reverse arrival order)', async () => {
+ // Addendum 6 (order independence): the operator scenario is a STATEFUL Host
+ // with an active channel whose spec is then flipped to stateless:true. The
+ // decision is state-derived, not arrival-order-dependent — the confirmed
+ // channel must hard-reject from the very first stateless-requesting
+ // reconcile; stateless must never be transiently enabled.
+ const { reconciler, appsApi, customApi } = createReconciler({
+ countCommunicationChannels: () => 1,
+ })
+ // Prior stateful projection: the Host ran active with the channel and is
+ // now flipped to stateless:true. The AP-1 fresh read agrees with the cached
+ // snapshot — this scenario has no concurrent heartbeat transition, and the
+ // shared mock's default fresh object is a SUSPENDED host, which would
+ // otherwise inject an unrelated echo.
+ const host = makeStatelessHost({
+ status: { lifecycle: { state: 'active', wakeHandledGeneration: 0 } },
+ })
+ customApi.getNamespacedCustomObject.mockResolvedValue({
+ metadata: { name: host.name, namespace: host.namespace },
+ spec: host.spec,
+ status: host.status,
+ })
+
+ await reconciler.reconcile(host)
+
+ const writes = lifecycleStatusWrites(customApi)
+ // Never transiently enabled: EVERY status write carries the rejection and
+ // stays active. (This tree has no status.lifecycle.effectiveMode field, so
+ // the "never transiently stateless" invariant is asserted through the
+ // durable rejection condition + state, which is what it projects here.)
+ expect(writes.length).toBeGreaterThan(0)
+ for (const write of writes) {
+ expect(write.lifecycle?.state).toBe('active')
+ expect(rejectedCondition(write)).toMatchObject({
+ status: 'True',
+ reason: 'ActiveCommunicationChannels',
+ })
+ }
+ // The status reason is present immediately, naming the count + recovery.
+ expect(writes.at(-1)!.lifecycle?.reason).toBe(
+ '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle'
+ )
+ // Stateful active runtime (no lifecycle env).
+ expect(hostDeploymentBody(appsApi, host.name).spec?.replicas).toBe(1)
+ expect(containerEnv(hostDeploymentBody(appsApi, host.name)).map(e => e.name)).not.toContain(
+ 'CLERUM_STATELESS_LIFECYCLE'
+ )
+ })
+
+ it('surfaces the disassociation recovery action in the StatelessEnableRejected condition message', async () => {
+ // Operator-visibility contract (control-ui renders condition.message
+ // verbatim): the recovery action MUST live in the condition message, not
+ // only in lifecycle.reason.
+ const { reconciler, customApi } = createReconciler({
+ countCommunicationChannels: () => 3,
+ })
+
+ await reconciler.reconcile(makeStatelessHost())
+
+ const condition = rejectedCondition(lifecycleStatusWrites(customApi).at(-1)!)
+ expect(condition.status).toBe('True')
+ expect(condition.reason).toBe('ActiveCommunicationChannels')
+ expect(condition.message).toBe(
+ '3 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle'
+ )
+ })
})
describe('HostReconciler stateless lifecycle — kill-switches', () => {
@@ -1321,7 +1388,7 @@ describe('HostReconciler stateless lifecycle — kill-switches', () => {
expect(writes[0].lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 3,
- reason: '1 CommunicationChannel(s) reference this Host',
+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
expect(rejectedCondition(writes[0]).status).toBe('True')
})
@@ -1535,7 +1602,7 @@ describe('HostReconciler stateless lifecycle — AP-1 fresh-read status writer',
expect(writes.at(-1)?.lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 3,
- reason: '1 CommunicationChannel(s) reference this Host',
+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
})
@@ -1563,7 +1630,7 @@ describe('HostReconciler stateless lifecycle — AP-1 fresh-read status writer',
expect(writes.at(-1)?.lifecycle).toEqual({
state: 'active',
wakeHandledGeneration: 2,
- reason: '1 CommunicationChannel(s) reference this Host',
+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
})
@@ -1589,7 +1656,7 @@ describe('HostReconciler stateless lifecycle — AP-1 fresh-read status writer',
expect(writes.at(-1)?.lifecycle).toEqual({
state: 'suspended',
wakeHandledGeneration: 5,
- reason: '1 CommunicationChannel(s) reference this Host',
+ reason: '1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',
})
})
diff --git a/scripts/e2e/e2e-stateless-suspend-wake.sh b/scripts/e2e/e2e-stateless-suspend-wake.sh
index bda013524..6f6c4fb9a 100755
--- a/scripts/e2e/e2e-stateless-suspend-wake.sh
+++ b/scripts/e2e/e2e-stateless-suspend-wake.sh
@@ -404,6 +404,17 @@ deployment_has_stateless_template() {
' >/dev/null
}
+# A STATEFUL effective template is discriminated ONLY by the effective-mode
+# markers: no interactive priority class and no CLERUM_STATELESS_LIFECYCLE env.
+# The requested stateless STORAGE layout (workspace-layout-init init container +
+# the /var/lib/clerum/state and /workspace subPath mounts) is durable-
+# compatibility state that a HARD REJECTION deliberately RETAINS — exactly like
+# a spec.desktop/SFS rejection (buildDeployment gates the storage layout on the
+# spec REQUEST `usesStatelessStorageLayout`, never on effective mode, so a
+# rejection never remounts the PVC root and creates a second state.db). So the
+# storage layout must NOT be part of the stateful discriminator: this helper
+# must pass for a genuinely-stateful host (no layout) AND a channel/desktop hard-
+# rejected stateless-requesting host (layout retained). See Addendum 6.
deployment_has_stateful_template() {
local deployment
deployment="$(kctl get deployment "$HOST_REF" -n "$MCP_HOST_NS" -o json 2>/dev/null)" || return 2
@@ -411,9 +422,7 @@ deployment_has_stateful_template() {
.spec.template.spec as $pod
| [
($pod.priorityClassName != "clerum-interactive-host"),
- ([ $pod.initContainers[]? | select(.name == "workspace-layout-init") ] | length == 0),
- ([ $pod.containers[] | select(.name == "mcp-host") | .env[]? | select(.name == "CLERUM_STATELESS_LIFECYCLE") ] | length == 0),
- ([ $pod.containers[] | select(.name == "mcp-host") | .volumeMounts[]? | select(.name == "workspace" and (.subPath == "workspace" or .subPath == "state")) ] | length == 0)
+ ([ $pod.containers[] | select(.name == "mcp-host") | .env[]? | select(.name == "CLERUM_STATELESS_LIFECYCLE") ] | length == 0)
] | all
' >/dev/null
}
@@ -800,6 +809,87 @@ fi
post_wake || { fail "wake POST failed resurrecting for 2d"; print_results; exit 1; }
wait_for_ready_pod "$POD_READY_TIMEOUT" >/dev/null || { fail "no pod after wake for 2d"; print_results; exit 1; }
+# (d-pre) REVERSE arrival order: a genuinely stateful Host that ALREADY has a
+# CommunicationChannel, then flipped to spec.lifecycle.stateless:true, must
+# hard-reject from the FIRST stateless-requesting reconcile -- the requested
+# stateless lifecycle must NEVER be transiently enabled. Direct CRD writes are
+# used deliberately: control-api blocks this flip at the admin API with a 409
+# (stateless_host_communication_channel_conflict), so the state-derived HCC
+# backstop is exactly the racing/direct-write path under test. Uses the shared
+# $HOST_REF sequentially (the suite's established pattern; test 11 also flips
+# spec.lifecycle.stateless on it) and restores it via the cleanup trap.
+header "Test 2d-pre -- reverse arrival: channel-bound host flipped to stateless hard-rejects"
+# 1. Make the Host genuinely stateful (direct CRD).
+kctl patch host "$HOST_REF" -n "$MCP_HOST_NS" --type=merge \
+ -p '{"spec":{"lifecycle":{"stateless":false}}}' >/dev/null 2>&1 \
+ || { fail "2d-pre: failed to flip spec.lifecycle.stateless:false"; print_results; exit 1; }
+STATELESS_DISABLED=1
+wait_for_deployment_template stateful 120 "2d-pre: baseline genuinely stateful" || { print_results; exit 1; }
+# 2. Associate a CommunicationChannel with the stateful Host (direct CRD).
+CREATED_CHANNEL="e2e-stateless-prekillswitch-${RUN_ID}"
+printf '%s\n' \
+"apiVersion: clerum.io/v1alpha1" \
+"kind: CommunicationChannel" \
+"metadata:" \
+" name: ${CREATED_CHANNEL}" \
+" namespace: ${CHANNELS_NS:-channels}" \
+"spec:" \
+" hostRef: ${HOST_REF}" \
+" telegram:" \
+" - channelId: \"e2e-prekillswitch-${RUN_ID}\"" \
+" chatType: \"private\"" \
+" userIds: [\"000000000\"]" \
+ | kctl apply -f - >/dev/null 2>&1 || { fail "2d-pre: failed to apply CommunicationChannel"; print_results; exit 1; }
+# Deterministic barrier: wait until HCC has OBSERVED the channel (it provisions
+# channel-reader-<host> from the same watcher cache that countCommunicationChannels
+# reads), so the channel is in cache BEFORE the stateless flip -- the first
+# stateless reconcile cannot momentarily see zero channels and enable stateless.
+cr_elapsed=0; cr_ok=0
+while [ "$cr_elapsed" -lt 120 ]; do
+ if kctl get deployment "channel-reader-${HOST_REF}" -n "${CHANNELS_NS:-channels}" >/dev/null 2>&1; then cr_ok=1; break; fi
+ sleep "$POLL_INTERVAL"; cr_elapsed=$((cr_elapsed + POLL_INTERVAL))
+done
+[ "$cr_ok" = "1" ] || { fail "2d-pre: HCC did not provision channel-reader-${HOST_REF} within 120s (cannot prove the channel is observed before the stateless flip)"; print_results; exit 1; }
+# 3. Flip spec.lifecycle.stateless:true on the channel-bound Host (direct CRD).
+kctl patch host "$HOST_REF" -n "$MCP_HOST_NS" --type=merge \
+ -p '{"spec":{"lifecycle":{"stateless":true}}}' >/dev/null 2>&1 \
+ || { fail "2d-pre: failed to flip spec.lifecycle.stateless:true"; print_results; exit 1; }
+STATELESS_DISABLED=0
+# 4. Assert hard rejection to stateful active with the channel-count reason. The
+# effective mode is stateful throughout (genuinely-stateful -> rejected-
+# stateful, never a transient stateless): replicas 1, StatelessEnableRejected=True.
+dp_elapsed=0; dp_ok=0
+while [ "$dp_elapsed" -lt 120 ]; do
+ cond="$(kctl get host "$HOST_REF" -n "$MCP_HOST_NS" -o jsonpath='{.status.conditions[?(@.type=="StatelessEnableRejected")].status}' 2>/dev/null || true)"
+ emode="$(kctl get host "$HOST_REF" -n "$MCP_HOST_NS" -o jsonpath='{.status.lifecycle.effectiveMode}' 2>/dev/null || true)"
+ reps="$(deployment_replicas)"
+ if [ "$cond" = "True" ] && [ "$emode" = "stateful" ] && [ "${reps:-0}" = "1" ] && deployment_has_stateful_template; then dp_ok=1; break; fi
+ sleep "$POLL_INTERVAL"; dp_elapsed=$((dp_elapsed + POLL_INTERVAL))
+done
+if [ "$dp_ok" != "1" ]; then
+ fail "2d-pre: expected hard rejection to stateful after stateless flip on channel-bound host (cond=${cond:-<none>} effectiveMode=${emode:-<none>} state=$(lifecycle_state) replicas=$(deployment_replicas) reason=$(lifecycle_reason))"; print_results; exit 1
+fi
+# The durable rejection reason must name the channel count + recovery action
+# (control-ui renders the StatelessEnableRejected message verbatim).
+pre_reason="$(lifecycle_reason)"
+case "$pre_reason" in
+ *"CommunicationChannel(s) reference this Host"*disassociate*)
+ ok "2d-pre: reverse-order flip hard-rejects to stateful with the channel-count reason (${pre_reason})" ;;
+ *)
+ fail "2d-pre: rejection reason missing channel-count/disassociate recovery text (got '${pre_reason}')"; print_results; exit 1 ;;
+esac
+# 5. Disassociate the channel (direct CRD) -> stateless activates and suspends.
+kctl delete communicationchannel "$CREATED_CHANNEL" -n "${CHANNELS_NS:-channels}" --ignore-not-found >/dev/null 2>&1
+CREATED_CHANNEL=""
+if wait_for_deployment_template stateless "$POD_READY_TIMEOUT" "2d-pre: channel removed" \
+ && wait_for_ready_pod "$POD_READY_TIMEOUT" >/dev/null && force_idle_and_suspend; then
+ ok "2d-pre: stateless activates and suspends after the channel is disassociated (state-derived recovery)"
+else
+ fail "2d-pre: stateless did not activate after channel disassociation (reverse-order recovery)"; print_results; exit 1
+fi
+post_wake || { fail "wake POST failed resurrecting for 2d"; print_results; exit 1; }
+wait_for_ready_pod "$POD_READY_TIMEOUT" >/dev/null || { fail "no pod after wake for 2d"; print_results; exit 1; }
+
# (d) channel post-enable -> kill-switch
header "Test 2d -- CommunicationChannel post-enable flips to always-on"
CREATED_CHANNEL="e2e-stateless-killswitch-${RUN_ID}"