Skip to content

chore(llmobs): dispatch stream.created from the Anthropic and OpenAI SDK streams - #22128

Open
avara1986 wants to merge 3 commits into
mainfrom
alberto.vara/sdk-stream-created-hook
Open

avara1986 wants to merge 3 commits into
mainfrom
alberto.vara/sdk-stream-created-hook

Conversation

@avara1986

@avara1986 avara1986 commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Description

Jira: APPSEC-71908

The Anthropic and OpenAI SDKs build every streamed response as a Stream or AsyncStream. Every consumer reads its events from that object's event iterator (_iterator): the caller of create(stream=True), the SDK message accumulators (MessageStream, ChatCompletionStream, with their snapshots and final messages), the tool runners, and the streams returned by .parse() of with_raw_response and with_streaming_response.

This PR adds a product-neutral core event on that event source, so that a product can see or replace the events before any SDK consumer reads them:

  • ddtrace/contrib/internal/_sdk_streams.py: traced_stream_init wraps Stream.__init__ / AsyncStream.__init__ and dispatches anthropic.stream.created or openai.stream.created with a StreamEvents carrier. The carrier holds the httpx response of the stream (whose request is the one the SDK sent), the event iterator, and whether the stream is async. The contrib installs the iterator that a listener leaves on the carrier.
    • Older SDKs set _iterator in the constructor. Newer ones make it on first use as a cached property, from a copy of the stream (anthropic 2.x). For those, the carrier holds a lazy iterator that makes the SDK one on the first read, after every subclass constructor has run. For example, BedrockStream sets its AWS decoder after super().__init__(). The lazy iterator refers to the stream through a weak reference, so the replaced iterator does not keep the stream alive.
    • When no product listens, the hook only calls core.has_listeners.
  • The Anthropic and OpenAI patch() functions wrap and unwrap the two constructors.

Nothing listens to these events yet. #22020 uses them to move AI Guard's stream evaluation below the SDK accumulators.

Testing

  • tests/contrib/anthropic/test_anthropic_stream_hook.py, with a mocked transport:
    • a listener that replaces the events is seen by create(stream=True) and by the sync and async messages.stream() accumulators;
    • streams are unchanged without a listener;
    • a Stream subclass that sets attributes after super().__init__() keeps them.
  • tests/contrib/openai/test_openai_stream_hook.py: the same for sync and async Chat Completions streams and with_streaming_response(...).parse(), plus streams unchanged without a listener.
  • The patch tests check that the two constructors are wrapped once and unwrapped.
  • Local runs:
    • anthropic 0.28, <1, 1.x and 2.x;
    • openai 1.0.0, <2, 3.26 and latest.
  • ddtrace/contrib/internal/_sdk_streams.py is added to the llmobs suitespec component, so changes to it select the Anthropic and OpenAI suites.

Risks

  • The hook relies on the SDK _iterator attribute of Stream / AsyncStream: an instance attribute in older SDKs, and a cached property in newer ones. It skips a stream that has neither.
  • Every Anthropic and OpenAI stream now goes through the wrapped constructor; with no listener, the cost is one core.has_listeners lookup per stream.

Additional Notes

  • No release note: nothing listens to the new events in this PR, so there is no customer-visible change.
  • Benchmarks: no scenario in benchmarks/ covers the Anthropic or OpenAI SDKs, so this path has no benchmark coverage. Measured directly instead, with timeit on Stream(...) construction and no listener: about +0.6-0.75 µs per streamed response (anthropic 2.8.0 on Python 3.15: ~450 ns to ~1040-1200 ns; anthropic 0.28.0 on Python 3.9: ~750 ns to ~1300-1470 ns). The cost is once per stream, not per chunk.

🤖 Generated with Claude Code

…SDK streams

Wrap Stream.__init__ and AsyncStream.__init__ of both SDKs and dispatch
anthropic.stream.created / openai.stream.created with the stream response
and its event iterator, so a product can see or replace the events before
any SDK consumer reads them. Newer SDKs make the iterator on first use;
the hook then hands listeners a lazy iterator, so a subclass constructor
still runs first.

