Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): soft quarantine warning for assigning a stale model (operator path)
Diego Zacarias9dc1e007b989
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 9b40bbd85..e874f5db2 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.437",+ "version": "0.1.442","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.437",+ "version": "0.1.442","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex 513de4d55..6492eff89 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.437",+ "version": "0.1.442","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/hostSpecValidation.ts b/control-api/src/routes/admin/hostSpecValidation.tsindex afa4ae825..29bc4b3bc 100644--- a/control-api/src/routes/admin/hostSpecValidation.ts+++ b/control-api/src/routes/admin/hostSpecValidation.ts@@ -4,7 +4,10 @@ import {PROVIDER_CREDENTIAL_SLOTS,isLlmProviderId,} from '@clerum/llm-providers'-import { isModelAllowed as isModelAllowedDefault } from '../../services/llmAllowedModels.js'+import {+ getModelAllowlistState as getModelAllowlistStateDefault,+ isModelAllowed as isModelAllowedDefault,+} from '../../services/llmAllowedModels.js'import { isPlainObject } from '../../utils/isPlainObject.js'import {type HostSpecIncoherenceToleratedEvent,@@ -15,6 +18,7 @@ import {isNonWorseningToleration,offeredKey,} from './modelAllowlistTolerance.js'+import { STALE_MODEL_ASSIGNED, type StaleModelWarning } from './staleModelWarning.js'// A Kubernetes Secret/ConfigMap data key: `[-._a-zA-Z0-9]`, max 253 chars.// A fallback `credentialSlot` names a key inside the chatllm-api-keys Secret, so@@ -53,6 +57,16 @@ const HostApprovalSchema = zexport interface HostSpecValidationDeps {isModelAllowed: (provider: string, model: string) => Promise<boolean>+ /**+ * Full `{ enabled, stale }` allowlist state for a pair (Fase 6). OPTIONAL and+ * defaulted so existing callers that inject only `isModelAllowed` keep working;+ * it is consulted ONLY when `context.warnings` is supplied (the stale-warning+ * sink), so a caller not requesting warnings never triggers this lookup.+ */+ getModelAllowlistState?: (+ provider: string,+ model: string+ ) => Promise<{ enabled: boolean; stale: boolean } | null>}/**@@ -73,6 +87,16 @@ export interface HostSpecValidationContext {* step (secretRef check, K8s conflict) rejects leaves no audit record.*/tolerations?: HostSpecIncoherenceToleratedEvent[]+ /**+ * OUTPUT sink for Fase 6 soft-quarantine warnings. When present, the validator+ * appends a warning for every NEW assignment of an `enabled` but `stale` model+ * (a live reference in `stored` is never revalidated). Same emit-after-persist+ * discipline as `tolerations`: the validator only fills the sink on ACCEPT; the+ * caller returns it in the success body only after the write persists — a write+ * rejected by a later gate carries no warning. Independent of `stored`: warnings+ * apply on both create (all assignments new) and update.+ */+ warnings?: StaleModelWarning[]}// spec.lifecycle follows the facade's contract for optional spec objects,@@ -123,7 +147,10 @@ const HostLifecycleSchema = z*/export async function validateHostSpec(spec: Record<string, unknown>,- deps: HostSpecValidationDeps = { isModelAllowed: isModelAllowedDefault },+ deps: HostSpecValidationDeps = {+ isModelAllowed: isModelAllowedDefault,+ getModelAllowlistState: getModelAllowlistStateDefault,+ },context: HostSpecValidationContext = {}): Promise<{ errors: Array<{ field: string; message: string }> } | null> {// Contract guard (mini-spec 01): passing `stored` enables tolerance, so the@@ -171,10 +198,13 @@ export async function validateHostSpec(// introduce a disabled model.const tol: HostToleranceBundle = {context,+ deps,storedRoles: storedRoleSets(context.stored),incomingCov: hostCoverage(spec),storedCov: hostCoverage(context.stored),pending: [],+ warnings: [],+ warnedKeys: new Set(),}// R3 model allowlist. Enforcement is keyed on the PRESENCE of `spec.model.name`@@ -216,6 +246,9 @@ export async function validateHostSpec(],}}+ // Fase 6: an ENABLED pair that passed the gate may still be `stale`. Warn (no+ // block) if this is a NEW assignment.+ if (allowed) await maybeWarnStale(provider, name, 'spec.model.name', tol)}// R5 provider-fallback policy. Opt-in and additive: a spec with no `llmPolicy`@@ -239,6 +272,11 @@ export async function validateHostSpec(// record (mini-spec 01, persist-ordering fix).if (context.tolerations) context.tolerations.push(...tol.pending)+ // Fase 6: hand the queued soft-quarantine warnings to the caller via the sink,+ // on ACCEPT only — same persist-ordering as tolerations, so a write a later gate+ // rejects (secretRef check, K8s conflict) surfaces no warning.+ if (context.warnings) context.warnings.push(...tol.warnings)+return null}@@ -333,6 +371,7 @@ function hostCoverage(spec: Record<string, unknown> | undefined): CoverageSet {/** The precomputed no-worsening tolerance inputs, shared by the 3 Host gates. */interface HostToleranceBundle {context: HostSpecValidationContext+ deps: HostSpecValidationDepsstoredRoles: StoredRoleSetsincomingCov: CoverageSetstoredCov: CoverageSet@@ -344,6 +383,40 @@ interface HostToleranceBundle {* leaves no audit record. One event per tolerated gate decision.*/pending: HostSpecIncoherenceToleratedEvent[]+ /**+ * Fase 6 soft-quarantine warnings, ACCUMULATED here and copied into+ * `context.warnings` only on ACCEPT (same persist-ordering as `pending`).+ */+ warnings: StaleModelWarning[]+ /** Pair keys already warned, so a model in two roles warns at most once. */+ warnedKeys: Set<string>+}++/**+ * Fase 6 soft quarantine. Queue a NON-BLOCKING warning when an `enabled` but+ * `stale` model is assigned to something NEW. NO-OP unless `context.warnings` is+ * provided (opt-in sink), so callers that do not request warnings pay no lookup.+ * A pair already referenced by the STORED record is a live reference and is never+ * revalidated (spec §3.3) → no warning. Called ONLY on the `enabled` path (after+ * the gate accepted the pair), so a disabled/tolerated pair (Fase 2) never routes+ * here.+ */+async function maybeWarnStale(+ provider: string,+ model: string,+ field: string,+ tol: HostToleranceBundle+): Promise<void> {+ if (!tol.context.warnings) return+ const key = offeredKey(provider, model)+ if (tol.storedRoles.any.has(key)) return+ if (tol.warnedKeys.has(key)) return+ const getState = tol.deps.getModelAllowlistState ?? getModelAllowlistStateDefault+ const state = await getState(provider, model)+ if (state?.enabled && state.stale) {+ tol.warnedKeys.add(key)+ tol.warnings.push({ code: STALE_MODEL_ASSIGNED, provider, model, field })+ }}/**@@ -454,6 +527,8 @@ async function validateAllowedModels(],}}+ // Fase 6 soft quarantine on the per-host offered subset.+ if (allowed) await maybeWarnStale(provider, model, `${base}.model`, tol)offered.add(offeredKey(provider, model))}@@ -610,6 +685,8 @@ async function validateLlmPolicy(],}}+ // Fase 6 soft quarantine on a fallback assignment.+ if (allowed) await maybeWarnStale(provider, model, `${base}.model`, tol)}return nulldiff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.tsindex 5aae16b21..ee1b5af30 100644--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts@@ -7,7 +7,7 @@ import {import { asyncHandler } from '../../http/asyncHandler.js'import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'import { createPluginWorkloadSdkAdminRateLimit } from '../../middleware/pluginWorkloadSdkRateLimits.js'-import { listEnabledModelNamesForProvider } from '../../services/llmAllowedModels.js'+import { listEnabledModelsWithStaleForProvider } from '../../services/llmAllowedModels.js'import {MAX_ALLOWLIST_ENTRY_LENGTH,MAX_ALLOWLIST_ITEMS,@@ -38,6 +38,7 @@ import {isNonWorseningToleration,offeredKey,} from './modelAllowlistTolerance.js'+import { STALE_MODEL_ASSIGNED, type StaleModelWarning } from './staleModelWarning.js'// ─── Plugin Workload SDK — admin routes (plan §2.6) ──────────────────────// Admin auth is enforced upstream by the control-ui auth gate in app.ts@@ -398,6 +399,11 @@ export function createAdminPluginWorkloadSdkRouter(// ACCEPTED (right before upsert). A grant rejected by a later 400 leaves no// audit record.const pendingGrantTolerations: HostSpecIncoherenceToleratedEvent[] = []+ // Fase 6 soft-quarantine warnings for NEW assignments of enabled-but-stale+ // models. Returned in the 200 body only after the upsert lands (below); a+ // grant rejected by a later 400 returns before the response and carries none.+ const grantWarnings: StaleModelWarning[] = []+ const grantWarnedKeys = new Set<string>()if (capabilityFamily === 'promptBridge') {const rawProvider = typeof body.provider === 'string' ? body.provider.trim() : ''if (!rawProvider) {@@ -461,7 +467,33 @@ export function createAdminPluginWorkloadSdkRouter(storedCoverage = new Set(storedGrant?.allowedModels ?? [])}for (const [targetProvider, targetModels] of modelsByProvider) {- const enabled = new Set(await listEnabledModelNamesForProvider(targetProvider))+ const enabledRows = await listEnabledModelsWithStaleForProvider(targetProvider)+ const enabled = new Set(enabledRows.map(row => row.model))+ const staleEnabled = new Set(enabledRows.filter(row => row.stale).map(row => row.model))++ // Fase 6 soft quarantine: warn (never block) when a NEW target assigns an+ // ENABLED but `stale` model. A live reference already in the stored grant+ // is not revalidated (spec §3.3). The stored grant is loaded lazily — only+ // when a stale-enabled candidate is actually present — so the all-fresh /+ // no-stale happy path keeps its single-query cost.+ for (const model of targetModels) {+ if (!enabled.has(model) || !staleEnabled.has(model)) continue+ const pairKey = offeredKey(targetProvider, model)+ if (grantWarnedKeys.has(pairKey)) continue+ grantWarnedKeys.add(pairKey)+ await loadStoredGrant()+ if (storedAnyTarget.has(pairKey)) continue+ const i = promptTargets.findIndex(+ target => target.provider === targetProvider && target.model === model+ )+ grantWarnings.push({+ code: STALE_MODEL_ASSIGNED,+ provider: targetProvider,+ model,+ field: i >= 0 ? `promptTargets[${i}].model` : 'promptTargets',+ })+ }+const rawOffenders = targetModels.filter(model => !enabled.has(model))if (rawOffenders.length === 0) continueawait loadStoredGrant()@@ -545,7 +577,11 @@ export function createAdminPluginWorkloadSdkRouter(// Grant PERSISTED: NOW emit any Pieza D tolerations (never before the upsert// lands, so a failed upsert leaves no audit record — mini-spec 01).for (const event of pendingGrantTolerations) emitIncoherenceTolerated(event)- res.status(200).json({ grant })+ // Fase 6: attach any soft-quarantine warnings additively (older clients+ // ignore the field). Absent when there is nothing to warn about.+ res+ .status(200)+ .json(grantWarnings.length > 0 ? { grant, warnings: grantWarnings } : { grant })}))diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.tsindex 74a088e38..14f2707f0 100644--- a/control-api/src/routes/admin/resources.ts+++ b/control-api/src/routes/admin/resources.ts@@ -23,6 +23,7 @@ import {type HostSpecIncoherenceToleratedEvent,emitHostSpecIncoherenceTolerated,} from './hostWriteGateAudit.js'+import type { StaleModelWarning } from './staleModelWarning.js'const PROVIDER_SETTINGS_FIELDS: Readonly<Record<string, readonly string[]>> = {telegramSettings: ['botHandle', 'replyOnlyWhenMentioned'],@@ -385,6 +386,10 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {}credentials?: Record<string, string>}+ // Fase 6 soft-quarantine warnings granted during Host validation, returned+ // in the 201 body only after the CR persists (below). Empty for every+ // non-host create.+ const hostWarnings: StaleModelWarning[] = []if (plural === 'communicationchannels' && body.spec) {const errors = validateCommunicationChannelSpec(body.spec)@@ -490,6 +495,9 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {// apply — a fresh Host may not introduce a disabled model.const issue = await validateHostSpec(body.spec, undefined, {hostRef: { namespace: ns, name: body.metadata.name },+ // Fase 6: a fresh Host has no stored CR, so EVERY assignment is new — a+ // stale enabled model warns (never blocks). Emitted after the CR lands.+ warnings: hostWarnings,})if (issue) {res.status(422).json(issue)@@ -529,7 +537,15 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {return}}- res.status(201).json(created)+ // Host CR persisted: attach any Fase 6 warnings additively (older clients+ // ignore the field). Absent when there is nothing to warn about.+ res+ .status(201)+ .json(+ hostWarnings.length > 0+ ? { ...(created as Record<string, unknown>), warnings: hostWarnings }+ : created+ )}))@@ -557,6 +573,9 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {// Pieza D tolerations granted during Host validation, emitted only after// the CR persists (below). Empty for every non-host / non-tolerated write.const hostTolerations: HostSpecIncoherenceToleratedEvent[] = []+ // Fase 6 soft-quarantine warnings, returned in the 200 body only after the+ // CR persists (below). Empty for every non-host / non-stale write.+ const hostWarnings: StaleModelWarning[] = []if (plural === 'communicationchannels' && body.spec) {const errors = validateCommunicationChannelSpec(body.spec)@@ -600,6 +619,10 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {// the CR persists (mini-spec 01), so a secretRef 422 or a K8s conflict// leaves no audit record.tolerations: hostTolerations,+ // Fase 6 warnings: a NEW assignment of an enabled-but-stale model warns+ // (never blocks). A live reference already in the stored CR is not+ // revalidated. Returned in the body only after the CR persists.+ warnings: hostWarnings,})if (issue) {res.status(422).json(issue)@@ -676,7 +699,13 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {return}}- res.status(200).json(updated)+ res+ .status(200)+ .json(+ hostWarnings.length > 0+ ? { ...(updated as Record<string, unknown>), warnings: hostWarnings }+ : updated+ )} catch (err) {// AP-6: the caller sent the resourceVersion it read and the resource// changed underneath it. Machine-readable so the UI can tell thediff --git a/control-api/src/routes/admin/staleModelWarning.ts b/control-api/src/routes/admin/staleModelWarning.tsnew file mode 100644index 000000000..783c691a4--- /dev/null+++ b/control-api/src/routes/admin/staleModelWarning.ts@@ -0,0 +1,27 @@+/**+ * Fase 6 — soft quarantine of `stale` models (operator write path only).+ *+ * The Fase 4 catalog sync flags models that vanished from the external catalog as+ * `stale=true` WITHOUT disabling them (`enabled` stays intact — they still work).+ * When the operator assigns such a model to something NEW (editing a Host,+ * upserting a grant), the write SUCCEEDS (200/201) and carries this informational,+ * NON-BLOCKING warning in the response body.+ *+ * NEVER a 422/409 for `stale` alone: the flag is heuristic and flappy and the+ * model still functions. This is orthogonal to Fase 2's `enabled=false` gate — a+ * `stale` model is `enabled`, so it passes `model_not_allowed`; Fase 6 only ADDS+ * the warning when the assignment is new. Live references are never revalidated.+ *+ * The shape is shared by the Host and grant write paths so it cannot drift; the+ * success response gains an additive `warnings: StaleModelWarning[]` field (older+ * clients ignore it).+ */+export const STALE_MODEL_ASSIGNED = 'stale_model_assigned' as const++export interface StaleModelWarning {+ code: typeof STALE_MODEL_ASSIGNED+ provider: string+ model: string+ /** Request-body field the stale assignment arrived on (e.g. `spec.model.name`). */+ field: string+}diff --git a/control-api/src/services/llmAllowedModels.ts b/control-api/src/services/llmAllowedModels.tsindex 0269ab385..4d3bb51eb 100644--- a/control-api/src/services/llmAllowedModels.ts+++ b/control-api/src/services/llmAllowedModels.ts@@ -401,6 +401,53 @@ export async function listEnabledModelNamesForProvider(return (result.rows as Record<string, unknown>[]).map(row => String(row.model))}+/**+ * Full allowlist state for one `(provider, model)`: `{ enabled, stale }`, or+ * `null` when no row exists. Fase 6 (soft quarantine of `stale` models) reads+ * this on the operator write path so the gate can WARN — never block — when an+ * `enabled` but `stale` model (vanished from the external catalog, Fase 4) is+ * assigned to something NEW. `isModelAllowed` stays the boolean fail-closed gate+ * (unchanged callers, unchanged semantics); this is strictly additive.+ */+export async function getModelAllowlistState(+ provider: string,+ model: string,+ db: DbClient = pool+): Promise<{ enabled: boolean; stale: boolean } | null> {+ const result = await db.query(+ `SELECT enabled, stale FROM llm_allowed_models+ WHERE provider = $1 AND model = $2+ LIMIT 1`,+ [provider, model]+ )+ const row = result.rows[0] as Record<string, unknown> | undefined+ if (!row) return null+ return { enabled: Boolean(row.enabled), stale: Boolean(row.stale) }+}++/**+ * Enabled model names for one provider WITH their `stale` flag (Fase 6 grant+ * gate). Same `enabled`-only filter as `listEnabledModelNamesForProvider`; adds+ * `stale` so the grant write gate can warn on a NEW assignment of an enabled-but-+ * stale model without a second round-trip. A `stale` model is still `enabled`, so+ * it still appears here — quarantine is a warning, not a de-listing (R3.7).+ */+export async function listEnabledModelsWithStaleForProvider(+ provider: string,+ db: DbClient = pool+): Promise<Array<{ model: string; stale: boolean }>> {+ const result = await db.query(+ `SELECT model, stale FROM llm_allowed_models+ WHERE provider = $1 AND enabled+ ORDER BY model ASC`,+ [provider]+ )+ return (result.rows as Record<string, unknown>[]).map(row => ({+ model: String(row.model),+ stale: Boolean(row.stale),+ }))+}+/*** Enabled rows grouped by provider, shaped for the ConfigMap materializer.* Only providers with at least one enabled row appear. Deterministic orderingdiff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.tsindex 7a8a0d30a..1d5634253 100644--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts@@ -808,4 +808,87 @@ describe('routes/admin/pluginWorkloadSdk — quota & audit', () => {expect.objectContaining({ method: undefined, status: undefined }))})++ // Fase 6 — soft quarantine of `stale` models on the grant write path. An ENABLED+ // but `stale` model assigned to a NEW target answers 200 with an additive+ // `warnings` array — NEVER a 400 — and a live reference already in the stored+ // grant is not revalidated. Assert the HTTP body (T4).+ describe('stale soft-quarantine warnings (Fase 6)', () => {+ // Stored grant derived through the real row producer (`mapGrantRow`) so the+ // fixture cannot drift from what the DB layer emits (T1).+ const makeStoredGrant = (+ over: { promptTargets?: unknown; allowedModels?: string[] } = {}+ ): sdkDb.PluginWorkloadSdkGrant =>+ sdkDb.mapGrantRow({+ id: 'g-stored',+ recipe_namespace: validGrantBody.recipeNamespace,+ recipe_name: validGrantBody.recipeName,+ capability_family: 'promptBridge',+ provider: 'zai',+ allowed_models: over.allowedModels ?? validGrantBody.allowedModels,+ prompt_targets: over.promptTargets ?? validGrantBody.promptTargets,+ created_at: '2026-01-01T00:00:00.000Z',+ updated_at: '2026-01-01T00:00:00.000Z',+ })++ it('NEW target assigning an enabled+stale model → 200 + warnings, never 400', async () => {+ // glm-4.7 is enabled AND stale; there is no stored grant → the assignment is+ // new.+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ model: 'glm-4.7', stale: true }],+ rowCount: 1,+ } as never)+ vi.mocked(sdkDb.listGrants).mockResolvedValue([])+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g1' } as never)++ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send(validGrantBody)++ expect(res.status).toBe(200)+ expect(res.body.warnings).toEqual([+ {+ code: 'stale_model_assigned',+ provider: 'zai',+ model: 'glm-4.7',+ field: 'promptTargets[0].model',+ },+ ])+ expect(sdkDb.upsertGrant).toHaveBeenCalled()+ })++ it('EXISTING stale target (already in the stored grant) → 200 + NO warnings (not revalidated)', async () => {+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ model: 'glm-4.7', stale: true }],+ rowCount: 1,+ } as never)+ // The stored grant already references glm-4.7 as its target.+ vi.mocked(sdkDb.listGrants).mockResolvedValue([makeStoredGrant()] as never)+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g1' } as never)++ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send(validGrantBody)++ expect(res.status).toBe(200)+ expect(res.body.warnings).toBeUndefined()+ expect(sdkDb.upsertGrant).toHaveBeenCalled()+ })++ it('enabled non-stale target → 200 + NO warnings', async () => {+ vi.mocked(pool.query).mockResolvedValue({+ rows: [{ model: 'glm-4.7', stale: false }],+ rowCount: 1,+ } as never)+ vi.mocked(sdkDb.listGrants).mockResolvedValue([])+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g1' } as never)++ const res = await request(buildApp())+ .post('/admin/plugin-workload-sdk/grants')+ .send(validGrantBody)++ expect(res.status).toBe(200)+ expect(res.body.warnings).toBeUndefined()+ })+ })})diff --git a/control-api/test/routes.hostSpecValidation.test.ts b/control-api/test/routes.hostSpecValidation.test.tsindex 6bad3806c..39d4cc1bc 100644--- a/control-api/test/routes.hostSpecValidation.test.ts+++ b/control-api/test/routes.hostSpecValidation.test.ts@@ -721,4 +721,120 @@ describe('validateHostSpec', () => {expect(tolerations).toEqual([])})})++ // Fase 6 — soft quarantine of `stale` models on the operator path. An ENABLED+ // but `stale` model assigned to something NEW passes the gate (never 422) and+ // yields a NON-BLOCKING warning; a live reference (already in the stored CR) is+ // never revalidated. Orthogonal to Fase 2 (`enabled=false`).+ describe('stale soft-quarantine warnings (Fase 6)', () => {+ // Everything enabled; `stale` keyed on `${provider}:${model}`.+ const enabledAll = () => vi.fn(() => Promise.resolve(true))+ const stateFn = (...staleKeys: string[]) => {+ const stale = new Set(staleKeys)+ return vi.fn((p: string, m: string) =>+ Promise.resolve({ enabled: true, stale: stale.has(`${p}:${m}`) })+ )+ }++ it('NEW assignment of an enabled+stale primary → null (no error) + warning, never 422', async () => {+ const isModelAllowed = enabledAll()+ const getModelAllowlistState = stateFn('claude:M')+ const warnings: Array<Record<string, unknown>> = []+ const res = await validateHostSpec(+ { model: { provider: 'claude', name: 'M' } },+ { isModelAllowed, getModelAllowlistState },+ { warnings } // no stored → create → assignment is new+ )+ // Never a rejection for stale alone.+ expect(res).toBeNull()+ expect(warnings).toEqual([+ { code: 'stale_model_assigned', provider: 'claude', model: 'M', field: 'spec.model.name' },+ ])+ })++ it('EXISTING reference to a stale model (already in stored) → no warning (not revalidated)', async () => {+ const isModelAllowed = enabledAll()+ const getModelAllowlistState = stateFn('claude:M')+ const warnings: Array<Record<string, unknown>> = []+ const stored = { model: { provider: 'claude', name: 'M' } }+ const res = await validateHostSpec(+ { model: { provider: 'claude', name: 'M' } },+ { isModelAllowed, getModelAllowlistState },+ { stored, tolerations: [], warnings }+ )+ expect(res).toBeNull()+ expect(warnings).toEqual([])+ // A live reference is never revalidated — the state lookup is skipped.+ expect(getModelAllowlistState).not.toHaveBeenCalled()+ })++ it('NEW assignment of an enabled but NON-stale model → no warning', async () => {+ const isModelAllowed = enabledAll()+ const getModelAllowlistState = stateFn() // nothing stale+ const warnings: Array<Record<string, unknown>> = []+ const res = await validateHostSpec(+ { model: { provider: 'claude', name: 'M' } },+ { isModelAllowed, getModelAllowlistState },+ { warnings }+ )+ expect(res).toBeNull()+ expect(warnings).toEqual([])+ })++ it('warns for a NEW stale fallback and a NEW stale subset entry (all 3 gates)', async () => {+ const isModelAllowed = enabledAll()+ const getModelAllowlistState = stateFn('claude:P', 'claude:F', 'claude:S')+ const warnings: Array<{ field: string; model: string }> = []+ const res = await validateHostSpec(+ {+ model: { provider: 'claude', name: 'P' },+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'F' }] },+ allowedModels: [+ { provider: 'claude', model: 'P' },+ { provider: 'claude', model: 'F' },+ { provider: 'claude', model: 'S' },+ ],+ },+ { isModelAllowed, getModelAllowlistState },+ { warnings }+ )+ expect(res).toBeNull()+ // One warning per distinct pair (deduped), across primary/fallback/subset.+ const byModel = Object.fromEntries(warnings.map(w => [w.model, w.field]))+ expect(byModel).toEqual({+ P: 'spec.model.name',+ F: 'spec.llmPolicy.fallbacks[0].model',+ S: 'spec.allowedModels[2].model',+ })+ })++ it('a DISABLED model (Fase 2) is not turned into a Fase 6 warning — it rejects', async () => {+ // enabled=false → the R3 gate 422s (create, no tolerance). Fase 6 never runs+ // for a rejected pair, and the state lookup is not even consulted.+ const isModelAllowed = vi.fn(() => Promise.resolve(false))+ const getModelAllowlistState = stateFn('claude:M') // would-be stale, but disabled+ const warnings: Array<Record<string, unknown>> = []+ const res = await validateHostSpec(+ { model: { provider: 'claude', name: 'M' } },+ { isModelAllowed, getModelAllowlistState },+ { warnings }+ )+ expect(res).not.toBeNull()+ expect(res!.errors[0].message).toContain('model_not_allowed')+ expect(warnings).toEqual([])+ expect(getModelAllowlistState).not.toHaveBeenCalled()+ })++ it('does not consult the state lookup at all when no warnings sink is provided', async () => {+ const isModelAllowed = enabledAll()+ const getModelAllowlistState = stateFn('claude:M')+ const res = await validateHostSpec(+ { model: { provider: 'claude', name: 'M' } },+ { isModelAllowed, getModelAllowlistState }+ // no context.warnings → opt-out, zero extra queries+ )+ expect(res).toBeNull()+ expect(getModelAllowlistState).not.toHaveBeenCalled()+ })+ })})diff --git a/control-api/test/routes.resources.staleModelWarning.test.ts b/control-api/test/routes.resources.staleModelWarning.test.tsnew file mode 100644index 000000000..9d9d9d875--- /dev/null+++ b/control-api/test/routes.resources.staleModelWarning.test.ts@@ -0,0 +1,112 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'+import { config } from '../src/config.js'+import { createAdminResourcesRouter } from '../src/routes/admin/resources.js'+import { MockGateway } from './mockGateway.js'++// Fase 6 — soft quarantine of `stale` models, OPERATOR PATH ONLY. Route-level+// proof (T4: assert the HTTP body) that a NEW assignment of an enabled-but-stale+// model answers 200/201 with an additive `warnings` array — NEVER a 422/409 — and+// that a live reference is not revalidated, that a non-stale model warns nothing,+// and that a write that fails to persist surfaces no warning.++const llm = vi.hoisted(() => ({+ isModelAllowed: vi.fn(),+ getModelAllowlistState: vi.fn(),+}))+vi.mock('../src/services/llmAllowedModels.js', async () => {+ const actual = await vi.importActual<typeof import('../src/services/llmAllowedModels.js')>(+ '../src/services/llmAllowedModels.js'+ )+ return {+ ...actual,+ isModelAllowed: llm.isModelAllowed,+ getModelAllowlistState: llm.getModelAllowlistState,+ }+})++const HOSTS_NS = config.hostsNamespace++function buildApp(gateway: MockGateway) {+ const app = express()+ app.use(express.json())+ app.use(createAdminResourcesRouter(gateway as never))+ return app+}++// `M` is the enabled-but-stale model; everything else is enabled and fresh.+beforeEach(() => {+ llm.isModelAllowed.mockReset()+ llm.getModelAllowlistState.mockReset()+ llm.isModelAllowed.mockResolvedValue(true) // all models enabled by default+ llm.getModelAllowlistState.mockImplementation((_p: string, m: string) =>+ Promise.resolve({ enabled: true, stale: m === 'M' })+ )+})++const staleSpec = { model: { provider: 'claude', name: 'M' } }+const freshSpec = { model: { provider: 'claude', name: 'OTHER' } }++describe('Host stale soft-quarantine warnings (Fase 6)', () => {+ it('CREATE with an enabled+stale model → 201 + warnings, never 422', async () => {+ const gateway = new MockGateway(HOSTS_NS)+ const res = await request(buildApp(gateway))+ .post('/admin/hosts')+ .send({ metadata: { name: 'h1' }, spec: staleSpec })++ expect(res.status).toBe(201)+ expect(res.body.warnings).toEqual([+ { code: 'stale_model_assigned', provider: 'claude', model: 'M', field: 'spec.model.name' },+ ])+ })++ it('EDIT introducing a stale model (new pair) → 200 + warnings', async () => {+ const gateway = new MockGateway(HOSTS_NS)+ // Stored default is a fresh model; the edit switches it to the stale M.+ await gateway.createResource('hosts', { metadata: { name: 'h1' }, spec: freshSpec }, HOSTS_NS)++ const res = await request(buildApp(gateway)).put('/admin/hosts/h1').send({ spec: staleSpec })++ expect(res.status).toBe(200)+ expect(res.body.warnings).toEqual([+ { code: 'stale_model_assigned', provider: 'claude', model: 'M', field: 'spec.model.name' },+ ])+ })++ it('EDIT keeping an EXISTING stale reference → 200 + NO warnings (not revalidated)', async () => {+ const gateway = new MockGateway(HOSTS_NS)+ // The stale M was already the stored default — a live reference.+ await gateway.createResource('hosts', { metadata: { name: 'h1' }, spec: staleSpec }, HOSTS_NS)++ const res = await request(buildApp(gateway)).put('/admin/hosts/h1').send({ spec: staleSpec })++ expect(res.status).toBe(200)+ expect(res.body.warnings).toBeUndefined()+ })++ it('EDIT to an enabled non-stale model → 200 + NO warnings', async () => {+ const gateway = new MockGateway(HOSTS_NS)+ await gateway.createResource('hosts', { metadata: { name: 'h1' }, spec: staleSpec }, HOSTS_NS)++ const res = await request(buildApp(gateway)).put('/admin/hosts/h1').send({ spec: freshSpec })++ expect(res.status).toBe(200)+ expect(res.body.warnings).toBeUndefined()+ })++ it('does NOT surface a warning when the write fails to persist (updateResource throws)', async () => {+ class ThrowingGateway extends MockGateway {+ override async updateResource(): Promise<unknown> {+ throw new Error('k8s write failed')+ }+ }+ const gateway = new ThrowingGateway(HOSTS_NS)+ await gateway.createResource('hosts', { metadata: { name: 'h1' }, spec: freshSpec }, HOSTS_NS)++ const res = await request(buildApp(gateway)).put('/admin/hosts/h1').send({ spec: staleSpec })++ expect(res.status).toBeGreaterThanOrEqual(500)+ expect(res.body.warnings).toBeUndefined()+ })+})diff --git a/control-api/test/services.llmAllowedModels.test.ts b/control-api/test/services.llmAllowedModels.test.tsindex eff381105..cbe8d688b 100644--- a/control-api/test/services.llmAllowedModels.test.ts+++ b/control-api/test/services.llmAllowedModels.test.ts@@ -4,10 +4,12 @@ import {createAllowedModel,createLlmAllowedModelSchema,deleteAllowedModel,+ getModelAllowlistState,isModelAllowed,listAllowedModels,listEnabledGroupedByProvider,listEnabledModelNamesForProvider,+ listEnabledModelsWithStaleForProvider,updateAllowedModel,updateLlmAllowedModelSchema,} from '../src/services/llmAllowedModels.js'@@ -217,6 +219,59 @@ describe('llmAllowedModels service', () => {})})+ describe('getModelAllowlistState (Fase 6)', () => {+ it('returns {enabled, stale} for an existing row (enabled+stale)', async () => {+ const query = vi+ .fn()+ .mockResolvedValue({ rows: [{ enabled: true, stale: true }], rowCount: 1 })+ expect(await getModelAllowlistState('claude', 'M', fakeDb(query))).toEqual({+ enabled: true,+ stale: true,+ })+ // The gate MUST NOT filter on `enabled` here — it needs the state of both an+ // enabled AND a disabled row so Fase 2 (disabled) and Fase 6 (stale) can be+ // told apart. It also reads `stale`.+ const [sql] = query.mock.calls[0]+ expect(String(sql)).toMatch(/stale/)+ expect(String(sql)).not.toMatch(/AND enabled\b/)+ })++ it('returns null when no row exists (unknown pair)', async () => {+ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })+ expect(await getModelAllowlistState('claude', 'nope', fakeDb(query))).toBeNull()+ })++ it('coerces a disabled non-stale row correctly', async () => {+ const query = vi+ .fn()+ .mockResolvedValue({ rows: [{ enabled: false, stale: false }], rowCount: 1 })+ expect(await getModelAllowlistState('claude', 'D', fakeDb(query))).toEqual({+ enabled: false,+ stale: false,+ })+ })+ })++ describe('listEnabledModelsWithStaleForProvider (Fase 6)', () => {+ it('returns enabled models with their stale flag', async () => {+ const query = vi.fn().mockResolvedValue({+ rows: [+ { model: 'glm-4.7', stale: false },+ { model: 'glm-legacy', stale: true },+ ],+ rowCount: 2,+ })+ expect(await listEnabledModelsWithStaleForProvider('zai', fakeDb(query))).toEqual([+ { model: 'glm-4.7', stale: false },+ { model: 'glm-legacy', stale: true },+ ])+ // Same enabled-only filter as the name variant — a stale model is still+ // enabled and must still appear (quarantine warns, it does not de-list).+ const [sql] = query.mock.calls[0]+ expect(String(sql)).toMatch(/WHERE provider = \$1 AND enabled/)+ })+ })+describe('listAllowedModels (catalog lifecycle, F1)', () => {it('selects and maps the four catalog lifecycle columns', async () => {const query = vi.fn().mockResolvedValue({