Skip to content

refactor(contrib): migrate database integrations to events API - #21859

Merged
gh-worker-dd-mergequeue-cf854d[bot] merged 18 commits into
mainfrom
quinna/db-events-migration
Dec 1, 2026
Merged

gh-worker-dd-mergequeue-cf854d[bot] merged 18 commits into
mainfrom
quinna/db-events-migration

Conversation

@quinna-h

@quinna-h quinna-h commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Description

Migrate shared sync/async DB-API wrappers, asyncpg connection/query instrumentation, and aiomysql queries to typed database events and the shared tracing lifecycle.

  • DatabaseOperationEvent extends TracingEvent; DatabaseTracingSubscriber extends TracingSubscriber.
  • Carry connection tags as a dictionary and apply collected result metadata when the operation ends.
  • Keep query preparation separate: DBM owns propagation policy and argument rewriting.
  • Move Snowflake query IDs into the result-metadata hook and remove the old private span-taking hook and compatibility bridge.
  • Collect cursor metadata on a best-effort basis, preserving driver return values, original errors, and cancellation.

Original query resources, parent relationships, measured flags, security checks, and DBM exclusions for fetches, stored procedures, and prepared statements are preserved.

Customer impact

This updates an unreleased internal refactor. Supported driver operations retain their behavior; span metadata adopts the shared tracing conventions described below.

Testing

  • 349 tests passed across sync/async DB-API, SQLite, DBM policy, asyncpg, aiomysql, and Snowflake; 12 Snowflake skips. Python 3.9 and 3.12 were exercised.
  • Regression coverage includes metadata collection after success, driver errors and cancellation; result tags; transactions; context isolation; and patch/unpatch behavior.
  • A real SQLite trace capture verified original SQL resources and errors, parent restoration, expected span count, and a DBM traceparent matching the actual query span.
  • Formatting, typing, scripts/lint checks, and dependency/import-cycle comparisons passed.

Risks

A cursor metadata failure can omit row counts or query IDs. It does not change the driver's query result or replace its exception.

Additional Notes

The shared lifecycle adds standard _dd.svc_src service-source attribution and uses the shared component/span-kind tagging order instead of per-driver event flags. The asyncpg snapshots reflect the intended attribution change.

The internal _set_post_execute_tags(span) hook is removed. Result metadata uses _get_post_execute_result(context).

@cit-pr-commenter-54b7da

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

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.

.agents/skills/apm-integrations/references/reference-integrations.md    @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/_trace/_registration.py                                         @DataDog/apm-sdk-capabilities
ddtrace/_trace/events.py                                                @DataDog/apm-sdk-capabilities
ddtrace/_trace/subscribers/database.py                                  @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/contrib/_events/dbapi.py                                        @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/contrib/dbapi.py                                                @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/contrib/dbapi_async.py                                          @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/contrib/internal/aiomysql/patch.py                              @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/contrib/internal/asyncpg/patch.py                               @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/contrib/internal/psycopg/cursor.py                              @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/contrib/internal/snowflake/patch.py                             @DataDog/apm-python-guild @DataDog/apm-idm-python
ddtrace/propagation/_database_monitoring.py                             @DataDog/apm-sdk-capabilities
docs/contributing-integrations.rst                                      @DataDog/apm-python-guild
tests/contrib/aiomysql/test_aiomysql.py                                 @DataDog/apm-python-guild @DataDog/apm-idm-python
tests/contrib/asyncpg/test_asyncpg.py                                   @DataDog/apm-python-guild @DataDog/apm-idm-python
tests/contrib/dbapi/test_dbapi.py                                       @DataDog/apm-python-guild @DataDog/apm-idm-python
tests/contrib/dbapi_async/test_dbapi_async.py                           @DataDog/apm-python-guild @DataDog/apm-idm-python
tests/contrib/snowflake/test_snowflake.py                               @DataDog/apm-python-guild @DataDog/apm-idm-python
tests/snapshots/tests.contrib.asyncpg.test_asyncpg.test_configure_service_name_env_v0.json  @DataDog/apm-core-python @DataDog/apm-python
tests/snapshots/tests.contrib.asyncpg.test_asyncpg.test_configure_service_name_env_v1.json  @DataDog/apm-core-python @DataDog/apm-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 17, 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=99)
ddtrace.llmobs._integrations.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=97)
ddtrace.llmobs._integrations.base -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=97)
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

