Skip to content
Merged
Show file tree
Hide file tree
Changes from 61 commits
Commits
Show all changes
62 commits
Select commit Hold shift + click to select a range
262b4eb
fix: orchestrate structured provider features
seonghobae Aug 21, 2026
1f6b665
fix: bound local structured synthesis output
seonghobae Aug 21, 2026
16276d6
fix: preserve structured orchestration request contracts
seonghobae Aug 21, 2026
503e639
fix: preserve responses optional fields
seonghobae Aug 21, 2026
836a1a7
fix: keep structured judge calls bounded
seonghobae Aug 21, 2026
ee5cf34
fix: enforce spend budgets for structured provider calls
seonghobae Aug 21, 2026
79f2ab2
Merge remote-tracking branch 'origin/fix/auto-reasoning-effort-contra…
seonghobae Aug 21, 2026
e2a74a5
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
7cf488e
ci: verify and repair PR 805 runtime accounting
seonghobae Aug 21, 2026
a87af91
fix: close structured orchestration review gaps
seonghobae Aug 21, 2026
5c536de
chore: remove self-modifying review workflow
seonghobae Aug 21, 2026
e20d88d
test: stage PR 805 passthrough accounting repair
seonghobae Aug 21, 2026
207e25e
ci: execute the remaining PR 805 accounting repair
seonghobae Aug 21, 2026
2544b86
fix: account ordinary provider passthrough
seonghobae Aug 21, 2026
53f2aa4
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
3eb73f9
Merge remote-tracking branch 'origin/fix/auto-reasoning-effort-contra…
seonghobae Aug 21, 2026
daa508d
test: stage request-scoped sampling isolation repair
seonghobae Aug 21, 2026
db4e1eb
fix: preserve native responses orchestration lineage
seonghobae Aug 21, 2026
e494e4b
ci: harden the staged sampling repair runner
seonghobae Aug 21, 2026
85f9baf
ci: execute request-scoped sampling isolation repair
seonghobae Aug 21, 2026
d4c11ad
fix: isolate request sampling settings
seonghobae Aug 21, 2026
02e306d
ci: keep tests workflow read-only
seonghobae Aug 21, 2026
dbd7c3d
Merge remote PR 805 fixes with native Responses orchestration
seonghobae Aug 21, 2026
4f79492
test: close structured orchestration quality gaps
seonghobae Aug 21, 2026
f1d61d6
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
51b22d8
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
afe102c
test: stage Responses multimodal synthesis repair
seonghobae Aug 21, 2026
41680a1
ci: verify Responses multimodal synthesis repair
seonghobae Aug 21, 2026
387ee19
fix: preserve Responses multimodal synthesis
seonghobae Aug 21, 2026
8a30eb3
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
2da526d
ci: remove completed Responses repair workflow
seonghobae Aug 21, 2026
d01311e
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
3a60530
Merge gateway control stack with native Responses orchestration
seonghobae Aug 21, 2026
87421f0
fix: account Responses passthrough usage
seonghobae Aug 21, 2026
1207d55
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
afd683c
refactor: preserve provider usage totals
seonghobae Aug 21, 2026
0fe5cd3
fix: preserve structured contracts on HTTP
seonghobae Aug 21, 2026
6589dfa
fix: retain the gateway model identity
seonghobae Aug 21, 2026
c90c1f6
fix: preserve local Responses contracts and usage
seonghobae Aug 21, 2026
1103487
fix: preserve local response schemas and usage accounting
seonghobae Aug 21, 2026
ad142aa
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
976dca7
fix: record provider-reported structured usage
seonghobae Aug 21, 2026
b2c71d1
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
6e915c2
fix: include in-flight workflow spend in final budget gate
seonghobae Aug 21, 2026
c203207
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
7a0c61b
fix: enforce structured verification and provider contracts
seonghobae Aug 21, 2026
714e1c5
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
aa8a5fe
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
e47242c
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
b86ddbe
fix: persist model judge spend
seonghobae Aug 21, 2026
ea37a1e
fix: contain provider errors in structured flows
seonghobae Aug 21, 2026
47ff9d9
fix: preserve Responses text format precedence
seonghobae Aug 21, 2026
a47a0c8
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
d0a2aa4
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
5764fb9
fix: preserve Responses metadata for providers
seonghobae Aug 21, 2026
39c3c4d
fix: emit native Responses usage fields
seonghobae Aug 21, 2026
82bdbb4
Merge remote-tracking branch 'origin/fix/structured-output-orchestrat…
seonghobae Aug 21, 2026
68bdda6
fix: attribute every metered workflow call
seonghobae Aug 21, 2026
9a3f32d
refactor: remove judge ledger string coupling
seonghobae Aug 21, 2026
1d11e7d
fix: bound raw workflow retention
seonghobae Aug 21, 2026
e975711
Merge remote-tracking branch 'origin/fix/auto-reasoning-effort-contra…
seonghobae Aug 21, 2026
3bd723c
fix: synchronize runtime analytics snapshots
seonghobae Aug 21, 2026
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
7 changes: 6 additions & 1 deletion contextual_orchestrator/cost_ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ class NoopUsageTelemetrySink:
"""Default sink for callers that do not wire telemetry yet."""

