Skip to content

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

TypeScript

fix(control-api): serialize host↔model writes with a per-model advisory lock (R1-H3 fase 1)

Diego Zacarias9dfd4a27511b
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index f3aa19e5b..4f1a278a1 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.451",
+ "version": "0.1.452",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.451",
+ "version": "0.1.452",
"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 6cb10e86a..c33a8dbab 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.451",
+ "version": "0.1.452",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index cd7a8f2a1..0f0852cd0 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -59,6 +59,20 @@ const MAX_CONNECTION_TIMEOUT_MS = 30_000
const MIN_STATEMENT_TIMEOUT_MS = 100
const MAX_STATEMENT_TIMEOUT_MS = 30_000
+// R1-H3 fase 1 (host↔model serialization). The reductor (llm-model disable/
+// delete) and the referencer (host create/update) both take a per-MODEL-NAME
+// advisory lock and HOLD it across the K8s write (Decisión A of
+// work-tracker/reviews/pr-339/minispec-R1-H3-concurrency.md). While the carrier
+// transaction awaits the K8s API it is idle-in-transaction, so neither
+// statement_timeout nor lock_timeout bounds the lock/connection tenancy — only
+// idle_in_transaction_session_timeout does (adenda A2). We set it per-carrier-
+// transaction (SET LOCAL) so a hung K8s call fails fast and releases the lock +
+// the scarce pool connection (core pool max defaults to 10) instead of pinning
+// them indefinitely.
+const MIN_CARRIER_IDLE_TIMEOUT_MS = 1_000
+const MAX_CARRIER_IDLE_TIMEOUT_MS = 60_000
+const DEFAULT_CARRIER_IDLE_TIMEOUT_MS = 15_000
+
const DEFAULT_CORE_POOL_MAX = 10
const DEFAULT_CORE_POOL_IDLE_TIMEOUT_MS = 30_000
const DEFAULT_CORE_POOL_CONNECTION_TIMEOUT_MS = 2_000
@@ -5680,3 +5694,68 @@ export async function withTransaction<T>(work: (db: DbClient) => Promise<T>): Pr
client.release(releaseError)
}
}
+
+// ── R1-H3 fase 1: host↔model write serialization ────────────────────────────
+//
+// A single advisory-lock namespace for the LLM-model availability seam. EVERY
+// writer that can either reduce a model's availability (llm-model disable/delete,
+// the reductor) or create a live reference to it (Host CR create/update, the
+// referencer) takes THIS lock, so the impact enumeration and the mutation/write
+// cannot interleave and strand a reference (INV-1). The lock is derived from ONE
+// place (regla D4) so the two sides can never disagree on the key.
+//
+// GRANULARITY = MODEL NAME, not (provider, model): the impact enumeration matches
+// grants by model name only (`listGrantsReferencingModel`), and an
+// `allowed_models` entry may carry no derivable provider, so a per-pair key would
+// leave that seam unserialized (adenda A1). By name, a disable of (provA, M) and a
+// host-create of (provB, M) merely contend — harmless at admin QPS — while each
+// side's impact recompute is still per-pair, so independent pairs both win.
+const LLM_MODEL_LOCK_NAMESPACE = 'llm-model:'
+
+export const HOST_MODEL_WRITE_CARRIER_IDLE_TIMEOUT_MS = boundedEnvInteger(
+ 'CONTROL_API_HOST_MODEL_WRITE_LOCK_IDLE_TIMEOUT_MS',
+ DEFAULT_CARRIER_IDLE_TIMEOUT_MS,
+ MIN_CARRIER_IDLE_TIMEOUT_MS,
+ MAX_CARRIER_IDLE_TIMEOUT_MS
+)
+
+/**
+ * Take the transaction-scoped advisory lock for one model NAME. Auto-released on
+ * COMMIT/ROLLBACK and on backend death, so it never orphans. Must be a statement
+ * inside an open transaction (`withTransaction`); the caller HOLDS it across the
+ * subsequent impact read + mutation / K8s write.
+ */
+export async function advisoryLockModelName(db: DbClient, model: string): Promise<void> {
+ await db.query(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [
+ `${LLM_MODEL_LOCK_NAMESPACE}${model}`,
+ ])
+}
+
+/**
+ * Take the advisory locks for several model NAMES in one transaction. Dedups and
+ * acquires in a TOTAL (ascending) order to preclude deadlock when two operations
+ * reference an overlapping set (adenda A5). A host that references no allowlist
+ * pair acquires nothing (an empty set is a no-op). Key derivation stays in
+ * `advisoryLockModelName` (regla D4).
+ */
+export async function advisoryLockModelNames(db: DbClient, models: string[]): Promise<void> {
+ const ordered = Array.from(new Set(models)).sort()
+ for (const model of ordered) {
+ await advisoryLockModelName(db, model)
+ }
+}
+
+/**
+ * Bound the idle-in-transaction tenancy of a carrier transaction that HOLDS a
+ * model advisory lock across a Kubernetes write (Decisión A / adenda A2). While
+ * the transaction awaits the K8s API no statement runs, so this is the only
+ * timeout that can release the lock + connection if that call hangs. SET LOCAL
+ * scope: reverts on COMMIT/ROLLBACK. The value is milliseconds (the GUC's base
+ * unit) and comes from a bounded env, so it can never inject SQL.
+ */
+export async function boundCarrierTransactionIdleTimeout(
+ db: DbClient,
+ ms: number = HOST_MODEL_WRITE_CARRIER_IDLE_TIMEOUT_MS
+): Promise<void> {
+ await db.query(`SELECT set_config('idle_in_transaction_session_timeout', $1, true)`, [String(ms)])
+}
diff --git a/control-api/src/routes/admin/hostModelReferences.ts b/control-api/src/routes/admin/hostModelReferences.ts
index 173319f23..220b1aafe 100644
--- a/control-api/src/routes/admin/hostModelReferences.ts
+++ b/control-api/src/routes/admin/hostModelReferences.ts
@@ -41,6 +41,14 @@ export interface HostModelReferenceEntry {
key: string
/** The spec location this reference came from. */
role: HostModelRole
+ /** The trimmed provider id, as declared in the spec. */
+ provider: string
+ /**
+ * The trimmed model name, as declared in the spec. Exposed so callers that key
+ * on the model NAME (the R1-H3 advisory lock is by name, adenda A1) reuse this
+ * one enumeration instead of re-walking the spec (regla D4).
+ */
+ model: string
}
/**
@@ -60,7 +68,8 @@ export function enumerateHostModelReferences(spec: unknown): HostModelReferenceE
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' })
+ if (name && provider)
+ refs.push({ key: offeredKey(provider, name), role: 'primary', provider, model: name })
}
// 2. allowedModels — spec.allowedModels[]
@@ -70,7 +79,8 @@ export function enumerateHostModelReferences(spec: unknown): HostModelReferenceE
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' })
+ if (provider && m)
+ refs.push({ key: offeredKey(provider, m), role: 'allowedModels', provider, model: m })
}
}
@@ -81,7 +91,8 @@ export function enumerateHostModelReferences(spec: unknown): HostModelReferenceE
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' })
+ if (provider && m)
+ refs.push({ key: offeredKey(provider, m), role: 'fallback', provider, model: m })
}
}
diff --git a/control-api/src/routes/admin/llmModels.ts b/control-api/src/routes/admin/llmModels.ts
index ef2ac191b..6e8a857b4 100644
--- a/control-api/src/routes/admin/llmModels.ts
+++ b/control-api/src/routes/admin/llmModels.ts
@@ -1,6 +1,12 @@
import { type Request, type Response, Router } from 'express'
import { z } from 'zod'
import { config } from '../../config.js'
+import {
+ type DbClient,
+ advisoryLockModelName,
+ boundCarrierTransactionIdleTimeout,
+ withTransaction,
+} from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import type { K8sGateway } from '../../k8s.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
@@ -19,11 +25,29 @@ import {
import { computeAttention } from '../../services/llmAttention.js'
import { getLastCatalogSyncRun, syncDiscoveredModels } from '../../services/llmCatalogSync.js'
import {
+ type ModelImpact,
computeModelImpact,
modelImpactHasReferences,
modelImpactSourcesFromGateway,
+ modelImpactSourcesFromGatewayTx,
} from '../../services/llmModelImpact.js'
+// The reductor lost the availability-reduction race: a live Host/grant reference
+// to the pair was enumerated UNDER the advisory lock, so disabling/removing it
+// would strand that reference (INV-1). Thrown from inside the carrier transaction
+// so it ROLLS BACK (the mutation never persists) and mapped to the same
+// 409 `model_in_use` body the gate has always returned.
+class ModelInUseError extends Error {
+ constructor(readonly impact: ModelImpact) {
+ super('model_in_use')
+ this.name = 'ModelInUseError'
+ }
+}
+
+// The 409 message is unchanged (mini-spec §6: the response shape is byte-stable).
+const MODEL_IN_USE_MESSAGE =
+ 'this model is still referenced by one or more Hosts or grants; retry with ?force=true to disable/remove it and leave those references pointing at a disabled/removed model'
+
// `id` is a UUID column; a malformed id would otherwise reach Postgres and
// raise 22P02 (→ 500). Treat a non-UUID id as a missing row (404).
const idSchema = z.string().uuid()
@@ -105,29 +129,49 @@ export function createAdminLlmModelsRouter(gateway: K8sGateway): Router {
// this single module (regla D4).
const impactSources = modelImpactSourcesFromGateway(gateway, hostNamespaces)
- // Availability-reduction gate (Fase 3). A DELETE (always), a PUT that flips
- // `enabled` true→false, or a PUT that RENAMES an enabled pair (its old
- // identity leaves the ConfigMap on re-materialize) yanks the model out of the
- // runtime allowlist ConfigMap. The caller computes the impact over whichever
- // pair leaves — the OLD one on rename.
- // Without `?force`, if any Host/grant still references `(provider, model)`,
- // answer 409 WITH the impact body so the operator sees what would be stranded
- // instead of breaking it silently. Returns true when a 409 was sent (the
- // caller must stop). `?force=true` skips the enumeration entirely and proceeds.
- async function blockedByImpact(
- req: Request,
- res: Response,
+ // Availability-reduction gate (Fase 3), now SERIALIZED (R1-H3 fase 1). A DELETE
+ // (always), a PUT that flips `enabled` true→false, or a PUT that RENAMES an
+ // enabled pair (its old identity leaves the ConfigMap on re-materialize) yanks
+ // the model out of the runtime allowlist ConfigMap. The caller computes the
+ // impact over whichever pair leaves — the OLD one on rename.
+ //
+ // The whole gate runs inside a carrier transaction that HOLDS the per-model-name
+ // advisory lock across the impact read AND the mutation, so a concurrent host
+ // create/update cannot slip a reference in between (INV-1). Grants are read on
+ // the transaction client; Hosts are LISTed LIVE from K8s under the lock. If any
+ // Host/grant still references the pair, a `ModelInUseError` rolls the
+ // transaction back — nothing is mutated — and the caller answers 409 WITH the
+ // impact body. `?force=true` never reaches here (the caller mutates without the
+ // lock, deliberately renouncing INV-1 — mini-spec §6).
+ async function gatedReduce<T>(
provider: string,
- model: string
- ): Promise<boolean> {
- if (isForced(req)) return false
- const impact = await computeModelImpact(provider, model, impactSources)
- if (!modelImpactHasReferences(impact)) return false
+ model: string,
+ mutate: (db: DbClient) => Promise<T>
+ ): Promise<T> {
+ return withTransaction(async db => {
+ // Bound the idle-in-transaction tenancy first: the lock is held across a
+ // live K8s LIST, during which the connection is idle-in-transaction.
+ await boundCarrierTransactionIdleTimeout(db)
+ await advisoryLockModelName(db, model)
+ const impact = await computeModelImpact(
+ provider,
+ model,
+ modelImpactSourcesFromGatewayTx(gateway, hostNamespaces, db)
+ )
+ if (modelImpactHasReferences(impact)) throw new ModelInUseError(impact)
+ return mutate(db)
+ })
+ }
+
+ // Map a caught `ModelInUseError` to the stable 409 body; return true when it was
+ // handled so the caller stops. Non-`ModelInUseError` errors are left to the
+ // caller's existing `handleServiceError` / rethrow path.
+ function sentModelInUse(res: Response, error: unknown): boolean {
+ if (!(error instanceof ModelInUseError)) return false
res.status(409).json({
error: 'model_in_use',
- message:
- 'this model is still referenced by one or more Hosts or grants; retry with ?force=true to disable/remove it and leave those references pointing at a disabled/removed model',
- impact,
+ message: MODEL_IN_USE_MESSAGE,
+ impact: error.impact,
})
return true
}
@@ -264,16 +308,20 @@ export function createAdminLlmModelsRouter(gateway: K8sGateway): Router {
(parsed.data.provider !== undefined && parsed.data.provider !== existing.provider) ||
(parsed.data.model !== undefined && parsed.data.model !== existing.model)
const oldPairLeavesConfigMap = existing.enabled === true && (disables || renamed)
- if (
- oldPairLeavesConfigMap &&
- (await blockedByImpact(req, res, existing.provider, existing.model))
- ) {
- return
- }
+ // Serialize the mutation only when the gate actually runs: the OLD pair
+ // leaves the ConfigMap AND this is not a `?force` override. A metadata edit
+ // that keeps the pair in the ConfigMap strands nothing, so it takes no lock
+ // and runs on the pool exactly as before (mini-spec §7, item 3).
+ const runGate = oldPairLeavesConfigMap && !isForced(req)
let model
try {
- model = await updateAllowedModel(req.params.id, parsed.data, actorOf(req))
+ model = runGate
+ ? await gatedReduce(existing.provider, existing.model, db =>
+ updateAllowedModel(req.params.id, parsed.data, actorOf(req), db)
+ )
+ : await updateAllowedModel(req.params.id, parsed.data, actorOf(req))
} catch (error) {
+ if (sentModelInUse(res, error)) return
if (handleServiceError(res, error)) return
throw error
}
@@ -303,11 +351,19 @@ export function createAdminLlmModelsRouter(gateway: K8sGateway): Router {
res.status(404).json({ error: 'not_found' })
return
}
- if (await blockedByImpact(req, res, existing.provider, existing.model)) return
+ // A DELETE always removes the pair, so the gate runs unconditionally unless
+ // `?force`. When it runs, the impact read + the delete are serialized under
+ // the per-model-name advisory lock (INV-1); `?force` deletes on the pool
+ // without the lock (renounces INV-1, mini-spec §6).
let deleted
try {
- deleted = await deleteAllowedModel(req.params.id, actorOf(req))
+ deleted = isForced(req)
+ ? await deleteAllowedModel(req.params.id, actorOf(req))
+ : await gatedReduce(existing.provider, existing.model, db =>
+ deleteAllowedModel(req.params.id, actorOf(req), db)
+ )
} catch (error) {
+ if (sentModelInUse(res, error)) return
if (handleServiceError(res, error)) return
throw error
}
diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.ts
index 14f2707f0..11b3d173d 100644
--- a/control-api/src/routes/admin/resources.ts
+++ b/control-api/src/routes/admin/resources.ts
@@ -1,10 +1,17 @@
import { type NextFunction, type Request, type Response, Router } from 'express'
import { config } from '../../config.js'
+import {
+ type DbClient,
+ advisoryLockModelNames,
+ boundCarrierTransactionIdleTimeout,
+ withTransaction,
+} from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
import { enforceNamespace } from '../../http/namespaceAudit.js'
import { validateCommunicationChannelSpec } from '../../http/validateCommunicationChannelSpec.js'
import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'
import { K8sGateway } from '../../k8s.js'
+import { getModelAllowlistState, isModelAllowed } from '../../services/llmAllowedModels.js'
import { K8sConflictError } from '../../services/resourceService.js'
import { secretKeyNames } from '../../services/secretKeyNames.js'
import { ClerumResourceType } from '../../types.js'
@@ -17,8 +24,9 @@ import {
extractK8sStatusCode,
preserveCommunicationChannelCredentialsSecretRef,
} from './communicationChannelSpecHelpers.js'
+import { enumerateHostModelReferences } from './hostModelReferences.js'
import { validateHostSecretRef } from './hostSecrets.js'
-import { validateHostSpec } from './hostSpecValidation.js'
+import { type HostSpecValidationDeps, validateHostSpec } from './hostSpecValidation.js'
import {
type HostSpecIncoherenceToleratedEvent,
emitHostSpecIncoherenceTolerated,
@@ -345,6 +353,39 @@ function resolveResource(param: string): { plural: AdminResourceType; ns: string
return { plural, ns: resourceNamespace(plural) }
}
+// R1-H3 fase 1: a Host write (create/update) validates its model references and
+// writes the CR INSIDE a carrier transaction that holds the per-model-name
+// advisory lock across the K8s write, so a concurrent llm-model disable/delete
+// cannot strand a reference (INV-1). `validateHostSpec` returning an issue must
+// abort the whole thing WITHOUT persisting: it throws this so `withTransaction`
+// rolls back (releasing the lock) and the caller answers 422 with the issue.
+class HostSpecInvalidError extends Error {
+ constructor(readonly issue: { errors: Array<{ field: string; message: string }> }) {
+ super('host_spec_invalid')
+ this.name = 'HostSpecInvalidError'
+ }
+}
+
+// Every distinct model NAME a Host spec references (primary + allowedModels +
+// fallbacks). Reuses the single Host-reference enumeration (regla D4); the raw
+// model name is what the advisory lock keys on (adenda A1). Dedup + total order
+// are handled by `advisoryLockModelNames`.
+function hostModelLockNames(spec: unknown): string[] {
+ return enumerateHostModelReferences(spec).map(ref => ref.model)
+}
+
+// Bind the Host-spec validation gates to the carrier TRANSACTION client so the
+// allowlist reads happen under the advisory lock, on the same connection. BOTH
+// `isModelAllowed` (the fail-closed gate) AND `getModelAllowlistState` (the
+// stale-warning lookup) are bound — leaving the latter defaulted would let
+// `maybeWarnStale` escape to the global pool under the lock (adenda A3).
+function hostValidationDeps(db: DbClient): HostSpecValidationDeps {
+ return {
+ isModelAllowed: (provider, model) => isModelAllowed(provider, model, db),
+ getModelAllowlistState: (provider, model) => getModelAllowlistState(provider, model, db),
+ }
+}
+
export function createAdminResourcesRouter(gateway: K8sGateway): Router {
const router = Router()
@@ -488,27 +529,56 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
return
}
- // Early validation for Host specs — spec.approval.tools shape + R3 model
- // allowlist enforcement (fail-closed for a declared spec.model.name).
+ // Host create (R1-H3 fase 1): validate + CREATE the CR INSIDE a carrier
+ // transaction that HOLDS the per-model-name advisory lock across the K8s
+ // write, so a concurrent llm-model disable/delete cannot strand the new
+ // reference (INV-1). The impact gate on the reductor side takes the SAME
+ // lock and LISTs Hosts live, so whichever side commits first wins and the
+ // loser re-reads under the lock and aborts.
if (plural === 'hosts' && body.spec) {
- // Create: no stored CR, so the no-worsening tolerance (Pieza D) can never
- // apply — a fresh Host may not introduce a disabled model.
- const issue = await validateHostSpec(body.spec, undefined, {
- hostRef: { namespace: ns, name: body.metadata.name },
- // Fase 6: a fresh Host has no stored CR, so EVERY assignment is new — a
- // stale enabled model warns (never blocks). Emitted after the CR lands.
- warnings: hostWarnings,
- })
- if (issue) {
- res.status(422).json(issue)
- return
- }
- // Anti-spoofing: an existing secretRef target must be an LLM host Secret.
- const secretRefIssue = await validateHostSecretRef(gateway, body.spec)
- if (secretRefIssue) {
- res.status(422).json(secretRefIssue)
- return
+ const hostSpec = body.spec
+ let created: unknown
+ try {
+ created = await withTransaction(async db => {
+ // Bound idle-in-transaction tenancy first (the lock is held across the
+ // live K8s write), then acquire the model-name locks in total order.
+ await boundCarrierTransactionIdleTimeout(db)
+ await advisoryLockModelNames(db, hostModelLockNames(hostSpec))
+ // Create: no stored CR, so the no-worsening tolerance (Pieza D) can
+ // never apply — a fresh Host may not introduce a disabled model. The
+ // allowlist gates read UNDER the lock (deps bound to `db`).
+ const issue = await validateHostSpec(hostSpec, hostValidationDeps(db), {
+ hostRef: { namespace: ns, name: body.metadata.name },
+ // Fase 6: a fresh Host has no stored CR, so EVERY assignment is new —
+ // a stale enabled model warns (never blocks). Emitted after the CR
+ // lands (below), so a rejected write surfaces no warning.
+ warnings: hostWarnings,
+ })
+ if (issue) throw new HostSpecInvalidError(issue)
+ // Anti-spoofing: an existing secretRef target must be an LLM host
+ // Secret. Kept before the write and inside the lock so precedence
+ // (spec issue → secretRef issue) is byte-identical to before.
+ const secretRefIssue = await validateHostSecretRef(gateway, hostSpec)
+ if (secretRefIssue) throw new HostSpecInvalidError(secretRefIssue)
+ // K8s write INSIDE the held lock: the COMMIT that releases the lock
+ // happens only after the CR is durable.
+ return gateway.createResource(plural, body, ns)
+ })
+ } catch (err) {
+ if (err instanceof HostSpecInvalidError) {
+ res.status(422).json(err.issue)
+ return
+ }
+ throw err
}
+ res
+ .status(201)
+ .json(
+ hostWarnings.length > 0
+ ? { ...(created as Record<string, unknown>), warnings: hostWarnings }
+ : created
+ )
+ return
}
// Early validation for McpServer specs — UX safety net + defense-in-depth.
@@ -597,11 +667,19 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
}
}
+ // Host update (R1-H3 fase 1): validate + REPLACE the CR INSIDE a carrier
+ // transaction holding the per-model-name advisory lock across the K8s write,
+ // exactly like create. The revalidation under the lock reuses the SAME
+ // `validateHostSpec` — which already encapsulates the no-worsening tolerance
+ // (Pieza D) — so the tolerance is preserved, not tightened (mini-spec §7).
if (plural === 'hosts' && body.spec) {
- // Update: read the stored CR so the write gate can tolerate a pre-existing
+ const hostSpec = body.spec
+ // Read the stored CR so the write gate can tolerate a pre-existing
// model_not_allowed incoherence this write does not worsen (Pieza D — the
// editability trap). If the stored CR cannot be read, tolerance is skipped
- // (fail-closed: the gate behaves exactly as before this feature).
+ // (fail-closed: the gate behaves exactly as before this feature). Read
+ // before the lock: it feeds tolerance, not the availability race, and the
+ // K8s resourceVersion precondition guards CR-level concurrency.
let storedHostSpec: Record<string, unknown> | undefined
try {
const existing = (await gateway.getResource(plural, req.params.name, ns)) as {
@@ -612,27 +690,55 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
} catch {
storedHostSpec = undefined
}
- const issue = await validateHostSpec(body.spec, undefined, {
- stored: storedHostSpec,
- hostRef: { namespace: ns, name: req.params.name },
- // Sink for tolerations granted by validation; emitted below ONLY after
- // the CR persists (mini-spec 01), so a secretRef 422 or a K8s conflict
- // leaves no audit record.
- tolerations: hostTolerations,
- // Fase 6 warnings: a NEW assignment of an enabled-but-stale model warns
- // (never blocks). A live reference already in the stored CR is not
- // revalidated. Returned in the body only after the CR persists.
- warnings: hostWarnings,
- })
- if (issue) {
- res.status(422).json(issue)
- return
- }
- const secretRefIssue = await validateHostSecretRef(gateway, body.spec)
- if (secretRefIssue) {
- res.status(422).json(secretRefIssue)
- return
+ let updated: unknown
+ try {
+ updated = await withTransaction(async db => {
+ await boundCarrierTransactionIdleTimeout(db)
+ // Lock the models the INCOMING spec references — a newly added
+ // reference is the only one this write can strand.
+ await advisoryLockModelNames(db, hostModelLockNames(hostSpec))
+ const issue = await validateHostSpec(hostSpec, hostValidationDeps(db), {
+ stored: storedHostSpec,
+ hostRef: { namespace: ns, name: req.params.name },
+ // Sink for tolerations granted by validation; emitted below ONLY
+ // after the CR persists (mini-spec 01), so a secretRef 422 or a K8s
+ // conflict leaves no audit record.
+ tolerations: hostTolerations,
+ // Fase 6 warnings: a NEW assignment of an enabled-but-stale model
+ // warns (never blocks). A live reference already in the stored CR is
+ // not revalidated. Returned in the body only after the CR persists.
+ warnings: hostWarnings,
+ })
+ if (issue) throw new HostSpecInvalidError(issue)
+ const secretRefIssue = await validateHostSecretRef(gateway, hostSpec)
+ if (secretRefIssue) throw new HostSpecInvalidError(secretRefIssue)
+ return gateway.updateResource(plural, req.params.name, body, ns)
+ })
+ } catch (err) {
+ if (err instanceof HostSpecInvalidError) {
+ res.status(422).json(err.issue)
+ return
+ }
+ // AP-6: the caller sent the resourceVersion it read and the resource
+ // changed underneath it. Machine-readable so the UI can tell the operator
+ // to reload — never retried server-side with the stale body.
+ if (err instanceof K8sConflictError) {
+ res.status(409).json({ error: 'conflict', reason: 'resource_changed' })
+ return
+ }
+ throw err
}
+ // Host CR persisted: NOW emit any Pieza D tolerations (never before the
+ // write lands, so a K8s conflict/error leaves no audit record).
+ for (const event of hostTolerations) emitHostSpecIncoherenceTolerated(event)
+ res
+ .status(200)
+ .json(
+ hostWarnings.length > 0
+ ? { ...(updated as Record<string, unknown>), warnings: hostWarnings }
+ : updated
+ )
+ return
}
const isCommunicationChannelUpdate = plural === 'communicationchannels' && body.spec
diff --git a/control-api/src/services/llmModelImpact.ts b/control-api/src/services/llmModelImpact.ts
index 39cbbdc92..e9a8deea1 100644
--- a/control-api/src/services/llmModelImpact.ts
+++ b/control-api/src/services/llmModelImpact.ts
@@ -49,6 +49,7 @@
* (`routes/admin/llmModels.ts`) and, later, `GET /admin/attention` (Fase 5).
* Neither reconstructs the impact — both call `computeModelImpact`.
*/
+import type { DbClient } from '../db.js'
import {
type HostModelRole,
enumerateHostModelReferences,
@@ -118,11 +119,30 @@ interface HostListGateway {
export function modelImpactSourcesFromGateway(
gateway: HostListGateway,
hostNamespaces: string[]
+): ModelImpactSources {
+ // Delegates with `db` unset so the grant query defaults to the global pool —
+ // ONE derivation of the sources (regla D4), shared with the transactional form.
+ return modelImpactSourcesFromGatewayTx(gateway, hostNamespaces)
+}
+
+/**
+ * The impact sources for the R1-H3 reductor path: the grant query is bound to the
+ * caller's TRANSACTION client `db` (so the impact recompute happens under the
+ * advisory lock, on the same connection), while the Host LIST still reads K8s LIVE
+ * (a consistent etcd read — never a watch-cache, adenda A5 — so the reductor sees
+ * a CR a concurrent host-create just committed). Passing `db` omitted reproduces
+ * the non-transactional form exactly (grant query on the pool). `computeModelImpact`
+ * and its fail-loud contract are untouched.
+ */
+export function modelImpactSourcesFromGatewayTx(
+ gateway: HostListGateway,
+ hostNamespaces: string[],
+ db?: DbClient
): ModelImpactSources {
return {
hostNamespaces,
listHostsInNamespace: namespace => gateway.listResource('hosts', namespace),
- listGrantsForModel: model => listGrantsReferencingModel(model),
+ listGrantsForModel: model => listGrantsReferencingModel(model, db),
}
}
diff --git a/control-api/test/routes.adminLlmModels.test.ts b/control-api/test/routes.adminLlmModels.test.ts
index 06deb5f46..4dc1f9eb9 100644
--- a/control-api/test/routes.adminLlmModels.test.ts
+++ b/control-api/test/routes.adminLlmModels.test.ts
@@ -12,6 +12,15 @@ vi.mock('../src/db.js', () => ({
pool: {
query: (...args: unknown[]) => mockPoolQuery(...args),
},
+ // R1-H3 fase 1: the reductor gate now runs inside a carrier transaction. Route
+ // the transaction client's queries through the SAME `mockPoolQuery` so the
+ // sequenced expectations are unchanged; the advisory lock / idle-timeout guards
+ // are no-ops here (serialization is covered by the real-Postgres race test).
+ withTransaction: (work: (db: { query: (...a: unknown[]) => unknown }) => Promise<unknown>) =>
+ work({ query: (...args: unknown[]) => mockPoolQuery(...args) }),
+ advisoryLockModelName: async () => {},
+ advisoryLockModelNames: async () => {},
+ boundCarrierTransactionIdleTimeout: async () => {},
}))
vi.mock('../src/utils/auth/adminAuthToken.js', () => ({
diff --git a/control-api/test/routes.adminLlmModelsImpact.test.ts b/control-api/test/routes.adminLlmModelsImpact.test.ts
index a6978a44d..aa15a1568 100644
--- a/control-api/test/routes.adminLlmModelsImpact.test.ts
+++ b/control-api/test/routes.adminLlmModelsImpact.test.ts
@@ -20,6 +20,15 @@ vi.mock('../src/db.js', () => ({
pool: {
query: (...args: unknown[]) => mockPoolQuery(...args),
},
+ // R1-H3 fase 1: the reductor gate now runs inside a carrier transaction. Route
+ // the transaction client's queries through the SAME `mockPoolQuery` so the
+ // sequenced expectations are unchanged; the advisory lock / idle-timeout guards
+ // are no-ops here (serialization is covered by the real-Postgres race test).
+ withTransaction: (work: (db: { query: (...a: unknown[]) => unknown }) => Promise<unknown>) =>
+ work({ query: (...args: unknown[]) => mockPoolQuery(...args) }),
+ advisoryLockModelName: async () => {},
+ advisoryLockModelNames: async () => {},
+ boundCarrierTransactionIdleTimeout: async () => {},
}))
vi.mock('../src/utils/auth/adminAuthToken.js', () => ({
diff --git a/control-api/test/routes.hostModelReferences.test.ts b/control-api/test/routes.hostModelReferences.test.ts
index 024580a73..d8f411083 100644
--- a/control-api/test/routes.hostModelReferences.test.ts
+++ b/control-api/test/routes.hostModelReferences.test.ts
@@ -29,10 +29,15 @@ describe('enumerateHostModelReferences — example coverage (T4)', () => {
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' },
+ {
+ key: k('claude', 'claude-haiku-4-5'),
+ role: 'primary',
+ provider: 'claude',
+ model: 'claude-haiku-4-5',
+ },
+ { key: k('openai', 'gpt-5'), role: 'allowedModels', provider: 'openai', model: 'gpt-5' },
+ { key: k('groq', 'llama-4'), role: 'allowedModels', provider: 'groq', model: 'llama-4' },
+ { key: k('zai', 'glm-4'), role: 'fallback', provider: 'zai', model: 'glm-4' },
])
})
@@ -44,9 +49,9 @@ describe('enumerateHostModelReferences — example coverage (T4)', () => {
}
const key = k('claude', 'm')
expect(enumerateHostModelReferences(spec)).toEqual([
- { key, role: 'primary' },
- { key, role: 'allowedModels' },
- { key, role: 'fallback' },
+ { key, role: 'primary', provider: 'claude', model: 'm' },
+ { key, role: 'allowedModels', provider: 'claude', model: 'm' },
+ { key, role: 'fallback', provider: 'claude', model: 'm' },
])
})
@@ -73,9 +78,9 @@ describe('enumerateHostModelReferences — example coverage (T4)', () => {
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' },
+ { key: k('claude', 'm'), role: 'primary', provider: 'claude', model: 'm' },
+ { key: k('openai', 'gpt-5'), role: 'allowedModels', provider: 'openai', model: 'gpt-5' },
+ { key: k('zai', 'glm-4'), role: 'fallback', provider: 'zai', model: 'glm-4' },
])
})
diff --git a/control-api/test/routes.llmModelHostRace.realPostgres.integration.test.ts b/control-api/test/routes.llmModelHostRace.realPostgres.integration.test.ts
new file mode 100644
index 000000000..39d97374d
--- /dev/null
+++ b/control-api/test/routes.llmModelHostRace.realPostgres.integration.test.ts
@@ -0,0 +1,280 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { randomBytes } from 'node:crypto'
+import { Pool } from 'pg'
+import request from 'supertest'
+
+// R1-H3 fase 1 (host↔model) — regression test for the TOCTOU race the advisory
+// lock closes (mini-spec §7 / T3 / T4). It drives the race through the REAL route
+// handlers over HTTP against a REAL Postgres, so the SAME file, run against the
+// parent commit (bb51c5eb, no lock), fails BY ASSERTION: without serialization the
+// reductor enumerates an empty impact (the host is parked before its CR lands),
+// deletes the model, and the host CR is then created referencing a deleted model —
+// a dangling reference, and the reductor answers 204 instead of 409.
+//
+// Determinism WITHOUT a production test hook (adenda A4): a `MockGateway` subclass
+// defers `createResource`/`listResource` for Hosts on a barrier the test controls,
+// parking one writer WHILE it holds (child) / would hold (parent) the lock, then
+// firing the other. Fixtures come from the REAL producers (T1): the allowlist row
+// from `createAllowedModel`, the Host CR from the same `gateway.createResource` the
+// impact enumeration later LISTs. Skipped without CONTROL_API_REAL_PG_ADMIN_URL.
+
+const mockVerifyAdminToken = vi.fn()
+const mockIsAdminTokenRevoked = vi.fn()
+const mockFindAdminById = vi.fn()
+
+vi.mock('../src/utils/auth/adminAuthToken.js', () => ({
+ verifyAdminToken: (...args: unknown[]) => mockVerifyAdminToken(...args),
+}))
+
+vi.mock('../src/services/adminAuthService.js', () => ({
+ findAdminById: (...args: unknown[]) => mockFindAdminById(...args),
+ isAdminTokenRevoked: (...args: unknown[]) => mockIsAdminTokenRevoked(...args),
+}))
+
+const ADMIN_CLAIMS = {
+ sub: '00000000-0000-4000-8000-000000000001',
+ typ: 'user' as const,
+ role: 'admin' as const,
+ jti: 'admin-jti',
+ exp: Math.floor(Date.now() / 1000) + 3600,
+}
+const ACTIVE_ADMIN = {
+ id: ADMIN_CLAIMS.sub,
+ username: 'admin',
+ email: '[email protected]',
+ passwordHash: 'hash',
+ sessionVersion: 0,
+ role: 'admin' as const,
+ status: 'active' as const,
+ failedAttempts: 0,
+ lockedUntil: null,
+}
+const COOKIE = 'control_ui_admin_session=admin-token'
+
+const PROVIDER = 'claude'
+const MODEL = 'meta-llama/Llama-3.1-8B' // a name with a slash — never a valid lock/key separator
+
+function deferred<T = void>(): { promise: Promise<T>; resolve: (v: T | PromiseLike<T>) => void } {
+ let resolve!: (v: T | PromiseLike<T>) => void
+ const promise = new Promise<T>(r => {
+ resolve = r
+ })
+ return { promise, resolve }
+}
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+describeRealPostgres('llm-model reductor ↔ host referencer serialization (R1-H3 fase 1)', () => {
+ const database = `control_api_host_model_race_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? 'postgresql://[email protected]/postgres',
+ database
+ )
+ const previousPgEnv = process.env.CONTROL_API_PG_CONNECTION_STRING
+
+ let adminPool: Pool
+ let corePool: Pool
+ // Loaded dynamically AFTER the env points the module pool at the test DB.
+ let mod: {
+ createApp: (gateway: unknown) => import('express').Express
+ config: typeof import('../src/config.js').config
+ pool: import('../src/db.js').DbClient
+ createAllowedModel: typeof import('../src/services/llmAllowedModels.js').createAllowedModel
+ MockGateway: typeof import('./mockGateway.js').MockGateway
+ }
+ let BarrierGatewayClass: new (ns?: string) => BarrierGatewayShape
+
+ interface BarrierGatewayShape {
+ blockHostCreate: boolean
+ blockHostList: boolean
+ hostCreateEntered: ReturnType<typeof deferred>
+ releaseHostCreate: ReturnType<typeof deferred>
+ hostListEntered: ReturnType<typeof deferred>
+ releaseHostList: ReturnType<typeof deferred>
+ listResource: (plural: string, ns?: string) => Promise<unknown[]>
+ }
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+
+ // Point the process at the fresh DB BEFORE importing db/config/app so the
+ // module pool (and everything the app wires) connects there.
+ process.env.CONTROL_API_PG_CONNECTION_STRING = connectionString
+
+ const dbMod = await import('../src/db.js')
+ // The module core pool holds idle connections; when afterAll terminates
+ // backends before DROP DATABASE, those idle clients surface a 57P01 error.
+ // Absorb it so teardown is clean (the pool is being torn down anyway).
+ corePool = dbMod.pool as unknown as Pool
+ corePool.on('error', () => {})
+ const migratePool = new Pool({ connectionString })
+ await dbMod.initDb({ connect: () => migratePool.connect() })
+ await migratePool.end()
+
+ const appMod = await import('../src/app.js')
+ const configMod = await import('../src/config.js')
+ const allowlistMod = await import('../src/services/llmAllowedModels.js')
+ const { MockGateway } = await import('./mockGateway.js')
+ mod = {
+ createApp: appMod.createApp as never,
+ config: configMod.config,
+ pool: dbMod.pool,
+ createAllowedModel: allowlistMod.createAllowedModel,
+ MockGateway,
+ }
+
+ // A gateway that can park Host create / Host list on a barrier the test drives.
+ class BarrierGateway extends MockGateway {
+ blockHostCreate = false
+ blockHostList = false
+ hostCreateEntered = deferred()
+ releaseHostCreate = deferred()
+ hostListEntered = deferred()
+ releaseHostList = deferred()
+
+ override async createResource(
+ plural: Parameters<InstanceType<typeof MockGateway>['createResource']>[0],
+ body: Parameters<InstanceType<typeof MockGateway>['createResource']>[1],
+ namespace?: string
+ ): Promise<unknown> {
+ if (plural === 'hosts' && this.blockHostCreate) {
+ this.hostCreateEntered.resolve()
+ await this.releaseHostCreate.promise
+ }
+ return super.createResource(plural, body, namespace)
+ }
+
+ override async listResource(
+ plural: Parameters<InstanceType<typeof MockGateway>['listResource']>[0],
+ namespace?: string
+ ): Promise<unknown[]> {
+ if (plural === 'hosts' && this.blockHostList) {
+ this.hostListEntered.resolve()
+ await this.releaseHostList.promise
+ }
+ return super.listResource(plural, namespace)
+ }
+ }
+ BarrierGatewayClass = BarrierGateway as never
+ }, 60_000)
+
+ afterAll(async () => {
+ if (previousPgEnv === undefined) delete process.env.CONTROL_API_PG_CONNECTION_STRING
+ else process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgEnv
+ // Drain the module pool's connections first so DROP DATABASE has no live users.
+ await corePool?.end().catch(() => {})
+ if (!adminPool) return
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ })
+
+ beforeEach(async () => {
+ mockVerifyAdminToken.mockReset().mockReturnValue(ADMIN_CLAIMS)
+ mockIsAdminTokenRevoked.mockReset().mockResolvedValue(false)
+ mockFindAdminById.mockReset().mockResolvedValue(ACTIVE_ADMIN)
+ // Clean slate per test: no rows, no hosts leaking between orderings.
+ await mod.pool.query('DELETE FROM llm_allowed_models')
+ })
+
+ afterEach(async () => {
+ await mod.pool.query('DELETE FROM llm_allowed_models')
+ })
+
+ async function seedEnabledModel(): Promise<string> {
+ const row = await mod.createAllowedModel(
+ { provider: PROVIDER, model: MODEL, enabled: true },
+ 'test-actor'
+ )
+ return row.id
+ }
+
+ const hostBody = (name: string) => ({
+ metadata: { name },
+ spec: { model: { provider: PROVIDER, name: MODEL } },
+ })
+
+ async function modelRow(id: string): Promise<{ enabled: boolean } | undefined> {
+ const res = await mod.pool.query('SELECT enabled FROM llm_allowed_models WHERE id = $1', [id])
+ return res.rows[0] as { enabled: boolean } | undefined
+ }
+
+ it('host commits first → reductor sees the CR under the lock and 409s (no dangling reference)', async () => {
+ const id = await seedEnabledModel()
+ const gateway = new BarrierGatewayClass()
+ const app = mod.createApp(gateway)
+
+ // 1. Park the host-create INSIDE createResource — it holds the model lock.
+ gateway.blockHostCreate = true
+ const hostDone = (async () =>
+ request(app).post('/api/v1/admin/hosts').set('Cookie', COOKIE).send(hostBody('race-host')))()
+ await gateway.hostCreateEntered.promise
+
+ // 2. Fire the non-forced DELETE reductor; give it time to block on the lock
+ // (child) or to read+delete an empty impact (parent) before we release.
+ const reductorDone = (async () =>
+ request(app).delete(`/api/v1/admin/llm-models/${id}`).set('Cookie', COOKIE))()
+ await new Promise(r => setTimeout(r, 400))
+
+ // 3. Let the host CR land + commit, releasing the lock.
+ gateway.releaseHostCreate.resolve()
+ const [hostRes, reductorRes] = await Promise.all([hostDone, reductorDone])
+
+ // Observable final state (T4): the host was created, the reductor was refused
+ // with the impact naming the host, and the model row still exists ENABLED — no
+ // Host CR points at a removed pair.
+ expect(hostRes.status).toBe(201)
+ expect(reductorRes.status).toBe(409)
+ expect(reductorRes.body.error).toBe('model_in_use')
+ expect(
+ (reductorRes.body.impact.hostsAffected as Array<{ name: string }>).map(h => h.name)
+ ).toContain('race-host')
+ expect((await modelRow(id))?.enabled).toBe(true)
+ const hosts = await gateway.listResource('hosts', mod.config.hostsNamespace)
+ expect(hosts).toHaveLength(1)
+ }, 30_000)
+
+ it('reductor commits first → host revalidates under the lock and 422s (no dangling reference)', async () => {
+ const id = await seedEnabledModel()
+ const gateway = new BarrierGatewayClass()
+ const app = mod.createApp(gateway)
+
+ // 1. Park the reductor INSIDE its impact Host LIST — it holds the model lock.
+ gateway.blockHostList = true
+ const reductorDone = (async () =>
+ request(app).delete(`/api/v1/admin/llm-models/${id}`).set('Cookie', COOKIE))()
+ await gateway.hostListEntered.promise
+
+ // 2. Fire the host-create; give it time to block on the lock (child) before we
+ // release the reductor's LIST.
+ const hostDone = (async () =>
+ request(app)
+ .post('/api/v1/admin/hosts')
+ .set('Cookie', COOKIE)
+ .send(hostBody('race-host-2')))()
+ await new Promise(r => setTimeout(r, 400))
+
+ // 3. Let the reductor finish its (empty) impact, delete, and commit — releasing
+ // the lock so the host revalidates against the now-deleted model.
+ gateway.releaseHostList.resolve()
+ const [reductorRes, hostRes] = await Promise.all([reductorDone, hostDone])
+
+ expect(reductorRes.status).toBe(204)
+ expect(hostRes.status).toBe(422)
+ expect(await modelRow(id)).toBeUndefined()
+ const hosts = await gateway.listResource('hosts', mod.config.hostsNamespace)
+ expect(hosts).toHaveLength(0)
+ }, 30_000)
+})
diff --git a/control-api/test/routes.resources.hostTolerance.test.ts b/control-api/test/routes.resources.hostTolerance.test.ts
index 4f5409c68..06b4487f4 100644
--- a/control-api/test/routes.resources.hostTolerance.test.ts
+++ b/control-api/test/routes.resources.hostTolerance.test.ts
@@ -9,6 +9,22 @@ import { MockGateway } from './mockGateway.js'
// after the Host CR persists — never on a rejected or failed write. isModelAllowed
// is mocked to disable the model; the logger is mocked to observe emission.
+// R1-H3 fase 1: Host create/update wrap validation + the K8s write in a carrier
+// transaction holding a per-model-name advisory lock. Keep db.js real; stub only
+// the transaction runner + lock / idle-timeout guards so these route tests need no
+// live Postgres (serialization is covered by the real-Postgres race test).
+vi.mock('../src/db.js', async () => {
+ const actual = await vi.importActual<typeof import('../src/db.js')>('../src/db.js')
+ return {
+ ...actual,
+ withTransaction: (work: (db: { query: (...a: unknown[]) => unknown }) => Promise<unknown>) =>
+ work({ query: async () => ({ rows: [], rowCount: 0 }) }),
+ advisoryLockModelName: async () => {},
+ advisoryLockModelNames: async () => {},
+ boundCarrierTransactionIdleTimeout: async () => {},
+ }
+})
+
const llm = vi.hoisted(() => ({ isModelAllowed: vi.fn() }))
vi.mock('../src/services/llmAllowedModels.js', async () => {
const actual = await vi.importActual<typeof import('../src/services/llmAllowedModels.js')>(
diff --git a/control-api/test/routes.resources.staleModelWarning.logInjection.test.ts b/control-api/test/routes.resources.staleModelWarning.logInjection.test.ts
index 188e78225..9048b485b 100644
--- a/control-api/test/routes.resources.staleModelWarning.logInjection.test.ts
+++ b/control-api/test/routes.resources.staleModelWarning.logInjection.test.ts
@@ -33,6 +33,22 @@ vi.mock('../src/observability/logger.js', async () => {
return { rootLogger }
})
+// R1-H3 fase 1: Host create/update wrap validation + the K8s write in a carrier
+// transaction holding a per-model-name advisory lock. Keep db.js real; stub only
+// the transaction runner + lock / idle-timeout guards so these route tests need no
+// live Postgres (serialization is covered by the real-Postgres race test).
+vi.mock('../src/db.js', async () => {
+ const actual = await vi.importActual<typeof import('../src/db.js')>('../src/db.js')
+ return {
+ ...actual,
+ withTransaction: (work: (db: { query: (...a: unknown[]) => unknown }) => Promise<unknown>) =>
+ work({ query: async () => ({ rows: [], rowCount: 0 }) }),
+ advisoryLockModelName: async () => {},
+ advisoryLockModelNames: async () => {},
+ boundCarrierTransactionIdleTimeout: async () => {},
+ }
+})
+
const llm = vi.hoisted(() => ({
isModelAllowed: vi.fn(),
getModelAllowlistState: vi.fn(),
diff --git a/control-api/test/routes.resources.staleModelWarning.test.ts b/control-api/test/routes.resources.staleModelWarning.test.ts
index a6aa1cada..cf99437fe 100644
--- a/control-api/test/routes.resources.staleModelWarning.test.ts
+++ b/control-api/test/routes.resources.staleModelWarning.test.ts
@@ -11,6 +11,22 @@ import { MockGateway } from './mockGateway.js'
// that a live reference is not revalidated, that a non-stale model warns nothing,
// and that a write that fails to persist surfaces no warning.
+// R1-H3 fase 1: Host create/update wrap validation + the K8s write in a carrier
+// transaction holding a per-model-name advisory lock. Keep db.js real; stub only
+// the transaction runner + lock / idle-timeout guards so these route tests need no
+// live Postgres (serialization is covered by the real-Postgres race test).
+vi.mock('../src/db.js', async () => {
+ const actual = await vi.importActual<typeof import('../src/db.js')>('../src/db.js')
+ return {
+ ...actual,
+ withTransaction: (work: (db: { query: (...a: unknown[]) => unknown }) => Promise<unknown>) =>
+ work({ query: async () => ({ rows: [], rowCount: 0 }) }),
+ advisoryLockModelName: async () => {},
+ advisoryLockModelNames: async () => {},
+ boundCarrierTransactionIdleTimeout: async () => {},
+ }
+})
+
const llm = vi.hoisted(() => ({
isModelAllowed: vi.fn(),
getModelAllowlistState: vi.fn(),
diff --git a/control-api/test/routes.resources.test.ts b/control-api/test/routes.resources.test.ts
index cb0e07f8d..1318d1361 100644
--- a/control-api/test/routes.resources.test.ts
+++ b/control-api/test/routes.resources.test.ts
@@ -11,6 +11,23 @@ vi.mock('node:dns/promises', () => ({
lookup: vi.fn(),
}))
+// R1-H3 fase 1: Host create/update now wrap validation + the K8s write in a
+// carrier transaction that holds a per-model-name advisory lock. Keep the rest of
+// db.js real; stub only the transaction runner + lock / idle-timeout guards so
+// these route tests need no live Postgres (serialization is covered by the
+// real-Postgres race test).
+vi.mock('../src/db.js', async () => {
+ const actual = await vi.importActual<typeof import('../src/db.js')>('../src/db.js')
+ return {
+ ...actual,
+ withTransaction: (work: (db: { query: (...a: unknown[]) => unknown }) => Promise<unknown>) =>
+ work({ query: async () => ({ rows: [], rowCount: 0 }) }),
+ advisoryLockModelName: async () => {},
+ advisoryLockModelNames: async () => {},
+ boundCarrierTransactionIdleTimeout: async () => {},
+ }
+})
+
class PruningCommunicationChannelGateway extends MockGateway {
override async createResource(
plural: Parameters<MockGateway['createResource']>[0],