@pr-commenter

pr-commenter Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-25 20:04:53

Comparing candidate commit f7fdaf4 in PR branch quinna/db-events-migration with baseline commit d3e9a7e in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 600 metrics, 10 unstable metrics, 1 flaky benchmarks without significant changes.

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 ----------------------------------'

Unstable benchmarks

These benchmarks have a confidence interval too wide to call a change; treat them as noise rather than signal.

scenario:coreapiscenario-context_with_data_listeners

  • unstable execution_time [-637.468ns; +832.229ns] or [-6.028%; +7.870%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-37.614ns; +40.538ns] or [-5.906%; +6.366%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1705.070ns; +2097.231ns] or [-8.629%; +10.613%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-2284.880ns; +1395.945ns] or [-11.613%; +7.095%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-376.450ns; +381.424ns] or [-8.869%; +8.986%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-201.634ns; +252.758ns] or [-7.650%; +9.590%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-86.946ns; +94.197ns] or [-6.387%; +6.919%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-5378.597ns; +3960.924ns] or [-10.953%; +8.066%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-1062.905ns; +839.844ns] or [-10.271%; +8.115%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-58.862µs; +53.938µs] or [-10.025%; +9.187%]

Known flaky benchmarks

These benchmarks are marked as flaky and will not trigger a failure. Modify FLAKY_BENCHMARKS_REGEX to control which benchmarks are marked as flaky.

Known flaky benchmarks without significant changes:

  • scenario:packagespackageforrootmodulemapping-cache_off

@datadog-prod-us1-6

datadog-prod-us1-6 Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

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

Base automatically changed from codex/explicit-subscriber-registration to main November 17, 2026 21:42
@quinna-h quinna-h added the changelog/no-changelog A changelog entry is not required for this PR. label Nov 19, 2026
Publish optional query preparation and context-associated result metadata events. Keep propagation policy in its listener and preserve legacy cursor hooks through the tracing subscriber.
@quinna-h
quinna-h marked this pull request as ready for review November 19, 2026 21:32
@quinna-h
quinna-h requested review from a team as code owners November 19, 2026 21:32
@quinna-h
quinna-h requested review from wconti27, yaronguro-datadog and zacharycmontoya and removed request for a team November 19, 2026 21:32
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 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-25T19:42:13.185884Z f7fdaf4 New commits
ℹ️ 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.

@datadog-prod-us1-6 datadog-prod-us1-6 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.

Bits Code Review: PASS

More details

Runtime validation covered the shared synchronous and asynchronous DB-API wrappers; database-backed driver behavior was assessed statically only.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit f5b74c4

@zacharycmontoya zacharycmontoya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

From the SDK capabilities side, LGTM

Restore legacy propagator arguments and compose metadata hooks with existing span hooks. Preserve driver exceptions and cancellation when result collection fails.

@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: 52de33a813

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread ddtrace/_trace/subscribers/database.py Resolved

@datadog-prod-us1-6 datadog-prod-us1-6 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.

Bits Code Review: WARN

The PR moves database tracing to typed events and includes cursor compatibility and driver-error preservation fixes. One architectural concern remains: the new tracing subscriber imports contrib despite LA-1; the supplied range received static review only.

Open Bits AI session

🤖 Bits Code Review · Commit 52de33a

