Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ and this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html)

## [0.2.0] - Unreleased

### Fixed

- Model discovery now treats every KV credential as an independent account/catalog boundary, removes provider-family collapsing, and offers secret-free `--verbose` progress diagnostics. Logical equivalence and latency-based switching remain explicit `model_group` decisions only.
- Model-group evidence now reports peak observed RPM and provider-reported TPM over a real 60-second completion window without generating probe traffic or inferring missing usage.

### Added

- Generalized the Models.dev free-cost cross-reference (ADR 0032) beyond
Expand Down
15 changes: 15 additions & 0 deletions contextual_orchestrator/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import argparse
import json
import logging
import os
import sys
from dataclasses import replace
Expand Down Expand Up @@ -265,6 +266,11 @@ def _discover_models_command(argv: list[str]) -> None:
prog="python -m contextual_orchestrator discover-models",
description="Discover models from every provider with a KV-registered credential.",
)
parser.add_argument(
"--verbose",
action="store_true",
help="Emit secret-free provider discovery diagnostics to stderr.",
)
parser.add_argument(
"--agents-db",
default=None,
Expand Down Expand Up @@ -298,6 +304,8 @@ def _discover_models_command(argv: list[str]) -> None:
help="Optional reviewed CA bundle for configured-gateway discovery TLS verification.",
)
args = parser.parse_args(argv)
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
if args.enable_cheapest and not args.agents_db:
parser.error("--enable-cheapest requires --agents-db")

Expand Down Expand Up @@ -457,6 +465,11 @@ def main(argv: list[str] | None = None) -> None:
help="Optional sqlite path to persist runs/audit/analytics across restarts (default: in-memory).")
parser.add_argument("--mode", choices=["auto", "route", "conduct"], default="auto")
parser.add_argument("--serve", action="store_true", help="Run the chat completions HTTP server.")
parser.add_argument(
"--verbose",
action="store_true",
help="Emit secret-free runtime and model-discovery diagnostics to stderr.",
)
parser.add_argument(
"--release-authority-json",
default=None,
Expand Down Expand Up @@ -546,6 +559,8 @@ def main(argv: list[str] | None = None) -> None:
help="discover source-declared chat-capable models at startup and activate them",
)
args = parser.parse_args(arguments)
if args.verbose:
logging.basicConfig(level=logging.DEBUG)

