From 3934a1718a4430f02b5a6613dac0d2007de1b7d6 Mon Sep 17 00:00:00 2001 From: Ym <173550318+MaxonT@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:33:29 -0600 Subject: [PATCH] fix(otel): name the Workflow and Step operation spans in Execution view log records Signed-off-by: Ym <173550318+MaxonT@users.noreply.github.com> --- .../README.md | 21 ++++-- .../execution_plugin.py | 59 +++++++++++----- .../log_filter.py | 7 +- .../test_concurrent_log_correlation_int.py | 12 ++-- .../tests/e2e/test_view_registration.py | 15 ++-- .../tests/test_execution_plugin.py | 70 +++++++++++++------ 6 files changed, 125 insertions(+), 59 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python-otel/README.md b/packages/aws-durable-execution-sdk-python-otel/README.md index d61c669c1..ee2f12fda 100644 --- a/packages/aws-durable-execution-sdk-python-otel/README.md +++ b/packages/aws-durable-execution-sdk-python-otel/README.md @@ -498,13 +498,20 @@ active for the emitting invocation onto log records, using these attributes: - `spanId`: 16-char hex span identifier - `otelTraceSampled`: boolean indicating if the trace is sampled -Which span a record carries follows the emitting thread: the operation attempt -span inside a step, the context span inside a child context, and the Invocation -span for top-level handler code. A span you start yourself on the execution -trace is used for records emitted inside it. A span the runtime already had -active when the invocation started — the Lambda invocation span the ADOT layer -creates under X-Ray active tracing — is the parent of the Invocation span rather -than a substitute for it, so a top-level record still names the Invocation span. +Which span a record carries follows the emitting thread. With +`ExecutionOtelPlugin`, a record carries the logical span: the Workflow span for +top-level handler code (the same span ID before a durable wait and after resume), +the Step operation span inside a step body (the same span ID for every retry +attempt, and a step nested in a child context uses its own span), and the Child +operation span inside a child context. Attempt spans stay current in the OTel +context, so tracing topology is unchanged. `InvocationOtelPlugin` keeps its +previous mapping: the operation attempt span inside a step, the context span +inside a child context, and the Invocation span for top-level handler code. A +span you start yourself on the execution trace is used for records emitted +inside it. A span the runtime already had active when the invocation started +(the Lambda invocation span the ADOT layer creates under X-Ray active tracing) +does not replace these spans, so a top-level record still names the Workflow +span (Execution view) or the Invocation span (Invocation view). Correlation holds from the first statement of the handler, before any durable operation, and holds when several invocations run concurrently in one environment (Lambda Managed Instances): the plugin claims the invocation thread diff --git a/packages/aws-durable-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/execution_plugin.py b/packages/aws-durable-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/execution_plugin.py index 265c01074..335c36b15 100644 --- a/packages/aws-durable-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/execution_plugin.py +++ b/packages/aws-durable-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/execution_plugin.py @@ -187,6 +187,9 @@ def __init__(self, config: OtelPluginConfig | None = None) -> None: # recorded by _record_enclosing_span. Used only to resolve log # correlation; see get_current_span_context. self._enclosing_span_context: SpanContext | None = None + # Attempt span ID -> its Step operation span context, so a record + # emitted in a step body carries the Step operation span ID. + self._attempt_operation_contexts: dict[int, SpanContext] = {} self._operation_spans: dict[str, Span] = {} # CONTEXT operations that emitted a durable START hook this invocation. # A context absent from this set is checkpointless (for example, a FLAT @@ -324,27 +327,39 @@ def _detach_remaining_contexts(self) -> None: def get_current_span_context(self) -> SpanContext | None: """Return the active span context for log correlation (see log_filter). - A span that became current *inside* this invocation wins: the attempt - span inside a step, the context span inside a child context, or a span - the handler body starts itself. The span that enclosed this invocation is - excluded, so top-level handler records resolve to the Invocation span - rather than to the Workflow span this plugin makes current at invocation - start, which the SDK carries into the thread running the handler body. + Records resolve to the logical Workflow or operation span: the Workflow + span for top-level handler code, the Step operation span inside a step + body (the same span for every retry attempt), and the Child operation + span inside a child context. A span the handler body starts itself is + used as is. The attempt span stays current in the OTel context so + tracing topology is unchanged; only the span ID stamped on the record + maps from the attempt to its Step operation. """ span_context = trace.get_current_span().get_span_context() - if ( - span_context - and span_context.is_valid - and not self._is_enclosing_span(span_context) - ): - return span_context - for candidate in (self._invocation_span, self._workflow_span): - if candidate is not None: - ctx = candidate.get_span_context() - if ctx and ctx.is_valid: - return ctx + if span_context and span_context.is_valid: + if self._is_enclosing_span(span_context): + workflow = self._valid_context(self._workflow_span) + if workflow is not None: + return workflow + else: + with self._lock: + operation = self._attempt_operation_contexts.get( + span_context.span_id + ) + return operation or span_context + for candidate in (self._workflow_span, self._invocation_span): + ctx = self._valid_context(candidate) + if ctx is not None: + return ctx return None + @staticmethod + def _valid_context(span: Span | None) -> SpanContext | None: + if span is None: + return None + ctx = span.get_span_context() + return ctx if ctx and ctx.is_valid else None + def _record_enclosing_span(self) -> None: """Record the span that is current now, as this invocation's body begins. @@ -993,6 +1008,12 @@ def on_user_function_start(self, info: UserFunctionStartInfo) -> None: deterministic=False, ) self._note_parent_start(info.operation_id, info.start_time) + operation_context = self._operation_span_context(info.operation_id) + if operation_context is not None: + with self._lock: + self._attempt_operation_contexts[ + span.get_span_context().span_id + ] = operation_context else: # CONTEXT # A child context can suspend before completing, so hold a # non-recording placeholder while it runs; on_operation_end @@ -1046,6 +1067,10 @@ def on_user_function_end(self, info: UserFunctionEndInfo) -> None: popped = self._pop_span(key) if popped is not None: + with self._lock: + self._attempt_operation_contexts.pop( + popped.get_span_context().span_id, None + ) popped.end(end_time=end_timestamp) # Restore the enclosing context by releasing the scope this user diff --git a/packages/aws-durable-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/log_filter.py b/packages/aws-durable-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/log_filter.py index 48f3e764b..b56d69d34 100644 --- a/packages/aws-durable-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/log_filter.py +++ b/packages/aws-durable-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/log_filter.py @@ -204,9 +204,10 @@ class OtelContextLogFilter(logging.Filter): time, on the thread that emits the record, so one installed filter serves any number of concurrent invocations. Resolution is described in the module docstring; the span itself comes from that invocation's - ``get_current_span_context()``, which returns the active operation span - inside steps and child contexts and falls back to the invocation span for - top-level handler code. + ``get_current_span_context()``, which returns the span the plugin + names for the record: for the Execution view the Step operation, Child + operation or Workflow span, for the Invocation view the active operation + span inside steps and child contexts and the invocation span at top level. The filter never caches identifiers and always returns ``True`` so it never drops a record. diff --git a/packages/aws-durable-execution-sdk-python-otel/tests/e2e/test_concurrent_log_correlation_int.py b/packages/aws-durable-execution-sdk-python-otel/tests/e2e/test_concurrent_log_correlation_int.py index 1a410253b..907ec2295 100644 --- a/packages/aws-durable-execution-sdk-python-otel/tests/e2e/test_concurrent_log_correlation_int.py +++ b/packages/aws-durable-execution-sdk-python-otel/tests/e2e/test_concurrent_log_correlation_int.py @@ -269,12 +269,13 @@ def invoke(owner: str) -> None: for owner in OWNERS: assert results[owner]["Status"] == InvocationStatus.SUCCEEDED.value - # Each invocation's Invocation span identifies its execution by ARN, so - # the expected identifiers are read back from the exported spans rather - # than recomputed. + # Each parent span identifies its execution by ARN, so the expected + # identifiers are read back from the exported spans rather than + # recomputed. A top-level record names the Workflow span in the + # Execution view and the Invocation span in the Invocation view. expected: dict[str, tuple[str, str]] = {} for span in exporter.get_finished_spans(): - if span.name != "Invocation": + if span.name != parent_name: continue assert span.attributes is not None arn = span.attributes["durable.execution.arn"] @@ -296,8 +297,7 @@ def invoke(owner: str) -> None: assert stamped == { owner: expected[_execution_arn(owner)] for owner in OWNERS }, f"records carried {stamped}" - # Log correlation keeps its existing Invocation fallback in both views; - # durable operation parenting distinguishes the selected view. + # Durable operation parenting distinguishes the selected view. parents = { str(span.attributes["durable.execution.arn"]): span.context for span in exporter.get_finished_spans() diff --git a/packages/aws-durable-execution-sdk-python-otel/tests/e2e/test_view_registration.py b/packages/aws-durable-execution-sdk-python-otel/tests/e2e/test_view_registration.py index 7493ff844..c71f50442 100644 --- a/packages/aws-durable-execution-sdk-python-otel/tests/e2e/test_view_registration.py +++ b/packages/aws-durable-execution-sdk-python-otel/tests/e2e/test_view_registration.py @@ -613,12 +613,17 @@ def recovered(_event: Any, durable: DurableContext) -> str: with DurableFunctionTestRunner(handler=wrapped) as runner: assert runner.run(input="{}", timeout=15).status.value == "SUCCEEDED" record = next(r for r in handler.records if r.name == "recovery") - attempt = next( - s for s in exporter.get_finished_spans() if s.name == "logged-step attempt 1" + # The Execution view names the Step operation span; the Invocation view + # names the attempt span. + span_name = ( + "logged-step" + if classes[0] is ExecutionOtelPluginFactory + else "logged-step attempt 1" ) - assert attempt.context is not None - assert getattr(record, "traceId", None) == f"{attempt.context.trace_id:032x}" - assert getattr(record, "spanId", None) == f"{attempt.context.span_id:016x}" + logged = next(s for s in exporter.get_finished_spans() if s.name == span_name) + assert logged.context is not None + assert getattr(record, "traceId", None) == f"{logged.context.trace_id:032x}" + assert getattr(record, "spanId", None) == f"{logged.context.span_id:016x}" assert len(handler.filters) == 1 diff --git a/packages/aws-durable-execution-sdk-python-otel/tests/test_execution_plugin.py b/packages/aws-durable-execution-sdk-python-otel/tests/test_execution_plugin.py index 6481d36f7..14120be69 100644 --- a/packages/aws-durable-execution-sdk-python-otel/tests/test_execution_plugin.py +++ b/packages/aws-durable-execution-sdk-python-otel/tests/test_execution_plugin.py @@ -1709,14 +1709,13 @@ def _span_id_hex(span: Span) -> str: return format(span.get_span_context().span_id, "016x") -def test_top_level_log_names_invocation_span_not_the_attached_workflow_span(): - """A top-level handler record names the Invocation span, not the Workflow span. - - This plugin makes the Workflow span current at invocation start so - auto-instrumented spans join the execution trace, and the SDK carries the - invocation thread's context into the thread that runs the handler body. The - Workflow span spans the whole execution, so it is less specific than the - Invocation span for a record emitted by one invocation's top-level code. +def test_top_level_log_names_the_workflow_span(): + """A top-level handler record names the Workflow span. + + This plugin makes the Workflow span current at invocation start, and the SDK + carries the invocation thread's context into the thread that runs the + handler body. The Workflow span has a stable identity across invocations, + so top-level records before a wait and after resume carry the same span ID. """ plugin, _ = _create_plugin() plugin.on_invocation_start(_invocation_start_info()) @@ -1728,30 +1727,59 @@ def test_top_level_log_names_invocation_span_not_the_attached_workflow_span(): stamped = _stamped_span_id() - assert stamped == _span_id_hex(plugin._invocation_span) - assert stamped != _span_id_hex(plugin._workflow_span) + assert stamped == _span_id_hex(plugin._workflow_span) + assert stamped != _span_id_hex(plugin._invocation_span) finally: plugin.on_invocation_end(_invocation_end_info()) -def test_step_attempt_log_names_the_attempt_span(): - """A record inside a step names the attempt span, not the Invocation span. +def test_step_log_names_the_step_operation_span_across_attempts(): + """A record inside a step names the Step operation span, not the attempt span. - Excluding the Workflow span from log correlation must not also exclude spans - that become current inside the invocation. + The attempt span stays current so tracing topology is unchanged; only the + stamped span ID maps to the Step operation, which is the same for every + attempt. Leaving the step restores the Workflow span. """ plugin, _ = _create_plugin() plugin.on_invocation_start(_invocation_start_info()) try: - plugin.on_user_function_start(_step_start_info("step-1")) - attempt_span = plugin._get_span("step-1:attempt:1") - assert attempt_span is not None - assert plugin._invocation_span is not None + assert plugin._workflow_span is not None + operation_span_id = format( + operation_id_to_span_id(EXECUTION_ARN, "step-1"), "016x" + ) + stamped_by_attempt = [] + for attempt in (1, 2): + plugin.on_user_function_start(_step_start_info("step-1", attempt=attempt)) + attempt_span = plugin._get_span(f"step-1:attempt:{attempt}") + assert attempt_span is not None + assert trace.get_current_span() is attempt_span + stamped_by_attempt.append(_stamped_span_id()) + assert stamped_by_attempt[-1] != _span_id_hex(attempt_span) + plugin.on_user_function_end(_step_end_info("step-1", attempt=attempt)) + assert _stamped_span_id() == _span_id_hex(plugin._workflow_span) + + assert stamped_by_attempt == [operation_span_id, operation_span_id] + finally: + plugin.on_invocation_end(_invocation_end_info()) - stamped = _stamped_span_id() - assert stamped == _span_id_hex(attempt_span) - assert stamped != _span_id_hex(plugin._invocation_span) +def test_nested_step_log_names_its_own_operation_span_and_restores_child(): + """A step inside a child context logs its own operation span; leaving it + restores the Child operation span.""" + plugin, _ = _create_plugin() + plugin.on_invocation_start(_invocation_start_info()) + try: + plugin.on_user_function_start(_context_start_info("ctx-1")) + child_span_id = _stamped_span_id() + child_span = plugin._get_span("ctx-1") + assert child_span is not None + assert child_span_id == _span_id_hex(child_span) + plugin.on_user_function_start(_step_start_info("step-1", parent_id="ctx-1")) + assert _stamped_span_id() == format( + operation_id_to_span_id(EXECUTION_ARN, "step-1"), "016x" + ) + plugin.on_user_function_end(_step_end_info("step-1")) + assert _stamped_span_id() == child_span_id finally: plugin.on_invocation_end(_invocation_end_info())