Comment thread ddtrace/_trace/subscribers/database.py Resolved
Comment thread ddtrace/_trace/subscribers/database.py Resolved
Comment thread ddtrace/contrib/_events/dbapi.py Resolved
Comment thread ddtrace/contrib/_events/dbapi.py Resolved
Comment thread ddtrace/contrib/_events/dbapi.py Resolved

@dubloom dubloom 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.

Additional comments from Claude

Comment thread ddtrace/contrib/dbapi.py Resolved
Comment thread ddtrace/contrib/dbapi.py Resolved
Comment thread ddtrace/contrib/dbapi.py Resolved
Comment thread docs/contributing-integrations.rst Resolved
@quinna-h
quinna-h requested review from a team as code owners November 24, 2026 23:15
@quinna-h
quinna-h requested review from juanjux and removed request for a team November 24, 2026 23:15

@datadog-prod-us1-6 datadog-prod-us1-6 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.

Bits Code Review: FAIL

Legacy cursor hooks can apply chained service mappings twice, assigning database spans to the wrong service even when the hook leaves the service unchanged.

Open Bits AI session

🤖 Bits Code Review · Commit 603bc79

Comment thread ddtrace/_trace/subscribers/database.py Resolved

@datadog-prod-us1-6 datadog-prod-us1-6 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.

Bits Code Review: PASS

More details

The PR centralizes DB-API, asyncpg, and aiomysql tracing and DBM preparation through typed database events. Removing the legacy hook bridge fixes the earlier double service-mapping defect; metadata failures now preserve driver outcomes, and no review findings remain open.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 4125af8

@quinna-h
quinna-h requested a review from dubloom November 25, 2026 19:20
@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot merged commit e4e011c into main Dec 1, 2026
1021 of 1023 checks passed
@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot deleted the quinna/db-events-migration branch December 1, 2026 16:23
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Dec 3, 2026
## Description

Follow-up to #21859. Database events carried two tag dicts, `connection_tags` and `tags`, and the database subscriber re-applied both in `on_started` and again in `on_ended`. Every DB-API query wrote its connection tags two times and its per-call tags three times.

This change folds them into the single `tags` field that `TracingEvent` already applies when the span starts:

- **dbapi / aiomysql**: pass the connection's tag dict directly, or `{**db_tags, **extra_tags}` when the call has extra tags, which still take precedence.
- **asyncpg connect**: host, port, user and database are only known after connecting, so they are published through `DatabaseResultEvent.tags`, which `on_ended` already applies.
- **Subscriber**: `on_started` is removed; `on_ended` only applies the result.
- **`DatabaseOperationEvent`**: drops its redeclarations of `component`, `integration_config`, `resource` and `span_type` in favour of the `TracingEvent` fields, and sets `span_type = SpanTypes.SQL` on the class. `operation_name` stays redeclared because `TracingEvent` declares it with `init=False`.
- **Port type**: `Span.set_tag` converts `network.destination.port` to `int`, but the shared lifecycle writes tags with `_set_attribute`. `_normalize_db_tags` converts the port once when the tags are captured, so the port keeps its current type.

## Customer impact

DB-API `*.connection.commit` and `*.connection.rollback` spans now have span type `sql` instead of none, consistent with query spans and with dd-trace-go. Tags are unchanged.

## Testing

- Updated the dbapi and dbapi_async unit tests and the mariadb and snowflake commit/rollback snapshots for the `sql` span type.
- Relying on CI for the dbapi, sqlite3, asyncpg, aiomysql, pymysql, mysqlclient, psycopg and mariadb suites.

## Risks

- Commit and rollback spans changing type could affect span-type-based queries.
- Connection tags now skip `Span.set_tag`'s special-key handling. Only the port conversion applied to them, and it is kept by `_normalize_db_tags`.

## Additional Notes

Benchmark not run yet; the change removes per-query tag writes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


Co-authored-by: louis.tricot <louis.tricot@datadoghq.com>
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.

4 participants