Repository navigation
fix(platform): serve, govern, and bill models as configured - #3161
Merged
Merged
Conversation
resolveModelGovernanceForUser cut every candidate at its first '/', so a bare catalog id like z-ai/glm-5.1 was compared against rule lists that kept the slash: an allowlist dropped every slash id (Auto refused with no-accessible-model) and a blocklist admitted the blocked ones (Auto picked them, the turn-boundary check then refused the message). The candidates are the catalog's own ids; the evaluator already normalizes both sides through the one ref grammar (stripModelRefQualifier — colon qualifier, @quant pin), so pass them through unmodified, exactly as the composer's picker filter does.
resolveEffectiveLimits flagged the whole effective triple as team-scoped the moment ANY field came from a team rule, so a per-member token cap resolved from the default tier was checked against the team's combined tokens (tripping TOKEN_LIMIT for the whole team), while a user-tier override emptied the team list and silently lifted the team's shared cap. The resolver now returns each team's own caps as teamLimits — that team's rule values, tightest per field — and every enforcer (the 0.5 checkTtsBudget behind the composer gate, TTS, and video links; the reused checkBudget and computeRollingRemainingCostCents) measures a team cap against that team's aggregate only, with the personal triple kept to the member's own usage.
The updateCredential adapter forwarded only name/status/allowlist/secret,
so the broker Replace-configuration dialog ({broker}), the env Replace
dialog ({envName}), the edit dialog's endpointUrl, and isDefault were
dropped on the floor — the backend acked the empty patch, wrote an audit
row, and nothing changed. The adapter now mirrors the create row field
for field (broker → secret JSON); the backend accepts envName for env
credentials (prefix-gated), validates an edited endpoint, skips the
masked preview on a broker rotation like creation does, refuses an empty
patch (400 CREDENTIAL_PATCH_EMPTY), and refuses promoting a disabled
credential to default — serving reads the active default only, so a
disabled default is a connector that serves nothing.
…list Azure OpenAI and Nous Portal declare catalog: none — the provider files and the docs both say the credential's model allowlist becomes the availability set — yet every lane (composer walk, direct and subscription serving walks, pinned serving, chat resolveModel, the title lane) gated on catalog membership and getProviderCatalog answered [] for them, so a connector configured exactly as documented could never serve anything. getServableCatalog is the one read every lane now goes through: a provider with a catalog serves it (allowlist still a filter); a catalog-less provider synthesizes neutral chat entries from the credential's allowlist (no invented pricing or vision, an assumed context floor). The chat lane reads the default credential's allowlist for such a connector — the same credential its wire resolves.
The composer walked EVERY active credential while every serving path (the chat wire, agent walks, vision, TTS, title) resolves a provider's active DEFAULT credential — so after a routine key rotation (add B, disable or delete default A) the picker kept listing the provider's models and every send failed with "No default credential is configured". listServingCredentialFacts is now the one credential read behind both the picker and the Auto pick: the active default per provider, exactly the row serving resolves. A connector without an active default drops out of the picker (the settings page already flags it) instead of failing every turn.
createPgUsageLedger stamped costEstimateCents: 0 on every chat and title turn — its comment promised an analytics-time join that nothing performs: getOrgUsageMetricsPg, checkTtsBudget, and the budget-status gate all sum the stored column. The usage dashboard therefore showed $0 for all LLM activity and no maxCostCents rule could ever count model spend. Turns are now priced at booking from the serving connector's catalog pricing through estimateCostCents — the same formula the pipeline stamps on the message — with an unpriced model booking an honest 0 and a failed lookup logging and booking 0 rather than losing the token row.
provisionSessionGatewayKey caught a failed buildProviderProvision — the resolve that throws CREDENTIAL_DISABLED / CREDENTIAL_NONE_CONFIGURED for a disabled or deleted credential — and continued; mintVirtualKey then resolved the org's still-present upstream gateway key by its stable name and minted a working virtual key bound to the revoked secret. An admin disabling a compromised provider key saw chat refuse while sandbox agent turns kept consuming it. The mint now fails closed: every provider the session's models need must resolve to a live credential, or nothing is minted, and the refusal carries the credential's own message onto the run. Deleting the org's upstream key from the gateway (and revoking in-flight virtual keys) on credential disable/delete remains open — see the PR.
Both subscription serving paths warned only when the catalog entry lacked supportsVision, under a comment that every shipped subscription pair was vision-capable. Z.ai's Anthropic-compatible coding door drops every image content block with a 200 — glm-4.6v carries the flag and still answers blind — so an agent on a GLM Coding Plan read screenshots and scanned invoices it never saw and reported confidently on them. The capability is now a fact of the resolved pathway: subscription auth entries declare imageInputs (forwarded | dropped; zai declares dropped), the serving result carries whether images are readable (endpoint forwards AND model reads — the lane has no vision polyfill), and both agent hosts act on it: a turn whose staged inputs include image files is refused before anything is minted, with the reason and the fix on the run; every other blind turn briefs the agent to name an image it could not read instead of inventing its contents.
… walks The shared credential shim answered getDefaultCredentialInternal without model_allowlist, so every reused 0.4 walk running on 0.5 — the direct and pinned agent serving, the llm node, the title lane, and the chat lane's catalog-less lookup — saw a credential with no allowlist: an allowlist that narrows a credential was never enforced on those lanes, and a catalog-less provider (whose allowlist IS its availability set) served nothing through them. The row now carries the allowlist; the resolver ignores the extra field.
A send naming a model the org cannot serve — its provider's default
credential disabled or deleted, or a composer still holding a model the
picker has since dropped — threw CHAT_MODEL_UNKNOWN (and the credential
codes) out of the route unmapped, so the composer got a bare Internal
Server Error. The pre-turn serving refusals now come back as the same
{ status: 'refused', reason } shape every other refusal uses, carrying
the serving layer's own sentence; anything else stays an internal error.
The probe tries to promote a disabled credential to default; a backend that wrongly accepts it (the recorded defect) leaves the provider with a disabled default and starves every later openai-backed lane. Re-assert the env credential as default so the probe fails on its own line.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes the verified review class "the model/provider serving layer silently serves the wrong thing, keeps serving what should be gone, and mis-accounts usage" — eight findings, one commit per seam. The lens throughout: the picker only offers what will actually serve, an image never silently vanishes, a disabled credential stops serving everywhere, usage and cost reflect reality, an allowlist means what the docs say, and a saved credential edit takes effect.
Per finding
1. Auto model pick strips
vendor/from model ids —054632572Root cause.
resolveModelGovernanceForUserhad a localstripQualifierthat cut every candidate at its first/. Catalog ids such asz-ai/glm-5.1carry the slash as part of the id (the 0.5 ref grammar qualifies with:), while the rule lists went through the canonicalstripModelRefQualifierand kept the slash — so an allowlist dropped every slash id (Auto refused withno-accessible-model) and a blocklist admitted the blocked ones (Auto picked them; the turn-boundary check then refused the message).Fix. The divergent parser is deleted; candidates go to
filterAccessibleModelsunmodified, exactly as the composer's picker filter does, so picker and Auto agree by construction.Tests.
domains/governance/service.test.ts(5 cases overz-ai/glm-5.1,openrouter:anthropic/claude-sonnet-4.6@fp8, bare ids; allowlist, blocklist, agreement with the turn-boundary verdict, pin dropped when refused) — 4/5 red on base. Integration:checkGovernanceallowlist carriesvendor/itest-model; the Auto governance read keeps exactly it.User impact. Orgs with model-access policies and aggregator-style ids get a working Auto: allowed slash ids are picked, blocked ones never are.
2. zai subscription lane serves vision-capable GLM models blind —
4b4c96eceRoot cause. Both subscription serving paths warned only on
!entry.supportsVision("every shipped subscription pair is vision-capable today"). Z.ai's Anthropic-compatible coding door drops every image block with a 200 (live-verified 2026-08-26) —glm-4.6vcarries the flag and still answers blind; the lane has no vision polyfill (no gateway key). The flag guarded the wrong fact.Fix. The capability is a property of the resolved pathway: subscription auth entries declare
imageInputs: forwarded | dropped(schema +zai/provider.ymldeclaresdropped);subscriptionVisionCapability= endpoint forwards AND model reads; the serving result carriesvision: { readable } | { readable: false, reason }. Both agent hosts act on it: a turn whose staged inputs include image files is refused before anything is minted, with the reason and the fix on the run (refuseBlindImageTurn); any other blind turn carries explicit guidance so the agent names an image it could not read instead of inventing its contents.stageWorkflowFilesnow returns the staged paths so the automation lane can apply the same rule as the task lane.Tests.
subscription_vision.test.ts(capability over zai/anthropic fixtures, image detection, refusal, guidance);agent_serving.test.ts(+3: zai vision GLM reads as blind with the drop reason; forwarding endpoint + vision model readable; text-only blind) — 6 red on base incl. the updated result shape.User impact. A GLM Coding Plan agent no longer "reads" invoices it never saw: image-bearing runs fail with an actionable reason; other runs say plainly which image they could not read.
3.
catalog: noneproviders (Azure, Nous Portal) can never serve anything —730bba914Root cause. The provider files and the docs say the credential's allowlist "becomes the availability set", but
getProviderCataloganswered[]forsource: noneand every lane (composer walk, direct/subscription serving walks, pinned serving, chatresolveModel, title lane) gated on catalog membership — a connector configured exactly as documented could never serve.Fix. One read for every lane:
getServableCatalog(provider, allowlist)— a provider with a catalog serves it (the allowlist stays a filter); a catalog-less provider synthesizes neutral chat entries from the allowlist (lib/shared/providers/allowlist_catalog.ts: no invented pricing or vision, an assumed 128k context floor, ids trimmed/deduped). The chat lane reads the default credential's allowlist for such a connector — the same credential its wire resolves. The docs (models.md,admin/providers.md) are now simply true; no doc change.Tests.
allowlist_catalog.test.ts;agent_serving.test.ts(+4: pinned Nous marketplace model, pinned Azure deployment, unpinned direct walk finds the deployment, empty allowlist serves nothing) — 3 red on base. Integration: an org provideritestdeploywithcatalog: none+ an allowlisted deployment name appears in the composer picker and serves a real chat turn end to end (turncompleted, ledger row booked).Companion seam —
0dcc871a2. The integration probe exposed that the shared credential shim answeredgetDefaultCredentialInternalwithoutmodel_allowlist, so every reused 0.4 walk on 0.5 (direct/pinned agent serving, the llm node, the title lane, the chat lane's catalog-less lookup) saw a credential with NO allowlist — a catalog-less provider served nothing through them, and an allowlist that narrows a credential was never enforced on those lanes at all. The row now carries the allowlist. Consequence worth knowing: an automation llm/agent node naming a model outside its credential's allowlist now refuses (the documented contract, and what the picker already did) instead of serving it.User impact. Azure OpenAI and Nous Portal credentials serve as documented; credential allowlists bind every lane.
4. Disabling/deleting the default credential kills serving while the picker still offers its models —
c57376b8eRoot cause. The composer walked EVERY active credential; every serving path resolves a provider's active DEFAULT (
getDefaultCredentialInternal:is_default AND status='active'). After a routine key rotation (add B, disable/delete default A) the picker kept listing the models and every send failed.Fix (intended model per
admin/providers.md"Choosing the default credential").listServingCredentialFacts— the active default per provider — is the one credential read behind both the picker (listComposerModels) and the Auto pick's credential shim. A connector without an active default drops out of the picker (the settings page already flags it) instead of failing every turn. Complementary contract enforcement (with #8): a disabled credential cannot be promoted to default.Companion seam —
da1dab42d. The integration probe showed the user-visible half: a send naming a model the org cannot serve (default disabled, or a composer still holding a model the picker has since dropped) threwCHAT_MODEL_UNKNOWNout of the route unmapped — a bare 500. The pre-turn serving refusals (CHAT_MODEL_UNKNOWN,CHAT_CREDENTIAL_UNSUPPORTED,CHAT_PROVIDER_ENDPOINT_MISSING,CREDENTIAL_NONE_CONFIGURED,CREDENTIAL_DISABLED,CREDENTIAL_KEY_ROTATED,CREDENTIAL_ENV_UNSET) now come back as the same{ status: 'refused', reason }shape every other refusal uses; anything else stays an internal error.Tests. Integration: with a second active non-default credential present, disabling the default removes the provider's models from the picker and a stale send comes back
refused, naming the model; re-enabling brings the models back.User impact. What the picker offers is what a turn can run — and a stale pick says why it cannot.
5. Disabled/deleted credentials keep serving sandbox sessions via stale gateway keys —
78224fbbdRoot cause.
provisionSessionGatewayKeycaught a failedbuildProviderProvision(which throwsCREDENTIAL_DISABLED/CREDENTIAL_NONE_CONFIGURED) and continued;mintVirtualKeythen resolved the org's still-present upstream key by its stable name and minted a working virtual key bound to the revoked secret.Fix. The mint fails closed: every provider the session's models need must resolve to a live credential now, or nothing is minted; the refusal carries the credential's own message onto the run as the reason the turn could not start.
Tests.
gateway_provisioning.test.ts: disabled credential → rejects, no provision, no mint; deleted default → rejects — 2 red on base (the old test that locked the continue-past behaviour is replaced).SCOPE-DEFERRED (honestly). Key lifecycle traced: virtual keys are per turn and revoked at finalize (
agent_host/agent_run_host); the org's upstream key (tale-<org>-<provider>) is never deleted, andreprovisionProviderhas no callers. With this fix no NEW virtual key can bind to a revoked credential. What remains open is the in-flight window: turns already running keep their virtual key (bound to the stale upstream key) until they finalize or hit the 12h deadline. Closing it means, on credential disable/delete, deleting the org's upstream key (DELETE /api/providers/:p/keys/:id— bifrost's key sub-resource) and revoking the org's running virtual keys for that provider, then letting the next provision self-heal (a missing key re-POSTs). That reaches into the gateway/sandbox subsystem and its live semantics (a VK bound to a deleted key id) are unverified here, so it is not half-done in this PR.User impact. Disabling or deleting a credential stops sandbox agent turns from minting against it.
6. LLM turns booked at cost 0 —
3af46cb88Root cause.
createPgUsageLedgerstampedcostEstimateCents: 0on every chat and title turn under a comment promising an analytics-time join;getOrgUsageMetricsPg,checkTtsBudget(the budget-status Send gate, TTS, video links) all sum the stored column. The dashboard showed $0 for all LLM activity; nomaxCostCentsrule could count model spend.Fix. Priced at booking from the serving connector's catalog
pricingthroughlib/chat/turn.estimateCostCents— the same formula the pipeline stamps on the message (the Convex-era ledger did exactly this). An unpriced model books an honest 0; a failed lookup logs and books 0 rather than losing the token row.Tests.
domains/chat/store.test.ts(pricing from catalog; unpriced/unknown → 0; catalog failure → 0 + warn; the ledger writes the priced cost into all three period buckets) — 4/4 red on base. Integration: the fake provider listing carriespricing;checkGovernanceasserts theitest-chatdaily bucket's cost > 0.Refuted-as-scoped sub-item. Dictation also books 0 — but no per-minute price fact exists anywhere in the catalog schema, so there is nothing to book from; noted rather than fabricating a rate.
User impact. Usage dashboard and cost budgets see real model spend.
7. Team budget check applies user/default-resolved caps to team aggregate usage —
43420094aRoot cause.
resolveEffectiveLimitsseteffectiveTeamIdswhen ANY field came from a team rule, and every enforcer then checked the whole mixed triple against team-aggregate usage: a per-member default-tier token cap was measured against the team's combined tokens (TOKEN_LIMIT for the whole team); conversely a user-tier override emptied the list and silently lifted the team's shared cap.Fix. The resolver returns each team's own caps as
teamLimits(that team's rule values, tightest per field); the personal triple stays measured against the member's own usage; every enforcer — the live 0.5checkTtsBudget(composer gate, TTS, video links) and the reusedcheckBudget/computeRollingRemainingCostCents— measures a team cap against that team's aggregate only.Tests.
budget_enforcement.test.ts(+6: mixed default+team resolution, user override keeps the team cap, per-team own values, tightest per field, no rule-bearing team) — 6 red on base. Integration: over the real enforcer, two members whose combined tokens exceed the per-member cap both stay allowed; the team's own cost cap still binds the aggregate (COST_LIMIT at its value).User impact. Teams stop seeing "Budget exceeded" at limits the admin set per person; team pools stay enforced.
8. Credential update adapter drops broker and endpointUrl —
ff9875d0eRoot cause. The
updateCredentialadapter forwarded only name/status/allowlist/secret; the broker Replace-configuration dialog ({broker}), the env Replace dialog ({envName}), the edit dialog'sendpointUrl, andisDefaultwere dropped; the backend acked the empty patch and wrote an audit row.Fix. The adapter mirrors the create row field for field (
broker → secretJSON); the backend acceptsenvNamefor env credentials (prefix-gated), validates an edited endpoint, skips the masked preview on a broker rotation like creation does, refuses an empty patch (400CREDENTIAL_PATCH_EMPTY) and refuses promoting a disabled credential to default (400CREDENTIAL_DISABLED_DEFAULT).Tests.
app/lib/backend/settings-provider-credentials.test.ts(4 adapter body cases) — 3/4 red on base. Integration: endpoint edit lands on the row, env re-point resolves the new variable, empty patch → 400, disabled → default → 400, broker rotation keeps no preview.User impact. A saved credential edit takes effect, or the save says why not.
Gates (observed)
tsc --noEmit: clean. Platformoxlint --type-aware(workspacelint): exit 0. Full platform vitest (server+piiprojects): 377 files, 72,310 tests passed, exit 0.backend:integrationon a fresh throwaway PG + MinIO (every run on a recreatedtale-db+ MinIO with a freshTALE_CONFIG_DIR) — branch: 283/283 checks passed, exit 0 (base's 279 + the 4 new records); base (main tip6eed31e60, its own integration-check): 279/279 checks passed, exit 0; base source + this branch's integration-check: 278/283, exit 1, no fatal — exactly the five records the new probes touch are red on base (credential edits; catalog-less serving; picker-vs-serving; governance with the slash-id Auto read and cost 0; budget scopes tripping TOKEN_LIMIT on the team aggregate) and every pre-existing check still passes.Cross-class discoveries (not fixed here)
checkBudget/computeRollingRemainingCostCentshave no 0.5 callers; the server-side chat turn enforces no budget of its own (the composer's pre-sendbudget-statusgate is the only LLM-lane budget stop).reprovisionProvider(gateway) has zero callers although its doc says credential-save calls it; upstream gateway keys are never deleted (see optimize chat agent #5's deferral).