Skip to content

fix(discovery): persist provider token ceilings and context windows - #952

Merged
seonghobae merged 14 commits into
mainfrom
codex/commercial-loop-20260831-issue927-root-cause
Sep 1, 2026
Merged

fix(discovery): persist provider token ceilings and context windows#952
seonghobae merged 14 commits into
mainfrom
codex/commercial-loop-20260831-issue927-root-cause

Conversation

@seonghobae

@seonghobae seonghobae commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

Summary

  • persist per-model and from discovery without conflating the two
  • carry those fields through agent persistence, CLI output, and API contract surfaces
  • clamp explicit outgoing token-budget fields to a known provider output ceiling

Testing

  • ============================= test session starts ==============================
    platform darwin -- Python 3.13.14, pytest-9.0.3, pluggy-1.6.0
    rootdir: /Users/seonghobae/Documents/ChatGPT/contextual-orchestrator
    configfile: pyproject.toml
    plugins: cov-7.1.0, anyio-4.14.1, hypothesis-6.165.10
    collected 0 items

============================ no tests ran in 0.37s =============================

  • ============================= test session starts ==============================
    platform darwin -- Python 3.13.14, pytest-9.0.3, pluggy-1.6.0
    rootdir: /Users/seonghobae/Documents/ChatGPT/contextual-orchestrator
    configfile: pyproject.toml
    plugins: cov-7.1.0, anyio-4.14.1, hypothesis-6.165.10
    collected 4 items

tests/test_api_contract.py .... [100%]

============================== 4 passed in 0.66s ===============================

Closes #927.


Devin Review

Summary by CodeRabbit

  • 새로운 기능
    • 모델 검색 결과에 최대 출력 토큰과 컨텍스트 창 정보가 표시됩니다.
    • 에이전트 생성·수정 시 두 제한값을 설정할 수 있습니다.
    • 제한값이 에이전트 구성과 데이터베이스에 저장되고 재시작 후에도 유지됩니다.
  • 개선 사항
    • 요청의 토큰 예산이 에이전트의 최대 출력 한도에 맞게 자동 조정됩니다.
    • 다양한 모델 정보 제공처의 제한값을 검증·병합하며, 불일치하거나 유효하지 않은 값은 제외합니다.
  • 문서
    • 모델 제한값의 해석 및 적용 기준을 문서화했습니다.

@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

Next included review available in 15 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: 31bef3d9-4111-459c-8ee9-e7e4ae62617d

📥 Commits

Reviewing files that changed from the base of the PR and between 72e5ef9 and 9bfec18.

📒 Files selected for processing (4)
  • contextual_orchestrator/model_discovery.py
  • contextual_orchestrator/provider_catalog_store.py
  • tests/test_model_discovery.py
  • tests/test_provider_catalog_store.py
📝 Walkthrough

Walkthrough

모델 검색 결과에 max_output_tokenscontext_window가 추가되었습니다. 두 필드는 에이전트 설정, SQLite 및 PostgreSQL 저장소, API, CLI 출력으로 전달됩니다. 알려진 출력 상한은 요청의 토큰 예산에 적용됩니다.

Changes

모델 한도 검색 및 합의

Layer / File(s) Summary
모델 한도 검색 및 합의
contextual_orchestrator/model_discovery.py, tests/test_model_discovery.py
여러 검색 소스에서 한도 메타데이터를 검증하고 병합합니다. 배포 값이 누락되거나 충돌하면 해당 플래그를 설정합니다. 중복 모델의 충돌 값은 제거합니다.

에이전트 계약, 저장소 및 요청 제한

Layer / File(s) Summary
에이전트 계약 및 요청 제한
contextual_orchestrator/orchestrator.py, tests/test_orchestrator_client_boundaries.py
ModelAgent가 두 필드를 검증하고 직렬화합니다. ModelClient의 일반, 스트리밍, 원시, 배치 요청은 알려진 max_output_tokens를 초과하지 않도록 토큰 예산을 제한합니다.
에이전트 영속화 및 API 연결
contextual_orchestrator/orchestrator.py, contextual_orchestrator/server.py, contextual_orchestrator/api_contract.py, tests/test_agent_pool_db.py, tests/test_api_contract.py
SQLite 스키마와 마이그레이션, 삽입, 갱신, 조회 경로가 새 필드를 처리합니다. 생성 및 패치 API와 관리자 응답이 필드를 노출합니다.
Provider catalog 저장 및 복원
contextual_orchestrator/provider_catalog_store.py, docs/provider_catalog_database.sql, tests/test_provider_catalog_store.py
provider_model 컬럼을 nullable bigint로 변경하고 범위 제약을 추가합니다. 메모리 및 PostgreSQL 저장 경로가 누락 값과 충돌 플래그를 처리합니다.

CLI 보고 및 통합 검증

