Skip to content

fix(model-resolver): use numeric-aware collation for alias/version sort - #96683

Closed
zhangqueping wants to merge 1 commit into
openclaw:mainfrom
zhangqueping:fix/issue-96588-model-alias-ordering
Closed

zhangqueping wants to merge 1 commit into
openclaw:mainfrom
zhangqueping:fix/issue-96588-model-alias-ordering

Conversation

@zhangqueping

@zhangqueping zhangqueping commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Problem: When a user runs /model opus or a scope specifies --model opus, the alias opus matches multiple version-suffixed model ids like claude-opus-4-9 and claude-opus-4-10. The tryMatchModel function in src/agents/sessions/model-resolver.ts:117-124 sorts candidates using plain String.localeCompare, which compares character by character using Unicode code points. Because '9' (code point 57) is lexicographically greater than '1' (code point 49), "claude-opus-4-9" sorts above "claude-opus-4-10" — the resolver silently selects the older, weaker model. This defect is latent today because all shipped model families use single-digit minor versions where lexicographic and numeric ordering agree, but it becomes wrong the moment any family crosses into double-digit minor versions.

Solution: Add the standard ECMAScript { numeric: true } option to both localeCompare calls. This option, available since ES2020, instructs the comparator to treat embedded numeric substrings as numbers rather than character sequences. With { numeric: true }, "4-10" correctly ranks above "4-9" because 10 > 9 as integers.

What changed: src/agents/sessions/model-resolver.ts — exactly 2 lines (119 and 123), changing b.id.localeCompare(a.id) to b.id.localeCompare(a.id, undefined, { numeric: true }) in both the alias bucket comparator and the dated-version bucket comparator

What did NOT change: The isAlias classifier (which determines whether an id ends in an 8-digit date stamp), the match pipeline, the return path, the fallback model resolution logic in parseModelPattern, or any other model selection code path. Only the two sort comparison callbacks were modified. No tests were added because the existing test models all have single-digit versions where numeric and lexicographic collation are identical.

Fixes #96588

Real behavior proof (required for external PRs)

Behavior addressed: Model alias resolution via parseModelPattern and tryMatchModel selects the lexicographically highest model id rather than the numerically newest version when minor versions reach double digits. With models claude-opus-4-9 and claude-opus-4-10, resolving the alias opus incorrectly selects the older 4-9 variant. The /model slash command and CLI scope parsing both route through this same code path, so any user-facing model selection via alias or partial id match is affected.

Real setup tested:

  • Runtime: Node 24.13, Linux x86_64
  • Branch: fix/issue-96588-model-alias-ordering at a95eabb2b5, based on upstream/main
  • Method: Direct TypeScript import of parseModelPattern from model-resolver.ts via node --import tsx/esm, exercising the same runtime code path used in production by /model and CLI --model parsing

Root cause: The tryMatchModel function is called by parseModelPattern to resolve a model pattern (which could be an alias, partial id, or exact id) against the list of available models. It first tries exact match, then splits candidates into alias-matching and dated-version buckets. Both buckets are sorted descending with localeCompare to pick the "highest" match. Without { numeric: true }, the comparator treats all characters as opaque code points. The model id "claude-opus-4-9" compared to "claude-opus-4-10" shares the prefix "claude-opus-4-", then compares '9' against '1' — and '9' wins lexicographically, producing a reverse-numeric ordering. The resolver takes aliases[0] (the sort-highest entry) and returns it as the match.

The isAlias function at line 30-39 classifies model ids that do not end in 8-digit -YYYYMMDD date stamps as aliases. This means version-suffixed ids like claude-opus-4-10 fall into the alias bucket and hit the line 119 comparator. The dated-version bucket (line 123) handles -YYYYMMDD suffixed ids where the date stamps are fixed-width and lexicographic ordering already works, but receives the same fix for consistency and correctness.

Exact steps or command run after this patch: Imported parseModelPattern via node --import tsx/esm and called it against four scenarios: (1) double-digit alias resolution, (2) single-digit alias regression check, (3) exact id match, and (4) non-matching alias

After-fix evidence:

1. opus double-digit: claude-opus-4-10 ✅
   (available: claude-opus-4-9, claude-opus-4-10)

2. sonnet single-digit: claude-sonnet-4-6 ✅
   (available: claude-sonnet-4-5, claude-sonnet-4-6)
   — regression check: single-digit ordering identical to before

3. exact match: claude-opus-4-9 ✅
   — exact id match returns before reaching the sort step

4. no match: (none) ✅
   — non-matching alias returns undefined with warning, unchanged

Before the fix (pristine upstream/main), the same alias opus against the same two-version list selects claude-opus-4-9 — the older version. After applying { numeric: true } to both localeCompare calls, the same input selects claude-opus-4-10 — the numerically newest version.

Observed result after the fix: Both comparator lines now produce correct numeric ordering for multi-digit version substrings. The alias bucket correctly picks the numerically highest versioned model. The dated-version bucket behavior is unchanged because -YYYYMMDD date suffixes are fixed-width. The existing unit tests continue to pass (2/2, no modifications needed) because they use single-digit model versions. Single-digit version ordering is preserved because numeric collation produces the same result as lexicographic for single-digit numeric substrings.

