Skip to content

feat(core): unify model identifier vocabulary and harden ModelRegistry(PR #2097 perfected) - #3965

Merged
jujn merged 4 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/model-registry-optimization
Nov 10, 2026
Merged

jujn merged 4 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/model-registry-optimization

Conversation

@xzxiaoshan

@xzxiaoshan xzxiaoshan commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

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 ModelRegistry safe 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:

ReActAgent.builder().model(myModelInstance)                        // fixed instance
ReActAgent.builder().model("mytokenplan01@dashscope:qwen-plus")    // registry-managed reference

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 modelIdentity string on RuntimeContext. 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:

// resolve behind your own auth/allowlist, then pin the instance:
Model choice = ModelRegistry.resolve("mytokenplan01@dashscope:qwen-plus");
ctx.put(Model.class, choice);   // no pin = the agent's build-time model

ctx.put(Model.class, ...) is the only per-call channel, and it is fully developer-controlled: build and cache instances yourself, or let ModelRegistry manage 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 configured fallbackModel.

Identifier vocabulary

Five nouns, one per concept, used consistently across API names, javadoc, and EN/ZH docs:

Term Example Meaning
providerId dashscope Routing key, the prefix of a modelId
modelId dashscope:qwen-max providerId:modelName, the recipe: what to create
modelCreationContextId (arg: contextId) mytokenplan01 Handle of a registered creation context: with what inputs
modelInstanceId my-prod-model-01 Handle of a whole pinned instance (register / unregister / getRegistered)
modelIdentity mytokenplan01@dashscope:qwen-max Selection string: which model to use. Input of resolve(String) and the agent-level model(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.
  • Named creation contexts (registerCreationContext and 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.
  • Cache identity coherence: an ENABLED context with no standard fields shares the legacy bucket instead of spawning duplicate instances (two HTTP clients for identical inputs), and fingerprints are length-prefixed so values containing | or = cannot collide.
  • SPI determinism: multiple providers claiming one id now fail with all candidates listed instead of first-discovered-wins; the not-found message lists the provider ids actually installed; reloadProviders() evicts entries that can only have come from SPI providers.
  • Registration races are closed by ordering: factory registration adds first and evicts afterwards, and resolve publishes 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 interim modelIdentity are removed with no deprecated bridge. The commit that introduced them is in no released tag (git tag --contains cffb72979 comes back empty), so this reworks an unreleased API rather than breaking a shipped one.
  • Plain 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 to getModel(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; use resolve(id) or getRegistered(id).
  • Conflicting SPI providers throw IllegalArgumentException instead of logging and picking whichever was discovered first.

Known trade-offs

Things reviewers flagged that we looked at and decided to keep as-is:

  • A hand-built cacheId stays 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 what registerCreationContext is for, and the docs say so in EN and ZH.
  • Extension metadata paths (AgentScopeAdapter, MetricsHook, admin compaction) still resolve synchronously via getModel(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 concrete Model at build time, so the eager/lazy split between the two builders is intentional and documented.
  • evictResolvedCache(null, modelId) remains ambiguous between the String and ModelCreationContext overloads; the javadoc tells you to pass a blank string instead, and evictResolvedCacheForContext(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, and integration/model/index.md were updated to match, including a note that client-supplied identities must be resolved behind the application's own auth/allowlist before pinning.

@mintlify

mintlify Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit c525f4c.

Approve preview

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
xzxiaoshan force-pushed the feat/model-registry-optimization branch from 46426b3 to 03a944a Compare November 4, 2026 10:04
@jujn jujn added the P2 重要不紧急 label Nov 7, 2026
- 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
@xzxiaoshan xzxiaoshan changed the title feat(core): unify model identifier vocabulary and harden ModelRegistry feat(core): unify model identifier vocabulary and harden ModelRegistry(PR #2097 perfected) Nov 9, 2026
… 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
jujn merged commit c05e4b9 into agentscope-ai:main Nov 10, 2026
7 checks passed
@xzxiaoshan
xzxiaoshan deleted the feat/model-registry-optimization branch November 12, 2026 08:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants