On this page
- Status: Accepted
- Date: 2026-06-23
- Context: CLAUDE.md §61, the AI Adapter (
/admin/ai,/settings/ai) - Supersedes / relates: the single-row
ai_configsmodel
Context#
Per-org AI runtime was a single ai_configs row (one provider + one model + one
key). Three problems compounded:
- No resilience. When the configured provider/model timed out or died, every AI feature (chat, dashboard insights, MI insights, prompt preview) failed with no fallback.
- Duplicated config plumbing. The "read
ai_configs→ decrypt the key → map the provider slug (gemini→google) → build the model config" pipeline was copy-pasted across ~5 call sites. The copies drifted: the provider maps disagreed (one was exhaustive incl.mistral, the others special-cased onlygemini), error handling diverged (412 vs warn-skip vs PRECONDITION_FAILED), and the enum even differed (the settings router omittedmistral). A sixth consumer (packages/agent) was about to copy it again. - Backend leaked to end users. The chat header rendered
ollama · kimi-k2.6:cloudand the public landing page hardcodedclaude · sonnet-4-6plusAnthropic / OpenAI / Geminivendor chips — exposing the BYO-LLM backend a customer must never see (same class as never exposing 3rd-party source names).
Decision#
1. ai_connections — many ordered connections per org
A new org-scoped table (RLS via org_only_tables, is_sample). Each row:
provider, friendly label, an ORDERED models[] ([0] = primary model,
[1..] = intra-connection backup models tried on the same key/endpoint),
envelope-encrypted key, baseUrl, a priority integer (cross-connection
failover order, 0 = primary), and isActive. A partial unique index keeps at
most one active priority = 0 connection per org.
ai_configs is kept as a single-row back-compat pointer synced to the primary
connection on every save (many "is configured?" readers still hit it). Migration
0064 creates ai_connections and idempotently backfills the existing
ai_configs row at priority 0. A later migration drops ai_configs and the
dead ai_configs_role once every reader is migrated.
2. One resolver (kills the dedup)
The read→decrypt→provider-map→flatten pipeline now lives in exactly one place:
resolveAiCandidates(rows, opts)— pure (packages/ai/src/resolve.ts): decrypt (@yng/crypto),toRegistryProvider(gemini→google, the single provider map inproviders.ts), and flatten the connections (priority order) × theirmodels[](array order) into one orderedAiConfig[]. Index 0 = the primary connection's primary model. Returns a discriminated{ ok, candidates, rawProviderSlug } | { ok:false, reason }.resolveOrgAi(orgId, opts)/loadAiConnectionRows(orgId)— the DB loader (@yng/ai/server) bothapps/webandapps/workerimport, so the SELECT + ordering live in one copy.opts.modelOverride(the MI insight model) is applied on the primary connection;opts.draftshort-circuits to a single test-before-save candidate.
Every call site collapses onto it: api/chat/route.ts,
worker/processors/ai.ts, routers/ai-prompts.ts (preview),
routers/ai-configs.ts (test/list). The pure core stays free of
@yng/schema/client; only the @yng/ai/server subpath pulls the DB.
3. One failover primitive
createFailoverModel(candidates) / createFailoverLanguageModel(configs)
(packages/ai/src/failover.ts) wraps the ordered candidate list into a single
LanguageModelV3:
doGenerate: try candidates in order, advance on a retryable error.doStream: peek-then-commit — buffer the leading control parts and fail over only if an error surfaces before the first content token; once committed, pass the stream through untouched (you cannot re-stream after emitting tokens).- Per-attempt TTFB timeout (
AbortSignal.anycomposed with the caller's signal; cleared at commit so a slow-but-progressing stream is never aborted). classifyFailover: auth/401/403, 4xx, 5xx, 429, timeout, network →retry-next(candidate B may have a valid key); only caller-abort + malformed-prompt (InvalidPromptError/TypeValidationError) →fatal-all.- A lone candidate is returned unwrapped — zero overhead, behaviour identical to the old single-connection path.
streamChat gained an optional pre-built model param so chat passes the
failover model while still using the primary AiConfig for tool-support gating +
prompt caching.
4. Model hidden from end users; Mistral first-class
Provider/model visibility is confined to the operator config screens
(/admin/ai, /settings/ai). The chat header now shows a neutral "Trợ lý sẵn
sàng" pill; the landing page shows a generic "AI" badge + "Pluggable LLM" tag with
its mockup copy routed through @yng/i18n. Mistral is now a first-class provider
across the registry, the settings form, and the resolver.
5. Correctness hardening
The chat system prompt gained a grounding contract (every number must be copied
verbatim from a tool result; never self-compute a sum/ratio/delta; abstain with
— when data is missing; never claim a trend without its period). forecastMetric
returns a confidence interval and abstains (mode='insufficient_data', chart
hidden) when there is too little history to project. The dashboard role-prompt
footer gained an explicit "only state numbers present in the data" clause.
Guardrail (§61)#
scripts/audit/ai-resolver-single-source.py (wired into audit:all):
(a) fails if decryptEnvelope( sits next to an aiConfigs/aiConnections read
outside the resolver (allowlist: the config router; suppress
// audit-ok-ai-resolver:); (b) fails on a raw AI vendor name or LLM model id on
an end-user surface (suppress // audit-ok-ai-model-id:). Not metric-bearing → no
verify:data assertion.
Consequences#
- Operators configure a primary + ordered backup connections, each with ordered
backup models, in the redesigned
/admin/aiUI (a single combobox per model — the old duplicate "type the id again" field is gone). - Failover is one-way once a stream commits (post-first-token errors propagate) — accepted, bounded by tight TTFB timeouts. Each attempt is a real provider call, so a failover can incur a partial billed call on the dead candidate.
- Cross-provider candidate sets used for tool-calling chat should be tool-capable; the admin UI is the place to warn (follow-up).
2026-07-05 update — resolver soft-degrade + bounded insight jobs#
Three resilience refinements shipped after operating the failover runtime.
A1 — a corrupt envelope key degrades soft, never 500s
resolveAiCandidates now decrypts each connection's key defensively (a per-row
try/catch, packages/ai/src/resolve.ts). A corrupt envelope — the "Unsupported
state or unable to authenticate data" case that appears after importing an org
between machines encrypted under a different ENCRYPTION_KEY, or a botched key
rotation — no longer throws up through every AI surface. Behaviour:
- a backup connection with a good key still wins (the failover intent is preserved);
- only when EVERY active connection fails to decrypt does the resolver return the
new discriminated
{ ok:false, reason:'decrypt_failed' }— distinct fromnot_configured(nothing set) andunknown_provider(config bug).
Callers map decrypt_failed to a soft state, never a raw 500: /api/chat → 412
with a "re-save the key in /admin/ai" message; marketIntel.requestInsight →
PRECONDITION_FAILED (the insight card renders "AI chưa sẵn sàng", i18n
marketIntel.aiNotConfigured); the worker logs and skips cleanly. The
single-source fix means EVERY AI surface benefits at once (§61). Locked by
apps/web/src/__tests__/ai-resolve.test.ts (decrypt-fail + backup-survives +
override-dropped cases).
A2 — total per-job time budget for insight generation
The worker insight loop (truncation / malformed / transient retries, MAX_ATTEMPTS)
nests the intra-candidate failover (N candidates × per-attempt timeout), so the
naive worst case was MAX_ATTEMPTS × N × timeout — minutes for a single stuck job
parking a worker slot. runBoundedInsightGeneration
(apps/worker/src/processors/insight-generation.ts) adds ONE job-level
AbortController deadline (WORKER_AI_JOB_DEADLINE_MS, default 120 s): it is
threaded as the abortSignal into every generate call, so a fired deadline both
aborts the in-flight attempt AND stops candidate-walking (the failover model
re-throws on abortSignal.aborted instead of advancing); the loop then breaks
without retrying (an AbortError classifies as retry-next, which would otherwise
burn the next attempt). §63 preserved: budget exhaustion publishes NOTHING (the
surface shows its empty/retry state). The loop is pure with an injected generate,
so it is unit-tested against a deliberately slow candidate
(insight-generation.test.ts).
A3 — insight worker concurrency default 2 → 4
WORKER_AI_CONCURRENCY now defaults to 4, so a dashboard's ~20 insight widgets
fill in ~5 waves instead of ~10. Safe now that each job is time-bounded (A2). Both
knobs are documented in .env.example (WORKER_AI_CONCURRENCY,
WORKER_AI_JOB_DEADLINE_MS). Raise further only after checking the provider's own
rate limit (too high trades 429s for throughput).
A4 — chat TTFB (measurement note)
The /api/chat pre-stream context reads were parallelised into one Promise.all
batch (logged as [chat] pre-stream {ms}). Effectiveness is measured on real
traffic; if the prep step stays > 150 ms the next candidate is a short-TTL per-org
cache for resolveOrgAi (it decrypts on every request). Not built speculatively —
it waits on the measurement (§55).