Layer / File(s) Summary
CLI 보고 및 자동 검색 갱신
contextual_orchestrator/__main__.py, tests/test_discover_models_cli.py, tests/test_auto_discovery_server.py
discover-models 보고서가 두 필드를 출력합니다. 자동 검색은 기존 에이전트의 한도를 갱신하고, 운영자 설정을 유지하며, 변경된 에이전트를 다시 동기화합니다.
조사 및 회귀 문서
docs/library_research.md, docs/product-technical-gap-baseline.md
필드 매핑, 출력 예산 제한, provider catalog 동기화 및 관련 검증 결과를 기록합니다.

Estimated code review effort: 4 (Complex) | ~60 minutes

Merge Risk: 🟡 Moderate · up to 72e5e

The PR persists provider limits and uses them to constrain outgoing token budgets, but invalid discovered values can retain stale ceilings and gateway context metadata can bypass deployment-consensus checks. These bounded correctness issues may cause incorrect request limits in production, so merge should wait for fixes or explicit owner acceptance.

Sequence Diagram(s)

sequenceDiagram
  participant ModelProvider as Model provider
  participant ModelDiscovery as model_discovery
  participant AgentPool as agent_pool
  participant ModelClient
  participant ProviderAPI as Provider API

  ModelProvider->>ModelDiscovery: model limit metadata
  ModelDiscovery->>ModelDiscovery: validate and merge metadata
  ModelDiscovery->>AgentPool: persist ModelAgent limits
  AgentPool-->>ModelClient: load max_output_tokens
  ModelClient->>ProviderAPI: clamp outgoing token budget
Loading
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning 토큰 제한 메타데이터 작업과 직접 관련이 없는 변경이 포함되어 있습니다. 특히 docs/product-technical-gap-baseline.md의 Strix gateway 및 provider catalog 장애 분석과 일부 discovery 재시도·ZDR·크레딧 게이팅 변경은 [#927]의 범위를 벗어납니다. 범위를 벗어난 문서와 기능 변경을 별도 pull request로 분리하십시오. 이 pull request에는 [#927]에 필요한 provider limit discovery, persistence, propagation, clamping 및 관련 테스트만 남기십시오.
Docstring Coverage ⚠️ Warning Docstring coverage is 44.93% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 69 functions across 12 files. (3 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 모델 탐색에서 provider token ceiling과 context window를 저장하는 핵심 변경을 정확하고 간결하게 설명합니다.
Linked Issues check ✅ Passed 직접 연결된 이슈 [#927]의 핵심 요구사항을 충족합니다. DiscoveredModel과 ModelAgent에 두 메타데이터를 추가하고, provider discovery·저장소·API·CLI로 전달합니다. 알려진 max_output_tokens를 요청 예산에 적용하고 충돌 및 미확인 값을 별도로 처리합니다.
Full details: Docstring Coverage

Explanation

Docstring coverage is 44.93% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 69 functions across 12 files. (3 skipped: 2 unsupported, 1 too large.)

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/commercial-loop-20260831-issue927-root-cause

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

devin-ai-integration[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@seonghobae

Copy link
Copy Markdown
Contributor Author

Cross-PR integration contract: routing identity is provider-neutral model_group only; do not add or preserve a provider-family abstraction. OpenRouter discovery must retain concrete free model IDs, while the aggregate openrouter/free router is not a serving candidate. OpenCode, Noema, and Strix must call contextual-orchestrator. Do not impose fixed wall-clock deadlines on inference, initial ping, readiness/health, provider discovery, or OpenRouter ZDR-list retrieval; use explicit cancellation and evidence-backed transport failure instead. Reconcile this PR with #971 and central .github #1508 before merge.

devin-ai-integration[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 new potential issue.

Devin Review

context_window=context_window,
max_output_tokens_conflicted=(
row.get("_max_output_tokens_conflicted") is True
or any(value is None for value in output_limits)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Missing enrichment clears saved limits

When Models.dev omits a limit, _merge_models_dev_metadata inserts None, which becomes a conflict. A successful refresh then deletes the saved limit.

Prompt for agents
Distinguish absent Models.dev limit metadata from explicitly invalid provider metadata. _merge_models_dev_metadata currently always writes max_output_tokens and context_window, using None when limit.output or limit.context is absent; _parse_openai_compatible now interprets any present invalid value as a conflict, and provider catalog refreshes use that conflict to clear persisted limits. Preserve the conflict signal for explicit invalid values, but omit candidate keys when the upstream source supplied no value. Add coverage for a previously saved limit followed by Models.dev metadata that omits one or both limits, alongside the existing explicit zero/negative invalid-metadata cases.
Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@seonghobae
seonghobae merged commit 4099e2e into main Sep 1, 2026
22 of 23 checks passed
@seonghobae
seonghobae deleted the codex/commercial-loop-20260831-issue927-root-cause branch September 1, 2026 07:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Capture and expose real per-model max-output-tokens / context-window data from discovery

1 participant