Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
36 changes: 35 additions & 1 deletion engine/src/agent_control_engine/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -315,9 +316,14 @@ async def _evaluate_leaf(

selector_path = selector.path or "*"
data = select_data(request.step, selector_path)
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:
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:
Expand Down Expand Up @@ -347,6 +353,24 @@ async def _evaluate_leaf(
exc_info=True,
)
result = self._build_error_result(error_msg)
finally:
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",
Expand Down Expand Up @@ -676,13 +700,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) and extensions is not None:
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

Expand Down
28 changes: 28 additions & 0 deletions engine/tests/test_execution_duration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
20 changes: 20 additions & 0 deletions evaluators/contrib/galileo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,23 @@ 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.
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.

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.
Original file line number Diff line number Diff line change
Expand Up @@ -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, time_ns
from typing import Any, Literal, get_args
from urllib.parse import urlsplit

Expand All @@ -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.
Expand Down Expand Up @@ -527,6 +528,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:
Expand Down Expand Up @@ -560,8 +562,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
}
Expand All @@ -570,20 +575,45 @@ 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
client_submit_unix_ns: int | None = None
try:
client_acquire_started = perf_counter()
client = await self._get_client()
response = await client.post(
endpoint,
json=request_body,
headers=request_headers,
timeout=timeout,
)
client_acquire_ms = (perf_counter() - client_acquire_started) * 1000
http_started = perf_counter()
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()
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:
Expand All @@ -596,6 +626,27 @@ 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,
"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,
},
)

async def close(self) -> None:
"""Close HTTP clients and release resources."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,20 @@ 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,
}
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,
Expand Down
Loading
Loading