Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
18926e8
fix(acp): await task/create instead of backgrounding it (#519)
chakrris Sep 22, 2026
d718f78
feat(tracing): stamp sgp evals run and row ids on SGP spans
mohammadatallah-scale Oct 7, 2026
43211ba
fix(tracing): keep list-shaped eval spans searchable and drop stale e…
mohammadatallah-scale Oct 7, 2026
a348297
fix(tracing): stamp sgp evals ids on local activity spans too
mohammadatallah-scale Oct 7, 2026
618f226
fix(tracing): drop a worker's eval attrs when a task's activities car…
mohammadatallah-scale Oct 7, 2026
ce0dcfa
fix(tracing): pin eval ids on a span when it starts so a reused task …
mohammadatallah-scale Oct 7, 2026
f1d9eb4
fix(tracing): pin eval ids for plain spans and keep them until the up…
mohammadatallah-scale Oct 7, 2026
3e31b85
chore: restore uv.lock
mohammadatallah-scale Oct 7, 2026
848212a
fix(tracing): keep eval span id captures apart from plain span pins s…
mohammadatallah-scale Oct 7, 2026
a789175
fix(tracing): stamp eval ids on child workflow spans and skip span pi…
mohammadatallah-scale Oct 12, 2026
8a170c1
style: sort interceptor imports
mohammadatallah-scale Oct 12, 2026
b45d3b3
fix(tracing): stamp an unpinned span only with ids its task had when …
mohammadatallah-scale Oct 14, 2026
6a57f9a
fix(tracing): keep eval ids on spans that start on another Temporal w…
mohammadatallah-scale Oct 14, 2026
0a79a58
ci(tutorials): pin pydantic below 2.14 for the openai-websearch-mcp s…
mohammadatallah-scale Oct 14, 2026
798ee8c
Merge origin/main into mohammad/ove-1253-sgp-evals-span-metadata
mohammadatallah-scale Dec 3, 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
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ def _websearch_env():
),
StdioServerParameters(
command="uvx",
args=["openai-websearch-mcp"],
# mcp 1.13.1, pinned by openai-websearch-mcp, imports a pydantic internal that 2.14 removed.
args=["--with", "pydantic<2.14", "openai-websearch-mcp"],
env=_websearch_env(),
),
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from agentex.types.agent import Agent
from agentex.types.event import Event
from agentex.protocol.acp import SendEventParams, CreateTaskParams, InterruptTaskParams
from agentex.lib.core.tracing import sgp_evals
from agentex.lib.environment_variables import EnvironmentVariables
from agentex.lib.core.clients.temporal.types import WorkflowState, ConflictWorkflowPolicy
from agentex.lib.core.temporal.types.workflow import SignalName
Expand Down Expand Up @@ -91,6 +92,9 @@ async def submit_task(self, agent: Agent, task: Task, params: dict[str, Any] | N
execution_timeout = timedelta(seconds=timeout_seconds) if timeout_seconds and timeout_seconds > 0 else None
# USE_EXISTING makes task/create idempotent
# If same task ID is already running Temporal returns a handle to the existing run instead of raising WorkflowAlreadyStarted
# Eval tasks carry their span attrs in the memo so the worker can stamp them.
eval_attrs = sgp_evals.span_attrs_from_task_metadata(task.task_metadata)
memo_kwargs: dict[str, Any] = {"memo": {sgp_evals.MEMO_KEY: eval_attrs}} if eval_attrs else {}
with _acp_dispatch_span("acp.task_create", task_id=task.id):
return await self._temporal_client.start_workflow(
workflow=self._env_vars.WORKFLOW_NAME,
Expand All @@ -103,6 +107,7 @@ async def submit_task(self, agent: Agent, task: Task, params: dict[str, Any] | N
task_queue=self._env_vars.WORKFLOW_TASK_QUEUE,
execution_timeout=execution_timeout,
conflict_policy=ConflictWorkflowPolicy.USE_EXISTING,
**memo_kwargs,
)

async def get_state(self, task_id: str) -> WorkflowState:
Expand Down
3 changes: 2 additions & 1 deletion src/agentex/lib/core/temporal/workers/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from agentex.lib.core.compat.version_guard import assert_backend_compatible
from agentex.lib.core.clients.temporal.auth import connect_temporal_client
from agentex.lib.core.observability.sgp_obs_setup import init_sgp_obs, shutdown_sgp_obs
from agentex.lib.core.tracing.sgp_evals_interceptor import SGPEvalsInterceptor
from agentex.lib.core.tracing.tracing_processor_manager import shutdown_sync_tracing_processors

logger = make_logger(__name__)
Expand Down Expand Up @@ -276,7 +277,7 @@ async def run(
build_id=str(uuid.uuid4()),
debug_mode=debug_enabled, # Disable deadlock detection in debug mode
# Temporal inherits client tracing before these business interceptors.
interceptors=self.interceptors,
interceptors=[SGPEvalsInterceptor(), *self.interceptors],
)

logger.info(f"Starting workers for task queue: {self.task_queue}")
Expand Down
24 changes: 18 additions & 6 deletions src/agentex/lib/core/tracing/processors/sgp_tracing_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from scale_gp_beta.lib.tracing.span import Span as SGPSpan

from agentex.types.span import Span
from agentex.lib.core.tracing import code_revision
from agentex.lib.core.tracing import sgp_evals, code_revision
from agentex.lib.types.tracing import SGPTracingProcessorConfig
from agentex.lib.utils.logging import make_logger
from agentex.lib.core.observability import tracing_metrics_recording as _metrics
Expand Down Expand Up @@ -71,7 +71,7 @@ def _add_source_to_span(span: Span, env_vars: EnvironmentVariables) -> None:


def _sgp_metadata(span: Span) -> Any:
"""Metadata for the SGP write: ``span.data`` plus the opt-in commit SHA.
"""Metadata for the SGP write: ``span.data`` plus the opt-in commit SHA and evals run/row ids.

Returns a COPY rather than mutating ``span``. ``trace.py`` hands the same
Span instance to every registered processor, so anything written onto
Expand All @@ -83,13 +83,19 @@ def _sgp_metadata(span: Span) -> Any:
leak like that today. Left as-is: changing five long-shipped fields is not
this change's business.)
"""
eval_attrs = sgp_evals.attrs_for_span(span)
extra: dict[str, Any] = dict(eval_attrs)
commit_sha = code_revision.commit_sha()
if commit_sha is None:
if commit_sha is not None:
extra[code_revision.COMMIT_SHA_KEY] = commit_sha
if not extra:
return span.data
if isinstance(span.data, dict):
return {**span.data, code_revision.COMMIT_SHA_KEY: commit_sha}
# List-shaped data is an accepted `data` shape and has nowhere to put a
# metadata key; leave it untouched rather than dropping the caller's data.
return {**span.data, **extra}
# List-shaped data has nowhere to put a key. Eval spans must stay searchable by run and row,
# so their list moves under "data". Otherwise it is left untouched rather than reshaped.
if eval_attrs and isinstance(span.data, list):
return {**extra, "data": span.data}
return span.data


Expand Down Expand Up @@ -129,6 +135,7 @@ def __init__(self, config: SGPTracingProcessorConfig):
disabled=disabled,
)
self.env_vars = EnvironmentVariables.refresh()
sgp_evals.enable_capture()
logger.info(
"SGP tracing span-start upsert %s (%s)",
"disabled — end-only ingest" if _skip_span_start_enabled() else "enabled",
Expand All @@ -148,6 +155,7 @@ def on_span_start(self, span: Span) -> None:
def on_span_end(self, span: Span) -> None:
sgp_span = _build_sgp_span(span, self.env_vars)
sgp_span.end_time = span.end_time.isoformat() # type: ignore[union-attr]
sgp_evals.release_span(span.id)
sgp_span.flush(blocking=False)

@override
Expand All @@ -170,6 +178,7 @@ def __init__(self, config: SGPTracingProcessorConfig):
asyncio.AbstractEventLoop, AsyncSGPClient
] = weakref.WeakKeyDictionary()
self.env_vars = EnvironmentVariables.refresh()
sgp_evals.enable_capture()
logger.info(
"SGP tracing span-start upsert %s (%s)",
"disabled — end-only ingest" if _skip_span_start_enabled() else "enabled",
Expand Down Expand Up @@ -251,6 +260,9 @@ async def on_spans_end(self, spans: list[Span]) -> None:
sgp_span.end_time = span.end_time.isoformat() # type: ignore[union-attr]
sgp_spans.append(sgp_span)
await client.spans.upsert_batch(items=[s.to_request_params() for s in sgp_spans])
# Released only after the upload so a queue retry rebuilds the span with the same ids.
for span in spans:
sgp_evals.release_span(span.id)
_metrics.record_export_success(
event_type="end", span_count=len(spans), processor="sgp"
)
Expand Down
149 changes: 149 additions & 0 deletions src/agentex/lib/core/tracing/sgp_evals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"""Run/row attribution for spans of SGP evals generation-unit tasks.

The evals service tags each unit's task with ``task_metadata`` carrying
``sgp_evals`` plus the run, row and attempt it belongs to. The ids are copied
onto the SGP copy of every span as flat ``sgp_evals_*`` keys so a spans search
on ``extra_metadata`` finds a unit's spans. Flat because sgp-traces treats
dotted keys differently on ClickHouse and Postgres.
"""

from __future__ import annotations

import threading
from typing import Any
from datetime import UTC, datetime
from collections import OrderedDict

from agentex.types.span import Span

__all__ = (
"MEMO_KEY",
"register_task",
"register_workflow_task",
"register_task_metadata",
"span_attrs_from_task_metadata",
"attrs_for_span",
"enable_capture",
"capture_for_span",
"release_span",
)

TASK_METADATA_MARKER = "sgp_evals"
SPAN_KEY_PREFIX = "sgp_evals_"
_TASK_METADATA_KEYS = ("generation_run_id", "row_id", "attempt_idx")
# Temporal workflow memo key the ACP server sets so the worker process can stamp the same attrs.
MEMO_KEY = "sgp_evals_span_attrs"

# Only eval tasks are stored, so this stays tiny. The LRU bound caps a long-lived agent process.
_MAX_TASKS = 10_000
# Each task's attrs with when they took effect, so an unpinned span only gets attrs its task had at its start.
_attrs_by_task: OrderedDict[str, tuple[dict[str, Any], datetime]] = OrderedDict()
# Attrs captured when a span starts, so a later registry change cannot alter a span still queued for export.
_attrs_by_span: OrderedDict[str, dict[str, Any]] = OrderedDict()
# Spans pinned with no attrs live apart so a flood of plain spans cannot evict an eval span's pinned ids.
_plain_spans: OrderedDict[str, None] = OrderedDict()
_lock = threading.Lock()
_WHOLE_WORKFLOW = datetime.min.replace(tzinfo=UTC)
# Only the SGP processor reads the pins, so a process without one never takes the lock per span.
_capture_enabled = False


def span_attrs_from_task_metadata(task_metadata: Any) -> dict[str, Any] | None:
"""The flat span attrs for an evals generation-unit task, or None for any other task."""
if not isinstance(task_metadata, dict) or task_metadata.get(TASK_METADATA_MARKER) is None:
return None
attrs = {
f"{SPAN_KEY_PREFIX}{key}": task_metadata[key] for key in _TASK_METADATA_KEYS if task_metadata.get(key) is not None
}
return attrs or None


def register_task(task_id: str, attrs: dict[str, Any], effective_from: datetime | None = None) -> None:
with _lock:
since = effective_from or datetime.now(UTC)
current = _attrs_by_task.get(task_id)
# Every event re-registers the same attrs, which must not move their start past the task's earlier spans.
if current is not None and current[0] == attrs:
since = min(since, current[1])
_attrs_by_task[task_id] = (attrs, since)
_attrs_by_task.move_to_end(task_id)
while len(_attrs_by_task) > _MAX_TASKS:
_attrs_by_task.popitem(last=False)


def register_workflow_task(task_id: str, attrs: dict[str, Any]) -> None:
"""Register ids read from a workflow memo, which also cover spans the workflow started before this worker saw it."""
register_task(task_id, attrs, effective_from=_WHOLE_WORKFLOW)


def register_task_metadata(task_id: str, task_metadata: Any) -> dict[str, Any] | None:
"""Remember an eval task's span attrs. No-op (and no lookup cost) for every other task."""
attrs = span_attrs_from_task_metadata(task_metadata)
if attrs is not None:
register_task(task_id, attrs)
else:
unregister_task(task_id)
return attrs


def unregister_task(task_id: str) -> None:
if _attrs_by_task:
with _lock:
_attrs_by_task.pop(task_id, None)


def _lookup(span: Span, started_at: datetime | None = None) -> dict[str, Any]:
for key in (span.task_id, span.trace_id):
entry = _attrs_by_task.get(key) if key else None
if entry is not None and (started_at is None or entry[1] <= started_at):
Comment thread
mohammadatallah-scale marked this conversation as resolved.
Resolved
return dict(entry[0])
return {}


def _aware(moment: datetime) -> datetime:
return moment if moment.tzinfo is not None else moment.replace(tzinfo=UTC)


def enable_capture() -> None:
global _capture_enabled
_capture_enabled = True


def capture_for_span(span: Span) -> None:
Comment thread
mohammadatallah-scale marked this conversation as resolved.
Resolved
"""Pin the span's attrs at start, empty included, so an eval task registered later cannot claim it."""
if not _capture_enabled:
return
Comment thread
mohammadatallah-scale marked this conversation as resolved.
Resolved
with _lock:
attrs = _lookup(span)
store: OrderedDict[str, Any] = _attrs_by_span if attrs else _plain_spans
store[span.id] = attrs or None
while len(store) > _MAX_TASKS:
store.popitem(last=False)


def release_span(span_id: str) -> None:
if _attrs_by_span or _plain_spans:
with _lock:
_attrs_by_span.pop(span_id, None)
_plain_spans.pop(span_id, None)


def attrs_for_span(span: Span) -> dict[str, Any]:
"""Attrs captured at span start, else those its task (``span.task_id`` then ``span.trace_id``) had at its start."""
if not _attrs_by_task and not _attrs_by_span and not _plain_spans:
return {}
with _lock:
if span.id in _attrs_by_span:
return dict(_attrs_by_span[span.id])
if span.id in _plain_spans:
return {}
# Unpinned (started on another worker, before an SGP processor existed, or evicted).
return _lookup(span, _aware(span.start_time))


def clear() -> None:
"""Reset the registry (test isolation)."""
with _lock:
_attrs_by_task.clear()
_attrs_by_span.clear()
_plain_spans.clear()
112 changes: 112 additions & 0 deletions src/agentex/lib/core/tracing/sgp_evals_interceptor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""Carry an eval task's span attrs from its Temporal workflow memo into the worker's activities.

Spans are emitted by activities in the worker process, which never sees the ACP
server's task. The ACP server puts the attrs in the workflow memo, the outbound
interceptor copies them onto each activity's headers, and the activity
interceptor registers them for the task so the SGP processor can stamp spans.
A child workflow gets the attrs and the task id in its own memo, since it inherits neither.
Non-eval workflows have no memo entry and get no header.
"""

from __future__ import annotations

from typing import Any, override

from temporalio import activity, workflow
from temporalio.worker import (
Interceptor,
StartActivityInput,
ExecuteActivityInput,
StartChildWorkflowInput,
StartLocalActivityInput,
ActivityInboundInterceptor,
WorkflowInboundInterceptor,
WorkflowOutboundInterceptor,
)
from temporalio.converter import default

from agentex.lib.utils.logging import make_logger
from agentex.lib.core.tracing.sgp_evals import MEMO_KEY, unregister_task, register_workflow_task

logger = make_logger(__name__)

ATTRS_HEADER = "sgp-evals-span-attrs"
TASK_ID_HEADER = "sgp-evals-task-id"
TASK_ID_MEMO_KEY = "sgp_evals_task_id"
_converter = default().payload_converter


class SGPEvalsInterceptor(Interceptor):
@override
def intercept_activity(self, next: ActivityInboundInterceptor) -> ActivityInboundInterceptor:
return _ActivityInbound(next)

@override
def workflow_interceptor_class(self, input: Any) -> type[WorkflowInboundInterceptor] | None:
return _WorkflowInbound


class _WorkflowInbound(WorkflowInboundInterceptor):
@override
def init(self, outbound: WorkflowOutboundInterceptor) -> None:
super().init(_WorkflowOutbound(outbound))


def _memo_attrs() -> dict[str, Any] | None:
attrs = workflow.memo_value(MEMO_KEY, default=None)
return attrs if isinstance(attrs, dict) and attrs else None
Comment on lines +55 to +57

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Later spans keep old IDs

When an event/send changes or removes a running Temporal task’s eval metadata, _memo_attrs still reads the IDs saved when the workflow started. send_event forwards the updated task but never refreshes that memo. New worker spans therefore keep the old run and row IDs, so searches can show work under an eval run it no longer belongs to.

Update the workflow’s attribution when it receives changed task metadata, while preserving the IDs already saved for earlier spans.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agentex/lib/core/tracing/sgp_evals_interceptor.py
Line: 55-57

Comment:
**Later spans keep old IDs**

When an `event/send` changes or removes a running Temporal task’s eval metadata, `_memo_attrs` still reads the IDs saved when the workflow started. `send_event` forwards the updated task but never refreshes that memo. New worker spans therefore keep the old run and row IDs, so searches can show work under an eval run it no longer belongs to.

Update the workflow’s attribution when it receives changed task metadata, while preserving the IDs already saved for earlier spans.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex



def _task_id() -> str:
# The workflow id is the task id (see TemporalTaskService.submit_task), except in a child workflow.
return workflow.memo_value(TASK_ID_MEMO_KEY, default=None) or workflow.info().workflow_id


def _add_attrs_header(input: StartActivityInput | StartLocalActivityInput) -> None:
attrs = _memo_attrs()
if attrs:
input.headers = {
**input.headers,
ATTRS_HEADER: _converter.to_payload(attrs),
TASK_ID_HEADER: _converter.to_payload(_task_id()),
}


class _WorkflowOutbound(WorkflowOutboundInterceptor):
@override
def start_activity(self, input: StartActivityInput) -> workflow.ActivityHandle[Any]:
Comment thread
mohammadatallah-scale marked this conversation as resolved.
Resolved
_add_attrs_header(input)
return super().start_activity(input)

@override
def start_local_activity(self, input: StartLocalActivityInput) -> workflow.ActivityHandle[Any]:
_add_attrs_header(input)
return super().start_local_activity(input)

@override
async def start_child_workflow(self, input: StartChildWorkflowInput) -> workflow.ChildWorkflowHandle[Any, Any]:
attrs = _memo_attrs()
if attrs:
input.memo = {**(input.memo or {}), MEMO_KEY: attrs, TASK_ID_MEMO_KEY: _task_id()}
return await super().start_child_workflow(input)


class _ActivityInbound(ActivityInboundInterceptor):
@override
async def execute_activity(self, input: ExecuteActivityInput) -> Any:
payload = input.headers.get(ATTRS_HEADER)
task_id_payload = input.headers.get(TASK_ID_HEADER)
# Older workers send no task id header, and outside a child workflow the workflow id is the task id.
task_id = activity.info().workflow_id
Comment thread
mohammadatallah-scale marked this conversation as resolved.
Resolved
if task_id and payload is None:
# A reused workflow id must not inherit a previous eval run's ids.
unregister_task(task_id)
Comment thread
mohammadatallah-scale marked this conversation as resolved.
Resolved
elif payload is not None:
try:
if task_id_payload is not None:
task_id = _converter.from_payload(task_id_payload, str)
if task_id:
register_workflow_task(task_id, _converter.from_payload(payload, dict))
except Exception:
logger.warning("failed to read sgp evals span attrs from activity headers", exc_info=True)
return await super().execute_activity(input)
Comment thread
mohammadatallah-scale marked this conversation as resolved.
Resolved
Loading
Loading