def emit_usage(self, event: UsageTelemetryEvent) -> None:
"""Discard one prompt-safe usage event."""
return None


Expand All @@ -342,12 +343,14 @@ def __init__(self, max_events: int = 512) -> None:
self._lock = threading.Lock()

def emit_usage(self, event: UsageTelemetryEvent) -> None:
"""Append one usage event while retaining only the configured limit."""
with self._lock:
self._events.append(event)
if len(self._events) > self._max_events:
del self._events[: len(self._events) - self._max_events]

def events(self) -> List[UsageTelemetryEvent]:
"""Return a thread-safe snapshot of retained usage events."""
with self._lock:
return list(self._events)

Expand All @@ -363,6 +366,7 @@ class UsageTelemetryHealth:
last_error_type: Optional[str] = None

def as_dict(self) -> Dict[str, Any]:
"""Return operator-safe counters as a serializable mapping."""
return {
"records_accepted": self.records_accepted,
"records_stored": self.records_stored,
Expand Down Expand Up @@ -442,6 +446,7 @@ def flush(self, timeout: Optional[float] = None) -> bool:
return True

def telemetry_health(self) -> Dict[str, Any]:
"""Return a thread-safe snapshot of persistence health counters."""
with self._lock:
return self._health.as_dict()

Expand Down Expand Up @@ -669,7 +674,7 @@ def query(self, start: Optional[int] = None, end: Optional[int] = None) -> List[
_USAGE_QUERY_SQL[(self._paramstyle, start is not None, end is not None)],
tuple(params),
)
return [dict(zip(_USAGE_COLUMNS, values)) for values in cur.fetchall()]
return [dict(zip(_USAGE_COLUMNS, values, strict=True)) for values in cur.fetchall()]


def _within_window(created_at: int, start: Optional[int], end: Optional[int]) -> bool:
Expand Down
175 changes: 152 additions & 23 deletions contextual_orchestrator/cost_router.py
Comment thread
seonghobae marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
RoutingHints,
RoutingPolicy,
)
from .cost_ledger import CostLedger, PriceBook
from .cost_ledger import CostLedger, PriceBook, UsageRecord
from .kv_config import InMemoryConfigStore
from .token_counting import HeuristicTokenCounter, build_token_counter

Expand Down Expand Up @@ -161,6 +161,63 @@ def _served_provider_model(self, result: Dict[str, Any], fallback_model: str) ->
pass
return "unknown", fallback_model

@staticmethod
def _provider_usage_counts(usage: Any) -> tuple[int, int] | None:
"""Return validated provider token counts, accepting Chat and Responses names."""
if not isinstance(usage, dict):
return None
prompt_tokens = usage.get("prompt_tokens", usage.get("input_tokens"))
completion_tokens = usage.get("completion_tokens", usage.get("output_tokens"))
if (
type(prompt_tokens) is not int
or prompt_tokens < 0
or type(completion_tokens) is not int
or completion_tokens < 0
):
return None
return prompt_tokens, completion_tokens
Comment thread
seonghobae marked this conversation as resolved.
Resolved

def _record_provider_workflow_usage(
self,
result: Dict[str, Any],
*,
attribution: Optional[Dict[str, Any]],
model_name: str,
) -> tuple[List[UsageRecord], int]:
"""Record every provider-reported workflow call under one run lineage."""
steps = [step for step in result.get("trace", []) if isinstance(step, dict)]
verification = result.get("verification")
if isinstance(verification, dict) and isinstance(verification.get("judge_usage"), dict):
judge_step = {
"agent_id": verification.get("judge_agent_id"),
"usage": verification["judge_usage"],
}
# Provider-facing synthesis is the final persisted trace step.
steps.insert(max(0, len(steps) - 1), judge_step)

records: List[UsageRecord] = []
unmetered_count = 0
for step in steps:
counts = self._provider_usage_counts(step.get("usage"))
if counts is None:
unmetered_count += 1
continue
records.append(
self._record_completion(
messages=[],
answer="",
route_mode=result.get("mode"),
request_channel="sync",
attribution=attribution,
model_name=model_name,
provider_model=self._served_provider_model({"trace": [step]}, model_name),
workflow_run_id=result.get("workflow_run_id"),
prompt_tokens=counts[0],
completion_tokens=counts[1],
)
)
return records, unmetered_count
Comment thread
seonghobae marked this conversation as resolved.
Resolved

# ------------------------------------------------------------------
# Sync + batch completion
# ------------------------------------------------------------------
Expand All @@ -174,19 +231,26 @@ def complete(
model_name: str = "contextual-orchestrator",
workflow_run_id: Optional[str] = None,
response_format: Optional[Dict[str, Any]] = None,
provider_request: Optional[Dict[str, Any]] = None,
provider_endpoint: str = "chat/completions",
) -> Dict[str, Any]:
"""Route a request (sync or batch) and record its usage + cost.

Sync requests run the orchestrator immediately and return the completion
augmented with ``channel``, ``routing_reason``, ``usage``, and the
``usage_record_id``. Batch requests are dispatched to the batch backend
and return a job envelope; their cost is recorded on retrieval.
and return a job envelope; their cost is recorded on retrieval. When a
validated ``provider_request`` is supplied, final synthesis preserves
that Chat or Responses wire contract while this coordinator still owns
the cost record.
"""
routing_hints = hints if isinstance(hints, RoutingHints) else RoutingHints.from_mapping(hints)
prompt_tokens_estimate = self.token_counter.count_messages(messages, model_name)
decision = self.policy.decide(routing_hints, prompt_tokens_estimate)

structured_output_forced_sync = decision.channel == "batch" and response_format is not None
structured_output_forced_sync = decision.channel == "batch" and (
response_format is not None or provider_request is not None
)
if decision.channel == "batch" and not structured_output_forced_sync:
request = BatchRequest(
messages=messages,
Expand All @@ -204,35 +268,100 @@ def complete(
"request_count": job.request_count,
}

result = self.orchestrator.run(
messages,
mode=mode,
workflow_run_id=workflow_run_id,
output_contract=response_format,
)
record = self._record_completion(
messages=messages,
answer=result.get("answer", ""),
route_mode=result.get("mode"),
request_channel="sync",
attribution=attribution,
model_name=model_name,
provider_model=self._served_provider_model(result, model_name),
workflow_run_id=result.get("workflow_run_id"),
)
provider_response: Optional[Dict[str, Any]] = None
if provider_request is None:
result = self.orchestrator.run(
messages,
mode=mode,
workflow_run_id=workflow_run_id,
output_contract=response_format,
)
else:
if provider_endpoint not in {"chat/completions", "responses"}:
raise ValueError("provider_endpoint must be chat/completions or responses")
provider_response = self.orchestrator.proxy_completion(
provider_request,
endpoint=provider_endpoint,
)
orchestration = provider_response.get("orchestration")
if not isinstance(orchestration, dict) or not isinstance(
orchestration.get("workflow_run_id"), str
):
raise RuntimeError("provider completion omitted orchestration lineage")
result = dict(
self.orchestrator.get_workflow_run(orchestration["workflow_run_id"])
)
result["provider_response"] = provider_response
Comment thread
seonghobae marked this conversation as resolved.
Resolved
records: List[UsageRecord] = []
unmetered_count = 0
if provider_response is not None:
records, unmetered_count = self._record_provider_workflow_usage(
result,
attribution=attribution,
model_name=model_name,
)
if not records:
provider_usage = (
provider_response.get("usage")
if isinstance(provider_response, dict)
and isinstance(provider_response.get("usage"), dict)
else {}
)
counts = self._provider_usage_counts(provider_usage)
record = self._record_completion(
messages=messages,
answer=result.get("answer", ""),
route_mode=result.get("mode"),
request_channel="sync",
attribution=attribution,
model_name=model_name,
provider_model=self._served_provider_model(result, model_name),
workflow_run_id=result.get("workflow_run_id"),
prompt_tokens=counts[0] if counts is not None else None,
completion_tokens=counts[1] if counts is not None else None,
)
records = [record]
record = records[-1]
prompt_tokens = sum(item.prompt_tokens for item in records)
completion_tokens = sum(item.completion_tokens for item in records)
currencies = {item.currency_code for item in records}
cost = {
"cost_amount": (
round(sum(item.cost_amount for item in records), 6)
if len(currencies) == 1
else None
),
"currency_code": next(iter(currencies)) if len(currencies) == 1 else "MIXED",
}
result["channel"] = "sync"
result["routing_reason"] = (
f"{decision.reason};structured_output_forced_sync"
if structured_output_forced_sync
else decision.reason
)
result["usage_record_id"] = record.usage_record_id
result["usage_record_ids"] = [item.usage_record_id for item in records]
result["unmetered_provider_call_count"] = unmetered_count
result["usage"] = {
"prompt_tokens": record.prompt_tokens,
"completion_tokens": record.completion_tokens,
"total_tokens": record.total_tokens,
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": prompt_tokens + completion_tokens,
}
Comment thread
seonghobae marked this conversation as resolved.
Resolved
result["cost"] = {"cost_amount": record.cost_amount, "currency_code": record.currency_code}
result["cost"] = cost
provider_response = result.get("provider_response")
if isinstance(provider_response, dict):
orchestration = provider_response.get("orchestration")
if isinstance(orchestration, dict):
orchestration.update(
{
"channel": result["channel"],
"routing_reason": result["routing_reason"],
"usage_record_id": result["usage_record_id"],
"usage_record_ids": result["usage_record_ids"],
"unmetered_provider_call_count": unmetered_count,
"cost": result["cost"],
}
)
return result

def _record_completion(
Expand Down
20 changes: 17 additions & 3 deletions contextual_orchestrator/model_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,19 @@
DISCOVERY_TIMEOUT_SECONDS = 15.0


def _provider_discovery_error_code(exc: Exception) -> str:
"""Map provider failures to stable codes without retaining provider response text."""
if isinstance(exc, urllib.error.HTTPError):
return f"http_status_{exc.code}"
if isinstance(exc, TimeoutError):
return "timeout"
if isinstance(exc, urllib.error.URLError) or isinstance(exc, OSError):
return "transport_error"
if isinstance(exc, ValueError):
return "invalid_response"
return "provider_error"


@dataclass(frozen=True)
class ProviderModelSource:
"""Where and how to discover one provider's models."""
Expand Down Expand Up @@ -98,9 +111,10 @@ class DiscoveredModel:
class ProviderDiscoveryError(RuntimeError):
"""Raised when a provider's model list could not be fetched (network/auth failure)."""

def __init__(self, provider_name: str, detail: str) -> None:
def __init__(self, provider_name: str, error_code: str) -> None:
self.provider_name = provider_name
super().__init__(f"model discovery failed for provider {provider_name!r}: {detail}")
self.error_code = error_code
super().__init__(f"model discovery failed for provider {provider_name!r}: {error_code}")


def _fetch_json(
Expand Down Expand Up @@ -209,7 +223,7 @@ def discover_provider_models(
credential_name=source.credential_name,
)
except (urllib.error.URLError, TimeoutError, ValueError, RuntimeError, OSError) as exc: # pragma: no cover - network path
raise ProviderDiscoveryError(source.provider_name, str(exc)) from exc
raise ProviderDiscoveryError(source.provider_name, _provider_discovery_error_code(exc)) from None
if source.style == "bytez":
return _parse_bytez(payload, source)
return _parse_openai_compatible(payload, source)
Expand Down
Loading