Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): validate the reconcile interval, quieten expected cron states
Jose Ramirezc33ec2c84017
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 43b8f99e0..1460a7f48 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.409",+ "version": "0.1.410","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.409",+ "version": "0.1.410","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 ea98bcf7c..571d4ba58 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.409",+ "version": "0.1.410","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.tsindex 240f0d6d2..15dd35298 100644--- a/control-api/src/config.ts+++ b/control-api/src/config.ts@@ -279,6 +279,24 @@ function boundedIntegerFromEnv(name: string, defaultValue: number, maxValue: numreturn value}+/**+ * A background-loop interval: a positive integer of milliseconds that must also clear a+ * floor.+ *+ * The floor is the part `positiveIntegerFromEnv` cannot express. `1` parses perfectly and+ * still reconciles a thousand times a second, so for a value handed straight to+ * `setInterval` "positive" is not the same as "sane". Refused at boot rather than clamped,+ * for the same reason every other invalid value here is refused: a silently corrected+ * interval leaves the operator's setting and the running behaviour disagreeing forever.+ */+function intervalMsFromEnv(name: string, defaultValue: number, minValue: number): number {+ const value = positiveIntegerFromEnv(name, defaultValue)+ if (value < minValue) {+ throw new Error(`${name} must be an integer >= ${minValue} (milliseconds)`)+ }+ return value+}+// Also the target namespace for the allowlist ConfigMap (cross-service contract):// mcp-host + WRC read `clerum-llm-allowed-models` from here — see// services/llmAllowedModelsConfigMap.ts.@@ -288,6 +306,7 @@ const SANDBOX_NAMESPACE = process.env.CONTROL_API_SANDBOX_NAMESPACE || 'sandbox-const SANDBOX_UI_NAMESPACE = process.env.CONTROL_API_SANDBOX_UI_NAMESPACE || 'sandbox-ui'const DEFAULT_MCP_HOST_JWT_MAX_HOST_REFS = 32const DEFAULT_MCP_HOST_JWT_MAX_HOST_REF_LENGTH = 63 + 1 + 253+const REGISTRY_PULL_SECRET_RECONCILE_MIN_INTERVAL_MS = 10_000const WORKFLOW_MAX_WORKLOADS_PER_RECIPE_CEILING = 25const WORKFLOW_UI_EGRESS_INTERNAL_MAX_ITEMS_CEILING = 25const WORKFLOW_MAX_STEPS_CEILING = 100@@ -606,8 +625,15 @@ export const config: Config = {// already. Installs still provision synchronously, so this interval only bounds how long// a CRD created OUTSIDE control-api waits. Coarse (10 min) on purpose — each tick is a// few reads and no mint once the cluster is healthy.- registryPullSecretReconcileIntervalMs: Number(- process.env.REGISTRY_PULL_SECRET_RECONCILE_INTERVAL_MS || 600_000+ //+ // Validated, not merely parsed: this value goes straight into `setInterval`, and each tick+ // costs a Postgres advisory-lock transaction plus a Secret read per platform namespace. A+ // 10s floor is still two orders of magnitude below the default and far above anything that+ // could pass for a hot loop.+ registryPullSecretReconcileIntervalMs: intervalMsFromEnv(+ 'REGISTRY_PULL_SECRET_RECONCILE_INTERVAL_MS',+ 600_000,+ REGISTRY_PULL_SECRET_RECONCILE_MIN_INTERVAL_MS),// Danger-zone reservation TTL (§9.8a: ~2-3× the rollup lag, ~5 min). Short// enough that a hung reservation auto-frees; long enough that real spend hasdiff --git a/control-api/src/services/registryPullSecretReconcileCron.ts b/control-api/src/services/registryPullSecretReconcileCron.tsindex a937a6e25..436f48928 100644--- a/control-api/src/services/registryPullSecretReconcileCron.ts+++ b/control-api/src/services/registryPullSecretReconcileCron.ts@@ -19,6 +19,11 @@* distinguishes the two — legitimate no-ops return `skipped`, everything else throws — so* this file's only job is to swallow the throw and try again later.*+ * The LEVEL carries that distinction, because "swallow it" and "hide it" are not the same+ * thing. A known precondition on an unconnected cluster logs below warn; anything+ * unexpected, or a known precondition that has held for many consecutive ticks and is+ * therefore no longer plausibly transient, warns. See EXPECTED_PRECONDITION_REASONS.+ ** Serialization across replicas is handled inside the service by a per-org advisory lock.* That lock is what makes a PERIODIC loop safe at all: without it, two pods on a timer do* not race occasionally, they fight continuously — each pod's mint revokes the other's key@@ -33,6 +38,31 @@ import {const log = rootLogger.child({ service: 'registry_pull_secret_reconcile' })+/**+ * Precondition failures that are a NORMAL state for a cluster, not a fault: the registry+ * connect flow has not been completed, or the registry has not bound this deployment to an+ * org yet. Both resolve themselves the moment an operator finishes the flow.+ *+ * They are the two reasons `ensureInner` raises before it touches anything, and this loop+ * runs on every cluster whether or not anyone has asked it to — so warning on them means 144+ * warnings a day (at the 10-minute default) on a cluster where nothing is wrong, which+ * teaches operators to ignore this logger.+ */+const EXPECTED_PRECONDITION_REASONS: ReadonlySet<string> = new Set([+ 'registry_not_connected',+ 'org_unresolved',+])++/**+ * How many consecutive ticks an expected precondition may hold before it stops being+ * "expected" and warns. ~1h at the default interval — long enough to cover a connect flow in+ * progress, short enough that a cluster genuinely stuck this way is findable by an operator+ * grepping for warnings rather than silently unable to install private plugins.+ */+const PRECONDITION_WARN_AFTER_TICKS = 6++let consecutiveExpectedFailures = 0+/*** Run one reconcile pass. Never throws — a failure here is a logged warning, because the* cluster may legitimately not be ready to provision yet (no connect flow completed, no@@ -60,18 +90,40 @@ export async function reconcileRegistryPullSecret(gateway: K8sGateway): Promise<'provisioned the registry pull secret outside an install')}+ // A completed pass means whatever was blocking is gone. The streak has to reset with it,+ // or one bad hour makes every later blip look persistent.+ consecutiveExpectedFailures = 0return true} catch (err) {- // Expected while a cluster is unconnected or has no org bound yet. Warn, do not throw:- // this loop must not turn a normal pre-connect state into recurring errors.- log.warn(- {- event: 'registry_pull_secret_reconcile_skipped',- reason: (err as { reason?: string })?.reason,- err: err instanceof Error ? err.message : String(err),- },- 'registry pull secret reconcile did not complete; will retry on the next tick'- )+ // Never thrown, always logged — but not always at the same level. The level is the whole+ // difference between "this cluster has not been connected yet", which is normal and+ // recurs on a timer, and "something is wrong", which an operator has to find.+ const reason = (err as { reason?: string })?.reason+ const expected = reason !== undefined && EXPECTED_PRECONDITION_REASONS.has(reason)+ consecutiveExpectedFailures = expected ? consecutiveExpectedFailures + 1 : 0+ const persistent = consecutiveExpectedFailures >= PRECONDITION_WARN_AFTER_TICKS+ const payload = {+ event: 'registry_pull_secret_reconcile_skipped',+ reason,+ err: err instanceof Error ? err.message : String(err),+ ...(expected && { consecutiveTicks: consecutiveExpectedFailures }),+ }+ if (expected && !persistent) {+ log.debug(+ payload,+ 'registry pull secret reconcile skipped a known precondition; will retry on the next tick'+ )+ } else if (expected) {+ log.warn(+ payload,+ 'registry pull secret reconcile has been blocked on the same precondition for many ticks; private plugin installs cannot provision their pull credential until it clears'+ )+ } else {+ log.warn(+ payload,+ 'registry pull secret reconcile did not complete; will retry on the next tick'+ )+ }return false}}@@ -95,6 +147,9 @@ export function startRegistryPullSecretReconcileCron(}export function stopRegistryPullSecretReconcileCron(): void {+ // Before the early return: a stopped loop has no history, so a later start must not+ // inherit a stale streak and warn on its first tick.+ consecutiveExpectedFailures = 0if (!intervalHandle) returnclearInterval(intervalHandle)intervalHandle = nulldiff --git a/control-api/test/config.registryPullSecretReconcile.test.ts b/control-api/test/config.registryPullSecretReconcile.test.tsnew file mode 100644index 000000000..89ca7a9c1--- /dev/null+++ b/control-api/test/config.registryPullSecretReconcile.test.ts@@ -0,0 +1,49 @@+/**+ * The reconcile interval feeds `setInterval` directly, so an unvalidated value is not a+ * cosmetic problem: `0` and any sub-millisecond fraction turn a coarse background loop into+ * a hot one (each tick is three Secret reads plus a Postgres advisory-lock transaction), a+ * negative or `NaN` value produces a timer Node cannot honour, and both are silent.+ */+import { afterEach, describe, expect, it, vi } from 'vitest'++const KEY = 'REGISTRY_PULL_SECRET_RECONCILE_INTERVAL_MS'++async function loadConfigWith(value?: string) {+ const original = process.env[KEY]+ delete process.env[KEY]+ if (value !== undefined) process.env[KEY] = value+ vi.resetModules()+ try {+ const mod = await import('../src/config.js')+ return mod.config+ } finally {+ if (original === undefined) delete process.env[KEY]+ else process.env[KEY] = original+ }+}++describe('control-api registry pull secret reconcile interval config', () => {+ afterEach(() => {+ vi.resetModules()+ })++ it('defaults to 10 minutes when unset', async () => {+ const config = await loadConfigWith()+ expect(config.registryPullSecretReconcileIntervalMs).toBe(600_000)+ })++ it('accepts a positive integer override at or above the floor', async () => {+ const config = await loadConfigWith('60000')+ expect(config.registryPullSecretReconcileIntervalMs).toBe(60_000)+ })++ it.each(['0', '-1', '1.5', 'abc'])('rejects %s', async value => {+ await expect(loadConfigWith(value)).rejects.toThrow(new RegExp(KEY))+ })++ // A positive integer is not sufficient on its own: `1` parses fine and still reconciles a+ // thousand times a second. The floor is what actually rules out the hot loop.+ it('rejects a positive value below the floor', async () => {+ await expect(loadConfigWith('1')).rejects.toThrow(new RegExp(KEY))+ })+})diff --git a/control-api/test/registryPullSecretReconcileCron.test.ts b/control-api/test/registryPullSecretReconcileCron.test.tsindex 491243cee..6310c88b4 100644--- a/control-api/test/registryPullSecretReconcileCron.test.ts+++ b/control-api/test/registryPullSecretReconcileCron.test.ts@@ -21,6 +21,17 @@ vi.mock('../src/services/registryPullSecretService.js', () => ({platformWorkloadNamespaces: () => ['mcp-server', 'sandbox-recipes', 'sandbox-ui'],}))+// The log LEVEL is part of this loop's contract, not decoration: it runs unprompted on every+// cluster, so a level chosen per-state is what keeps a normal pre-connect cluster from+// looking broken while a genuinely stuck one stays findable.+const log = vi.hoisted(() => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+}))+vi.mock('../src/observability/logger.js', () => ({ rootLogger: { child: () => log } }))+const gateway = {} as K8sGatewaybeforeEach(() => {@@ -81,6 +92,67 @@ describe('reconcileRegistryPullSecret', () => {})})+/**+ * Level selection. `registry_not_connected` and `org_unresolved` are states this loop's own+ * comment calls expected — a cluster that has not finished the connect flow is not+ * misconfigured, it is early — and at the default interval a warn per tick is 144 warnings a+ * day that mean nothing. But "expected" stops being true if it never resolves, so the signal+ * has to survive somewhere an operator will look.+ */+describe('reconcileRegistryPullSecret — log level', () => {+ const notConnected = () =>+ Object.assign(new Error('registry connection is not active'), {+ reason: 'registry_not_connected',+ })++ it.each(['registry_not_connected', 'org_unresolved'])(+ 'logs %s below warn while it is still a plausible startup state',+ async reason => {+ ensureRegistryPullSecrets.mockRejectedValue(Object.assign(new Error('nope'), { reason }))+ await expect(reconcileRegistryPullSecret(gateway)).resolves.toBe(false)+ expect(log.warn).not.toHaveBeenCalled()+ expect(log.debug).toHaveBeenCalled()+ }+ )++ // Not "quiet forever": a precondition that has held for this many consecutive ticks is a+ // cluster somebody has to look at, and the operator debugging it greps for warnings.+ it('escalates to warn once a known precondition persists', async () => {+ ensureRegistryPullSecrets.mockRejectedValue(notConnected())+ for (let i = 0; i < 5; i += 1) {+ await reconcileRegistryPullSecret(gateway)+ }+ expect(log.warn).not.toHaveBeenCalled()++ await reconcileRegistryPullSecret(gateway)+ expect(log.warn).toHaveBeenCalledTimes(1)+ expect(log.warn.mock.calls[0][0]).toMatchObject({ reason: 'registry_not_connected' })+ })++ // An unexpected failure has no "this is normal at first" story, so it warns on tick one.+ it('warns immediately on an unexpected failure', async () => {+ ensureRegistryPullSecrets.mockRejectedValue(new Error('boom'))+ await expect(reconcileRegistryPullSecret(gateway)).resolves.toBe(false)+ expect(log.warn).toHaveBeenCalledTimes(1)+ })++ // A cluster that connects mid-run is back to normal, and the count that would escalate the+ // NEXT transient precondition has to go with it — otherwise one bad hour makes every later+ // blip look persistent.+ it('resets the escalation count after a pass succeeds', async () => {+ ensureRegistryPullSecrets.mockRejectedValue(notConnected())+ for (let i = 0; i < 5; i += 1) {+ await reconcileRegistryPullSecret(gateway)+ }+ ensureRegistryPullSecrets.mockResolvedValue(new Map())+ await reconcileRegistryPullSecret(gateway)++ ensureRegistryPullSecrets.mockRejectedValue(notConnected())+ await reconcileRegistryPullSecret(gateway)+ expect(log.warn).not.toHaveBeenCalled()+ })+})+describe('startRegistryPullSecretReconcileCron', () => {it('runs on the interval and is idempotent to start', async () => {vi.useFakeTimers()