client = ModelClient(
ca_bundle=args.provider_ca_bundle,
Expand Down
65 changes: 39 additions & 26 deletions contextual_orchestrator/model_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from decimal import Decimal
from concurrent.futures import ThreadPoolExecutor
import json
import logging
import math
import re
import ssl
Expand All @@ -40,6 +41,7 @@
from .cost_ledger import PriceBook

DISCOVERY_TIMEOUT_SECONDS = 15.0
_LOGGER = logging.getLogger(__name__)
# Some discovery endpoints (verified live: models.dev returns Cloudflare HTTP
# 403 error 1010) reject urllib's default "Python-urllib/X.Y" user agent as a
# bot signature. A stable, identifying user agent is not a credential and is
Expand Down Expand Up @@ -157,8 +159,8 @@ def configured_gateway_source(
)


# NVIDIA NIM is listed twice under two KV credential names (primary + sub) so both
# keys participate in upstream load balancing without a second provider identity.
# Each NVIDIA NIM KV credential is an independent account boundary and may expose
# a different catalog even though both currently use the same API endpoint.
PROVIDER_MODEL_SOURCES: tuple[ProviderModelSource, ...] = (
ProviderModelSource(
provider_name="openai",
Expand Down Expand Up @@ -442,9 +444,9 @@ def _price_per_1k(value: Any) -> float | None:
return per_1k if _valid_price_component(per_1k) else None


def _serving_identity(model: DiscoveredModel) -> tuple[str, str]:
"""Return the durable agent identity used by discovery synchronization."""
return (model.provider_name, model.model_id)
def _serving_identity(model: DiscoveredModel) -> tuple[str, str, str]:
"""Return the account-scoped identity used by discovery synchronization."""
return (model.provider_name, model.credential_name, model.model_id)
Comment on lines +451 to +453

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

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.

🔴 Account-specific models share serving identities

When two credentials expose one provider and model, _serving_identity retains both but agent_id_for gives them one ID. Synchronization overwrites one account, and either account’s pricing can govern both.

Devin Review

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

Comment on lines +451 to +453

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

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.

🔴 Account prices overwrite each other

When those accounts report different prices, refresh_price_book stores both under one provider-model key. The final row prices every account, corrupting selection and spend calculations.

Devin Review

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

Comment on lines +451 to +453

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

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.

🔍 Failure attribution remains provider-scoped

Same-provider accounts cannot report mixed discovery outcomes independently. One account failure marks successful siblings failed and rolls back their valid credentials.

Devin Review

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



def _source_tiebreaker(model: DiscoveredModel) -> tuple[str, str, str, str]:
Expand All @@ -462,13 +464,13 @@ def _deduplicate_discovered_models(
) -> list[DiscoveredModel]:
"""Collapse duplicate agent identities and withhold conflicting price evidence.

Exact duplicate catalog rows become one candidate. When the same provider/model
identity is repeated with conflicting metadata or prices, one deterministic
transport record is retained but its prices become unknown. Provider row order
Exact duplicate catalog rows from one credential become one candidate. When the
same account/model identity repeats with conflicting metadata or prices, one
deterministic transport record is retained but its prices become unknown. Provider row order
therefore cannot fabricate a cheaper bootstrap candidate or consume failover
capacity twice.
"""
unique: dict[tuple[str, str], DiscoveredModel] = {}
unique: dict[tuple[str, str, str], DiscoveredModel] = {}
for model in discovered:
identity = _serving_identity(model)
previous = unique.get(identity)
Expand Down Expand Up @@ -1110,7 +1112,15 @@ def discover_provider_models(
"""
api_key = get_credential(source.credential_name)
if not api_key:
_LOGGER.debug(
"model discovery skipped account=%s reason=key_missing",
source.provider_name,
)
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
return []
_LOGGER.debug(
"model discovery started account=%s",
source.provider_name,
)
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
url = source.list_url
if source.task_filter:
url = f"{url}?task={source.task_filter}"
Expand All @@ -1131,7 +1141,13 @@ def discover_provider_models(
# OSError covers ConnectionError/reset failures that are not URLError
# subclasses, so a raw provider transport failure can never escape the
# discovery boundary with provider text attached.
raise ProviderDiscoveryError(source.provider_name, _provider_discovery_error_code(exc)) from None
error_code = _provider_discovery_error_code(exc)
_LOGGER.debug(
"model discovery failed account=%s error_code=%s",
source.provider_name,
error_code,
)
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
raise ProviderDiscoveryError(source.provider_name, error_code) from None
if source.models_dev_provider_id:
if models_dev_metadata is _NOT_FETCHED:
metadata = _fetch_models_dev_metadata(timeout=timeout)
Expand Down Expand Up @@ -1175,7 +1191,13 @@ def discover_provider_models(
discovered = _parse_bytez(payload, source)
else:
discovered = _parse_openai_compatible(payload, source)
return [replace(model, evidence_only=source.evidence_only) for model in discovered]
result = [replace(model, evidence_only=source.evidence_only) for model in discovered]
_LOGGER.debug(
"model discovery completed account=%s model_count=%d",
source.provider_name,
len(result),
)
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
return result


def discover_all_models(
Expand Down Expand Up @@ -1439,13 +1461,6 @@ def _discovery_price_key(
return (0, cost, model.provider_name, model.model_id)


def _provider_family(provider_name: str) -> str:
"""Collapse credentials that share one upstream provider outage domain."""
if provider_name in {"nvidia_nim", "nvidia_nim_sub"}:
return "nvidia_nim"
return provider_name


def select_cheapest_discovered_agent(
discovered: list[DiscoveredModel], price_book: "PriceBook"
) -> DiscoveredModel | None:
Expand Down Expand Up @@ -1492,10 +1507,9 @@ def select_bootstrap_discovered_agents(
"""Build a deterministic, price-honest, provider-diverse initial pool.

Candidates retain the known-price-first ordering above, but the first pass
takes at most one model from each independent provider family. Remaining
capacity is filled in the same deterministic cost order. NVIDIA NIM primary
and sub credentials are one outage domain, so they participate in the second
pass only after independently hosted providers have had a chance to enter.
takes at most one model from each independently discovered provider account.
Remaining capacity is filled in the same deterministic cost order. No vendor
or endpoint name is used to infer a shared family or collapse credential state.
Duplicate serving identities never consume capacity twice.
"""
if limit <= 0:
Expand All @@ -1514,14 +1528,13 @@ def select_bootstrap_discovered_agents(
)
selected: list[DiscoveredModel] = []
deferred: list[DiscoveredModel] = []
provider_families: set[str] = set()
providers: set[str] = set()

for model in ranked:
family = _provider_family(model.provider_name)
if family in provider_families:
if model.provider_name in providers:
deferred.append(model)
continue
provider_families.add(family)
providers.add(model.provider_name)
selected.append(model)
if len(selected) == limit:
return selected
Expand Down
40 changes: 40 additions & 0 deletions contextual_orchestrator/model_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import math
import re
import threading
import time
from collections import deque
from collections.abc import Callable

from .conventions import require_object_name
Expand All @@ -44,6 +46,7 @@
#: Floor under the latency divisor so a zero/near-zero EWMA cannot explode
#: the score before any real latency is observable (1 ms).
MIN_ROUTING_LATENCY_SECONDS = 1e-3
RATE_OBSERVATION_WINDOW_SECONDS = 60.0

#: Neutral score assigned to members with no observations yet. All unobserved
#: members share it exactly, which makes intra-group ordering fall back to the
Expand Down Expand Up @@ -80,6 +83,7 @@ def __init__(
ewma_gain: float = EWMA_LATENCY_GAIN,
min_latency_seconds: float = MIN_ROUTING_LATENCY_SECONDS,
prior_resolver: Callable[[str], tuple[float, float]] | None = None,
clock: Callable[[], float] = time.monotonic,
) -> None:
if not 0 < ewma_gain <= 1:
raise ValueError("ewma_gain must be within (0, 1]")
Expand All @@ -88,10 +92,14 @@ def __init__(
self._ewma_gain = float(ewma_gain)
self._min_latency_seconds = float(min_latency_seconds)
self._prior_resolver = prior_resolver
self._clock = clock
self._lock = threading.Lock()
# member_id -> {"alpha", "beta", "ewma", "ewma_tps"}; ewma/ewma_tps are
# None until the first observation of each kind arrives.
self._members: dict[str, dict[str, float | None]] = {}
self._minute_observations: dict[str, deque[tuple[float, int | None]]] = {}
self._max_observed_rpm: dict[str, int] = {}
self._max_observed_tpm: dict[str, int] = {}

def register_member(self, member_id: str) -> None:
"""Ensure a member exists in the ledger (idempotent, keeps history)."""
Expand Down Expand Up @@ -119,12 +127,18 @@ def forget_members(self, keep_member_ids: set[str]) -> None:
for member_id in list(self._members):
if member_id not in keep_member_ids:
del self._members[member_id]
self._minute_observations.pop(member_id, None)
self._max_observed_rpm.pop(member_id, None)
self._max_observed_tpm.pop(member_id, None)

def reset_members(self, member_ids: set[str]) -> None:
"""Discard measurements whose group context changed."""
with self._lock:
for member_id in member_ids:
self._members.pop(member_id, None)
self._minute_observations.pop(member_id, None)
self._max_observed_rpm.pop(member_id, None)
self._max_observed_tpm.pop(member_id, None)

def update_prior(
self,
Expand Down Expand Up @@ -167,6 +181,7 @@ def observe_success(
member_id: str,
latency_seconds: float,
output_tokens: int | None = None,
total_tokens: int | None = None,
) -> None:
"""Record one successful attempt with its measured wall-clock latency.

Expand All @@ -189,6 +204,12 @@ def observe_success(
or output_tokens <= 0
):
raise ValueError("output_tokens must be a positive integer when provided")
if total_tokens is not None and (
isinstance(total_tokens, bool)
or not isinstance(total_tokens, int)
or total_tokens <= 0
):
raise ValueError("total_tokens must be a positive integer when provided")
clamped = max(latency, self._min_latency_seconds)
try:
throughput_sample = None if output_tokens is None else float(output_tokens) / clamped
Expand All @@ -213,6 +234,19 @@ def observe_success(
else (1.0 - self._ewma_gain) * float(tps)
+ self._ewma_gain * throughput_sample
)
observations = self._minute_observations.setdefault(member_id, deque())
now = self._clock()
observations.append((now, total_tokens))
cutoff = now - RATE_OBSERVATION_WINDOW_SECONDS
while observations and observations[0][0] <= cutoff:
observations.popleft()
self._max_observed_rpm[member_id] = max(
self._max_observed_rpm.get(member_id, 0), len(observations)
)
self._max_observed_tpm[member_id] = max(
self._max_observed_tpm.get(member_id, 0),
sum(tokens or 0 for _, tokens in observations),
)

def observe_failure(self, member_id: str) -> None:
"""Record one failed attempt (stability evidence only; no latency)."""
Expand Down Expand Up @@ -276,6 +310,9 @@ def _report_locked(self, member_id: str) -> dict[str, float | int | None]:
"success_posterior_mean": UNOBSERVED_MEMBER_SCORE,
"ewma_latency_seconds": None,
"ewma_tokens_per_second": None,
"max_observed_rpm": 0,
"max_observed_tpm": 0,
"rate_observation_window_seconds": int(RATE_OBSERVATION_WINDOW_SECONDS),
"success_count": 0,
"failure_count": 0,
"score": UNOBSERVED_MEMBER_SCORE,
Expand All @@ -290,6 +327,9 @@ def _report_locked(self, member_id: str) -> dict[str, float | int | None]:
"ewma_tokens_per_second": (
None if ewma_tps is None else round(float(ewma_tps), 6)
),
"max_observed_rpm": self._max_observed_rpm.get(member_id, 0),
"max_observed_tpm": self._max_observed_tpm.get(member_id, 0),
"rate_observation_window_seconds": int(RATE_OBSERVATION_WINDOW_SECONDS),
"success_count": int(alpha - float(state.get("prior_alpha", BETA_PRIOR_SUCCESS_COUNT))),
"failure_count": int(beta - float(state.get("prior_beta", BETA_PRIOR_FAILURE_COUNT))),
"score": round(self._score_locked(member_id), 9),
Expand Down
12 changes: 12 additions & 0 deletions contextual_orchestrator/orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5349,6 +5349,16 @@ def _usage_completion_tokens(usage: dict[str, Any] | None) -> int | None:
return None
return tokens

@staticmethod
def _usage_total_tokens(usage: dict[str, Any] | None) -> int | None:
"""Provider-reported total token count, or None when absent/invalid."""
if not isinstance(usage, dict):
return None
tokens = usage.get("total_tokens")
if isinstance(tokens, bool) or not isinstance(tokens, int) or tokens <= 0:
return None
return tokens

def conduct(
self,
messages: list[ChatMessage],
Expand Down Expand Up @@ -6570,11 +6580,13 @@ def call(agent: ModelAgent) -> tuple[str, str, dict[str, Any] | None]:
# are never inferred from text length or chunk counts.
usage = self.client.take_usage() if hasattr(self.client, "take_usage") else None
output_tokens = self._usage_completion_tokens(usage)
total_tokens = self._usage_total_tokens(usage)
if agent.group_name or allowed_agent_ids is not None:
self._group_router.observe_success(
agent.id,
time.perf_counter() - attempt_start,
output_tokens=output_tokens,
total_tokens=total_tokens,
)
self._record_success(agent.id)
return output, agent.id, usage
Expand Down
6 changes: 2 additions & 4 deletions contextual_orchestrator/provider_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
DiscoveredModel,
PROVIDER_MODEL_SOURCES,
_currency_is_comparable,
_provider_family,
agent_from_discovered,
agent_id_for,
discover_all_models,
Expand Down Expand Up @@ -232,11 +231,10 @@ def select_provider_diverse_models(
selected: list[DiscoveredModel] = []
seen_providers: set[str] = set()
for model in ordered:
provider_family = _provider_family(model.provider_name)
if provider_family in seen_providers:
if model.provider_name in seen_providers:
continue
selected.append(model)
seen_providers.add(provider_family)
seen_providers.add(model.provider_name)
Comment on lines +234 to +237

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.

🟡 Credential diversity still collapses accounts

Both bootstrap selectors use provider names as diversity keys, so same-provider credential accounts compete for one first-pass slot. Tight limits exclude independent accounts.

Prompt for agents
Use the full provider-account identity, at minimum provider_name plus credential_name, as the diversity key in both select_provider_diverse_models and select_bootstrap_discovered_agents. Add tests with two sources sharing provider_name but using different credential names, plus another provider and a limit smaller than the full catalog, to verify each credential account receives an independent first-pass slot.
Devin Review

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

if len(selected) >= limit:
return selected
selected_keys = {
Expand Down
Loading
Loading