APPSEC-71908

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@avara1986 avara1986 added the changelog/no-changelog A changelog entry is not required for this PR. label Nov 26, 2026
@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against main using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

ddtrace/contrib/internal/_sdk_streams.py                                @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/contrib/internal/anthropic/patch.py                             @DataDog/ml-observability
ddtrace/contrib/internal/openai/patch.py                                @DataDog/ml-observability @DataDog/asm-python
tests/contrib/anthropic/test_anthropic_patch.py                         @DataDog/ml-observability
tests/contrib/anthropic/test_anthropic_stream_hook.py                   @DataDog/ml-observability
tests/contrib/openai/test_openai_patch.py                               @DataDog/ml-observability
tests/contrib/openai/test_openai_stream_hook.py                         @DataDog/ml-observability
tests/llmobs/suitespec.yml                                              @DataDog/ml-observability

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

There are 22 dependency direction violations that already exist on the base branch and have not been changed by this PR.

Show existing violations (showing 5 of 22 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=103)
ddtrace.llmobs._integrations.base -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.llmobs._integrations.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.internal.span_bus -×-> ddtrace._trace.span  (internal-core -> product:tracing, score=35)
ddtrace.llmobs._llmobs -×-> ddtrace._trace.span  (product:llmobs -> product:tracing, score=33)

To see all violations, download the layers-base.json and layers-pr.json artifacts from this CI job and run:

uv run --script scripts/import-analysis/layers.py compare layers-base.json layers-pr.json

@datadog-datadog-prod-us1-2

datadog-datadog-prod-us1-2 Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 0f418f8 | Docs | View more details | Give us feedback!

@pr-commenter

pr-commenter Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-26 16:23:31

Comparing candidate commit 0f418f8 in PR branch alberto.vara/sdk-stream-created-hook with baseline commit 386a387 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 40 metrics, 0 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

avara1986 and others added 2 commits November 26, 2026 16:48
APPSEC-71908

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eam alive

APPSEC-71908

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@avara1986

avara1986 commented Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

Notes on the review of this PR:

  • Lifetime of the lazy iterator (P3): added in 0f418f8. test_replaced_iterator_does_not_keep_the_stream_alive runs sync and async. It keeps the replacement iterator, drops the stream, collects, and checks that the stream was freed and that a later read raises. It is skipped on SDKs that set the iterator in __init__. With the weak reference swapped for a strong one, both cases fail.
  • Carrying the request context with the stream: deferred on purpose. fix(aiguard): evaluate streamed responses at the SDK event source #22020 evaluates a stream from the request that the SDK sent. The one loss is client-managed MCP identity on Anthropic streamed answers, which is tracked with the other streaming gaps in APPSEC-72050, with strict xfail tests in fix(aiguard): evaluate streamed responses at the SDK event source #22020.
  • SDK compatibility: checked against the sources of anthropic 0.28, 0.84, 0.125 and 2.8 (including the 2.x cached_property iterator and BedrockStream setting its decoder after super().__init__()), and openai 1.3 to 3.51. The hook and patch tests ran on anthropic 0.28, <1, 1.x and 2.8 and on openai 1.0.0, <2, 3.26 and latest, including the subclass test.

@avara1986
avara1986 marked this pull request as ready for review November 26, 2026 16:35
@avara1986
avara1986 requested review from a team as code owners November 26, 2026 16:35
@avara1986
avara1986 requested review from dubloom and florentinl and removed request for a team November 26, 2026 16:35
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T16:39:33.645284Z 0f418f8 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0f418f8e26

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bits Code Review: PASS

More details

Runtime compatibility across Anthropic and OpenAI SDK versions remains unverified because SDK dependencies were unavailable and upstream source retrieval failed.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 0f418f8

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

Labels

changelog/no-changelog A changelog entry is not required for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant