Skip to content

feat(logger): preserve manual trace declarations in OTLP spans - #295

Open
pradystar wants to merge 7 commits into
mainfrom
feat/start-trace-otel-metadata
Open

pradystar wants to merge 7 commits into
mainfrom
feat/start-trace-otel-metadata

Conversation

@pradystar

@pradystar pradystar commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • On the OTLP path, start_trace() freezes the supplied name, metadata, tags, and dataset input, output, and metadata. The SDK exports these fields as splunk_ao.trace.* attributes on the SDK-owned root operation.
  • With no active trace, the first SDK operation becomes the root. An SDK-owned root already opened by instrumentation can accept its first declaration while it’s open. A duplicate declaration on an open SDK trace warns and raises ValueError.
  • When an upstream service owns the root, start_trace() warns and returns None. Downstream workflows and agents still join the same trace and can export completed spans independently.
  • Deprecates input and redacted_input on OTLP start_trace(), and output and redacted_output on conclude() when closing a manual trace envelope. Set actual and redacted I/O on operation spans. Ingestion-hook loggers still accept envelope I/O. created_at, duration_ns, and external_id are deprecated and ignored on start_trace().
  • Updates the README, architecture guide, changelog, tracing tests, and examples. Trace field projection requires the corresponding Orbit ingestion changes.

Validation

  • Full SDK suite on macOS with Python 3.13 and four workers passed with 2,667 tests passed and 4 skipped.

- Capture immutable trace fields on direct operation spans
- Keep automatic handler envelopes unmarked
- Reject known local trace redeclarations
- Deprecate start_trace timing and external ID arguments
- Add regression coverage and document backend compatibility
Merge origin/main and resolve logger and decorator conflicts.

Carry explicit conclude output and redacted output as trace attributes
on direct operations under declared trace envelopes. Keep sibling spans
and the frozen start declaration unchanged.
@pradystar
pradystar marked this pull request as ready for review December 2, 2026 00:26

@opikalova opikalova left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 This review was generated by the Astra agent (claude-opus-5-5). It may contain mistakes.

Verdict: request_changes — The new early return in start_trace() silently drops telemetry for code that worked before. Hook payloads also lose fields, and siblings are reparented under the first operation.

⚠️ This change has 5,106 diff lines. AI and human reviewers are more likely to miss errors in a large change. If possible, split it. This note is for information only, not a reason to reject it.

General Comments

  • 🟡 minor (documentation): Astra found no Jira ticket in the branch name, the title or the description.
  • 🟠 major (design): This change breaks existing callers, but CHANGELOG.md lists the new behaviour only under Added and Deprecated (lines 10-22):
  • start_trace() can return None and skip its lifecycle.
  • Hook-backed payloads lose created_at, duration_ns and external_id.
  • Siblings of a declared envelope get new OTel parents.

Add a Changed or breaking-change section that states each item and gives a migration step. Today a user who upgrades gets only a log warning, or a DeprecationWarning that is hidden by default. See the line comments for details.

Follow-ups

Suggested follow-up work that could be tracked as Jira tickets:

  • examples/logging-samples/span-names/trace_examples.py:187-190: The gateway example uses bare assert statements for control flow. Running with python -O skips these checks. Replace them with explicit checks that raise or log.

Skills and MCP tools used

  • Skills: none
  • MCP tools: none

Comment on lines +1243 to +1246
if not self._ingestion_hook and otel_trace.get_current_span().get_span_context().is_valid:
if root is None or (root.first_operation is not None and root.first_operation.completed):
self._logger.warning("start_trace() skipped because the active trace has no open SDK-owned root span.")
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 major (bug): This early return silently breaks the old manual-logging pattern whenever any OTel span is active. Examples are an auto-instrumented server span or a W3C parent that TracingMiddleware extracted.

Failure scenario:

  1. A caller runs start_trace(...), then add_llm_span(...), then conclude(). The README example at README.md:272-283 shows this pattern.
  2. start_trace() logs a warning and returns None. It opens no envelope.
  3. add_llm_span() has no current parent. _get_child_span_timestamp() raises (galileo_core traces_logger.py:166-168), or add_child_span_to_parent() raises (traces_logger.py:157-158).
  4. @warn_catch_exception(exceptions=(Exception,)) at logger.py:1517 catches the error, and the span is dropped.
  5. conclude() then fails with "No existing workflow to conclude" (logger.py:2131-2132).

Before this PR, add_trace() parented the envelope to the active context (logger.py:972-973), so this pattern exported correctly. The tests were changed to avoid the pattern instead of covering it:

  • tests/test_logger_distributed.py:198-204
  • tests/test_crewai_handler.py:823
  • tests/test_handler_context_completion.py:210-212
  • test_start_trace_does_not_declare_on_gateway_trace calls _start_trace_envelope before its leaf.

The new gateway example (trace_examples.py:189) also switches to add_single_llm_span_trace to avoid it. The same path affects a second logger instance that runs under another logger's open root. _active_otlp_steps() returns that foreign root, so the declaration lands there and the caller's own leaves are dropped.

The middleware docstring example (middleware/tracing.py:13) also logs this warning on every request that carries a traceparent.

Suggested fix: when no open SDK-owned root exists, still open an unmarked envelope through _start_trace_envelope() under the active context. Drop only the declaration, and say so in the warning. This keeps lifecycle compatibility, and the declaration still never reaches a non-SDK root. Add a regression test for start_trace() + add_llm_span() + conclude() under a remote parent.

🤖 Generated by the Astra agent

Comment on lines +1217 to +1219
for argument, value in (("created_at", created_at), ("duration_ns", duration_ns), ("external_id", external_id)):
if value is not None:
warnings.warn(f"start_trace() {argument} is deprecated and ignored.", DeprecationWarning, stacklevel=4)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 major (bug): For hook-backed loggers, created_at, duration_ns and external_id are now dropped. Before this PR they reached the ingestion payload, as origin/main start_trace() shows by passing them to add_trace(). The envelope is not exported on the OTLP path, so ignoring them there costs nothing. For an ingestion_hook, the hook receives the Trace model, and these fields are lost silently.

The test updates in tests/test_logger_batch.py:182,187,346,350 confirm the payload change. ARCHITECTURE.md:89 also contradicts the code: "Hook-backed loggers retain the existing envelope lifecycle and payload".

A deprecation should warn and keep the old behaviour for at least one release. Suggested fix: on the hook path, keep forwarding the three values to _start_trace_envelope(). Add external_id back to that private helper. Keep the DeprecationWarning. Ignore the values only when not self._ingestion_hook.

🤖 Generated by the Astra agent

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

ingestion hook itself is being deprecated, so I wont really fix this for ingestion hook

Comment on lines +691 to +693
operation = trace_ids.first_operation
if trace_ids.trace_attributes and operation is not None and operation is not ids:
return operation.span_context

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 major (design): For a declared envelope, every later sibling is exported as a child of the first operation, even after that operation ended. The tests assert this fabricated topology:

  • tests/test_logger_otel_egress.py:130: a workflow becomes a child of an earlier LLM leaf.
  • tests/test_logger_otel_egress.py:718-720: an LLM span becomes a child of a tool or retriever leaf.
  • The class docstring flow start_trace(); add_retriever_span(); add_llm_span() puts the LLM call under the retriever.

Consequences:

  • Trace UIs show causal nesting that never happened, with children outside the parent's time window.
  • Any backend logic that derives trace I/O from the root span now sees only the first operation's I/O.
  • Topology depends on whether the user called public start_trace(). Integration envelopes (_start_trace_envelope) still export sibling roots, so the same call sequence produces different trees.

AGENTS.md requires parent changes to be justified across all telemetry paths. Alternatives:

  1. Keep siblings as roots and attach the declaration to every top-level operation. Ingestion can take the earliest root.
  2. Keep siblings as roots, put the declaration on the first one only, and let ingestion find it by trace ID.

Please confirm which shape the Go ingestion expects before you lock in the reparenting.

🤖 Generated by the Astra agent

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

There is also a scoring regression when the first operation is an LLM span. This SDK test puts a later workflow and its nested LLM call under the first LLM span. The backend treats LLM spans as leaves and excludes their descendants from the scoring tree. Otherwise eligible descendants can therefore receive not_applicable (EMS 2033) and contribute no scores to roll-ups. Please preserve the sibling relationship when the first operation is a leaf.

Comment on lines +2137 to +2140
warnings.warn(
f"conclude() {argument} is deprecated for OTLP traces. Set it on the operation span.",
DeprecationWarning,
stacklevel=5,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 minor (bug): stacklevel=5 points at the nop_sync wrapper, not at the user's conclude() call. The call chain is _conclude → warn_catch_exception.inner → conclude → warn_catch_exception.inner → nop_sync.decorated → user. Python's default filter shows DeprecationWarning only when it is attributed to __main__. This warning is attributed to splunk_ao/utils/decorators/telemetry_toggle.py, so script users never see it.

I confirmed the frame count with a standalone script that reproduces the same decorator stack. stacklevel=5 reported the wrapper line, and start_trace's stacklevel=4 reported the caller correctly. The tests use pytest.warns (tests/test_logger_otel_egress.py:153), which captures the warning from any location, so they do not catch this. Use stacklevel=6, or compute the level once in conclude() and pass it down.

Suggested change
warnings.warn(
f"conclude() {argument} is deprecated for OTLP traces. Set it on the operation span.",
DeprecationWarning,
stacklevel=5,
stacklevel=6,

🤖 Generated by the Astra agent

Comment on lines +832 to +833
metadata=span_params.get("metadata"),
tags=span_params.get("tags"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 minor (question): The decorator now also copies span metadata and tags onto the internal envelope. On the OTLP path this has no effect because the envelope is not exported. For hook-backed loggers, the Trace payload now gets user_metadata and tags that it did not have before. CHANGELOG.md:26 describes the fix only for "operation spans". Is the trace-level copy intended? If not, pass metadata and tags only to add_workflow_span/add_agent_span.

🤖 Generated by the Astra agent

@opikalova opikalova left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

One contract question about declaring ground truth on an already-open SDK trace.

dataset_metadata=dataset_metadata,
)
if root is not None:
root.trace_attributes = attributes

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

question (non-blocking): Should start_trace(dataset_output=...) inside an already-open SDK root also supply ground truth to spans created after the call? This branch stores the value in the trace declaration. The path that opens a new envelope also passes it down as splunk_ao.dataset.output. With the already-open root, a span-level evaluator that requires ground truth can still see no expected output even though the trace has it. If that split is intentional, could the README state that late declarations set ground truth only on the trace?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants