Repository navigation
feat(core): unify model identifier vocabulary and harden ModelRegistry(PR #2097 perfected) - #3965
Merged
jujn merged 4 commits intoNov 10, 2026
Conversation
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
Follow-up to agentscope-ai#2097: rename the per-call model selection to modelIdentity, formalize the model identifier vocabulary (providerId, modelId, modelCreationContextId, modelInstanceId, modelIdentity), and harden ModelRegistry. Consumer layer: - RuntimeContext.modelId -> modelIdentity; ReActAgent.Builder.model(String) becomes a lazy per-call reference instead of resolving at build time (priority: ctx.modelIdentity > agent identity > Model instance; unresolvable identities fail the call instead of silently falling back) - New composite identity form contextId@modelId (e.g. mytokenplan01@dashscope:qwen-plus): the credentials pairing travels with the identity string, so cross-provider per-call switching needs no agent-level context assumption - Two configuration forms for an agent's model: a fixed Model instance or a registry-managed modelIdentity reference (one slot, last setter wins) ModelRegistry: - resolve(String) is the single identity entry: composite dispatch first, then registered instances (explicit pins outrank pattern routing and the cache), then derivation; the two-argument resolve(modelId, context) is purely the derivation path and never consults registered instances, closing the cross-tenant credentials shadowing; canResolve mirrors both - Named creation contexts: registerCreationContext / getCreationContext / unregisterCreationContext; re-registering a contextId rotates credentials by evicting explicit:<contextId> entries, effective for resolutions that start afterwards (residual window documented) - Cache identity coherence: ENABLED contexts without standard fields share the legacy bucket; length-prefixed fingerprints (no separator collisions); explicit-cacheId drift warning while the cacheId stays authoritative - SPI determinism: multiple providers claiming one id fail listing all candidates; the not-found message lists installed provider ids; reloadProviders evicts SPI-derived cache entries - API hygiene: register/unregister/getRegistered trim and reject blank or '@'-containing ids; '@' is reserved for the composite identity syntax; evictResolvedCache gained a string-keyed (contextId, modelId) overload Docs: concept dictionary and matching-rules table in ModelRegistry javadoc; modelId vs modelIdentity distinction in building-blocks/model.md and integration/model/index.md; per-call selection guide in building-blocks/context.md — EN/ZH aligned.
xzxiaoshan
force-pushed
the
feat/model-registry-optimization
branch
from
November 4, 2026 10:04
46426b3 to
03a944a
Compare
- Replace the RuntimeContext.modelIdentity string API with a typed pin (ctx.put(Model.class, ...)): per-call selection now pins a resolved instance, so applications resolve choices behind their own auth/allowlist instead of transporting identity strings - Resolve identity-mode agents once per run at run entry on a boundedElastic scheduler and memoize into the run context: no mid-run model switch, and a slow factory never blocks the subscriber's (possibly event-loop) thread - Harden creation-context rotation with generation-suffixed cache identities: an in-flight pre-rotation resolution can no longer poison post-rotation lookups - Update extension consumers (controlplane adapter, admin metrics, admin compaction) for identity-mode agents - Align EN/ZH docs with the new selection semantics
… semantics - Reject '#' in contextId registrations and hand-built cacheIds so named rotation generations (contextId#generation) can never collide with or over-purge another id's cache entries; add regression tests for the rejection and for rotation sparing unrelated cache ids. - Clarify in ReActAgent javadoc and EN/ZH docs that the RuntimeContext Model.class slot is intentionally the generic typed channel: callers may pin per-call, middleware/tools may replace the model mid-run; the framework itself resolves once at run entry and never switches the model on its own mid-response. - Align EN/ZH model docs with the generational cacheId semantics and add plain-terms registered-name wording for modelInstanceId/contextId.
jujn
approved these changes
Nov 10, 2026
5 tasks done
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.
Follow-up to #2097. The original goal still stands: one singleton agent serving many sessions that need different models, without reflection or per-tenant agent instances. Along the way this PR also straightens out the model identifier vocabulary and makes
ModelRegistrysafe under concurrent rotation. The description below reflects the final shape after two rounds of review; the design did move during review, so if you reviewed an earlier iteration, skim the per-call section again.Two ways to give a ReActAgent its model
Either you build the model yourself and hand it over, or you hand over a string and let the registry do the work:
The two overloads are one configuration slot, last setter wins. An identity string is held as a lazy reference and resolved once per run, at run entry, on a boundedElastic scheduler, so a slow factory never sits on the caller's thread (which may well be an event loop). The resolved instance is memoized into the run's context: the model is decided once and never switches mid-response. Re-registering an instance, factory, or creation context affects runs that start afterwards, not runs in flight. An identity that cannot be resolved fails the run at entry instead of quietly falling back to some other model.
Per-call selection is now a typed pin
An earlier iteration of this PR put a
modelIdentitystring onRuntimeContext. That API is gone in the final version, and the reasoning is worth spelling out: a context-level identity string invites passing client-supplied input straight through, and deciding whether a caller may use a given tenant's credentials is an application concern, not a framework concern.What remains is deliberately minimal:
ctx.put(Model.class, ...)is the only per-call channel, and it is fully developer-controlled: build and cache instances yourself, or letModelRegistrymanage creation and rotation and pin what it resolves. Nothing string-shaped about model selection travels through the context anymore. The pin outranks both agent-level forms, subagent spawning and durable sessions clear it, and a pinned model that fails at runtime is still covered by the configuredfallbackModel.Identifier vocabulary
Five nouns, one per concept, used consistently across API names, javadoc, and EN/ZH docs:
providerIddashscopemodelIddashscope:qwen-maxproviderId:modelName, the recipe: what to createmodelCreationContextId(arg:contextId)mytokenplan01modelInstanceIdmy-prod-model-01register/unregister/getRegistered)modelIdentitymytokenplan01@dashscope:qwen-maxresolve(String)and the agent-levelmodel(String)@is reserved for the composite form and rejected in instance and context ids, so a registration can never shadow a composite identity.Registry hardening
resolve(String)is the identity entry point: registered instances first, then composite dispatch, then the flat cache / user factory / SPI chain.resolve(modelId, context)is purely derivation and no longer consults registered instances; previously a named registration could shadow context-aware resolution and hand one tenant another party's credentials.registerCreationContextand friends) now carry a generation number inside their cache identity. Re-registering a contextId rotates credentials, and an in-flight resolution that started before the rotation can only publish under its retired generation, where no post-rotation lookup will find it. There is a deterministic concurrency test for exactly this interleaving.|or=cannot collide.reloadProviders()evicts entries that can only have come from SPI providers.resolvepublishes its cache entry before it picks a factory, so a resolution racing a registration cannot strand a stale entry.Behavior changes
RuntimeContext.modelId(feat(core): per-call model selection via RuntimeContext.modelId #2097) and the interimmodelIdentityare removed with no deprecated bridge. The commit that introduced them is in no released tag (git tag --contains cffb72979comes back empty), so this reworks an unreleased API rather than breaking a shipped one.getModel()now documents that it returns null for identity-mode agents; the extension consumers that relied on non-null (controlplane adapter, admin metrics, admin compaction) were moved togetModel(null)with a raw-identity fallback where a name is all that is needed.resolve(id, context)no longer returns registered instances for any context, including the empty one; useresolve(id)orgetRegistered(id).IllegalArgumentExceptioninstead of logging and picking whichever was discovered first.Known trade-offs
Things reviewers flagged that we looked at and decided to keep as-is:
cacheIdstays authoritative: resolving it with different credentials logs a drift warning and still returns the cached instance. Uniqueness of a hand-built cacheId is the developer's guarantee, same as any named registry key; credential rotation is whatregisterCreationContextis for, and the docs say so in EN and ZH.AgentScopeAdapter,MetricsHook, admin compaction) still resolve synchronously viagetModel(null)rather than hopping to boundedElastic. They read the warm registry cache and don't run on event loops, so I left them alone.HarnessAgent.Builder.model(String)still resolves eagerly at build time. Harness orchestration (subagents, memory, compaction) needs a concreteModelat build time, so the eager/lazy split between the two builders is intentional and documented.evictResolvedCache(null, modelId)remains ambiguous between theStringandModelCreationContextoverloads; the javadoc tells you to pass a blank string instead, andevictResolvedCacheForContext(String)covers the by-context case without any null.Tests and docs
Full core suite (1601 tests), the harness suite, and the controlplane and admin-starter suites all pass locally. New coverage includes the rotation race, run-scoped memoization, entry-point fail-fast, off-thread resolution, pin priority, and subagent/session isolation. EN/ZH pages for
model.md,context.md, andintegration/model/index.mdwere updated to match, including a note that client-supplied identities must be resolved behind the application's own auth/allowlist before pinning.