-
Notifications
You must be signed in to change notification settings - Fork 27
feat(benchmark): task-level routing stats for Harbor runs #116
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ayushag-nv
merged 5 commits into
main
from
rlempka/switch-1033-task-level-routing-stats
Jul 22, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
4a782f9
feat(serve): add --routing-log-file per-request JSONL routing log
ryan-lempka 7fa84ae
feat(benchmark): stamp task and session identity headers in the proxy…
ryan-lempka e192824
feat(benchmark): roll routing log up into routing_stats_by_task.json …
ryan-lempka 38f4627
fix(serve): offload routing-log writes off the event loop
ryan-lempka 7f4c816
fix(benchmark): key rollup buckets by model and tier
ryan-lempka File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
103 changes: 103 additions & 0 deletions
103
switchyard/lib/processors/routing_log_response_processor.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| """Response-side processor that appends one JSONL routing record per request.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import json | ||
| import logging | ||
| import threading | ||
| from collections.abc import Mapping | ||
| from datetime import UTC, datetime | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from switchyard.lib.chat_response.streaming_response_accumulator import ( | ||
| attach_final_response_callback, | ||
| ) | ||
| from switchyard.lib.proxy_context import CTX_PROXY_ACTUAL_MODEL, ProxyContext | ||
| from switchyard.lib.request_metadata import CTX_REQUEST_METADATA | ||
| from switchyard_rust.core import ChatResponse | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class RoutingLogResponseProcessor: | ||
| """Append one JSON line per completed request to ``log_file``. | ||
|
|
||
| Each record carries the routing decision (selected model and tier), the | ||
| caller-supplied task and session identity headers, and token usage, so a | ||
| benchmark harness can attribute router traffic to individual tasks. | ||
| Streaming responses log once the stream drains; write failures are logged | ||
| and never break the proxied response. | ||
| """ | ||
|
|
||
| def __init__(self, log_file: Path | str) -> None: | ||
| self._log_file = Path(log_file) | ||
| self._log_file.parent.mkdir(parents=True, exist_ok=True) | ||
| self._lock = threading.Lock() | ||
|
|
||
| async def process(self, ctx: ProxyContext, response: ChatResponse) -> ChatResponse: | ||
| """Log one routing record for the completed request; return the response unchanged.""" | ||
| served_model: str = ctx.selected_model or ctx.metadata.get( | ||
| CTX_PROXY_ACTUAL_MODEL, "unknown", | ||
| ) | ||
|
|
||
| async def _emit(final: ChatResponse) -> None: | ||
| await asyncio.to_thread(self._write_record, ctx, served_model, final) | ||
|
|
||
| attached = attach_final_response_callback( | ||
| response, served_model=served_model, callback=_emit, | ||
| ) | ||
| if not attached: | ||
| await _emit(response) | ||
| return response | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| def _write_record(self, ctx: ProxyContext, served_model: str, response: ChatResponse) -> None: | ||
| metadata = ctx.metadata.get(CTX_REQUEST_METADATA) | ||
| record = { | ||
| "ts": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z", | ||
| "task": getattr(getattr(metadata, "intake", None), "task", None), | ||
| "session_id": getattr(metadata, "session_id", None), | ||
| "model": served_model, | ||
| "tier": ctx.metadata.get("_random_routing_tier", "") or (ctx.selected_target or ""), | ||
| **_usage_tokens(response.body), | ||
| } | ||
| try: | ||
| line = json.dumps(record, separators=(",", ":")) | ||
| with self._lock, self._log_file.open("a", encoding="utf-8") as handle: | ||
| handle.write(line + "\n") | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| except OSError as exc: | ||
| logger.warning("Routing log: failed to append to %s: %s", self._log_file, exc) | ||
|
|
||
|
|
||
| def _usage_tokens(body: object) -> dict[str, int]: | ||
| """Token counts from any native usage shape (OpenAI Chat/Responses, Anthropic).""" | ||
| usage = _field(body, "usage") | ||
| prompt = _int_field(usage, "prompt_tokens") | ||
| completion = _int_field(usage, "completion_tokens") | ||
| if not prompt and not completion: | ||
| prompt = ( | ||
| _int_field(usage, "input_tokens") | ||
| + _int_field(usage, "cache_creation_input_tokens") | ||
| + _int_field(usage, "cache_read_input_tokens") | ||
| ) | ||
| completion = _int_field(usage, "output_tokens") | ||
| return { | ||
| "prompt_tokens": prompt, | ||
| "completion_tokens": completion, | ||
| "total_tokens": prompt + completion, | ||
| } | ||
|
|
||
|
|
||
| def _field(value: object, name: str) -> Any: | ||
| if isinstance(value, Mapping): | ||
| return value.get(name) | ||
| return getattr(value, name, None) | ||
|
|
||
|
|
||
| def _int_field(value: object, name: str) -> int: | ||
| field = _field(value, name) | ||
| return field if isinstance(field, int) else 0 | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.