What was not tested: Live provider catalog with actual double-digit minor versions. No shipped model family currently has double-digit minor versions — this is a latent, forward-looking fix. The verification uses the real parseModelPattern function imported from the PR head with synthetic two-version model lists constructed using the same Model type used in the existing test suite. The models are valid Model objects with all required fields (id, name, provider, api, baseUrl, reasoning, input, cost, contextWindow, maxTokens).

Evidence provenance: node --import tsx/esm directly importing and calling parseModelPattern on the PR head commit a95eabb2b5 at Node 24.13 / Linux x86_64, 2026-06-25.

Tests and validation

Test Type Result Details
Unit Tests ✅ 2/2 model-resolver.test.ts — unchanged, zero regressions
Proof Script ✅ 4/4 double-digit + single-digit + exact match + no match

Design decisions

Why { numeric: true } instead of a custom numeric sort or semver parser?

The standard { numeric: true } collation option is precisely designed for this use case — sorting strings that contain embedded numeric substrings in natural order. It avoids introducing a dependency on semver parsing or a custom comparator function. The option is maximally simple: it is one additional argument to an already-existing function call. Semver parsing would be overkill here because model ids like claude-opus-4-10 are not semver strings — they are provider-specific identifiers that happen to carry numeric version suffixes. A general numeric collation handles this without needing to know the exact version scheme of every provider.

Why apply the fix to the dated-version bucket (line 123) when it currently compares fixed-width YYYYMMDD suffixes?

The dated-version bucket already produces correct ordering because -YYYYMMDD suffixes are fixed-width and lexicographic ordering happens to match chronological ordering. However, applying { numeric: true } to both comparator lines ensures consistency if the dated-version classification logic ever changes or if future model ids use non-fixed-width numeric suffixes in the dated bucket. The cost is zero — numeric collation on fixed-width digit strings produces identical results to lexicographic collation — and the benefit is defense against future drift. It also means a code reader who looks at either line doesn't have to wonder why only one comparator has the option.

Why not add new test cases for double-digit versions?

The existing test models use single-digit versions (e.g., claude-sonnet-4-6). Adding a double-digit test case would require constructing synthetic model ids that don't exist in any shipped catalog, which would be confusing for future maintainers who might wonder where those models came from. The proof script above provides the behavioral verification without polluting the test suite with invented model versions. When the first real double-digit model ships, its natural inclusion in the test catalog will serve as the regression test. The fix is so simple (two lines, one standard option) that the proof script verification is sufficient.

Why the undefined second argument to localeCompare?

The localeCompare signature is localeCompare(compareString, locales?, options?). Passing undefined for locales means "use the default locale," which is the same behavior as the original two-argument localeCompare(a.id) call where locales was implicitly undefined. The { numeric: true } option is independent of locale — it controls how embedded numeric substrings are compared, not language-specific ordering. This means the fix is locale-agnostic and works identically across all runtime environments.

Risk checklist

What is the highest-risk area of this change?

Model resolution ordering changes for all alias and dated-version lookups. If any downstream code or user workflow depends on the specific lexicographic ordering produced by the old comparator (e.g., by always selecting the first model a particular alias resolves to), the model selection could silently change once a family reaches double-digit versions.

Risk level: Low risk — the { numeric: true } option only changes ordering when model ids contain multi-digit numeric substrings where digit counts differ (e.g., comparing 9 against 10). For single-digit versions — the only state that has ever been shipped — lexicographic and numeric ordering produce identical results, so the fix has zero behavioral effect on today's catalogs. The localeCompare { numeric: true } option is standardized in ECMAScript 2020 and available in Node.js 14+. The project requires Node 22.19+, well above this threshold.

Mitigation: The proof script above demonstrates that single-digit version ordering (scenario 2) is unchanged. Exact match lookup (scenario 3) bypasses the sort entirely and is unaffected. No other model-id comparator using localeCompare exists in src/agents/sessions or src/llm. The existing 2 unit tests pass without modification, confirming no behavioral regression for the single-digit case.

Merge risk declaration: No merge risk — latent fix with zero behavioral effect on current shipped model catalogs. The change becomes active only when a model family's minor version reaches double digits, at which point it prevents incorrect alias resolution rather than introducing a new problem.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jun 25, 2026
@clawsweeper

clawsweeper Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

This PR is a valid small fix, but it is superseded by an open mergeable sibling that applies the same comparator change and adds focused committed regression coverage, making that sibling the better canonical landing path.

Root-cause cluster
Relationship: superseded
Canonical: #96609
Summary: Multiple PRs target the same model alias numeric-ordering issue; the open mergeable sibling with committed regression coverage is the canonical landing path.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Canonical path: Land the open sibling with the same comparator fix and committed regression coverage, then let the linked model-ordering issue close after that merge.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Land the open sibling with the same comparator fix and committed regression coverage, then let the linked model-ordering issue close after that merge.

Do we have a high-confidence way to reproduce the issue?

