Skip to content

fix(tracing): isolate Celery contexts and guard unsampled tool spans - #45049

Merged
zyssyz123 merged 2 commits into
mainfrom
fix/crd720-tracing-context
Oct 29, 2026
Merged

zyssyz123 merged 2 commits into
mainfrom
fix/crd720-tracing-context

Conversation

@zyssyz123

Copy link
Copy Markdown
Contributor

Summary

Concurrent executions of the same Celery Task could overwrite the SQL commenter's shared context token, causing cross-Context detach errors and incomplete context restoration. Store the token on the invocation-local request and register SQL cleanup before OTel cleanup, so the contexts unwind in reverse activation order.

Handled Dify core-tool errors could also abort an Agent when Logfire wrapped an unsampled NonRecordingSpan as ReadableSpan. Check is_recording() before reading attributes, retaining the existing native-tool ownership checks and recoverable error observations.

Related to CRD-720.

If Celery was already instrumented externally, preserve its providers and spans and skip the additional SQL-commenter hooks; their required cleanup order cannot be established safely after registration. No dependency, lockfile, or deployment configuration changes are included.

Validation

  • API: 81 related tests passed, including 24 SQL-commenter tests using real Celery Task.apply, concurrent invocations, both completion orders, sampled/unsampled spans, failure, retry, cooperative stop, and pre-existing instrumentation.
  • Agent: 97 related tests passed. The new real Logfire/Pydantic AI matrix reproduced 3 failures and 9 passing controls before the fix; all 12 pass afterward.
  • make lint, targeted make type-check, and package Ruff/format/Pyrefly checks passed.
  • Dev deployed-container probes in isolated processes: Agent 3 failures → 12/12 passing; real gevent/Celery/OTel signal probe 0/16 passing with 8 detach errors → 16/16 passing with no detach errors and restored contexts. These probes use synthetic responses and do not call live models or business APIs.
  • Dev UI: handled tool-error observation, two overlapping successful Workflow runs, stop while the code node was running, and a successful subsequent run. Target exception counts remained zero in the patched API, both workers, and Agent Backend logs during validation. The initial five-second synthetic sleep hit the sandbox timeout; the successful concurrency cases used a three-second sleep.

The production detach logs do not include caller frames, so this fixes the reproduced SQL-commenter defect without claiming that every historical detach log had that origin. Production rollout and impact measurement remain separate follow-up work.

Checklist

  • Associated issue and regression evidence are linked above.
  • Tests cover the actual Celery and Logfire boundaries affected by the change.
  • Lint and targeted type checks passed.
  • Verified on dev before opening this PR.
  • Documentation update required (internal instrumentation fix; no user-facing configuration change).

From Codex

@github-actions github-actions Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Oct 29, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 80.31% 80.31% +0.00%
Strict coverage 80.00% 80.00% +0.00%
Typed symbols 77,394 77,408 +14
Untyped symbols 19,052 19,052 0
Modules 3990 3990 0

@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.73684% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 89.56%. Comparing base (290590c) to head (7774df3).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
api/extensions/otel/runtime.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #45049   +/-   ##
=======================================
  Coverage   89.55%   89.56%           
=======================================
  Files        6013     6013           
  Lines      377254   377253    -1     
  Branches    76379    76379           
=======================================
+ Hits       337860   337873   +13     
+ Misses      33401    33389   -12     
+ Partials     5993     5991    -2     
Flag Coverage Δ
api 89.42% <94.73%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zyssyz123
zyssyz123 enabled auto-merge October 29, 2026 08:32

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

Reviewed all five changed files and the surrounding worker/tool instrumentation paths. No blocking findings.

The SQL-commenter token is now invocation-local, and signal registration correctly unwinds the SQL context before the OTel task scope. Existing external Celery instrumentation is preserved. The early is_recording() guard avoids accessing attributes on Logfire-wrapped NonRecordingSpan objects while retaining native-tool ownership checks.

Verified CI for this head and its merge with main: API unit shards report 24,360 passed (4 skipped); Agent tests report 1,046 passed (13 skipped). API integration/controller tests, Python style, Pyrefly, CodeQL, and image builds also passed. Reviewed the real Celery concurrency and Logfire/Pydantic AI regression tests; no local test rerun was performed.

Production rollout and impact verification remain separate from this code review.

@zyssyz123
zyssyz123 added this pull request to the merge queue Oct 29, 2026
Merged via the queue into main with commit a141540 Oct 29, 2026
58 checks passed
@zyssyz123
zyssyz123 deleted the fix/crd720-tracing-context branch October 29, 2026 08:44
zyssyz123 added a commit that referenced this pull request Oct 29, 2026
MRZHUH pushed a commit that referenced this pull request Oct 29, 2026
@laipz8200 laipz8200 mentioned this pull request Nov 3, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants