Skip to content

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

TypeScript

feat(control-api): scheduled non-destructive LLM catalog sync cron + sanity guard (cron)

Diego Zacariasa95ca0151c01
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 4f27babd1..31b8ca7a5 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.435",
+ "version": "0.1.436",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.435",
+ "version": "0.1.436",
"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.json
index 1c47faa52..c73ab25e9 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.435",
+ "version": "0.1.436",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index 033cb2afe..96dcc8168 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -102,6 +102,26 @@ type Config = {
usageRollupDailyIntervalMs: number
usageRetentionIntervalMs: number
budgetReservationSweepIntervalMs: number
+ // LLM catalog discovery sync cron (Fase 4). Runs syncDiscoveredModels()
+ // periodically. DEFAULT OFF — the operator opts in consciously so a fresh
+ // plane never hammers models.dev on boot. When on, one tick every
+ // llmCatalogSyncIntervalMs (default 24h), cross-replica-deduped by a session
+ // advisory lock inside the cron.
+ llmCatalogSyncCronEnabled: boolean
+ llmCatalogSyncIntervalMs: number
+ // §4.5 sanity guard, layer 3: absolute plausibility floor. If a LIVE run's
+ // TOTAL mapped model count is below this, the whole run SKIPS stale-marking
+ // (a flappy/truncated external catalog must not mass-stale the allowlist);
+ // the inert `enabled=false` inserts still proceed. Calibrated off the vendored
+ // snapshot (~1051 mapped models across 21 providers) — a conservative <10%
+ // floor catches a catastrophic collapse without tripping on normal variation.
+ modelsDevMinPlausibleLiveTotal: number
+ // §4.5 sanity guard, layer 2: per-provider low/zero-live floor. A provider
+ // that returns FEWER than this many live models but still has discovery rows
+ // in DB is treated as suspicious and NOT stale-marked. 0 (the default) means
+ // only the zero-live case is guarded (the mandatory floor); a higher value
+ // also guards implausibly-low provider counts.
+ llmCatalogSyncProviderMinLive: number
registryPullSecretReconcileIntervalMs: number
budgetReservationTtlSeconds: number
approvalRetentionDays: number
@@ -284,6 +304,22 @@ function positiveIntegerFromEnv(name: string, defaultValue: number): number {
return value
}
+/**
+ * A non-negative integer env (>= 0). Unlike `positiveIntegerFromEnv`, 0 is a
+ * valid, meaningful value here (the per-provider stale floor's default: guard
+ * only the zero-live case). An unset/blank env yields the default; any other
+ * non-integer / negative value is refused at boot rather than silently coerced.
+ */
+function nonNegativeIntegerFromEnv(name: string, defaultValue: number): number {
+ const raw = process.env[name]
+ if (raw === undefined || raw.trim() === '') return defaultValue
+ const value = Number(raw)
+ if (!Number.isSafeInteger(value) || value < 0) {
+ throw new Error(`${name} must be a non-negative integer`)
+ }
+ return value
+}
+
function boundedIntegerFromEnv(name: string, defaultValue: number, maxValue: number): number {
const value = positiveIntegerFromEnv(name, defaultValue)
if (value > maxValue) {
@@ -320,6 +356,8 @@ const SANDBOX_UI_NAMESPACE = process.env.CONTROL_API_SANDBOX_UI_NAMESPACE || 'sa
const DEFAULT_MCP_HOST_JWT_MAX_HOST_REFS = 32
const DEFAULT_MCP_HOST_JWT_MAX_HOST_REF_LENGTH = 63 + 1 + 253
const REGISTRY_PULL_SECRET_RECONCILE_MIN_INTERVAL_MS = 10_000
+// A 24h-default cron should never be dialed below a minute — refuse a hot loop.
+const LLM_CATALOG_SYNC_MIN_INTERVAL_MS = 60_000
const WORKFLOW_MAX_WORKLOADS_PER_RECIPE_CEILING = 25
const WORKFLOW_UI_EGRESS_INTERNAL_MAX_ITEMS_CEILING = 25
const WORKFLOW_MAX_STEPS_CEILING = 100
@@ -632,6 +670,23 @@ export const config: Config = {
budgetReservationSweepIntervalMs: Number(
process.env.BUDGET_RESERVATION_SWEEP_INTERVAL_MS || 60_000
),
+ // Default OFF: `=== 'true'`, NOT the default-on `(x ?? 'true') !== 'false'`
+ // idiom used by the other crons. This one stays dark until an operator turns
+ // it on deliberately.
+ llmCatalogSyncCronEnabled: process.env.LLM_CATALOG_SYNC_CRON_ENABLED === 'true',
+ // Default 24h. Validated (not merely parsed): the value goes straight into
+ // setInterval and each tick opens a Postgres transaction + advisory lock. A
+ // 60s floor is orders of magnitude below the default and far above a hot loop.
+ llmCatalogSyncIntervalMs: intervalMsFromEnv(
+ 'LLM_CATALOG_SYNC_INTERVAL_MS',
+ 24 * 60 * 60 * 1000,
+ LLM_CATALOG_SYNC_MIN_INTERVAL_MS
+ ),
+ modelsDevMinPlausibleLiveTotal: positiveIntegerFromEnv(
+ 'MODELS_DEV_MIN_PLAUSIBLE_LIVE_TOTAL',
+ 100
+ ),
+ llmCatalogSyncProviderMinLive: nonNegativeIntegerFromEnv('LLM_CATALOG_SYNC_PROVIDER_MIN_LIVE', 0),
// How often to re-assert the platform image-pull credential. This is a standing
// invariant, not a fast path: a WorkflowRecipe created by `kubectl apply` or the WRC
// `deploy_recipe` tool never touches control-api, so the credential has to be there
diff --git a/control-api/src/main.ts b/control-api/src/main.ts
index b1183e1c0..38fe4612a 100644
--- a/control-api/src/main.ts
+++ b/control-api/src/main.ts
@@ -12,6 +12,7 @@ import {
startBudgetReservationSweepCron,
stopBudgetReservationSweepCron,
} from './services/budgetReservationSweepCron.js'
+import { startLlmCatalogSyncCron, stopLlmCatalogSyncCron } from './services/llmCatalogSyncCron.js'
import { runBootEnrollment } from './services/memberRegistrationEnrollment.js'
import {
startPluginWorkloadSdkMaintenanceCron,
@@ -78,6 +79,20 @@ async function main(): Promise<void> {
startBudgetReservationSweepCron(config.budgetReservationSweepIntervalMs)
startWorkflowApprovalTraceProjector()
+ // LLM catalog discovery sync cron (Fase 4). DEFAULT OFF — opt in with
+ // LLM_CATALOG_SYNC_CRON_ENABLED=true. Non-destructive: inserts disabled
+ // discovery rows, only stale-flags vanished ones under the §4.5 guards.
+ if (config.llmCatalogSyncCronEnabled) {
+ startLlmCatalogSyncCron({}, config.llmCatalogSyncIntervalMs)
+ console.log(
+ `[ControlAPI] LLM catalog sync cron enabled (interval=${config.llmCatalogSyncIntervalMs}ms)`
+ )
+ } else {
+ console.log(
+ '[ControlAPI] LLM catalog sync cron disabled (LLM_CATALOG_SYNC_CRON_ENABLED not "true")'
+ )
+ }
+
if (config.userApprovalRequestArchiveCronEnabled) {
startArchiveCron({
retentionDays: config.approvalRetentionDays,
@@ -171,6 +186,7 @@ main().catch(error => {
stopUsageRollupCron()
stopUsageRetentionCron()
stopBudgetReservationSweepCron()
+ stopLlmCatalogSyncCron()
stopWorkflowApprovalTraceProjector()
void pool.end()
process.exit(1)
diff --git a/control-api/src/services/llmCatalogSync.ts b/control-api/src/services/llmCatalogSync.ts
index 377661e9f..9d1f37617 100644
--- a/control-api/src/services/llmCatalogSync.ts
+++ b/control-api/src/services/llmCatalogSync.ts
@@ -36,7 +36,9 @@
* (which records operator actions) with 1000+ rows per run.
*/
import { type LlmProviderId, PROVIDER_IDS } from '@clerum/llm-providers'
+import { config } from '../config.js'
import { pool } from '../db.js'
+import { rootLogger } from '../observability/logger.js'
import { MAX_CONTEXT_WINDOW_TOKENS } from './llmAllowedModels.js'
import {
type DiscoveredModel,
@@ -86,6 +88,8 @@ export interface CatalogSyncRun {
// COMMIT/ROLLBACK.
const SYNC_ADVISORY_LOCK_KEY = 'llm-catalog-sync-v1'
+const log = rootLogger.child({ service: 'llm_catalog_sync' })
+
/** A row of the provider's existing catalog rows, for the source branch. */
interface ExistingRow {
id: string
@@ -121,6 +125,7 @@ async function reconcileProvider(
provider: LlmProviderId,
discovered: DiscoveredModel[],
markStale: boolean,
+ providerMinLive: number,
counters: { added: number; updated: number; staled: number }
): Promise<void> {
const existingRes = await client.query(
@@ -128,11 +133,14 @@ async function reconcileProvider(
[provider]
)
const existingByModel = new Map<string, ExistingRow>()
+ let existingDiscoveryCount = 0
for (const raw of existingRes.rows as Record<string, unknown>[]) {
+ const source = String(raw.source)
+ if (source === 'discovery') existingDiscoveryCount += 1
existingByModel.set(String(raw.model), {
id: String(raw.id),
model: String(raw.model),
- source: String(raw.source),
+ source,
})
}
@@ -192,11 +200,34 @@ async function reconcileProvider(
// VANISHED discovery rows → flag stale (never delete, never disable). Only
// from an authoritative (live) catalog — see the `markStale` doc above. Newly
- // inserted rows are in `discoveredIds`, so they are excluded. `<> ALL('{}')`
- // is true for every row, so an empty (live) catalog for a mapped provider
- // stales all its discovery rows (models genuinely gone) — still never
- // deleted/disabled.
+ // inserted rows are in `discoveredIds`, so they are excluded.
if (!markStale) return
+
+ // §4.5 sanity guard, LAYER 2 — per-provider zero/low-live floor. A provider
+ // that comes back with FEWER than the floor of live models but still has
+ // discovery rows in DB is treated as SUSPICIOUS (an external-catalog glitch,
+ // not a genuine mass-deprecation), and its rows are left untouched. This
+ // DELIBERATELY replaces the old catastrophic behavior where `model <> ALL('{}')`
+ // stale-marked EVERY discovery row of a provider whose live list came back
+ // empty. `providerMinLive` (default 0) makes the zero-live case the mandatory
+ // floor; a higher value also guards implausibly-low counts. The surgical case
+ // (a provider otherwise complete with one model gone) stays ABOVE the floor and
+ // is still stale-marked — an accepted, recoverable gap.
+ const providerFloor = Math.max(1, providerMinLive)
+ if (discovered.length < providerFloor && existingDiscoveryCount > 0) {
+ log.warn(
+ {
+ event: 'llm_catalog_sync_provider_floor_skip',
+ provider,
+ liveCount: discovered.length,
+ providerMinLive,
+ existingDiscoveryCount,
+ },
+ `skipping stale-marking for provider "${provider}": only ${discovered.length} live model(s) returned but ${existingDiscoveryCount} discovery row(s) exist (suspected flappy catalog)`
+ )
+ return
+ }
+
const staleRes = await client.query(
`UPDATE llm_allowed_models
SET stale = true
@@ -220,13 +251,43 @@ export async function syncDiscoveredModels(
opts: {
loadCatalog?: (o: { fetchImpl?: FetchLike }) => Promise<ModelsDevCatalogResult>
fetchImpl?: FetchLike
+ /** §4.5 layer-3 absolute floor (default from config). */
+ minPlausibleLiveTotal?: number
+ /** §4.5 layer-2 per-provider floor (default from config). */
+ providerMinLive?: number
} = {},
connector: SyncConnector = pool
): Promise<CatalogSyncResult> {
const load = opts.loadCatalog ?? loadModelsDevCatalog
+ const minPlausibleLiveTotal = opts.minPlausibleLiveTotal ?? config.modelsDevMinPlausibleLiveTotal
+ const providerMinLive = opts.providerMinLive ?? config.llmCatalogSyncProviderMinLive
const { source, fetchedAt, catalog } = await load({ fetchImpl: opts.fetchImpl })
const byProvider = mapCatalogToProviders(catalog)
+ // §4.5 sanity guard, LAYER 3 — absolute global plausibility floor. Compared
+ // BEFORE touching any row, against a config constant, with NO baseline / no
+ // persisted history / no per-provider math. If a LIVE run's TOTAL mapped model
+ // count is implausibly small, we suppress the vanished→stale inference for the
+ // WHOLE run — a flappy/truncated external catalog must not mass-stale the
+ // allowlist. "Abort" here means skip only the stale UPDATEs: the inert
+ // `INSERT enabled=false` rows for genuinely-new models still proceed (they
+ // never reach runtime until an operator enables them). Cold start (empty DB)
+ // is unaffected: the stale UPDATE's universe (source='discovery' AND
+ // stale=false) is empty, so it marks 0 rows with or without this guard.
+ const totalLive = PROVIDER_IDS.reduce((n, p) => n + (byProvider[p]?.length ?? 0), 0)
+ const sourceIsLive = source === 'live'
+ const globallyImplausible = sourceIsLive && totalLive < minPlausibleLiveTotal
+ if (globallyImplausible) {
+ log.warn(
+ {
+ event: 'llm_catalog_sync_implausible_live_total',
+ totalLive,
+ minPlausibleLiveTotal,
+ },
+ `LIVE catalog returned only ${totalLive} total model(s) (< floor ${minPlausibleLiveTotal}); suppressing ALL stale-marking this run (inserts still proceed)`
+ )
+ }
+
const client = await connector.connect()
let inTransaction = false
try {
@@ -235,13 +296,21 @@ export async function syncDiscoveredModels(
// Serialize concurrent syncs (xact-scoped advisory lock).
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [SYNC_ADVISORY_LOCK_KEY])
- // Only an authoritative (live) catalog may drive the vanished→stale
- // inference; a vendored fallback must not stale live models (see
- // reconcileProvider).
- const markStale = source === 'live'
+ // Layer 1 (source==='live') AND layer 3 (global plausibility) both gate the
+ // vanished→stale inference for the whole run; layer 2 (per-provider floor)
+ // is applied inside reconcileProvider. A vendored fallback must not stale
+ // live models (see reconcileProvider).
+ const markStale = sourceIsLive && !globallyImplausible
const counters = { added: 0, updated: 0, staled: 0 }
for (const provider of PROVIDER_IDS) {
- await reconcileProvider(client, provider, byProvider[provider] ?? [], markStale, counters)
+ await reconcileProvider(
+ client,
+ provider,
+ byProvider[provider] ?? [],
+ markStale,
+ providerMinLive,
+ counters
+ )
}
// Persist the run summary (the UI's "last synced"). ran_at defaults to NOW();
diff --git a/control-api/src/services/llmCatalogSyncCron.ts b/control-api/src/services/llmCatalogSyncCron.ts
new file mode 100644
index 000000000..b0e6c1c67
--- /dev/null
+++ b/control-api/src/services/llmCatalogSyncCron.ts
@@ -0,0 +1,169 @@
+/**
+ * LLM catalog discovery sync cron (spec 09 Fase 4).
+ *
+ * Periodically runs `syncDiscoveredModels()` — the SAME non-destructive
+ * reconciliation the on-demand `POST /admin/llm-models/discovery/sync` endpoint
+ * drives. No HTTP hop, no new auth: the tick calls the service directly. New
+ * models land as `enabled=false, source='discovery'` (inert until an operator
+ * enables them); vanished models are only ever flagged `stale=true` (never
+ * deleted, never disabled), and only when the §4.5 sanity guards agree the live
+ * catalog is trustworthy.
+ *
+ * Cross-replica dedup: control-api runs multiple replicas, and 24h ticks across
+ * them would otherwise pile up redundant runs. Each tick wraps its work in a
+ * SESSION-scoped `pg_try_advisory_lock(hashtext('llm-catalog-sync-cron-v1'))`
+ * on a dedicated client. If another replica already holds it, this tick is a
+ * no-op. A session lock (unlike the xact lock inside syncDiscoveredModels) is
+ * NOT auto-released on COMMIT, so it MUST be explicitly unlocked — a leaked lock
+ * would wedge every future tick. The `finally` guarantees unlock + release.
+ *
+ * The service's own `pg_advisory_xact_lock` still runs and still serializes a
+ * concurrent on-demand sync against this cron; the session lock here is an
+ * ADDITIONAL guard that avoids queuing redundant cron ticks behind it.
+ *
+ * Modeled on budgetReservationSweepCron.ts / workflowScheduleWorkerCron.ts:
+ * setInterval + unref, errors logged but NEVER thrown.
+ */
+import { pool } from '../db.js'
+import { rootLogger } from '../observability/logger.js'
+import type { CatalogSyncResult } from './llmCatalogSync.js'
+import { syncDiscoveredModels } from './llmCatalogSync.js'
+
+const log = rootLogger.child({ service: 'llm_catalog_sync_cron' })
+
+// Session-scoped advisory lock key. `-cron-v1` distinguishes it from the
+// service's own xact lock (`llm-catalog-sync-v1`) — they are different locks
+// with different scopes and must not collide.
+const CRON_LOCK_KEY_SQL = "hashtext('llm-catalog-sync-cron-v1')"
+
+/**
+ * Minimal client shape for the advisory-lock session. pg's PoolClient satisfies
+ * it. `release` accepts pg's optional destroy argument: passing a truthy value
+ * (an Error) DESTROYS the connection instead of returning it to the pool — the
+ * only way to guarantee a SESSION advisory lock is freed when unlock itself fails.
+ */
+type LockClient = {
+ query: (text: string, values?: unknown[]) => Promise<{ rows: unknown[]; rowCount: number | null }>
+ release: (destroy?: Error | boolean) => void
+}
+
+/** Injectable dependencies (test seam). Both default to production wiring. */
+export interface LlmCatalogSyncCronDeps {
+ connector?: { connect: () => Promise<LockClient> }
+ sync?: () => Promise<CatalogSyncResult>
+}
+
+/** Outcome of one tick — returned for tests/observability, never thrown. */
+export interface LlmCatalogSyncTickResult {
+ skippedLock: boolean
+ ran: boolean
+ errored: boolean
+}
+
+/**
+ * Run one cron tick: acquire the session advisory lock, run the sync, release.
+ * Never throws — a failure is logged and reported in the result. The lock is
+ * released in `finally` whether the tick ran, skipped, or failed.
+ */
+export async function runLlmCatalogSyncTick(
+ deps: LlmCatalogSyncCronDeps = {}
+): Promise<LlmCatalogSyncTickResult> {
+ const connector = deps.connector ?? pool
+ const sync = deps.sync ?? syncDiscoveredModels
+ let lockClient: LockClient | undefined
+ let locked = false
+ try {
+ lockClient = await connector.connect()
+ const lockRes = await lockClient.query(
+ `SELECT pg_try_advisory_lock(${CRON_LOCK_KEY_SQL}) AS acquired`
+ )
+ locked = (lockRes.rows[0] as { acquired?: boolean } | undefined)?.acquired === true
+ if (!locked) {
+ log.debug(
+ { event: 'llm_catalog_sync_cron_skipped_lock' },
+ 'llm catalog sync tick skipped: advisory lock held by another replica'
+ )
+ return { skippedLock: true, ran: false, errored: false }
+ }
+
+ const result = await sync()
+ log.info(
+ {
+ event: 'llm_catalog_sync_cron_tick',
+ source: result.source,
+ added: result.added,
+ updated: result.updated,
+ staled: result.staled,
+ },
+ `llm catalog sync tick complete (source=${result.source}, added=${result.added}, updated=${result.updated}, staled=${result.staled})`
+ )
+ return { skippedLock: false, ran: true, errored: false }
+ } catch (err) {
+ log.error(
+ {
+ event: 'llm_catalog_sync_cron_error',
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'llm catalog sync tick failed'
+ )
+ return { skippedLock: false, ran: false, errored: true }
+ } finally {
+ if (lockClient) {
+ // SESSION lock → explicit unlock is mandatory; only unlock what we acquired.
+ let destroyed = false
+ if (locked) {
+ try {
+ await lockClient.query(`SELECT pg_advisory_unlock(${CRON_LOCK_KEY_SQL})`)
+ } catch (unlockErr) {
+ // A SESSION lock is NOT freed by returning the connection to the pool —
+ // only by an explicit unlock or by CLOSING the session. Since the unlock
+ // failed, DESTROY the connection (release(err) ends the session), which
+ // guarantees the lock is released. A plain release() here would hand a
+ // live connection still holding the lock back to the pool and wedge every
+ // future tick — exactly the failure the module header promises to avoid.
+ const asError = unlockErr instanceof Error ? unlockErr : new Error(String(unlockErr))
+ log.warn(
+ {
+ event: 'llm_catalog_sync_cron_unlock_failed',
+ err: asError.message,
+ },
+ 'pg_advisory_unlock failed; destroying the connection to release the session lock'
+ )
+ lockClient.release(asError)
+ destroyed = true
+ }
+ }
+ // Only return the connection to the pool when we did NOT destroy it above
+ // (destroying already released it — a second release would double-release).
+ if (!destroyed) lockClient.release()
+ }
+ }
+}
+
+let intervalHandle: ReturnType<typeof setInterval> | null = null
+
+export function startLlmCatalogSyncCron(deps: LlmCatalogSyncCronDeps, intervalMs: number): void {
+ if (intervalHandle) return
+ intervalHandle = setInterval(() => {
+ // runLlmCatalogSyncTick never rejects, but keep a defensive catch so an
+ // unexpected throw can never crash the timer.
+ void runLlmCatalogSyncTick(deps).catch(err => {
+ log.error(
+ {
+ event: 'llm_catalog_sync_cron_unhandled',
+ err: err instanceof Error ? err.message : String(err),
+ },
+ 'unhandled error in llm catalog sync cron'
+ )
+ })
+ }, intervalMs)
+ intervalHandle.unref()
+ log.info({ event: 'llm_catalog_sync_cron_started', intervalMs }, 'llm catalog sync cron started')
+}
+
+export function stopLlmCatalogSyncCron(): void {
+ if (intervalHandle) {
+ clearInterval(intervalHandle)
+ intervalHandle = null
+ }
+}
diff --git a/control-api/src/services/modelsDevClient.ts b/control-api/src/services/modelsDevClient.ts
index 10003bc26..3d7edb978 100644
--- a/control-api/src/services/modelsDevClient.ts
+++ b/control-api/src/services/modelsDevClient.ts
@@ -17,8 +17,17 @@
import { type LlmProviderId, PROVIDER_IDS } from '@clerum/llm-providers'
import { VENDORED_MODELS_DEV_SNAPSHOT } from '../data/modelsDevSnapshot.js'
-/** The fixed, trusted catalog URL. Not operator-configurable by design. */
-export const MODELS_DEV_API_URL = 'https://models.dev/api.json'
+/**
+ * The catalog URL. Defaults to the fixed, trusted public endpoint. It is NOT
+ * an operator/tenant-input surface (no SSRF vector — see the module header), but
+ * `MODELS_DEV_API_URL` may override it via env so a non-prod plane (e.g. a test
+ * cluster with the periodic sync enabled) can be pointed at a local stub instead
+ * of hammering the real models.dev host. Trimmed; a blank env falls back to the
+ * default. The `fetchImpl`/`loadCatalog` DI seam remains the mechanism tests use.
+ */
+const DEFAULT_MODELS_DEV_API_URL = 'https://models.dev/api.json'
+export const MODELS_DEV_API_URL =
+ process.env.MODELS_DEV_API_URL?.trim() || DEFAULT_MODELS_DEV_API_URL
/** Fetch guards (defense-in-depth; the URL is fixed/trusted). */
const FETCH_TIMEOUT_MS = 10_000
@@ -188,15 +197,52 @@ function isRawCatalog(value: unknown): value is RawModelsDevCatalog {
}
/**
- * Fetch the LIVE catalog from the fixed URL with all guards, or fall back to the
- * vendored snapshot on ANY failure (network error, timeout, non-2xx, redirect,
- * over-cap body, parse/shape failure). Never throws — the sync must always run.
+ * Assert the resolved catalog URL is a safe egress target BEFORE any fetch. The
+ * module header promises an https-only guard; with the `MODELS_DEV_API_URL` env
+ * override in play, a misconfigured deploy could otherwise resolve to `http://`
+ * or an internal/link-local host (cloud metadata at 169.254.169.254, a cluster
+ * `.internal` Service). This is a deploy-time input, not operator/tenant-facing,
+ * but the boundary is real — so a bad URL is a hard error, not a silent
+ * vendored-fallback that would hide the misconfiguration forever.
+ */
+function assertSafeCatalogUrl(rawUrl: string): void {
+ let parsed: URL
+ try {
+ parsed = new URL(rawUrl)
+ } catch {
+ throw new Error(`models.dev catalog URL is not a valid URL: ${rawUrl}`)
+ }
+ if (parsed.protocol !== 'https:') {
+ throw new Error(`models.dev catalog URL must be https:// (got "${parsed.protocol}//")`)
+ }
+ const host = parsed.hostname.toLowerCase()
+ const linkLocalOrMetadata =
+ host === 'localhost' ||
+ host === '::1' ||
+ host === '169.254.169.254' ||
+ host.startsWith('169.254.') || // IPv4 link-local range (incl. cloud metadata)
+ host === 'metadata.google.internal' ||
+ host.endsWith('.internal')
+ if (linkLocalOrMetadata) {
+ throw new Error(`models.dev catalog URL host is not an allowed egress target: ${host}`)
+ }
+}
+
+/**
+ * Fetch the LIVE catalog from the resolved URL with all guards, or fall back to
+ * the vendored snapshot on ANY fetch/parse failure (network error, timeout,
+ * non-2xx, redirect, over-cap body, parse/shape failure) — so the sync always
+ * has data. A misconfigured (non-https / disallowed-host) catalog URL is a
+ * DEPLOY error, not a transient failure: it throws BEFORE any fetch rather than
+ * degrading to vendored, so the misconfiguration surfaces instead of hiding.
*/
export async function loadModelsDevCatalog(
opts: { fetchImpl?: FetchLike; now?: () => Date } = {}
): Promise<ModelsDevCatalogResult> {
const fetchImpl = opts.fetchImpl ?? fetch
const now = opts.now ?? (() => new Date())
+ // Egress guard — throws before touching the network on a bad URL.
+ assertSafeCatalogUrl(MODELS_DEV_API_URL)
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
try {
diff --git a/control-api/test/helpers/llmCatalogSyncFakeDb.ts b/control-api/test/helpers/llmCatalogSyncFakeDb.ts
new file mode 100644
index 000000000..c93742d17
--- /dev/null
+++ b/control-api/test/helpers/llmCatalogSyncFakeDb.ts
@@ -0,0 +1,166 @@
+/**
+ * A faithful in-memory model of the `llm_allowed_models` table for the subset of
+ * SQL that `syncDiscoveredModels` (and the ConfigMap materializer's
+ * `listEnabledGroupedByProvider`) actually issue. Unlike a SQL-shape spy, it
+ * APPLIES the mutations so tests can assert the OBSERVABLE ROW STATE (T4) after a
+ * run — which rows ended up `stale`, which stayed `enabled` — rather than probing
+ * intermediate SQL strings.
+ *
+ * The default `npm test` gate has no real Postgres (the *.realPostgres.* suites
+ * are `describe.skip` unless CONTROL_API_REAL_PG_ADMIN_URL is set), so this
+ * models the exact statement semantics the sync depends on. It intentionally
+ * implements ONLY those statements; anything else returns an empty result.
+ */
+import { vi } from 'vitest'
+
+export interface FakeRow {
+ id: string
+ provider: string
+ model: string
+ enabled: boolean
+ source: string
+ stale: boolean
+ context_window_tokens: number | null
+ display_name: string | null
+ vendor: string | null
+}
+
+export interface SeedRow {
+ provider: string
+ model: string
+ enabled?: boolean
+ source?: string
+ stale?: boolean
+ context_window_tokens?: number | null
+ display_name?: string | null
+ vendor?: string | null
+}
+
+export interface FakeDb {
+ connector: { connect: () => Promise<{ query: ReturnType<typeof vi.fn>; release: () => void }> }
+ /** Live view of the table after a run — assert against this. */
+ rows: FakeRow[]
+ /** Row lookup by (provider, model), for terse assertions. */
+ get: (provider: string, model: string) => FakeRow | undefined
+}
+
+let idSeq = 0
+
+export function makeFakeDb(seed: SeedRow[] = []): FakeDb {
+ const rows: FakeRow[] = seed.map(s => ({
+ id: `seed-${(idSeq += 1)}`,
+ provider: s.provider,
+ model: s.model,
+ enabled: s.enabled ?? false,
+ source: s.source ?? 'discovery',
+ stale: s.stale ?? false,
+ context_window_tokens: s.context_window_tokens ?? null,
+ display_name: s.display_name ?? null,
+ vendor: s.vendor ?? null,
+ }))
+
+ const query = vi.fn(async (sql: string, params: unknown[] = []) => {
+ const empty = { rows: [] as unknown[], rowCount: 0 as number | null }
+
+ if (/^\s*(BEGIN|COMMIT|ROLLBACK)\s*$/i.test(sql)) return { rows: [], rowCount: null }
+ if (/pg_advisory_xact_lock/.test(sql)) return { rows: [{ locked: true }], rowCount: 1 }
+
+ // Per-provider existing-rows SELECT (source branch).
+ if (/SELECT id, model, source FROM llm_allowed_models WHERE provider/.test(sql)) {
+ const provider = String(params[0])
+ const out = rows
+ .filter(r => r.provider === provider)
+ .map(r => ({ id: r.id, model: r.model, source: r.source }))
+ return { rows: out, rowCount: out.length }
+ }
+
+ // Materializer read (enabled rows only, stale IGNORED).
+ if (
+ /SELECT provider, model, vendor, display_name, context_window_tokens\s+FROM llm_allowed_models\s+WHERE enabled/.test(
+ sql
+ )
+ ) {
+ const out = rows
+ .filter(r => r.enabled)
+ .sort((a, b) => a.provider.localeCompare(b.provider) || a.model.localeCompare(b.model))
+ .map(r => ({
+ provider: r.provider,
+ model: r.model,
+ vendor: r.vendor,
+ display_name: r.display_name,
+ context_window_tokens: r.context_window_tokens,
+ }))
+ return { rows: out, rowCount: out.length }
+ }
+
+ // NEW row insert — ON CONFLICT (provider, model) DO NOTHING.
+ if (/INSERT INTO llm_allowed_models/.test(sql)) {
+ const [provider, model, ctx, display] = params as [
+ string,
+ string,
+ number | null,
+ string | null,
+ ]
+ if (rows.some(r => r.provider === provider && r.model === model)) return empty
+ rows.push({
+ id: `ins-${(idSeq += 1)}`,
+ provider,
+ model,
+ enabled: false,
+ source: 'discovery',
+ stale: false,
+ context_window_tokens: ctx ?? null,
+ display_name: display ?? null,
+ vendor: null,
+ })
+ return { rows: [], rowCount: 1 }
+ }
+
+ // PRESENT discovery row refresh — last_seen + stale=false + NULL-fill guarded
+ // to disabled rows (COALESCE), never touching `enabled`.
+ if (/UPDATE llm_allowed_models[\s\S]*SET\s+last_seen_at/.test(sql)) {
+ const [id, ctx, display] = params as [string, number | null, string | null]
+ const row = rows.find(r => r.id === id && r.source === 'discovery')
+ if (!row) return empty
+ row.stale = false
+ if (!row.enabled) {
+ row.context_window_tokens = row.context_window_tokens ?? ctx ?? null
+ row.display_name = row.display_name ?? display ?? null
+ }
+ return { rows: [], rowCount: 1 }
+ }
+
+ // VANISHED → stale=true (never delete, never disable).
+ if (/UPDATE llm_allowed_models[\s\S]*SET\s+stale = true/.test(sql)) {
+ const provider = String(params[0])
+ const present = new Set((params[1] as string[]) ?? [])
+ let n = 0
+ for (const r of rows) {
+ if (
+ r.provider === provider &&
+ r.source === 'discovery' &&
+ r.stale === false &&
+ !present.has(r.model)
+ ) {
+ r.stale = true
+ n += 1
+ }
+ }
+ return { rows: [], rowCount: n }
+ }
+
+ // Run summary.
+ if (/INSERT INTO llm_catalog_sync_runs/.test(sql)) {
+ return { rows: [{ ran_at: new Date('2026-08-12T00:00:00Z') }], rowCount: 1 }
+ }
+
+ return empty
+ })
+
+ const connector = { connect: vi.fn(async () => ({ query, release: vi.fn() })) }
+ return {
+ connector,
+ rows,
+ get: (provider, model) => rows.find(r => r.provider === provider && r.model === model),
+ }
+}
diff --git a/control-api/test/helpers/modelsDevFixtures.ts b/control-api/test/helpers/modelsDevFixtures.ts
new file mode 100644
index 000000000..cc302ff17
--- /dev/null
+++ b/control-api/test/helpers/modelsDevFixtures.ts
@@ -0,0 +1,65 @@
+/**
+ * Catalog fixtures for the sync/guard tests, DERIVED FROM THE REAL PRODUCER
+ * (the vendored snapshot of models.dev api.json) by TRIMMING it — never
+ * hand-written payloads (T1). `VENDORED_MODELS_DEV_SNAPSHOT` is the exact shape
+ * the live fetch parses to, so a fixture cut from it cannot encode a shape the
+ * real producer can't emit.
+ */
+import type { LlmProviderId } from '@clerum/llm-providers'
+import { VENDORED_MODELS_DEV_SNAPSHOT } from '../../src/data/modelsDevSnapshot.js'
+import {
+ type ModelsDevCatalogResult,
+ PROVIDER_KEY_MAP,
+ type RawModelsDevCatalog,
+} from '../../src/services/modelsDevClient.js'
+
+/** models.dev provider KEY for one of our provider ids (e.g. 'claude' → 'anthropic'). */
+export function providerKey(id: LlmProviderId): string {
+ return PROVIDER_KEY_MAP[id]
+}
+
+/**
+ * A trim spec per models.dev provider key: a count (first N models from the
+ * snapshot, in snapshot order) or an explicit list of model ids to keep.
+ */
+export type TrimSpec = Record<string, number | string[]>
+
+/**
+ * Cut a catalog down to the given provider keys / models, straight from the real
+ * snapshot. Unknown keys/ids throw so a typo can't silently produce an empty
+ * fixture that passes a test for the wrong reason.
+ */
+export function trimSnapshot(spec: TrimSpec): RawModelsDevCatalog {
+ const out: RawModelsDevCatalog = {}
+ for (const [key, pick] of Object.entries(spec)) {
+ const provider = VENDORED_MODELS_DEV_SNAPSHOT[key]
+ if (!provider) throw new Error(`trimSnapshot: provider key "${key}" not in snapshot`)
+ const allIds = Object.keys(provider.models)
+ const ids =
+ typeof pick === 'number'
+ ? allIds.slice(0, pick)
+ : pick.map(id => {
+ if (!provider.models[id]) {
+ throw new Error(`trimSnapshot: model "${id}" not in snapshot provider "${key}"`)
+ }
+ return id
+ })
+ const models: RawModelsDevCatalog[string]['models'] = {}
+ for (const id of ids) models[id] = provider.models[id]
+ out[key] = { name: provider.name, models }
+ }
+ return out
+}
+
+/** Count of models.dev entries in a catalog (pre-mapping/dedup). */
+export function catalogSize(catalog: RawModelsDevCatalog): number {
+ return Object.values(catalog).reduce((n, p) => n + Object.keys(p.models).length, 0)
+}
+
+/** A `loadCatalog` stub for syncDiscoveredModels' DI seam. */
+export function loadStub(
+ catalog: RawModelsDevCatalog,
+ source: 'live' | 'vendored' = 'live'
+): () => Promise<ModelsDevCatalogResult> {
+ return async () => ({ source, fetchedAt: '2026-08-12T00:00:00.000Z', catalog })
+}
diff --git a/control-api/test/services.llmCatalogSync.guard.test.ts b/control-api/test/services.llmCatalogSync.guard.test.ts
new file mode 100644
index 000000000..cb458a477
--- /dev/null
+++ b/control-api/test/services.llmCatalogSync.guard.test.ts
@@ -0,0 +1,151 @@
+/**
+ * §4.5 sanity guard — three orthogonal layers over the vanished→stale inference.
+ * Fixtures trimmed from the real snapshot (T1); assertions on observable row
+ * state (T4).
+ *
+ * L1 gate — only a LIVE catalog stales (vendored never does).
+ * L2 provider — a provider with <floor live models but existing discovery rows
+ * is NOT stale-marked.
+ * L3 global — a LIVE run whose TOTAL is below the absolute floor suppresses
+ * ALL stale-marking, but inert `enabled=false` inserts proceed.
+ *
+ * Accepted gap (documented): the SURGICAL case (one model of a full provider
+ * vanishes) IS stale-marked — stale is recoverable/non-destructive; the guard
+ * blinds the NOISY failure (mass-stale), not the surgical one.
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { syncDiscoveredModels } from '../src/services/llmCatalogSync.js'
+import { makeFakeDb } from './helpers/llmCatalogSyncFakeDb.js'
+import { loadStub, trimSnapshot } from './helpers/modelsDevFixtures.js'
+
+vi.mock('../src/observability/logger.js', () => ({
+ rootLogger: { child: () => ({ info() {}, warn() {}, error() {}, debug() {} }) },
+}))
+
+describe('§4.5 sanity guard', () => {
+ it('L1 — a VENDORED fallback never stales a vanished discovery row', async () => {
+ const db = makeFakeDb([
+ { provider: 'claude', model: 'claude-legacy-x', source: 'discovery', stale: false },
+ ])
+ const catalog = trimSnapshot({ anthropic: ['claude-opus-4-5'] })
+
+ const res = await syncDiscoveredModels(
+ { loadCatalog: loadStub(catalog, 'vendored'), minPlausibleLiveTotal: 1 },
+ db.connector
+ )
+
+ expect(db.get('claude', 'claude-legacy-x')!.stale).toBe(false)
+ expect(res.staled).toBe(0)
+ })
+
+ it('L2 — a provider that returns 0 live but has discovery rows is NOT mass-staled', async () => {
+ const db = makeFakeDb([
+ // gemini (models.dev key `google`) has TWO discovery rows...
+ { provider: 'gemini', model: 'gemini-old-a', source: 'discovery' },
+ { provider: 'gemini', model: 'gemini-old-b', source: 'discovery' },
+ // ...while claude has a genuinely-vanished row, in a run where anthropic is present.
+ { provider: 'claude', model: 'claude-legacy-x', source: 'discovery' },
+ ])
+ // Catalog carries anthropic (claude present, floor cleared) but NO google key
+ // → gemini comes back with 0 live models.
+ const catalog = trimSnapshot({ anthropic: ['claude-opus-4-5'] })
+
+ const res = await syncDiscoveredModels(
+ { loadCatalog: loadStub(catalog, 'live'), minPlausibleLiveTotal: 1 },
+ db.connector
+ )
+
+ // Per-provider floor protects the 0-live provider entirely.
+ expect(db.get('gemini', 'gemini-old-a')!.stale).toBe(false)
+ expect(db.get('gemini', 'gemini-old-b')!.stale).toBe(false)
+ // But a normally-present provider's vanished row IS staled (proves it is
+ // per-provider, not a global off-switch).
+ expect(db.get('claude', 'claude-legacy-x')!.stale).toBe(true)
+ expect(res.staled).toBe(1)
+ })
+
+ it('L2 with N>0 — an implausibly-LOW provider count (below the floor) is protected', async () => {
+ const db = makeFakeDb([{ provider: 'claude', model: 'claude-legacy-x', source: 'discovery' }])
+ // anthropic returns exactly ONE live model; with providerMinLive=3 that is
+ // below the floor → suspicious → no stale-marking for claude.
+ const catalog = trimSnapshot({ anthropic: ['claude-opus-4-5'] })
+
+ const res = await syncDiscoveredModels(
+ { loadCatalog: loadStub(catalog, 'live'), minPlausibleLiveTotal: 1, providerMinLive: 3 },
+ db.connector
+ )
+
+ expect(db.get('claude', 'claude-legacy-x')!.stale).toBe(false)
+ expect(res.staled).toBe(0)
+ })
+
+ it('L3 — a below-floor global total suppresses ALL stale-marking, but inserts proceed', async () => {
+ const db = makeFakeDb([
+ // A vanished discovery row that WOULD be staled if the guard let the run through.
+ { provider: 'claude', model: 'claude-legacy-x', source: 'discovery' },
+ ])
+ // A tiny LIVE catalog: one NEW model (insert must proceed) — total well below
+ // the injected floor of 9999.
+ const catalog = trimSnapshot({ anthropic: ['claude-opus-4-5'] })
+
+ const res = await syncDiscoveredModels(
+ { loadCatalog: loadStub(catalog, 'live'), minPlausibleLiveTotal: 9999 },
+ db.connector
+ )
+
+ // Stale-marking suppressed for the WHOLE run.
+ expect(db.get('claude', 'claude-legacy-x')!.stale).toBe(false)
+ expect(res.staled).toBe(0)
+ // The inert insert of the new model STILL happened (enabled=false, discovery).
+ const inserted = db.get('claude', 'claude-opus-4-5')
+ expect(inserted).toBeDefined()
+ expect(inserted!.enabled).toBe(false)
+ expect(inserted!.source).toBe('discovery')
+ expect(res.added).toBe(1)
+ })
+
+ it('cold start — empty DB: 0 rows staled (the "100%" case never happens)', async () => {
+ const db = makeFakeDb([]) // no rows at all
+ const catalog = trimSnapshot({ anthropic: ['claude-opus-4-5', 'claude-sonnet-5'] })
+
+ const res = await syncDiscoveredModels(
+ { loadCatalog: loadStub(catalog, 'live'), minPlausibleLiveTotal: 1 },
+ db.connector
+ )
+
+ expect(res.staled).toBe(0)
+ // New rows were inserted, all disabled.
+ expect(res.added).toBe(2)
+ expect(db.rows.every(r => r.enabled === false)).toBe(true)
+ expect(db.rows.every(r => r.stale === false)).toBe(true)
+ })
+
+ it('surgical case (accepted gap) — one model of a full provider vanishes → IS staled', async () => {
+ const db = makeFakeDb([
+ // The vanished one.
+ { provider: 'claude', model: 'claude-legacy-x', source: 'discovery' },
+ // A model that stays listed.
+ { provider: 'claude', model: 'claude-opus-4-5', source: 'discovery' },
+ ])
+ // anthropic comes back with MANY live models (well above any floor), just
+ // without claude-legacy-x.
+ const catalog = trimSnapshot({
+ anthropic: [
+ 'claude-opus-4-5',
+ 'claude-sonnet-4-5',
+ 'claude-haiku-4-5',
+ 'claude-opus-4-6',
+ 'claude-sonnet-5',
+ ],
+ })
+
+ const res = await syncDiscoveredModels(
+ { loadCatalog: loadStub(catalog, 'live'), minPlausibleLiveTotal: 1, providerMinLive: 0 },
+ db.connector
+ )
+
+ expect(db.get('claude', 'claude-legacy-x')!.stale).toBe(true)
+ expect(db.get('claude', 'claude-opus-4-5')!.stale).toBe(false)
+ expect(res.staled).toBe(1)
+ })
+})
diff --git a/control-api/test/services.llmCatalogSync.invariants.test.ts b/control-api/test/services.llmCatalogSync.invariants.test.ts
new file mode 100644
index 000000000..7badc55e7
--- /dev/null
+++ b/control-api/test/services.llmCatalogSync.invariants.test.ts
@@ -0,0 +1,90 @@
+/**
+ * Load-bearing invariants of the catalog sync that the Fase-4 cron MUST NOT
+ * break (spec 09 §2.2 / §4.5). Written FIRST (T5) and asserted against the
+ * EXISTING sync — they encode behavior we are preserving, not adding.
+ *
+ * Fixtures are trimmed from the real vendored snapshot (T1); assertions are on
+ * OBSERVABLE ROW / ConfigMap state (T4), never on intermediate SQL.
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { listEnabledGroupedByProvider } from '../src/services/llmAllowedModels.js'
+import { buildConfigMapData } from '../src/services/llmAllowedModelsConfigMap.js'
+import { syncDiscoveredModels } from '../src/services/llmCatalogSync.js'
+import { makeFakeDb } from './helpers/llmCatalogSyncFakeDb.js'
+import { loadStub, trimSnapshot } from './helpers/modelsDevFixtures.js'
+
+vi.mock('../src/observability/logger.js', () => ({
+ rootLogger: { child: () => ({ info() {}, warn() {}, error() {}, debug() {} }) },
+}))
+
+// A low global floor so these invariant runs never trip the layer-3 guard —
+// each invariant is about the stale/enabled mechanics, not the guard.
+const LOW_FLOOR = { minPlausibleLiveTotal: 1 }
+
+describe('catalog sync — load-bearing invariants (Fase 4)', () => {
+ it('(i) NEVER disables: a vanished model keeps `enabled`, only `stale` flips', async () => {
+ const db = makeFakeDb([
+ // An ENABLED discovery model that the catalog still lists → stays enabled, not stale.
+ { provider: 'claude', model: 'claude-opus-4-5', source: 'discovery', enabled: true },
+ // An ENABLED discovery model that VANISHES → must keep enabled, only stale flips.
+ { provider: 'claude', model: 'claude-legacy-x', source: 'discovery', enabled: true },
+ // A disabled discovery model that vanishes → stale flips too.
+ { provider: 'claude', model: 'claude-legacy-y', source: 'discovery', enabled: false },
+ ])
+ const catalog = trimSnapshot({ anthropic: ['claude-opus-4-5'] })
+
+ await syncDiscoveredModels(
+ { loadCatalog: loadStub(catalog, 'live'), ...LOW_FLOOR },
+ db.connector
+ )
+
+ // enabled is UNTOUCHED on every row.
+ expect(db.get('claude', 'claude-opus-4-5')!.enabled).toBe(true)
+ expect(db.get('claude', 'claude-legacy-x')!.enabled).toBe(true)
+ expect(db.get('claude', 'claude-legacy-y')!.enabled).toBe(false)
+ // Only vanished rows flipped stale; the still-listed one did not.
+ expect(db.get('claude', 'claude-opus-4-5')!.stale).toBe(false)
+ expect(db.get('claude', 'claude-legacy-x')!.stale).toBe(true)
+ expect(db.get('claude', 'claude-legacy-y')!.stale).toBe(true)
+ })
+
+ it('(ii) stale is auto-healing: a re-listed model flips stale back to false', async () => {
+ const db = makeFakeDb([
+ { provider: 'claude', model: 'claude-opus-4-5', source: 'discovery', stale: true },
+ ])
+ const catalog = trimSnapshot({ anthropic: ['claude-opus-4-5'] })
+
+ await syncDiscoveredModels(
+ { loadCatalog: loadStub(catalog, 'live'), ...LOW_FLOOR },
+ db.connector
+ )
+
+ expect(db.get('claude', 'claude-opus-4-5')!.stale).toBe(false)
+ })
+
+ it('(iii) a stale+enabled row is STILL materialized into the ConfigMap (stale ignored)', async () => {
+ const db = makeFakeDb([
+ {
+ provider: 'claude',
+ model: 'claude-opus-4-5',
+ source: 'discovery',
+ enabled: true,
+ stale: true,
+ display_name: 'Claude Opus 4.5',
+ context_window_tokens: 200000,
+ },
+ // A disabled row must NOT appear in the CM regardless of stale.
+ { provider: 'claude', model: 'claude-sonnet-5', source: 'discovery', enabled: false },
+ ])
+
+ // Drive the REAL materializer read against the fake db, then build the CM.
+ const client = await db.connector.connect()
+ const grouped = await listEnabledGroupedByProvider({ query: client.query })
+ const { data } = buildConfigMapData(grouped)
+
+ expect(data.claude).toBeDefined()
+ const models = (JSON.parse(data.claude) as Array<{ model: string }>).map(m => m.model)
+ expect(models).toContain('claude-opus-4-5') // stale + enabled → present
+ expect(models).not.toContain('claude-sonnet-5') // disabled → absent
+ })
+})
diff --git a/control-api/test/services.llmCatalogSync.test.ts b/control-api/test/services.llmCatalogSync.test.ts
index 96977d611..b432a536e 100644
--- a/control-api/test/services.llmCatalogSync.test.ts
+++ b/control-api/test/services.llmCatalogSync.test.ts
@@ -122,7 +122,13 @@ describe('syncDiscoveredModels — source-guarded reconciliation', () => {
claude: [{ id: 'gone', model: 'claude-legacy', source: 'discovery' }],
})
const catalog = catalogWith({ 'claude-opus-4-5': { id: 'claude-opus-4-5' } })
- const res = await syncDiscoveredModels({ loadCatalog: loadStub(catalog, 'live') }, connector)
+ // This test isolates the vanished→stale reconciliation, not the §4.5
+ // plausibility floor. The tiny 1-model catalog would otherwise trip the
+ // global floor (default 100), so lower it here to exercise stale-marking.
+ const res = await syncDiscoveredModels(
+ { loadCatalog: loadStub(catalog, 'live'), minPlausibleLiveTotal: 1 },
+ connector
+ )
const staleUpdates = CALL_FOR(calls, /SET stale = true/)
// One stale UPDATE per provider is issued; assert none delete / disable.
diff --git a/control-api/test/services.llmCatalogSyncCron.test.ts b/control-api/test/services.llmCatalogSyncCron.test.ts
new file mode 100644
index 000000000..8d4169d9f
--- /dev/null
+++ b/control-api/test/services.llmCatalogSyncCron.test.ts
@@ -0,0 +1,252 @@
+/**
+ * LLM catalog sync cron (Fase 4 §9): the tick calls syncDiscoveredModels under a
+ * SESSION advisory lock, deduping across replicas, releasing the lock in every
+ * path, and never propagating errors. The default-OFF flag is asserted at the
+ * config layer (the cron itself is flag-agnostic; main.ts gates on the flag).
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { CatalogSyncResult } from '../src/services/llmCatalogSync.js'
+import {
+ runLlmCatalogSyncTick,
+ startLlmCatalogSyncCron,
+ stopLlmCatalogSyncCron,
+} from '../src/services/llmCatalogSyncCron.js'
+
+vi.mock('../src/observability/logger.js', () => ({
+ rootLogger: { child: () => ({ info() {}, warn() {}, error() {}, debug() {} }) },
+}))
+
+const OK: CatalogSyncResult = {
+ source: 'live',
+ fetchedAt: '2026-08-12T00:00:00.000Z',
+ ranAt: '2026-08-12T00:00:00.000Z',
+ added: 0,
+ updated: 0,
+ staled: 0,
+}
+
+/**
+ * A fake pool sharing a single advisory-lock state across every client it hands
+ * out — the real cross-replica contract. `calls` records the lock lifecycle.
+ */
+function makeLockPool(
+ shared: { held: boolean },
+ calls: string[],
+ opts: { failUnlock?: boolean } = {}
+) {
+ const releaseArgs: Array<Error | boolean | undefined> = []
+ const connector = {
+ releaseArgs,
+ connect: vi.fn(async () => {
+ const query = vi.fn(async (sql: string) => {
+ if (/pg_try_advisory_lock/.test(sql)) {
+ const acquired = !shared.held
+ if (acquired) shared.held = true
+ calls.push(acquired ? 'acquire:ok' : 'acquire:skip')
+ return { rows: [{ acquired }], rowCount: 1 }
+ }
+ if (/pg_advisory_unlock/.test(sql)) {
+ // Simulate a broken unlock: the SESSION lock is NOT freed here.
+ if (opts.failUnlock) {
+ calls.push('unlock:throw')
+ throw new Error('unlock failed')
+ }
+ shared.held = false
+ calls.push('unlock')
+ return { rows: [{ pg_advisory_unlock: true }], rowCount: 1 }
+ }
+ return { rows: [], rowCount: 0 }
+ })
+ const release = vi.fn((destroy?: Error | boolean) => {
+ releaseArgs.push(destroy)
+ if (destroy) {
+ // Destroying the connection ends the session → the lock is freed even
+ // though the explicit unlock failed.
+ shared.held = false
+ calls.push('release:destroy')
+ } else {
+ calls.push('release')
+ }
+ })
+ return { query, release }
+ }),
+ }
+ return connector
+}
+
+afterEach(() => {
+ stopLlmCatalogSyncCron()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+describe('runLlmCatalogSyncTick', () => {
+ it('acquires the lock, runs the sync, then unlocks and releases — in order', async () => {
+ const calls: string[] = []
+ const connector = makeLockPool({ held: false }, calls)
+ const sync = vi.fn(async () => OK)
+
+ const res = await runLlmCatalogSyncTick({ connector, sync })
+
+ expect(sync).toHaveBeenCalledTimes(1)
+ expect(res).toEqual({ skippedLock: false, ran: true, errored: false })
+ // Full session-lock cycle: acquire → (work) → unlock → release.
+ expect(calls).toEqual(['acquire:ok', 'unlock', 'release'])
+ })
+
+ it('skips the tick when the lock is already held (no sync, no unlock, still releases)', async () => {
+ const calls: string[] = []
+ const connector = makeLockPool({ held: true }, calls) // lock already taken
+ const sync = vi.fn(async () => OK)
+
+ const res = await runLlmCatalogSyncTick({ connector, sync })
+
+ expect(sync).not.toHaveBeenCalled()
+ expect(res.skippedLock).toBe(true)
+ // We only unlock what we acquired: skip → no unlock, but the client is released.
+ expect(calls).toEqual(['acquire:skip', 'release'])
+ })
+
+ it('never propagates a sync error; still unlocks and releases', async () => {
+ const calls: string[] = []
+ const connector = makeLockPool({ held: false }, calls)
+ const sync = vi.fn(async () => {
+ throw new Error('boom')
+ })
+
+ const res = await runLlmCatalogSyncTick({ connector, sync })
+
+ expect(res.errored).toBe(true)
+ expect(res.ran).toBe(false)
+ // Lock released despite the failure — no wedged lock.
+ expect(calls).toEqual(['acquire:ok', 'unlock', 'release'])
+ })
+
+ it('DESTROYS the connection (not a plain release) when pg_advisory_unlock throws', async () => {
+ const calls: string[] = []
+ const shared = { held: false }
+ const connector = makeLockPool(shared, calls, { failUnlock: true })
+ const sync = vi.fn(async () => OK)
+
+ const res = await runLlmCatalogSyncTick({ connector, sync })
+
+ // The tick still ran and did not propagate; the unlock threw and was caught.
+ expect(res).toEqual({ skippedLock: false, ran: true, errored: false })
+ // No neutral pool-release on this path — the connection is DESTROYED with the
+ // error so the session (and thus the session lock) actually ends. Exactly one
+ // release call, and it carries the error (no double-release, no live-conn reuse).
+ expect(connector.releaseArgs).toHaveLength(1)
+ expect(connector.releaseArgs[0]).toBeInstanceOf(Error)
+ expect(calls).toEqual(['acquire:ok', 'unlock:throw', 'release:destroy'])
+ // Observable invariant: no lock left hanging on the (now destroyed) connection.
+ expect(shared.held).toBe(false)
+ })
+
+ it('does not propagate when connector.connect() throws (no hung state, no release)', async () => {
+ const connectErr = new Error('pool exhausted')
+ const connector = { connect: vi.fn(async () => Promise.reject(connectErr)) }
+ const sync = vi.fn(async () => OK)
+
+ const res = await runLlmCatalogSyncTick({ connector, sync })
+
+ // Caught and reported, never thrown; sync never reached; nothing to release.
+ expect(res).toEqual({ skippedLock: false, ran: false, errored: true })
+ expect(sync).not.toHaveBeenCalled()
+ expect(connector.connect).toHaveBeenCalledTimes(1)
+ })
+
+ it('two replicas do NOT run the tick concurrently (session advisory lock)', async () => {
+ const calls: string[] = []
+ const shared = { held: false }
+ const connector = makeLockPool(shared, calls)
+
+ // Replica A holds the lock while its sync is in flight (deferred).
+ let releaseA: () => void = () => {}
+ const syncA = vi.fn(
+ () =>
+ new Promise<CatalogSyncResult>(resolve => {
+ releaseA = () => resolve(OK)
+ })
+ )
+ const syncB = vi.fn(async () => OK)
+
+ const tickA = runLlmCatalogSyncTick({ connector, sync: syncA })
+ // Let A acquire the lock before B tries.
+ await vi.waitFor(() => expect(shared.held).toBe(true))
+
+ const resB = await runLlmCatalogSyncTick({ connector, sync: syncB })
+ expect(resB.skippedLock).toBe(true)
+ expect(syncB).not.toHaveBeenCalled()
+
+ releaseA()
+ const resA = await tickA
+ expect(resA.ran).toBe(true)
+ expect(syncA).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('startLlmCatalogSyncCron', () => {
+ it('unref()s the interval so it never holds the process open', () => {
+ const unref = vi.fn()
+ const spy = vi
+ .spyOn(global, 'setInterval')
+ .mockReturnValue({ unref } as unknown as ReturnType<typeof setInterval>)
+
+ startLlmCatalogSyncCron(
+ { connector: makeLockPool({ held: false }, []), sync: async () => OK },
+ 1000
+ )
+ expect(unref).toHaveBeenCalledTimes(1)
+ spy.mockRestore()
+ })
+
+ it('fires the tick on the interval and stops firing after stop', async () => {
+ vi.useFakeTimers()
+ const calls: string[] = []
+ const connector = makeLockPool({ held: false }, calls)
+ const sync = vi.fn(async () => OK)
+
+ startLlmCatalogSyncCron({ connector, sync }, 1000)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(sync).toHaveBeenCalledTimes(1)
+
+ stopLlmCatalogSyncCron()
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(sync).toHaveBeenCalledTimes(1) // no further ticks after stop
+ })
+
+ it('is idempotent — a second start does not create a second interval', () => {
+ const spy = vi.spyOn(global, 'setInterval')
+ const deps = { connector: makeLockPool({ held: false }, []), sync: async () => OK }
+ startLlmCatalogSyncCron(deps, 1000)
+ startLlmCatalogSyncCron(deps, 1000)
+ expect(spy).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('config flag — default OFF, strict === "true"', () => {
+ const ENV = 'LLM_CATALOG_SYNC_CRON_ENABLED'
+ afterEach(() => {
+ delete process.env[ENV]
+ vi.resetModules()
+ })
+
+ async function loadFlag(value?: string): Promise<boolean> {
+ vi.resetModules()
+ if (value === undefined) delete process.env[ENV]
+ else process.env[ENV] = value
+ const { config } = await import('../src/config.js')
+ return config.llmCatalogSyncCronEnabled
+ }
+
+ it('is false when unset', async () => {
+ expect(await loadFlag(undefined)).toBe(false)
+ })
+ it('is true only for exactly "true"', async () => {
+ expect(await loadFlag('true')).toBe(true)
+ })
+ it('is false for the default-on idiom values ("1", "false")', async () => {
+ expect(await loadFlag('1')).toBe(false)
+ expect(await loadFlag('false')).toBe(false)
+ })
+})
diff --git a/control-api/test/services.modelsDevClient.urlGuard.test.ts b/control-api/test/services.modelsDevClient.urlGuard.test.ts
new file mode 100644
index 000000000..5d29cdaa5
--- /dev/null
+++ b/control-api/test/services.modelsDevClient.urlGuard.test.ts
@@ -0,0 +1,60 @@
+/**
+ * Egress guard for the (env-overridable) models.dev catalog URL: the resolved
+ * URL must be https:// and not a link-local/metadata host, validated BEFORE any
+ * fetch. `MODELS_DEV_API_URL` is resolved at module import, so each case sets the
+ * env and re-imports fresh.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+const ENV = 'MODELS_DEV_API_URL'
+
+afterEach(() => {
+ delete process.env[ENV]
+ vi.resetModules()
+})
+
+async function loadWith(url: string | undefined) {
+ vi.resetModules()
+ if (url === undefined) delete process.env[ENV]
+ else process.env[ENV] = url
+ return import('../src/services/modelsDevClient.js')
+}
+
+describe('models.dev catalog URL egress guard', () => {
+ it('rejects an http:// override and never fetches', async () => {
+ const { loadModelsDevCatalog } = await loadWith('http://models.dev/api.json')
+ const fetchImpl = vi.fn()
+ await expect(loadModelsDevCatalog({ fetchImpl: fetchImpl as never })).rejects.toThrow(
+ /https:\/\//
+ )
+ expect(fetchImpl).not.toHaveBeenCalled()
+ })
+
+ it('rejects a link-local / cloud-metadata host and never fetches', async () => {
+ const { loadModelsDevCatalog } = await loadWith('https://169.254.169.254/latest/meta-data')
+ const fetchImpl = vi.fn()
+ await expect(loadModelsDevCatalog({ fetchImpl: fetchImpl as never })).rejects.toThrow(
+ /egress|host/i
+ )
+ expect(fetchImpl).not.toHaveBeenCalled()
+ })
+
+ it('rejects a `.internal` cluster host and never fetches', async () => {
+ const { loadModelsDevCatalog } = await loadWith('https://catalog.svc.cluster.internal/api.json')
+ const fetchImpl = vi.fn()
+ await expect(loadModelsDevCatalog({ fetchImpl: fetchImpl as never })).rejects.toThrow()
+ expect(fetchImpl).not.toHaveBeenCalled()
+ })
+
+ it('passes the guard for the default https host (fetch IS attempted)', async () => {
+ const { loadModelsDevCatalog } = await loadWith(undefined) // default https://models.dev/api.json
+ // A throwing fetch proves the guard let us THROUGH to the network; the loader
+ // then degrades to the vendored snapshot (its documented fetch-failure path).
+ const fetchImpl = vi.fn(async () => {
+ throw new Error('network down')
+ })
+ const res = await loadModelsDevCatalog({ fetchImpl: fetchImpl as never })
+ expect(fetchImpl).toHaveBeenCalledTimes(1)
+ expect(res.source).toBe('vendored')
+ })
+})