Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): dedupe host model-reference enumeration across impact and tolerance (R1-M3)
Diego Zacarias52e187adef2c
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 72a8a89e6..edf9f4388 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.448",+ "version": "0.1.449","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.448",+ "version": "0.1.449","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 411da771b..f80c3a0e7 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.448",+ "version": "0.1.449","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/hostModelReferences.ts b/control-api/src/routes/admin/hostModelReferences.tsnew file mode 100644index 000000000..173319f23--- /dev/null+++ b/control-api/src/routes/admin/hostModelReferences.ts@@ -0,0 +1,89 @@+/**+ * The SINGLE definition of "from which locations of a Host spec does a reference+ * to a `(provider, model)` pair come, and in which role" (regla D4).+ *+ * A Host references a `(provider, model)` pair iff it appears in one of THREE+ * spec locations:+ * 1. `spec.model` → role `primary` (the Host default)+ * 2. `spec.allowedModels[]` → role `allowedModels` (per-Host subset)+ * 3. `spec.llmPolicy.fallbacks[]` → role `fallback` (fallback policy)+ *+ * This business rule was implemented TWICE — the live impact enumeration+ * (`hostRolesReferencing` in services/llmModelImpact.ts, feeding the destructive+ * allowlist-mutation gate) and the stored-reference detection (`storedRoleSets`+ * in routes/admin/hostSpecValidation.ts, feeding no-worsening tolerance). Both+ * copies were consistent, but a future 4th location added to only one copy would+ * make the impact gate SILENTLY under-report while tolerance still saw it. This+ * module collapses the enumeration to one place: a 4th location is a one-line+ * change here that both callers inherit.+ *+ * Purely structural and defensive: any malformed/partial entry is skipped, never+ * throws. Normalization is `.trim()` on both provider and model, both required+ * non-empty, keyed via `offeredKey` (the same NUL-separated key the write-gate+ * uses, so a model id containing spaces can never collide with a distinct pair) —+ * IDENTICAL to what both callers did inline before the extraction.+ *+ * SCOPE (what this module does NOT do): it emits every reference, unfiltered and+ * un-deduped, in spec order (primary, then allowedModels[] in array order, then+ * fallbacks[] in array order). Target-filtering + role dedup (the impact caller)+ * and primary/any bucketing (the tolerance caller) are each caller's own concern,+ * applied on top of this common enumeration — no decision logic lives here.+ */+import { isPlainObject } from '../../utils/isPlainObject.js'+import { offeredKey } from './modelAllowlistTolerance.js'++/** Which Host spec location referenced a `(provider, model)` pair. */+export type HostModelRole = 'primary' | 'allowedModels' | 'fallback'++/** One `(provider, model)` reference emitted by a Host spec, tagged by its role. */+export interface HostModelReferenceEntry {+ /** `offeredKey(provider, model)` — the NUL-separated pair key. */+ key: string+ /** The spec location this reference came from. */+ role: HostModelRole+}++/**+ * Enumerate every `(provider, model)` reference a Host spec makes, tagged by the+ * role (location) it came from. Emitted in spec order — `primary` first, then+ * each `spec.allowedModels[]` entry, then each `spec.llmPolicy.fallbacks[]` entry+ * — with NO filtering and NO deduplication (a pair present in several locations+ * yields one entry per location). A non-object spec, or a spec whose locations+ * are absent/empty/malformed, yields the entries it can and skips the rest.+ */+export function enumerateHostModelReferences(spec: unknown): HostModelReferenceEntry[] {+ if (!isPlainObject(spec)) return []+ const refs: HostModelReferenceEntry[] = []++ // 1. primary — spec.model+ const model = spec.model+ if (isPlainObject(model)) {+ const name = typeof model.name === 'string' ? model.name.trim() : ''+ const provider = typeof model.provider === 'string' ? model.provider.trim() : ''+ if (name && provider) refs.push({ key: offeredKey(provider, name), role: 'primary' })+ }++ // 2. allowedModels — spec.allowedModels[]+ const allowedModels = spec.allowedModels+ if (Array.isArray(allowedModels)) {+ for (const entry of allowedModels) {+ if (!isPlainObject(entry)) continue+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''+ const m = typeof entry.model === 'string' ? entry.model.trim() : ''+ if (provider && m) refs.push({ key: offeredKey(provider, m), role: 'allowedModels' })+ }+ }++ // 3. fallback — spec.llmPolicy.fallbacks[]+ const llmPolicy = spec.llmPolicy+ if (isPlainObject(llmPolicy) && Array.isArray(llmPolicy.fallbacks)) {+ for (const entry of llmPolicy.fallbacks) {+ if (!isPlainObject(entry)) continue+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''+ const m = typeof entry.model === 'string' ? entry.model.trim() : ''+ if (provider && m) refs.push({ key: offeredKey(provider, m), role: 'fallback' })+ }+ }++ return refs+}diff --git a/control-api/src/routes/admin/hostSpecValidation.ts b/control-api/src/routes/admin/hostSpecValidation.tsindex 7224a9783..b366a25aa 100644--- a/control-api/src/routes/admin/hostSpecValidation.ts+++ b/control-api/src/routes/admin/hostSpecValidation.ts@@ -9,6 +9,7 @@ import {isModelAllowed as isModelAllowedDefault,} from '../../services/llmAllowedModels.js'import { isPlainObject } from '../../utils/isPlainObject.js'+import { enumerateHostModelReferences } from './hostModelReferences.js'import {type HostSpecIncoherenceToleratedEvent,type IncoherenceToleranceGate,@@ -306,38 +307,14 @@ interface StoredRoleSets {function storedRoleSets(stored: Record<string, unknown> | undefined): StoredRoleSets {const primary = new Set<string>()const any = new Set<string>()- if (!isPlainObject(stored)) return { primary, any }- const model = stored.model- if (- isPlainObject(model) &&- typeof model.name === 'string' &&- typeof model.provider === 'string'- ) {- const name = model.name.trim()- const provider = model.provider.trim()- if (name && provider) {- const key = offeredKey(provider, name)- primary.add(key)- any.add(key)- }- }- const llmPolicy = stored.llmPolicy- if (isPlainObject(llmPolicy) && Array.isArray(llmPolicy.fallbacks)) {- for (const entry of llmPolicy.fallbacks) {- if (!isPlainObject(entry)) continue- const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''- const fbModel = typeof entry.model === 'string' ? entry.model.trim() : ''- if (provider && fbModel) any.add(offeredKey(provider, fbModel))- }- }- const allowedModels = stored.allowedModels- if (Array.isArray(allowedModels)) {- for (const entry of allowedModels) {- if (!isPlainObject(entry)) continue- const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''- const model2 = typeof entry.model === 'string' ? entry.model.trim() : ''- if (provider && model2) any.add(offeredKey(provider, model2))- }+ // Location enumeration is shared verbatim with the live impact gate+ // (`enumerateHostModelReferences`, regla D4). This caller's own concern —+ // layered on top — is bucketing every referenced key into `any` and only the+ // `primary`-role keys into `primary`, so the active default slot stays strict+ // while non-active roles (fallback/subset) tolerate demotion.+ for (const ref of enumerateHostModelReferences(stored)) {+ any.add(ref.key)+ if (ref.role === 'primary') primary.add(ref.key)}return { primary, any }}diff --git a/control-api/src/services/llmModelImpact.ts b/control-api/src/services/llmModelImpact.tsindex dc6730fe5..39cbbdc92 100644--- a/control-api/src/services/llmModelImpact.ts+++ b/control-api/src/services/llmModelImpact.ts@@ -49,12 +49,20 @@* (`routes/admin/llmModels.ts`) and, later, `GET /admin/attention` (Fase 5).* Neither reconstructs the impact — both call `computeModelImpact`.*/+import {+ type HostModelRole,+ enumerateHostModelReferences,+} from '../routes/admin/hostModelReferences.js'import { offeredKey } from '../routes/admin/modelAllowlistTolerance.js'import { isPlainObject } from '../utils/isPlainObject.js'import { type PluginWorkloadSdkGrant, listGrantsReferencingModel } from './pluginWorkloadSdkDb.js'-/** Which Host spec source referenced the pair. A Host may match in several. */-export type HostModelRole = 'primary' | 'allowedModels' | 'fallback'+/**+ * Which Host spec source referenced the pair. A Host may match in several.+ * Re-exported from the shared enumeration module (regla D4) so existing importers+ * of this symbol from `llmModelImpact` keep working.+ */+export type { HostModelRole }/** A Host CR that references the pair, with the roles it matched in. */export interface HostModelReference {@@ -119,52 +127,25 @@ export function modelImpactSourcesFromGateway(}/**- * The roles in which a Host spec references the target `(provider, model)` pair- * (keyed via `offeredKey`, the same NUL-separated key the write-gate uses so a- * model id containing spaces can never collide with a distinct pair). Empty when- * the Host does not reference it. Purely structural and defensive: any- * malformed/partial entry is skipped, never throws.+ * The roles in which a Host spec references the TARGET `(provider, model)` pair.+ * Provider-aware match: keeps only the shared enumeration entries whose key+ * equals `targetKey` (the same NUL-separated `offeredKey` the write-gate uses, so+ * a model id containing spaces can never collide with a distinct pair), deduped+ * so each role appears at most once, in spec order (primary, allowedModels,+ * fallback). Empty when the Host does not reference the target.+ *+ * The location enumeration itself lives in `enumerateHostModelReferences` (regla+ * D4), shared verbatim with the tolerance seam's `storedRoleSets`. This caller's+ * own concern — layered on top — is target-filtering + role dedup.*/function hostRolesReferencing(spec: unknown, targetKey: string): HostModelRole[] {- if (!isPlainObject(spec)) return []const roles: HostModelRole[] = []-- // 1. primary — spec.model- const model = spec.model- if (isPlainObject(model)) {- const name = typeof model.name === 'string' ? model.name.trim() : ''- const provider = typeof model.provider === 'string' ? model.provider.trim() : ''- if (name && provider && offeredKey(provider, name) === targetKey) roles.push('primary')+ const seen = new Set<HostModelRole>()+ for (const ref of enumerateHostModelReferences(spec)) {+ if (ref.key !== targetKey || seen.has(ref.role)) continue+ seen.add(ref.role)+ roles.push(ref.role)}-- // 2. allowedModels — spec.allowedModels[]- const allowedModels = spec.allowedModels- if (Array.isArray(allowedModels)) {- for (const entry of allowedModels) {- if (!isPlainObject(entry)) continue- const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''- const m = typeof entry.model === 'string' ? entry.model.trim() : ''- if (provider && m && offeredKey(provider, m) === targetKey) {- roles.push('allowedModels')- break- }- }- }-- // 3. fallback — spec.llmPolicy.fallbacks[]- const llmPolicy = spec.llmPolicy- if (isPlainObject(llmPolicy) && Array.isArray(llmPolicy.fallbacks)) {- for (const entry of llmPolicy.fallbacks) {- if (!isPlainObject(entry)) continue- const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''- const m = typeof entry.model === 'string' ? entry.model.trim() : ''- if (provider && m && offeredKey(provider, m) === targetKey) {- roles.push('fallback')- break- }- }- }-return roles}diff --git a/control-api/test/routes.hostModelReferences.test.ts b/control-api/test/routes.hostModelReferences.test.tsnew file mode 100644index 000000000..024580a73--- /dev/null+++ b/control-api/test/routes.hostModelReferences.test.ts@@ -0,0 +1,268 @@+import { describe, expect, it } from 'vitest'+import fc from 'fast-check'+import {+ type HostModelRole,+ enumerateHostModelReferences,+} from '../src/routes/admin/hostModelReferences.js'+import { offeredKey } from '../src/routes/admin/modelAllowlistTolerance.js'+import { isPlainObject } from '../src/utils/isPlainObject.js'++// Unit + property coverage for the shared Host model-reference enumeration+// (regla D4, hallazgo R1-M3). The enumeration is the single definition of "which+// spec locations reference a (provider, model) pair, and in which role", consumed+// by BOTH the live impact gate (`hostRolesReferencing` in llmModelImpact.ts) and+// the tolerance seam (`storedRoleSets` in hostSpecValidation.ts). Neither of those+// two callers is exported, so behaviour-preservation is proven by re-deriving each+// caller's shape from the shared enumeration and asserting it against an ORACLE+// that reproduces the pre-refactor inline logic verbatim (T2/T4).++const k = (provider: string, model: string) => offeredKey(provider, model)++describe('enumerateHostModelReferences — example coverage (T4)', () => {+ it('emits one entry per location, in spec order (primary, allowedModels[], fallbacks[])', () => {+ const spec = {+ model: { provider: 'claude', name: 'claude-haiku-4-5' },+ allowedModels: [+ { provider: 'openai', model: 'gpt-5' },+ { provider: 'groq', model: 'llama-4' },+ ],+ llmPolicy: { fallbacks: [{ provider: 'zai', model: 'glm-4' }] },+ }+ expect(enumerateHostModelReferences(spec)).toEqual([+ { key: k('claude', 'claude-haiku-4-5'), role: 'primary' },+ { key: k('openai', 'gpt-5'), role: 'allowedModels' },+ { key: k('groq', 'llama-4'), role: 'allowedModels' },+ { key: k('zai', 'glm-4'), role: 'fallback' },+ ])+ })++ it('emits one entry per location for a pair present in all three (no dedup here)', () => {+ const spec = {+ model: { provider: 'claude', name: 'm' },+ allowedModels: [{ provider: 'claude', model: 'm' }],+ llmPolicy: { fallbacks: [{ provider: 'claude', model: 'm' }] },+ }+ const key = k('claude', 'm')+ expect(enumerateHostModelReferences(spec)).toEqual([+ { key, role: 'primary' },+ { key, role: 'allowedModels' },+ { key, role: 'fallback' },+ ])+ })++ it('handles all absences: no model, empty allowedModels, no fallbacks', () => {+ expect(enumerateHostModelReferences({ allowedModels: [] })).toEqual([])+ expect(enumerateHostModelReferences({ llmPolicy: {} })).toEqual([])+ expect(enumerateHostModelReferences({})).toEqual([])+ expect(enumerateHostModelReferences(undefined)).toEqual([])+ expect(enumerateHostModelReferences(null)).toEqual([])+ expect(enumerateHostModelReferences('nope')).toEqual([])+ expect(enumerateHostModelReferences([])).toEqual([])+ })++ it('trims provider/model and skips malformed or partial entries', () => {+ const spec = {+ model: { provider: ' claude ', name: ' m ' },+ allowedModels: [+ { provider: 'openai', model: 'gpt-5' },+ { provider: '', model: 'x' }, // empty provider -> skip+ { provider: 'groq' }, // no model -> skip+ 'not-an-object', // non-object -> skip+ { provider: 42, model: 'y' }, // non-string provider -> skip+ ],+ llmPolicy: { fallbacks: [{ provider: 'zai', model: ' glm-4' }, null] },+ }+ expect(enumerateHostModelReferences(spec)).toEqual([+ { key: k('claude', 'm'), role: 'primary' },+ { key: k('openai', 'gpt-5'), role: 'allowedModels' },+ { key: k('zai', 'glm-4'), role: 'fallback' },+ ])+ })++ it('ignores a non-array allowedModels and a non-object/absent llmPolicy', () => {+ expect(enumerateHostModelReferences({ allowedModels: { provider: 'x', model: 'y' } })).toEqual(+ []+ )+ expect(enumerateHostModelReferences({ llmPolicy: 'nope' })).toEqual([])+ expect(enumerateHostModelReferences({ llmPolicy: { fallbacks: 'nope' } })).toEqual([])+ })+})++// --- Oracles: verbatim reproduction of the PRE-refactor inline logic. ---++/** Old `storedRoleSets` from hostSpecValidation.ts (pre-R1-M3). */+function oracleStoredRoleSets(stored: unknown): {+ primary: Set<string>+ any: Set<string>+} {+ const primary = new Set<string>()+ const any = new Set<string>()+ if (!isPlainObject(stored)) return { primary, any }+ const model = stored.model+ if (+ isPlainObject(model) &&+ typeof model.name === 'string' &&+ typeof model.provider === 'string'+ ) {+ const name = model.name.trim()+ const provider = model.provider.trim()+ if (name && provider) {+ const key = offeredKey(provider, name)+ primary.add(key)+ any.add(key)+ }+ }+ const llmPolicy = stored.llmPolicy+ if (isPlainObject(llmPolicy) && Array.isArray(llmPolicy.fallbacks)) {+ for (const entry of llmPolicy.fallbacks) {+ if (!isPlainObject(entry)) continue+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''+ const fbModel = typeof entry.model === 'string' ? entry.model.trim() : ''+ if (provider && fbModel) any.add(offeredKey(provider, fbModel))+ }+ }+ const allowedModels = stored.allowedModels+ if (Array.isArray(allowedModels)) {+ for (const entry of allowedModels) {+ if (!isPlainObject(entry)) continue+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''+ const model2 = typeof entry.model === 'string' ? entry.model.trim() : ''+ if (provider && model2) any.add(offeredKey(provider, model2))+ }+ }+ return { primary, any }+}++/** Old `hostRolesReferencing` from llmModelImpact.ts (pre-R1-M3). */+function oracleHostRoles(spec: unknown, targetKey: string): HostModelRole[] {+ if (!isPlainObject(spec)) return []+ const roles: HostModelRole[] = []+ const model = spec.model+ if (isPlainObject(model)) {+ const name = typeof model.name === 'string' ? model.name.trim() : ''+ const provider = typeof model.provider === 'string' ? model.provider.trim() : ''+ if (name && provider && offeredKey(provider, name) === targetKey) roles.push('primary')+ }+ const allowedModels = spec.allowedModels+ if (Array.isArray(allowedModels)) {+ for (const entry of allowedModels) {+ if (!isPlainObject(entry)) continue+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''+ const m = typeof entry.model === 'string' ? entry.model.trim() : ''+ if (provider && m && offeredKey(provider, m) === targetKey) {+ roles.push('allowedModels')+ break+ }+ }+ }+ const llmPolicy = spec.llmPolicy+ if (isPlainObject(llmPolicy) && Array.isArray(llmPolicy.fallbacks)) {+ for (const entry of llmPolicy.fallbacks) {+ if (!isPlainObject(entry)) continue+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : ''+ const m = typeof entry.model === 'string' ? entry.model.trim() : ''+ if (provider && m && offeredKey(provider, m) === targetKey) {+ roles.push('fallback')+ break+ }+ }+ }+ return roles+}++// --- Caller shapes derived from the shared enumeration (what the code now does). ---++function sharedStoredRoleSets(stored: unknown): { primary: Set<string>; any: Set<string> } {+ const primary = new Set<string>()+ const any = new Set<string>()+ for (const ref of enumerateHostModelReferences(stored)) {+ any.add(ref.key)+ if (ref.role === 'primary') primary.add(ref.key)+ }+ return { primary, any }+}++function sharedHostRoles(spec: unknown, targetKey: string): HostModelRole[] {+ const roles: HostModelRole[] = []+ const seen = new Set<HostModelRole>()+ for (const ref of enumerateHostModelReferences(spec)) {+ if (ref.key !== targetKey || seen.has(ref.role)) continue+ seen.add(ref.role)+ roles.push(ref.role)+ }+ return roles+}++// --- Arbitraries: specs whose fields exercise every guard (trim, wrong types,+// absent/empty/malformed), so the property fuzzes the exact edge cases. ---++const arbProvider = fc.oneof(+ fc.constantFrom('claude', 'openai', 'groq', 'zai'),+ fc.constantFrom(' claude', 'claude ', '', ' '),+ fc.string({ maxLength: 4 })+)+const arbModelName = fc.oneof(+ fc.constantFrom('m', 'gpt-5', 'glm 4', ' m ', '', ' '),+ fc.string({ maxLength: 4 })+)+// An entry that may be well-formed, partial, mistyped, or not an object at all.+const arbEntry = fc.oneof(+ fc.record({ provider: arbProvider, model: arbModelName }),+ fc.record({ provider: arbProvider }),+ fc.record({ model: arbModelName }),+ fc.record({ provider: fc.integer(), model: arbModelName }),+ fc.constantFrom(null, 'x', 42, undefined)+)+const arbModelObj = fc.oneof(+ fc.record({ provider: arbProvider, name: arbModelName }),+ fc.record({ name: arbModelName }),+ fc.constantFrom(null, 'x', undefined)+)+const arbAllowedModels = fc.oneof(+ fc.constant(undefined),+ fc.constant([]),+ fc.array(arbEntry, { maxLength: 5 }),+ fc.constantFrom('nope', { not: 'an-array' })+)+const arbLlmPolicy = fc.oneof(+ fc.constant(undefined),+ fc.constant('nope'),+ fc.record({ fallbacks: fc.oneof(fc.array(arbEntry, { maxLength: 5 }), fc.constant('nope')) })+)+const arbSpec = fc.record(+ { model: arbModelObj, allowedModels: arbAllowedModels, llmPolicy: arbLlmPolicy },+ { requiredKeys: [] }+)++const sortedKeys = (s: Set<string>) => [...s].sort()++describe('enumerateHostModelReferences — behaviour-preserving for both callers (T2)', () => {+ it('storedRoleSets derived from the shared enumeration equals the pre-refactor oracle', () => {+ fc.assert(+ fc.property(arbSpec, spec => {+ const shared = sharedStoredRoleSets(spec)+ const oracle = oracleStoredRoleSets(spec)+ expect(sortedKeys(shared.primary)).toEqual(sortedKeys(oracle.primary))+ expect(sortedKeys(shared.any)).toEqual(sortedKeys(oracle.any))+ }),+ { numRuns: 5000 }+ )+ })++ it('hostRolesReferencing derived from the shared enumeration equals the pre-refactor oracle (order preserved)', () => {+ fc.assert(+ fc.property(arbSpec, arbProvider, arbModelName, (spec, p, m) => {+ // Target keys drawn from both random pairs AND the spec's own emitted+ // keys, so the equality is exercised on real hits, not only misses.+ const candidateKeys = [+ offeredKey(p.trim(), m.trim()),+ ...enumerateHostModelReferences(spec).map(r => r.key),+ ]+ for (const targetKey of candidateKeys) {+ expect(sharedHostRoles(spec, targetKey)).toEqual(oracleHostRoles(spec, targetKey))+ }+ }),+ { numRuns: 5000 }+ )+ })+})