From 936bafa02cf417fb3a4656bc5023dee69d52a1bd Mon Sep 17 00:00:00 2001 From: Namrata Ghadi Date: Tue, 24 Nov 2026 17:08:28 +0530 Subject: [PATCH 1/5] some diagnostics --- engine/src/agent_control_engine/core.py | 32 +++++++++- .../llm/client.py | 36 +++++++++++- .../llm/evaluator.py | 11 ++++ .../endpoints/evaluation.py | 58 ++++++++++++++++++- 4 files changed, 132 insertions(+), 5 deletions(-) diff --git a/engine/src/agent_control_engine/core.py b/engine/src/agent_control_engine/core.py index 58e270eb..b1bce893 100644 --- a/engine/src/agent_control_engine/core.py +++ b/engine/src/agent_control_engine/core.py @@ -56,6 +56,7 @@ def _env_positive_int(*names: str, default: int) -> int: "MAX_CONCURRENT_EVALUATIONS", default=3, ) +_DIAGNOSTIC_EXTENSION = "_agent_control_diagnostics" SELECTED_DATA_PREVIEW_MAX_CHARS = int( os.environ.get("AGENT_CONTROL_SELECTED_DATA_PREVIEW_MAX_CHARS", "500") @@ -315,9 +316,13 @@ async def _evaluate_leaf( selector_path = selector.path or "*" data = select_data(request.step, selector_path) + semaphore_wait_started = time.perf_counter() + semaphore_wait_ms: float | None = None try: async with semaphore: + acquired_at = time.perf_counter() + semaphore_wait_ms = (acquired_at - semaphore_wait_started) * 1000 evaluator = get_evaluator_instance(evaluator_spec) timeout = evaluator.get_timeout_seconds() if timeout <= 0: @@ -347,6 +352,21 @@ async def _evaluate_leaf( exc_info=True, ) result = self._build_error_result(error_msg) + finally: + diagnostic = extensions.get(_DIAGNOSTIC_EXTENSION) if extensions is not None else None + if isinstance(diagnostic, dict) and semaphore_wait_ms is not None and semaphore_wait_ms >= 1: + request_id = diagnostic.get("request_id") + control_id = diagnostic.get("control_id") + if isinstance(request_id, str) and isinstance(control_id, str): + logger.info( + "Control evaluator admission wait", + extra={ + "diagnostic_request_id": request_id, + "diagnostic_control_id": control_id, + "evaluator_name": evaluator_spec.name, + "semaphore_wait_ms": semaphore_wait_ms, + }, + ) trace = { "type": "leaf", @@ -676,13 +696,23 @@ async def process( async def evaluate_control(eval_task: _EvalTask) -> None: """Evaluate a single control, respecting cancellation and timeout.""" started_at = time.perf_counter() + control_extensions = extensions + diagnostic = extensions.get(_DIAGNOSTIC_EXTENSION) if extensions is not None else None + if isinstance(diagnostic, dict): + control_extensions = { + **extensions, + _DIAGNOSTIC_EXTENSION: { + **diagnostic, + "control_id": str(eval_task.item.id), + }, + } try: evaluation = await self._evaluate_condition( eval_task.item, eval_task.item.control.condition, request, semaphore, - extensions, + control_extensions, ) eval_task.result = evaluation.result diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py index a8aa64d8..462b8dec 100644 --- a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py @@ -10,7 +10,7 @@ from hashlib import sha256 from hmac import new as hmac_new from json import dumps -from time import time +from time import perf_counter, time from typing import Any, Literal, get_args from urllib.parse import urlsplit @@ -527,6 +527,7 @@ async def invoke( httpx.HTTPStatusError: If the invoke endpoint returns an error status code. httpx.RequestError: If the request fails before a response is received. """ + invoke_started = perf_counter() if step is None: raise ValueError("LLM scorer invocation requires a runtime step.") if execution_context is None: @@ -560,8 +561,11 @@ async def invoke( execution_context=execution_context, config=invoke_config, ).to_dict() + request_preparation_ms = (perf_counter() - invoke_started) * 1000 + auth_started = perf_counter() endpoint, auth_header = self._endpoint_and_auth_header() + auth_token_ms = (perf_counter() - auth_started) * 1000 request_headers = { k: v for k, v in (headers or {}).items() if k.lower() not in _BLOCKED_REQUEST_HEADERS } @@ -570,20 +574,32 @@ async def invoke( logger.debug("[GalileoLLMClient] POST %s", endpoint) logger.debug("[GalileoLLMClient] Request body: %s", request_body) + diagnostic_id = request_headers.get("X-Galileo-Diagnostic-ID") + client_acquire_ms: float | None = None + http_round_trip_ms: float | None = None + response_parse_ms: float | None = None + status_code: int | None = None try: + client_acquire_started = perf_counter() client = await self._get_client() + client_acquire_ms = (perf_counter() - client_acquire_started) * 1000 + http_started = perf_counter() response = await client.post( endpoint, json=request_body, headers=request_headers, timeout=timeout, ) + http_round_trip_ms = (perf_counter() - http_started) * 1000 + status_code = response.status_code response.raise_for_status() + parse_started = perf_counter() response_data = response.json() if not isinstance(response_data, dict): raise RuntimeError("Invalid response payload: not a JSON object") parsed = ScorerInvokeResponse.from_dict(response_data) + response_parse_ms = (perf_counter() - parse_started) * 1000 logger.debug("[GalileoLLMClient] Response: %s", parsed.raw_response) return parsed except httpx.HTTPStatusError as exc: @@ -596,6 +612,24 @@ async def invoke( except httpx.RequestError as exc: logger.error("[GalileoLLMClient] Request failed: %s", exc) raise + finally: + if diagnostic_id is not None: + client_total_ms = (perf_counter() - invoke_started) * 1000 + if client_total_ms >= 200 or status_code is None or status_code >= 400: + logger.info( + "Agent Control slow scorer-invoke client timing", + extra={ + "diagnostic_request_id": diagnostic_id, + "diagnostic_control_id": request_headers.get("X-Galileo-Diagnostic-Control-ID"), + "request_preparation_ms": request_preparation_ms, + "auth_token_ms": auth_token_ms, + "http_client_acquire_ms": client_acquire_ms, + "runners_http_round_trip_ms": http_round_trip_ms, + "response_parse_ms": response_parse_ms, + "client_total_ms": client_total_ms, + "http_status_code": status_code, + }, + ) async def close(self) -> None: """Close HTTP clients and release resources.""" diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/evaluator.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/evaluator.py index bc2c2d72..9f74f0c3 100644 --- a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/evaluator.py +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/evaluator.py @@ -341,12 +341,23 @@ async def _evaluate( scorer_kwargs["selected_data"] = data scorer_kwargs["selected_data_payload_field"] = self.config.payload_field scorer_kwargs["execution_context"] = execution_context + diagnostic_headers: dict[str, str] = {} + diagnostic = extensions.get("_agent_control_diagnostics") if extensions is not None else None + if isinstance(diagnostic, dict): + request_id = diagnostic.get("request_id") + control_id = diagnostic.get("control_id") + if isinstance(request_id, str) and isinstance(control_id, str): + diagnostic_headers = { + "X-Galileo-Diagnostic-ID": request_id, + "X-Galileo-Diagnostic-Control-ID": control_id, + } response = await self._get_client().invoke( **scorer_kwargs, input=input_text if _has_text(input_text) else None, output=output_text if _has_text(output_text) else None, config=self.config.scorer_config, timeout=self.get_timeout_seconds(), + headers=diagnostic_headers or None, ) if response.status.lower() != "success": diff --git a/server/src/agent_control_server/endpoints/evaluation.py b/server/src/agent_control_server/endpoints/evaluation.py index 7a46829e..017122d3 100644 --- a/server/src/agent_control_server/endpoints/evaluation.py +++ b/server/src/agent_control_server/endpoints/evaluation.py @@ -1,7 +1,10 @@ """Evaluation analysis endpoints.""" import json +import os +import time from dataclasses import dataclass +from uuid import uuid4 from agent_control_engine.core import ControlEngine from agent_control_models import ( @@ -12,7 +15,7 @@ JSONObject, ) from agent_control_models.errors import ErrorCode, ValidationErrorItem -from fastapi import APIRouter, Depends, Request +from fastapi import APIRouter, Depends, Request, Response from sqlalchemy import select from ..auth_framework import Operation, Principal, require_operation @@ -30,6 +33,13 @@ SAFE_EVALUATOR_TIMEOUT_ERROR = "Evaluation timed out before completion." SAFE_INVALID_STEP_REGEX_ERROR = "Control configuration error: invalid step name regex." SAFE_ENGINE_VALIDATION_MESSAGE = "Invalid evaluation request or control configuration." +_LATENCY_DIAGNOSTICS_ENV = "AGENT_CONTROL_LATENCY_DIAGNOSTICS_ENABLED" +_DIAGNOSTIC_EXTENSION = "_agent_control_diagnostics" + + +def _latency_diagnostics_enabled() -> bool: + """Return whether opt-in evaluation timing logs are enabled.""" + return os.getenv(_LATENCY_DIAGNOSTICS_ENV, "").strip().lower() in {"1", "true", "yes", "enabled"} @dataclass @@ -195,6 +205,7 @@ async def _load_engine_controls( ) async def evaluate( request: EvaluationRequest, + response: Response, principal: Principal = Depends( require_operation(Operation.RUNTIME_USE, context_builder=_evaluation_context) ), @@ -213,10 +224,25 @@ async def evaluate( on the server; SDKs reconstruct and emit those events separately through the observability ingestion endpoint. """ + handler_started = time.perf_counter() + diagnostic_id = uuid4().hex if _latency_diagnostics_enabled() else None + if diagnostic_id is not None: + response.headers["X-Galileo-Diagnostic-ID"] = diagnostic_id + + controls_started = time.perf_counter() engine_controls = await _load_engine_controls(request, principal) + controls_load_ms = (time.perf_counter() - controls_started) * 1000 engine = ControlEngine(engine_controls) try: - raw_response = await engine.process(request, extensions=_principal_extensions(principal)) + extensions = _principal_extensions(principal) + if diagnostic_id is not None and extensions is not None: + extensions = { + **extensions, + _DIAGNOSTIC_EXTENSION: {"request_id": diagnostic_id}, + } + engine_started = time.perf_counter() + raw_response = await engine.process(request, extensions=extensions) + engine_ms = (time.perf_counter() - engine_started) * 1000 except ValueError: _logger.exception("Evaluation failed due to invalid configuration or input") raise APIValidationError( @@ -234,4 +260,30 @@ async def evaluate( ], ) - return _sanitize_evaluation_response(raw_response) + sanitize_started = time.perf_counter() + sanitized_response = _sanitize_evaluation_response(raw_response) + if diagnostic_id is not None: + control_results = [ + *(raw_response.matches or []), + *(raw_response.non_matches or []), + *(raw_response.errors or []), + ] + _logger.info( + "Evaluation latency diagnostics", + extra={ + "diagnostic_request_id": diagnostic_id, + "controls_load_ms": controls_load_ms, + "control_engine_ms": engine_ms, + "response_sanitize_ms": (time.perf_counter() - sanitize_started) * 1000, + "handler_total_ms": (time.perf_counter() - handler_started) * 1000, + "control_count": len(engine_controls), + "control_timings_ms": [ + { + "control_id": match.control_id, + "execution_ms": match.execution_duration_ms, + } + for match in control_results + ], + }, + ) + return sanitized_response From 8df8d464fe427fb6e5e0eca130ce2984a685df5d Mon Sep 17 00:00:00 2001 From: Namrata Ghadi Date: Tue, 24 Nov 2026 18:41:23 +0530 Subject: [PATCH 2/5] fix: correlate Luna load-test diagnostics and expose control timings --- engine/src/agent_control_engine/core.py | 16 +- engine/tests/test_execution_duration.py | 28 ++++ evaluators/contrib/galileo/README.md | 17 +++ .../llm/client.py | 4 +- .../llm/evaluator.py | 7 +- .../luna/client.py | 66 ++++++-- .../luna/evaluator.py | 11 ++ .../galileo/tests/test_luna_diagnostics.py | 141 ++++++++++++++++++ .../endpoints/evaluation.py | 23 ++- .../src/agent_control_server/logging_utils.py | 23 ++- server/tests/test_latency_diagnostics.py | 126 ++++++++++++++++ 11 files changed, 430 insertions(+), 32 deletions(-) create mode 100644 evaluators/contrib/galileo/tests/test_luna_diagnostics.py create mode 100644 server/tests/test_latency_diagnostics.py diff --git a/engine/src/agent_control_engine/core.py b/engine/src/agent_control_engine/core.py index b1bce893..8fc3fcdf 100644 --- a/engine/src/agent_control_engine/core.py +++ b/engine/src/agent_control_engine/core.py @@ -316,13 +316,14 @@ async def _evaluate_leaf( selector_path = selector.path or "*" data = select_data(request.step, selector_path) - semaphore_wait_started = time.perf_counter() + diagnostic = extensions.get(_DIAGNOSTIC_EXTENSION) if extensions is not None else None + semaphore_wait_started = time.perf_counter() if isinstance(diagnostic, dict) else None semaphore_wait_ms: float | None = None try: async with semaphore: - acquired_at = time.perf_counter() - semaphore_wait_ms = (acquired_at - semaphore_wait_started) * 1000 + if semaphore_wait_started is not None: + semaphore_wait_ms = (time.perf_counter() - semaphore_wait_started) * 1000 evaluator = get_evaluator_instance(evaluator_spec) timeout = evaluator.get_timeout_seconds() if timeout <= 0: @@ -353,8 +354,11 @@ async def _evaluate_leaf( ) result = self._build_error_result(error_msg) finally: - diagnostic = extensions.get(_DIAGNOSTIC_EXTENSION) if extensions is not None else None - if isinstance(diagnostic, dict) and semaphore_wait_ms is not None and semaphore_wait_ms >= 1: + if ( + isinstance(diagnostic, dict) + and semaphore_wait_ms is not None + and semaphore_wait_ms >= 1 + ): request_id = diagnostic.get("request_id") control_id = diagnostic.get("control_id") if isinstance(request_id, str) and isinstance(control_id, str): @@ -698,7 +702,7 @@ async def evaluate_control(eval_task: _EvalTask) -> None: started_at = time.perf_counter() control_extensions = extensions diagnostic = extensions.get(_DIAGNOSTIC_EXTENSION) if extensions is not None else None - if isinstance(diagnostic, dict): + if isinstance(diagnostic, dict) and extensions is not None: control_extensions = { **extensions, _DIAGNOSTIC_EXTENSION: { diff --git a/engine/tests/test_execution_duration.py b/engine/tests/test_execution_duration.py index b52c154b..12847128 100644 --- a/engine/tests/test_execution_duration.py +++ b/engine/tests/test_execution_duration.py @@ -252,3 +252,31 @@ async def test_precheck_error_has_no_execution_duration( assert len(response.errors) == 1 assert response.errors[0].execution_duration_ms is None clock.assert_not_called() + + +@pytest.mark.asyncio +async def test_opt_in_admission_wait_preserves_control_duration( + monkeypatch: pytest.MonkeyPatch, + evaluation_request: EvaluationRequest, + caplog: pytest.LogCaptureFixture, +) -> None: + # Given: diagnostic metadata and separate clock intervals for admission and total execution. + clock = Mock(side_effect=[10.0, 10.0, 10.005, 10.02]) + monkeypatch.setattr("agent_control_engine.core.time.perf_counter", clock) + caplog.set_level("INFO", logger="agent_control_engine.core") + + # When: evaluating through the public engine entrypoint with diagnostics enabled. + response = await ControlEngine([make_control()]).process( + evaluation_request, + extensions={"_agent_control_diagnostics": {"request_id": "a" * 32}}, + ) + + # Then: admission wait and the enclosing control duration retain the same IDs and units. + assert response.non_matches is not None + assert response.non_matches[0].execution_duration_ms == pytest.approx(20.0) + records = [r for r in caplog.records if r.msg == "Control evaluator admission wait"] + assert len(records) == 1 + fields = vars(records[0]) + assert fields["diagnostic_request_id"] == "a" * 32 + assert fields["diagnostic_control_id"] == "1" + assert fields["semaphore_wait_ms"] == pytest.approx(5.0) diff --git a/evaluators/contrib/galileo/README.md b/evaluators/contrib/galileo/README.md index 8191bb73..523cc40b 100644 --- a/evaluators/contrib/galileo/README.md +++ b/evaluators/contrib/galileo/README.md @@ -48,3 +48,20 @@ pip install agent-control-evaluator-galileo See full documentation in: https://docs.agentcontrol.dev/concepts/evaluators/contributing-evaluator Example with usage: https://docs.agentcontrol.dev/examples/galileo-luna + +## Latency diagnostics + +Set `AGENT_CONTROL_LATENCY_DIAGNOSTICS_ENABLED=true` on the server to enable diagnostic logs. +For target-bound evaluations, Agent Control generates a request ID and returns it in `X-Galileo-Diagnostic-ID`. +The Luna evaluator forwards that ID and `X-Galileo-Diagnostic-Control-ID` to the scorer endpoint. + +`Evaluation latency diagnostics` records handler stages. +`Evaluation control timing` records each returned control's ID and execution milliseconds as scalar fields. +The Luna client's `Agent Control scorer-invoke client timing` record measures request preparation, authentication, +HTTP client acquisition, Runners round trip, response parsing, and total time. +Failed HTTP calls retain elapsed time for the failed stage. Unreached stages have no measurement. +These timing records contain IDs, durations, and status codes without request contents or authentication values. + +On an instrumented Orbit Runners build, search `Runners scorer-invoke execution timing` with the same IDs. +It reports capacity wait, executor wait and execution, and service total time. +Disable the environment variable after the diagnostic session. diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py index 462b8dec..284768e9 100644 --- a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py @@ -620,7 +620,9 @@ async def invoke( "Agent Control slow scorer-invoke client timing", extra={ "diagnostic_request_id": diagnostic_id, - "diagnostic_control_id": request_headers.get("X-Galileo-Diagnostic-Control-ID"), + "diagnostic_control_id": request_headers.get( + "X-Galileo-Diagnostic-Control-ID" + ), "request_preparation_ms": request_preparation_ms, "auth_token_ms": auth_token_ms, "http_client_acquire_ms": client_acquire_ms, diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/evaluator.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/evaluator.py index 9f74f0c3..91a0594e 100644 --- a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/evaluator.py +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/evaluator.py @@ -342,7 +342,9 @@ async def _evaluate( scorer_kwargs["selected_data_payload_field"] = self.config.payload_field scorer_kwargs["execution_context"] = execution_context diagnostic_headers: dict[str, str] = {} - diagnostic = extensions.get("_agent_control_diagnostics") if extensions is not None else None + diagnostic = ( + extensions.get("_agent_control_diagnostics") if extensions is not None else None + ) if isinstance(diagnostic, dict): request_id = diagnostic.get("request_id") control_id = diagnostic.get("control_id") @@ -351,13 +353,14 @@ async def _evaluate( "X-Galileo-Diagnostic-ID": request_id, "X-Galileo-Diagnostic-Control-ID": control_id, } + if diagnostic_headers: + scorer_kwargs["headers"] = diagnostic_headers response = await self._get_client().invoke( **scorer_kwargs, input=input_text if _has_text(input_text) else None, output=output_text if _has_text(output_text) else None, config=self.config.scorer_config, timeout=self.get_timeout_seconds(), - headers=diagnostic_headers or None, ) if response.status.lower() != "success": diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py index c2111ace..0de9ab90 100644 --- a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py @@ -10,7 +10,7 @@ from hashlib import sha256 from hmac import new as hmac_new from json import dumps -from time import time +from time import perf_counter, time from typing import Any, Literal, get_args from urllib.parse import urlsplit @@ -540,6 +540,7 @@ async def invoke( httpx.HTTPStatusError: If the Luna invoke endpoint returns an error status code. httpx.RequestError: If the request fails before a response is received. """ + invoke_started = perf_counter() if not (_has_value(input) or _has_value(output)): raise ValueError("At least one of input or output must be provided.") @@ -580,7 +581,10 @@ async def invoke( config=invoke_config, ).to_dict() + request_preparation_ms = (perf_counter() - invoke_started) * 1000 + auth_started = perf_counter() endpoint, auth_header = self._endpoint_and_auth_header() + auth_token_ms = (perf_counter() - auth_started) * 1000 request_headers = { k: v for k, v in (headers or {}).items() if k.lower() not in _BLOCKED_REQUEST_HEADERS } @@ -589,20 +593,38 @@ async def invoke( logger.debug("[GalileoLunaClient] POST %s", endpoint) logger.debug("[GalileoLunaClient] Request body: %s", request_body) + diagnostic_id = request_headers.get("X-Galileo-Diagnostic-ID") + client_acquire_ms: float | None = None + http_round_trip_ms: float | None = None + response_parse_ms: float | None = None + status_code: int | None = None try: - client = await self._get_client() - response = await client.post( - endpoint, - json=request_body, - headers=request_headers, - timeout=timeout, - ) + client_acquire_started = perf_counter() + try: + client = await self._get_client() + finally: + client_acquire_ms = (perf_counter() - client_acquire_started) * 1000 + http_started = perf_counter() + try: + response = await client.post( + endpoint, + json=request_body, + headers=request_headers, + timeout=timeout, + ) + finally: + http_round_trip_ms = (perf_counter() - http_started) * 1000 + status_code = response.status_code response.raise_for_status() - response_data = response.json() - if not isinstance(response_data, dict): - raise RuntimeError("Invalid response payload: not a JSON object") - - parsed = ScorerInvokeResponse.from_dict(response_data) + parse_started = perf_counter() + try: + response_data = response.json() + if not isinstance(response_data, dict): + raise RuntimeError("Invalid response payload: not a JSON object") + + parsed = ScorerInvokeResponse.from_dict(response_data) + finally: + response_parse_ms = (perf_counter() - parse_started) * 1000 logger.debug("[GalileoLunaClient] Response: %s", parsed.raw_response) return parsed except httpx.HTTPStatusError as exc: @@ -615,6 +637,24 @@ async def invoke( except httpx.RequestError as exc: logger.error("[GalileoLunaClient] Request failed: %s", exc) raise + finally: + if diagnostic_id is not None: + logger.info( + "Agent Control scorer-invoke client timing", + extra={ + "diagnostic_request_id": diagnostic_id, + "diagnostic_control_id": request_headers.get( + "X-Galileo-Diagnostic-Control-ID" + ), + "request_preparation_ms": request_preparation_ms, + "auth_token_ms": auth_token_ms, + "http_client_acquire_ms": client_acquire_ms, + "runners_http_round_trip_ms": http_round_trip_ms, + "response_parse_ms": response_parse_ms, + "client_total_ms": (perf_counter() - invoke_started) * 1000, + "http_status_code": status_code, + }, + ) async def close(self) -> None: """Close HTTP clients and release resources.""" diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/evaluator.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/evaluator.py index a09b4ccf..ca46f7aa 100644 --- a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/evaluator.py +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/evaluator.py @@ -285,6 +285,17 @@ async def _evaluate( scorer_kwargs["selected_data_payload_field"] = self.config.payload_field if execution_context is not None: scorer_kwargs["execution_context"] = execution_context + diagnostic = ( + extensions.get("_agent_control_diagnostics") if extensions is not None else None + ) + if isinstance(diagnostic, dict): + request_id = diagnostic.get("request_id") + control_id = diagnostic.get("control_id") + if isinstance(request_id, str) and isinstance(control_id, str): + scorer_kwargs["headers"] = { + "X-Galileo-Diagnostic-ID": request_id, + "X-Galileo-Diagnostic-Control-ID": control_id, + } response = await self._get_client().invoke( **scorer_kwargs, input=input_text if _has_text(input_text) else None, diff --git a/evaluators/contrib/galileo/tests/test_luna_diagnostics.py b/evaluators/contrib/galileo/tests/test_luna_diagnostics.py new file mode 100644 index 00000000..9b567792 --- /dev/null +++ b/evaluators/contrib/galileo/tests/test_luna_diagnostics.py @@ -0,0 +1,141 @@ +"""Opt-in Luna diagnostics through the evaluator and HTTP client.""" + +from __future__ import annotations + +import logging +from itertools import count + +import httpx +import pytest +from agent_control_evaluator_galileo.luna import LunaEvaluator +from agent_control_evaluator_galileo.luna import client as luna_client +from agent_control_evaluator_galileo.luna.client import GalileoLunaClient +from agent_control_models import JSONObject, Step + +DIAGNOSTIC_ID = "a" * 32 + + +@pytest.fixture(autouse=True) +def luna_env(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("GALILEO_API_SECRET_KEY", "private-secret") + monkeypatch.setenv("GALILEO_LUNA_INVOKE_URL", "http://runners:8090") + monkeypatch.setenv("GALILEO_FEATURE_FLAG_SCORER_INVOKE_RUNTIME", "enabled") + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "diagnostic", + [ + None, + {"request_id": DIAGNOSTIC_ID}, + {"request_id": 42, "control_id": "7"}, + {"request_id": DIAGNOSTIC_ID, "control_id": "7"}, + ], +) +async def test_luna_diagnostics_reach_http_transport( + diagnostic: JSONObject | None, + caplog: pytest.LogCaptureFixture, + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Given: a real evaluator/client with only the network transport replaced. + evaluator = LunaEvaluator.from_dict({"scorer_id": "scorer-123", "threshold": 0.5}) + requests: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, json={"score": 0.8, "status": "success"}) + + evaluator._client._client = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + extensions: JSONObject = {"namespace_key": "org-1", "caller_id": "user-1"} + if diagnostic is not None: + extensions["_agent_control_diagnostics"] = diagnostic + ticks = count(1) + monkeypatch.setattr(luna_client, "perf_counter", lambda: next(ticks) / 1000) + caplog.set_level(logging.INFO, logger=luna_client.__name__) + + # When: the contextual evaluator invokes Luna. + try: + result = await evaluator.evaluate_with_extensions( + "private-input", Step(type="llm", name="answer", input="private-input"), extensions + ) + finally: + await evaluator._client.close() + + # Then: only complete diagnostic metadata enables correlation and timing logs. + assert result.error is None + assert result.matched is True + enabled = diagnostic == {"request_id": DIAGNOSTIC_ID, "control_id": "7"} + assert len(requests) == 1 + records = [r for r in caplog.records if r.msg == "Agent Control scorer-invoke client timing"] + if not enabled: + assert "X-Galileo-Diagnostic-ID" not in requests[0].headers + assert "X-Galileo-Diagnostic-Control-ID" not in requests[0].headers + assert records == [] + return + assert requests[0].headers.get("X-Galileo-Diagnostic-ID") == DIAGNOSTIC_ID + assert requests[0].headers.get("X-Galileo-Diagnostic-Control-ID") == "7" + assert len(records) == 1 + fields = vars(records[0]) + assert fields["diagnostic_request_id"] == DIAGNOSTIC_ID + assert fields["diagnostic_control_id"] == "7" + for field in ( + "request_preparation_ms", + "auth_token_ms", + "http_client_acquire_ms", + "runners_http_round_trip_ms", + "response_parse_ms", + ): + assert fields[field] == pytest.approx(1.0) + assert fields["client_total_ms"] == pytest.approx(10.0) + assert fields["http_status_code"] == 200 + assert "private-input" not in str(fields) + assert "private-secret" not in str(fields) + assert "Authorization" not in str(fields) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["http", "transport", "parse"]) +async def test_luna_diagnostics_capture_failed_stages( + failure: str, caplog: pytest.LogCaptureFixture +) -> None: + # Given: a client whose transport or response fails without real network I/O. + client = GalileoLunaClient() + + def handler(request: httpx.Request) -> httpx.Response: + if failure == "transport": + raise httpx.ConnectError("unavailable", request=request) + if failure == "http": + return httpx.Response(503, json={"error": "unavailable"}) + return httpx.Response(200, json=[]) + + client._client = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + caplog.set_level(logging.INFO, logger=luna_client.__name__) + + # When: invocation fails after diagnostic headers have been supplied. + try: + with pytest.raises((httpx.HTTPStatusError, httpx.ConnectError, RuntimeError)): + await client.invoke( + scorer_id="scorer-123", + input="private-input", + headers={ + "X-Galileo-Diagnostic-ID": DIAGNOSTIC_ID, + "X-Galileo-Diagnostic-Control-ID": "7", + }, + ) + finally: + await client.close() + + # Then: completed/failed stages remain timed and unreached stages remain absent. + records = [r for r in caplog.records if r.msg == "Agent Control scorer-invoke client timing"] + assert len(records) == 1 + fields = vars(records[0]) + assert fields["diagnostic_request_id"] == DIAGNOSTIC_ID + assert fields["diagnostic_control_id"] == "7" + assert fields["http_client_acquire_ms"] >= 0 + assert fields["runners_http_round_trip_ms"] >= 0 + assert fields["client_total_ms"] >= fields["runners_http_round_trip_ms"] + assert fields["http_status_code"] == {"http": 503, "transport": None, "parse": 200}[failure] + if failure == "parse": + assert fields["response_parse_ms"] >= 0 + else: + assert fields["response_parse_ms"] is None diff --git a/server/src/agent_control_server/endpoints/evaluation.py b/server/src/agent_control_server/endpoints/evaluation.py index 017122d3..2cef46d6 100644 --- a/server/src/agent_control_server/endpoints/evaluation.py +++ b/server/src/agent_control_server/endpoints/evaluation.py @@ -39,7 +39,12 @@ def _latency_diagnostics_enabled() -> bool: """Return whether opt-in evaluation timing logs are enabled.""" - return os.getenv(_LATENCY_DIAGNOSTICS_ENV, "").strip().lower() in {"1", "true", "yes", "enabled"} + return os.getenv(_LATENCY_DIAGNOSTICS_ENV, "").strip().lower() in { + "1", + "true", + "yes", + "enabled", + } @dataclass @@ -277,13 +282,15 @@ async def evaluate( "response_sanitize_ms": (time.perf_counter() - sanitize_started) * 1000, "handler_total_ms": (time.perf_counter() - handler_started) * 1000, "control_count": len(engine_controls), - "control_timings_ms": [ - { - "control_id": match.control_id, - "execution_ms": match.execution_duration_ms, - } - for match in control_results - ], }, ) + for match in control_results: + _logger.info( + "Evaluation control timing", + extra={ + "diagnostic_request_id": diagnostic_id, + "diagnostic_control_id": str(match.control_id), + "execution_ms": match.execution_duration_ms, + }, + ) return sanitized_response diff --git a/server/src/agent_control_server/logging_utils.py b/server/src/agent_control_server/logging_utils.py index 093e7c94..338a9667 100644 --- a/server/src/agent_control_server/logging_utils.py +++ b/server/src/agent_control_server/logging_utils.py @@ -20,10 +20,29 @@ "upstream_validation_total", "upstream_validation_status", ) +_LATENCY_DIAGNOSTIC_FIELDS = ( + "diagnostic_request_id", + "diagnostic_control_id", + "controls_load_ms", + "control_engine_ms", + "response_sanitize_ms", + "handler_total_ms", + "control_count", + "execution_ms", + "semaphore_wait_ms", + "evaluator_name", + "request_preparation_ms", + "auth_token_ms", + "http_client_acquire_ms", + "runners_http_round_trip_ms", + "response_parse_ms", + "client_total_ms", + "http_status_code", +) class _JsonLogFormatter(logging.Formatter): - """Render log messages and approved upstream diagnostics as valid JSON.""" + """Render log messages and approved diagnostics as valid JSON.""" def format(self, record: logging.LogRecord) -> str: payload: dict[str, object] = { @@ -32,7 +51,7 @@ def format(self, record: logging.LogRecord) -> str: "name": record.name, "msg": record.getMessage(), } - for field in _UPSTREAM_DIAGNOSTIC_FIELDS: + for field in (*_UPSTREAM_DIAGNOSTIC_FIELDS, *_LATENCY_DIAGNOSTIC_FIELDS): if field in record.__dict__: payload[field] = record.__dict__[field] if record.exc_info: diff --git a/server/tests/test_latency_diagnostics.py b/server/tests/test_latency_diagnostics.py new file mode 100644 index 00000000..5392252c --- /dev/null +++ b/server/tests/test_latency_diagnostics.py @@ -0,0 +1,126 @@ +"""Evaluation diagnostics without database or network dependencies.""" + +import json +import logging +from unittest.mock import AsyncMock + +import pytest +from agent_control_models import ( + ControlMatch, + EvaluationRequest, + EvaluationResponse, + EvaluatorResult, + Step, +) +from fastapi import Response + +from agent_control_server.auth_framework import Principal +from agent_control_server.endpoints import evaluation +from agent_control_server.logging_utils import _JsonLogFormatter + + +@pytest.mark.asyncio +@pytest.mark.parametrize("enabled", [False, True]) +async def test_evaluation_emits_scalar_control_timings( + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + enabled: bool, +) -> None: + # Given: the endpoint's storage and engine boundaries are replaced to avoid database I/O. + monkeypatch.setenv("AGENT_CONTROL_LATENCY_DIAGNOSTICS_ENABLED", str(enabled)) + monkeypatch.setattr(evaluation, "_load_engine_controls", AsyncMock(return_value=[])) + results = [ + ControlMatch( + control_id=index, + control_name=f"control-{index}", + action="deny", + result=EvaluatorResult(matched=False, confidence=1.0), + execution_duration_ms=duration, + ) + for index, duration in enumerate([0.0, 3.5, None], start=1) + ] + process = AsyncMock( + return_value=EvaluationResponse( + is_safe=True, + confidence=1.0, + matches=[results[0]], + non_matches=[results[1]], + errors=[results[2]], + ) + ) + monkeypatch.setattr(evaluation.ControlEngine, "process", process) + response = Response() + caplog.set_level(logging.INFO) + + # When: the endpoint evaluates a target-bound request. + await evaluation.evaluate( + EvaluationRequest( + agent_name="test-agent", + stage="pre", + step=Step(type="llm", name="answer", input="private-input"), + ), + response, + Principal(namespace_key="org-1", target_type="log_stream", target_id="run-1"), + ) + + # Then: emitted JSON contains one scalar timing per returned control, only when enabled. + records = [r for r in caplog.records if r.msg == "Evaluation control timing"] + summaries = [r for r in caplog.records if r.msg == "Evaluation latency diagnostics"] + if not enabled: + assert "X-Galileo-Diagnostic-ID" not in response.headers + assert records == [] + assert summaries == [] + assert "_agent_control_diagnostics" not in process.call_args.kwargs["extensions"] + return + diagnostic_id = response.headers["X-Galileo-Diagnostic-ID"] + assert process.call_args.kwargs["extensions"]["_agent_control_diagnostics"] == { + "request_id": diagnostic_id, + } + assert len(records) == 3 + for record, match in zip(records, results, strict=True): + payload = json.loads(_JsonLogFormatter().format(record)) + assert payload["diagnostic_request_id"] == diagnostic_id + assert payload["diagnostic_control_id"] == str(match.control_id) + assert payload["execution_ms"] == match.execution_duration_ms + assert "private-input" not in str(payload) + assert len(summaries) == 1 + summary = json.loads(_JsonLogFormatter().format(summaries[0])) + for key in ( + "controls_load_ms", + "control_engine_ms", + "response_sanitize_ms", + "handler_total_ms", + ): + assert summary[key] >= 0 + + +def test_json_formatter_retains_client_stages() -> None: + # Given: a safe client timing record with unrelated sensitive extras. + fields = { + "diagnostic_request_id": "a" * 32, + "diagnostic_control_id": "7", + "request_preparation_ms": 1.0, + "auth_token_ms": 2.0, + "http_client_acquire_ms": 3.0, + "runners_http_round_trip_ms": 4.0, + "response_parse_ms": 5.0, + "client_total_ms": 20.0, + "http_status_code": 200, + } + record = logging.makeLogRecord( + { + "msg": "Agent Control scorer-invoke client timing", + **fields, + "Authorization": "private-secret", + "request_body": "private-input", + } + ) + + # When: the server's JSON formatter renders the record. + payload = json.loads(_JsonLogFormatter().format(record)) + + # Then: all approved stages survive without exposing arbitrary extras. + for key, value in fields.items(): + assert payload[key] == value + assert "Authorization" not in payload + assert "request_body" not in payload From cea097dfea849aa73cbd0cd834aaf9a218864fe3 Mon Sep 17 00:00:00 2001 From: Namrata Ghadi Date: Tue, 24 Nov 2026 21:40:16 +0530 Subject: [PATCH 3/5] add more diagnostics --- evaluators/contrib/galileo/README.md | 3 + .../luna/client.py | 68 +++++++++- .../luna/pool_diagnostics.py | 122 ++++++++++++++++++ 3 files changed, 187 insertions(+), 6 deletions(-) create mode 100644 evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/pool_diagnostics.py diff --git a/evaluators/contrib/galileo/README.md b/evaluators/contrib/galileo/README.md index 523cc40b..c8272b0d 100644 --- a/evaluators/contrib/galileo/README.md +++ b/evaluators/contrib/galileo/README.md @@ -59,6 +59,9 @@ The Luna evaluator forwards that ID and `X-Galileo-Diagnostic-Control-ID` to the `Evaluation control timing` records each returned control's ID and execution milliseconds as scalar fields. The Luna client's `Agent Control scorer-invoke client timing` record measures request preparation, authentication, HTTP client acquisition, Runners round trip, response parsing, and total time. +Set `GALILEO_LUNA_HTTP_DIAGNOSTICS=true` to add HTTPcore connection-pool queue and transport-phase timings +to that record, including `http_pool_queue_ms` and `http_receive_headers_ms`. The pool adapter is +version-sensitive and runs only on correlated diagnostic requests. Failed HTTP calls retain elapsed time for the failed stage. Unreached stages have no measurement. These timing records contain IDs, durations, and status codes without request contents or authentication values. diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py index 0de9ab90..9b0d8c87 100644 --- a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py @@ -20,6 +20,7 @@ from ..records import UnsupportedStepTypeError, record_from_step from .config import ScorerInvokeConfig, scorer_invoke_runtime_enabled +from .pool_diagnostics import PoolTiming, begin_pool_diagnostics, pool_diagnostics_enabled logger = logging.getLogger(__name__) @@ -598,6 +599,44 @@ async def invoke( http_round_trip_ms: float | None = None response_parse_ms: float | None = None status_code: int | None = None + httpcore_first_event_ms: float | None = None + http_diagnostics_enabled = diagnostic_id is not None and pool_diagnostics_enabled() + transport_event_starts: dict[str, float] | None = {} if http_diagnostics_enabled else None + transport_event_durations: dict[str, float] | None = {} if http_diagnostics_enabled else None + pool_timing: PoolTiming | None = None + pool_timing_fields: dict[str, float | None] = {} + + async def trace_transport(event: str, _info: dict[str, Any]) -> None: + nonlocal httpcore_first_event_ms + if transport_event_starts is None or transport_event_durations is None: + return + try: + name, _, phase = event.rpartition(".") + field_name = { + "connection.connect_tcp": "http_connect_tcp_ms", + "connection.start_tls": "http_start_tls_ms", + "http11.send_request_headers": "http_send_headers_ms", + "http11.send_request_body": "http_send_body_ms", + "http11.receive_response_headers": "http_receive_headers_ms", + "http11.receive_response_body": "http_receive_body_ms", + }.get(name) + if field_name is None: + return + now = perf_counter() + if phase == "started": + if httpcore_first_event_ms is None: + httpcore_first_event_ms = (now - http_started) * 1000 + transport_event_starts[name] = now + elif phase in {"complete", "failed"}: + started = transport_event_starts.pop(name, None) + if started is not None: + transport_event_durations[field_name] = transport_event_durations.get( + field_name, 0.0 + ) + (now - started) * 1000 + except Exception: + # Diagnostics must never turn a successful scorer call into a failure. + logger.debug("Unable to record Luna HTTP transport timing", exc_info=True) + try: client_acquire_started = perf_counter() try: @@ -606,14 +645,28 @@ async def invoke( client_acquire_ms = (perf_counter() - client_acquire_started) * 1000 http_started = perf_counter() try: - response = await client.post( - endpoint, - json=request_body, - headers=request_headers, - timeout=timeout, - ) + if http_diagnostics_enabled: + request = client.build_request( + "POST", + endpoint, + json=request_body, + headers=request_headers, + timeout=timeout, + extensions={"trace": trace_transport}, + ) + pool_timing = begin_pool_diagnostics(request.extensions) + response = await client.send(request) + else: + response = await client.post( + endpoint, + json=request_body, + headers=request_headers, + timeout=timeout, + ) finally: http_round_trip_ms = (perf_counter() - http_started) * 1000 + if pool_timing is not None: + pool_timing_fields = pool_timing.finish() status_code = response.status_code response.raise_for_status() parse_started = perf_counter() @@ -650,6 +703,9 @@ async def invoke( "auth_token_ms": auth_token_ms, "http_client_acquire_ms": client_acquire_ms, "runners_http_round_trip_ms": http_round_trip_ms, + "httpcore_first_event_ms": httpcore_first_event_ms, + **(transport_event_durations or {}), + **pool_timing_fields, "response_parse_ms": response_parse_ms, "client_total_ms": (perf_counter() - invoke_started) * 1000, "http_status_code": status_code, diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/pool_diagnostics.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/pool_diagnostics.py new file mode 100644 index 00000000..2bbeb7f4 --- /dev/null +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/pool_diagnostics.py @@ -0,0 +1,122 @@ +"""Opt-in connection-pool timing for load-test diagnostic requests.""" + +from __future__ import annotations + +import logging +import os +import threading +from dataclasses import dataclass, field +from time import perf_counter_ns +from typing import Any + +_KEY = "galileo_luna_pool_timing" +_ENABLED_ENV = "GALILEO_LUNA_HTTP_DIAGNOSTICS" +_installed = False +_lock = threading.Lock() +logger = logging.getLogger(__name__) + + +@dataclass +class PoolTiming: + """Keep timing state on one diagnostic request without retaining payload data.""" + + started_ns: int = field(default_factory=perf_counter_ns) + queued_ns: int | None = None + assigned_ns: int | None = None + before_queue_ns: int | None = None + queue_wait_ns: int = 0 + housekeeping_ns: int = 0 + resume_ns: int = 0 + + def finish(self) -> dict[str, float | None]: + """Return connection-pool intervals in milliseconds.""" + ended_ns = perf_counter_ns() + if self.queued_ns is not None: + self.queue_wait_ns += max(0, ended_ns - self.queued_ns) + self.queued_ns = None + return { + "http_pool_before_queue_ms": _milliseconds(self.before_queue_ns), + "http_pool_queue_ms": _milliseconds(self.queue_wait_ns), + "http_pool_housekeeping_ms": _milliseconds(self.housekeeping_ns), + "http_pool_resume_ms": _milliseconds(self.resume_ns), + } + + +def _milliseconds(value_ns: int | None) -> float | None: + return value_ns / 1_000_000 if value_ns is not None else None + + +def _install_hooks() -> None: + """Observe HTTPcore's queue assignment without changing its pool decisions.""" + global _installed + with _lock: + if _installed: + return + from httpcore._async.connection_pool import AsyncPoolRequest + + original_init = AsyncPoolRequest.__init__ + original_assign = AsyncPoolRequest.assign_to_connection + original_clear = AsyncPoolRequest.clear_connection + original_wait = AsyncPoolRequest.wait_for_connection + + def initialize(self: Any, request: Any) -> None: + original_init(self, request) + timing = request.extensions.get(_KEY) + if isinstance(timing, PoolTiming): + now = perf_counter_ns() + timing.before_queue_ns = max(0, now - timing.started_ns) + timing.queued_ns = now + + def assign(self: Any, connection: Any) -> None: + original_assign(self, connection) + timing = self.request.extensions.get(_KEY) + if isinstance(timing, PoolTiming): + now = perf_counter_ns() + if timing.queued_ns is not None: + timing.queue_wait_ns += max(0, now - timing.queued_ns) + timing.queued_ns = None + timing.assigned_ns = now + + def clear(self: Any) -> None: + original_clear(self) + timing = self.request.extensions.get(_KEY) + if isinstance(timing, PoolTiming): + timing.queued_ns = perf_counter_ns() + timing.assigned_ns = None + + async def wait(self: Any, timeout: float | None = None) -> Any: + entered_ns = perf_counter_ns() + connection = await original_wait(self, timeout=timeout) + resumed_ns = perf_counter_ns() + timing = self.request.extensions.get(_KEY) + if isinstance(timing, PoolTiming) and timing.assigned_ns is not None: + timing.housekeeping_ns += max(0, entered_ns - timing.assigned_ns) + timing.resume_ns += max(0, resumed_ns - entered_ns) + return connection + + # HTTPcore does not expose a public connection-pool wait hook. Keep this + # version-sensitive adapter disabled unless explicitly enabled. + AsyncPoolRequest.__init__ = initialize # type: ignore[method-assign] + AsyncPoolRequest.assign_to_connection = assign # type: ignore[method-assign] + AsyncPoolRequest.clear_connection = clear # type: ignore[method-assign] + AsyncPoolRequest.wait_for_connection = wait # type: ignore[method-assign] + _installed = True + + +def pool_diagnostics_enabled() -> bool: + """Return whether detailed HTTP transport diagnostics were requested.""" + return os.environ.get(_ENABLED_ENV, "").lower() in {"1", "true", "enabled"} + + +def begin_pool_diagnostics(extensions: dict[str, Any]) -> PoolTiming | None: + """Attach timing only to opted-in diagnostic requests.""" + if not pool_diagnostics_enabled(): + return None + try: + _install_hooks() + except Exception: + logger.warning("Luna HTTP pool diagnostics could not be installed", exc_info=True) + return None + timing = PoolTiming() + extensions[_KEY] = timing + return timing From aa71e5b4bd939b6838da8593934d96558622c4b9 Mon Sep 17 00:00:00 2001 From: Namrata Ghadi Date: Wed, 25 Nov 2026 10:13:57 +0530 Subject: [PATCH 4/5] feat: capture scorer invoke submission timestamp --- .../llm/client.py | 29 ++++++++++++++----- .../luna/client.py | 14 ++++++--- .../src/agent_control_server/logging_utils.py | 1 + 3 files changed, 33 insertions(+), 11 deletions(-) diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py index 284768e9..6fac6aa6 100644 --- a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/llm/client.py @@ -10,7 +10,7 @@ from hashlib import sha256 from hmac import new as hmac_new from json import dumps -from time import perf_counter, time +from time import perf_counter, time, time_ns from typing import Any, Literal, get_args from urllib.parse import urlsplit @@ -33,6 +33,7 @@ # Headers that must never be forwarded to the scorer invoke endpoint (checked case-insensitively). _BLOCKED_REQUEST_HEADERS = frozenset({"galileo-api-key"}) +_DIAGNOSTIC_CLIENT_SENT_AT_HEADER = "X-Galileo-Diagnostic-Client-Sent-At-Unix-Ns" # Keep pooled-connection reuse shorter than typical server keepalive/worker # recycle windows so requests do not pick up sockets the server already closed. @@ -579,17 +580,30 @@ async def invoke( http_round_trip_ms: float | None = None response_parse_ms: float | None = None status_code: int | None = None + client_submit_unix_ns: int | None = None try: client_acquire_started = perf_counter() client = await self._get_client() client_acquire_ms = (perf_counter() - client_acquire_started) * 1000 http_started = perf_counter() - response = await client.post( - endpoint, - json=request_body, - headers=request_headers, - timeout=timeout, - ) + if diagnostic_id is not None: + request = client.build_request( + "POST", + endpoint, + json=request_body, + headers=request_headers, + timeout=timeout, + ) + client_submit_unix_ns = time_ns() + request.headers[_DIAGNOSTIC_CLIENT_SENT_AT_HEADER] = str(client_submit_unix_ns) + response = await client.send(request) + else: + response = await client.post( + endpoint, + json=request_body, + headers=request_headers, + timeout=timeout, + ) http_round_trip_ms = (perf_counter() - http_started) * 1000 status_code = response.status_code response.raise_for_status() @@ -627,6 +641,7 @@ async def invoke( "auth_token_ms": auth_token_ms, "http_client_acquire_ms": client_acquire_ms, "runners_http_round_trip_ms": http_round_trip_ms, + "runners_http_submit_unix_ns": client_submit_unix_ns, "response_parse_ms": response_parse_ms, "client_total_ms": client_total_ms, "http_status_code": status_code, diff --git a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py index 9b0d8c87..f5748087 100644 --- a/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py +++ b/evaluators/contrib/galileo/src/agent_control_evaluator_galileo/luna/client.py @@ -10,7 +10,7 @@ from hashlib import sha256 from hmac import new as hmac_new from json import dumps -from time import perf_counter, time +from time import perf_counter, time, time_ns from typing import Any, Literal, get_args from urllib.parse import urlsplit @@ -34,6 +34,7 @@ # Headers that must never be forwarded to the Luna invoke endpoint (checked case-insensitively). _BLOCKED_REQUEST_HEADERS = frozenset({"galileo-api-key"}) +_DIAGNOSTIC_CLIENT_SENT_AT_HEADER = "X-Galileo-Diagnostic-Client-Sent-At-Unix-Ns" # Keep pooled-connection reuse shorter than typical server keepalive/worker # recycle windows so requests do not pick up sockets the server already closed. @@ -600,6 +601,7 @@ async def invoke( response_parse_ms: float | None = None status_code: int | None = None httpcore_first_event_ms: float | None = None + client_submit_unix_ns: int | None = None http_diagnostics_enabled = diagnostic_id is not None and pool_diagnostics_enabled() transport_event_starts: dict[str, float] | None = {} if http_diagnostics_enabled else None transport_event_durations: dict[str, float] | None = {} if http_diagnostics_enabled else None @@ -645,16 +647,19 @@ async def trace_transport(event: str, _info: dict[str, Any]) -> None: client_acquire_ms = (perf_counter() - client_acquire_started) * 1000 http_started = perf_counter() try: - if http_diagnostics_enabled: + if diagnostic_id is not None: request = client.build_request( "POST", endpoint, json=request_body, headers=request_headers, timeout=timeout, - extensions={"trace": trace_transport}, + extensions={"trace": trace_transport} if http_diagnostics_enabled else {}, ) - pool_timing = begin_pool_diagnostics(request.extensions) + client_submit_unix_ns = time_ns() + request.headers[_DIAGNOSTIC_CLIENT_SENT_AT_HEADER] = str(client_submit_unix_ns) + if http_diagnostics_enabled: + pool_timing = begin_pool_diagnostics(request.extensions) response = await client.send(request) else: response = await client.post( @@ -703,6 +708,7 @@ async def trace_transport(event: str, _info: dict[str, Any]) -> None: "auth_token_ms": auth_token_ms, "http_client_acquire_ms": client_acquire_ms, "runners_http_round_trip_ms": http_round_trip_ms, + "runners_http_submit_unix_ns": client_submit_unix_ns, "httpcore_first_event_ms": httpcore_first_event_ms, **(transport_event_durations or {}), **pool_timing_fields, diff --git a/server/src/agent_control_server/logging_utils.py b/server/src/agent_control_server/logging_utils.py index 338a9667..40e0a762 100644 --- a/server/src/agent_control_server/logging_utils.py +++ b/server/src/agent_control_server/logging_utils.py @@ -35,6 +35,7 @@ "auth_token_ms", "http_client_acquire_ms", "runners_http_round_trip_ms", + "runners_http_submit_unix_ns", "response_parse_ms", "client_total_ms", "http_status_code", From 35b8353276926200e1418bdab2f3fe1c9893cb90 Mon Sep 17 00:00:00 2001 From: Namrata Ghadi Date: Wed, 25 Nov 2026 13:42:59 +0530 Subject: [PATCH 5/5] feat: split evaluation control database timings --- server/src/agent_control_server/db.py | 37 +++++++++++++++++++ .../endpoints/evaluation.py | 19 ++++++++-- .../src/agent_control_server/logging_utils.py | 3 ++ 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/server/src/agent_control_server/db.py b/server/src/agent_control_server/db.py index e65f76db..18445d75 100644 --- a/server/src/agent_control_server/db.py +++ b/server/src/agent_control_server/db.py @@ -1,8 +1,12 @@ import logging from collections.abc import AsyncGenerator +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from time import perf_counter from typing import Any from prometheus_client import Gauge +from sqlalchemy import event from sqlalchemy.engine.url import make_url from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.ext.asyncio.engine import AsyncEngine @@ -113,6 +117,39 @@ def _instrument_connection_pool(engine: AsyncEngine) -> None: ) +@dataclass +class ControlLoadDatabaseTiming: + """Record the connection acquisition and cursor execution for one control load.""" + + checkout_ms: float = field(init=False, default=0.0) + sql_ms: float = field(init=False, default=0.0) + statements: int = field(init=False, default=0) + _statement_started: float = field(init=False, default=0.0) + + def _before_cursor_execute(self, *_args: object) -> None: + self._statement_started = perf_counter() + + def _after_cursor_execute(self, *_args: object) -> None: + self.sql_ms += (perf_counter() - self._statement_started) * 1000 + self.statements += 1 + + @asynccontextmanager + async def measure(self, session: AsyncSession) -> AsyncGenerator[None, None]: + """Check out the session's connection once and time statements on that connection.""" + started = perf_counter() + connection = (await session.connection()).sync_connection + self.checkout_ms = (perf_counter() - started) * 1000 + before = self._before_cursor_execute + after = self._after_cursor_execute + event.listen(connection, "before_cursor_execute", before) + event.listen(connection, "after_cursor_execute", after) + try: + yield + finally: + event.remove(connection, "before_cursor_execute", before) + event.remove(connection, "after_cursor_execute", after) + + async def get_async_db() -> AsyncGenerator[AsyncSession, None]: async with AsyncSessionLocal() as session: yield session diff --git a/server/src/agent_control_server/endpoints/evaluation.py b/server/src/agent_control_server/endpoints/evaluation.py index 2cef46d6..9a2617b8 100644 --- a/server/src/agent_control_server/endpoints/evaluation.py +++ b/server/src/agent_control_server/endpoints/evaluation.py @@ -3,6 +3,7 @@ import json import os import time +from contextlib import nullcontext from dataclasses import dataclass from uuid import uuid4 @@ -19,7 +20,7 @@ from sqlalchemy import select from ..auth_framework import Operation, Principal, require_operation -from ..db import AsyncSessionLocal +from ..db import AsyncSessionLocal, ControlLoadDatabaseTiming from ..errors import APIValidationError, NotFoundError from ..logging_utils import get_logger from ..models import Agent @@ -170,11 +171,16 @@ async def _evaluation_context(request: Request) -> dict[str, object]: async def _load_engine_controls( request: EvaluationRequest, principal: Principal, + *, + db_timing: ControlLoadDatabaseTiming | None = None, ) -> list[ControlAdapter]: """Load and materialize controls before evaluator execution starts.""" namespace_key = principal.namespace_key - async with AsyncSessionLocal() as db: + async with ( + AsyncSessionLocal() as db, + db_timing.measure(db) if db_timing is not None else nullcontext(), + ): agent_result = await db.execute( select(Agent).where( Agent.name == request.agent_name, @@ -231,11 +237,13 @@ async def evaluate( """ handler_started = time.perf_counter() diagnostic_id = uuid4().hex if _latency_diagnostics_enabled() else None + db_timing = None if diagnostic_id is not None: response.headers["X-Galileo-Diagnostic-ID"] = diagnostic_id + db_timing = ControlLoadDatabaseTiming() controls_started = time.perf_counter() - engine_controls = await _load_engine_controls(request, principal) + engine_controls = await _load_engine_controls(request, principal, db_timing=db_timing) controls_load_ms = (time.perf_counter() - controls_started) * 1000 engine = ControlEngine(engine_controls) try: @@ -267,7 +275,7 @@ async def evaluate( sanitize_started = time.perf_counter() sanitized_response = _sanitize_evaluation_response(raw_response) - if diagnostic_id is not None: + if db_timing is not None: control_results = [ *(raw_response.matches or []), *(raw_response.non_matches or []), @@ -278,6 +286,9 @@ async def evaluate( extra={ "diagnostic_request_id": diagnostic_id, "controls_load_ms": controls_load_ms, + "controls_db_checkout_ms": db_timing.checkout_ms, + "controls_db_sql_ms": db_timing.sql_ms, + "controls_db_sql_count": db_timing.statements, "control_engine_ms": engine_ms, "response_sanitize_ms": (time.perf_counter() - sanitize_started) * 1000, "handler_total_ms": (time.perf_counter() - handler_started) * 1000, diff --git a/server/src/agent_control_server/logging_utils.py b/server/src/agent_control_server/logging_utils.py index 40e0a762..8dbf10ea 100644 --- a/server/src/agent_control_server/logging_utils.py +++ b/server/src/agent_control_server/logging_utils.py @@ -24,6 +24,9 @@ "diagnostic_request_id", "diagnostic_control_id", "controls_load_ms", + "controls_db_checkout_ms", + "controls_db_sql_ms", + "controls_db_sql_count", "control_engine_ms", "response_sanitize_ms", "handler_total_ms",