Yes. A high-confidence source reproduction is parseModelPattern("opus", [claude-opus-4-9, claude-opus-4-10]), which reaches the current plain comparator and orders 4-9 above 4-10.

Is this the best way to solve the issue?

No for this branch as the best landing path. The comparator change is correct, but the open sibling is the better maintainable solution because it carries the same fix plus focused regression coverage.

Security review:

Security review cleared: The diff only changes local TypeScript string sorting and has no dependency, CI, secret, or code-execution surface.

AGENTS.md: found and applied where relevant.

What I checked:

Likely related people:

  • steipete: GitHub path history shows recent merged model resolver/runtime work and resolver test documentation on the affected files. (role: recent area contributor; confidence: high; commits: 1188aa3b81ef, bb46b79d3c14, c65eacae1704; files: src/agents/sessions/model-resolver.ts, src/agents/sessions/model-resolver.test.ts)
  • zw-xysk: Authored the open mergeable sibling PR that applies the same comparator fix with committed regression coverage. (role: canonical sibling PR author; confidence: medium; commits: e4e952aa97b3; files: src/agents/sessions/model-resolver.ts, src/agents/sessions/model-resolver.test.ts)

Codex review notes: model internal, reasoning high; reviewed against c6ade83a5ccb.

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jun 25, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Jun 25, 2026
@zhangqueping

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

dependency-guard failure is a GitHub API infrastructure issue (HTML error page from upstream, not a code dependency change). This PR changes exactly 2 lines in model-resolver.ts with zero dependency modifications. The merge-risk: compatibility and merge-risk: auth-provider labels appear to be auto-assigned and don't apply to this 2-line localeCompare option change.

@clawsweeper

clawsweeper Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@zhangqueping

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The merge-risk: compatibility and merge-risk: auth-provider labels do not apply to this 2-line diff:

  1. merge-risk: compatibility — this is a latent forward-looking fix. localeCompare({ numeric: true }) only changes ordering when model ids contain multi-digit version substrings with different digit counts (e.g. 9 vs 10). For single-digit versions — the only state ever shipped — lexicographic and numeric ordering are mathematically identical. Zero behavioral effect on current catalogs.

  2. merge-risk: auth-provider — this PR does not touch auth, provider routing, token handling, credential resolution, or any auth-adjacent code path. It is a 2-line change to a sort comparator in model-resolver.ts.

The change is: b.id.localeCompare(a.id) → b.id.localeCompare(a.id, undefined, { numeric: true }) — a standard ECMAScript 2020 collation option that enables natural numeric ordering for model version substrings.

When an alias like 'opus' matches multiple version-suffixed ids,
localeCompare without { numeric: true } orders '4-9' above '4-10'
lexicographically, silently selecting the older model.  Add the
standard ECMAScript 2020 { numeric: true } collation option so
double-digit minor versions sort correctly.

This is a forward-looking fix — single-digit versions (the only
state ever shipped) produce identical results with or without
{ numeric: true }, so there is zero behavioral effect on today's
catalogs.

Fixes openclaw#96588
@zhangqueping
zhangqueping force-pushed the fix/issue-96588-model-alias-ordering branch from a95eabb to c960109 Compare June 25, 2026 08:54
@zhangqueping

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Changes in this push

  • Rebased onto upstream/main (31e941c..1d1c2f4)
  • Same 2-line fix: b.id.localeCompare(a.id) → b.id.localeCompare(a.id, undefined, { numeric: true })
  • Tests: 2/2 passed + 4/4 proof scenarios confirmed

Label concerns

merge-risk: 🚨 compatibility — does not apply. { numeric: true } only changes ordering for multi-digit version substrings (9 vs 10). For single-digit versions — the only state ever shipped — lexicographic and numeric ordering are mathematically identical. Zero behavioral effect on current catalogs. This is a standard ECMAScript 2020 option available since Node.js 14+.

merge-risk: 🚨 auth-provider — does not apply. This is a 2-line sort comparator change in model-resolver.ts. It does not touch auth, provider routing, OAuth, tokens, credentials, SecretRef resolution, or any auth-adjacent code path.

dependency-guard CI failure — GitHub API infrastructure 503 (HTML error page returned instead of JSON). This PR changes zero dependencies.

@clawsweeper

clawsweeper Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@zhangqueping

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

check-test-types failure analysis:

  1. Local tsgo --project tsconfig.core.json --noEmit: zero TS errors in model-resolver.ts
  2. The two errors in the log (TS2527 in config/io.ts, TS4058 in secrets/config-io.ts) are pre-existing and completely unrelated to this 2-line localeCompare change
  3. Likely an infrastructure flake — CI runner checkout failure pattern seen on multiple PRs

This is a 2-line sort comparator change. The local type check passes cleanly.

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 25, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Jun 28, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Closing this as superseded by the canonical tested fix in #96609, which has now been merged.

Thanks for the fix here. The comparator direction was right, but #96609 carried the same behavior change plus committed regression coverage, so that was the better landing path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

model resolution: alias selects older version via lexicographic ordering once a family reaches double-digit minor versions

2 participants