Repository navigation
feat(tracing): stamp sgp evals run and row ids on SGP spans #545
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
base: main
Are you sure you want to change the base?
Changes from all commits
18926e8
d718f78
43211ba
a348297
618f226
ce0dcfa
f1d9eb4
3e31b85
848212a
a789175
8a170c1
b45d3b3
6a57f9a
0a79a58
798ee8c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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): | ||
| 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: | ||
|
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 | ||
|
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() | ||
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When an Update the workflow’s attribution when it receives changed task metadata, while preserving the IDs already saved for earlier spans. Prompt To Fix With AIThis 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. |
||
|
|
||
|
|
||
| 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]: | ||
|
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 | ||
|
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) | ||
|
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) | ||
|
mohammadatallah-scale marked this conversation as resolved.
Resolved
|
||
Uh oh!
There was an error while loading. Please reload this page.