Skip to content

Suppress external instrumentations for fetch calls from ApiClient #1788

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

erin-allison
Copy link
Contributor

@erin-allison erin-allison commented Mar 12, 2025

This should address an issue that has come up a few times in Discord where @opentelemetry/instrumentation-undici causes nested traces to not render properly in the dashboard.

✅ Checklist

  • I have followed every step in the contributing guide
  • The PR title follows the convention.
  • I ran and tested the code works

Testing

Implemented the change as a pnpm patch and tested a handful of ApiClient calls with it.


Changelog

  • Add @opentelemetry/core as a dependency to @trigger.dev/core
  • Update zodFetch implementation to suppress further tracing once inside of traceZodFetch

Screenshots

Before:
image

After:
image

💯

Summary by CodeRabbit

  • New Features

    • Enhanced network request handling to streamline external monitoring.
  • Chores

    • Updated dependency management to support improved telemetry integration.

Copy link

changeset-bot bot commented Mar 12, 2025

🦋 Changeset detected

Latest commit: 8e8f670

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 13 packages
Name Type
@trigger.dev/core Patch
@trigger.dev/build Patch
trigger.dev Patch
@trigger.dev/python Patch
@trigger.dev/sdk Patch
@internal/redis-worker Patch
@internal/zod-worker Patch
@trigger.dev/react-hooks Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch
references-nextjs-realtime Patch
@internal/testcontainers Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Mar 12, 2025

Walkthrough

This pull request documents a patch update for the "@trigger.dev/core" package by adding an entry in the changeset file, introduces a new dependency ("@opentelemetry/core": "^1.30.1") in the package.json, and updates the ApiClient logic to suppress external instrumentation for fetch calls. The changes wrap the fetch call in a context using suppressTracing, while error handling and retry mechanisms remain unchanged.

Changes

Files Change Summary
.changeset/red-wasps-cover.md, packages/core/package.json Added patch update entry and introduced the dependency "@opentelemetry/core": "^1.30.1" in package.json.
packages/core/src/v3/apiClient/core.ts Added a new import for suppressTracing and modified the _doZodFetchWithRetries function to wrap its fetch call with a suppressed tracing context.

Sequence Diagram(s)

sequenceDiagram
    participant C as Caller
    participant A as ApiClient
    participant S as SuppressTracing Context
    participant R as Remote Server

    C->>A: Initiate fetch request
    A->>S: Enter suppressed tracing context
    S->>R: Execute fetch call
    R-->>S: Return response
    S-->>A: Pass fetch result
    A-->>C: Return data
Loading

Possibly related PRs

Poem

I’m a rabbit with a hop so spry,
In code I nibble as the bytes fly high.
Suppressing traces, quiet as night,
With carrots of code shining bright.
Update complete—I bounce with delight!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

Scope: all 2 workspace projects
 ERR_PNPM_OPTIONAL_DEPS_REQUIRE_PROD_DEPS  Optional dependencies cannot be installed without production dependencies

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3a04759 and 8e8f670.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • .changeset/red-wasps-cover.md (1 hunks)
  • packages/core/package.json (1 hunks)
  • packages/core/src/v3/apiClient/core.ts (2 hunks)
🔇 Additional comments (4)
.changeset/red-wasps-cover.md (1)

1-6: The changeset correctly documents the patch update.

This changeset appropriately describes the purpose of the changes as suppressing external instrumentation for fetch calls from ApiClient, which aligns with the PR objective to fix the issue with nested traces rendering improperly.

packages/core/package.json (1)

190-190: New dependency correctly added.

Adding the @opentelemetry/core dependency is necessary for the suppressTracing functionality you've implemented in the ApiClient to fix the nested traces issue.

packages/core/src/v3/apiClient/core.ts (2)

8-8: Import added for suppressTracing functionality.

The import of suppressTracing from @opentelemetry/core is correctly added to support the fix for nested traces.


220-222:

✅ Verification successful

Good implementation of tracing suppression.

This change effectively wraps the fetch call with a context that suppresses tracing, which should prevent the @opentelemetry/instrumentation-undici package from creating nested traces that render improperly in the dashboard. The implementation maintains all existing error handling and retry mechanisms.

You might want to verify this resolves the issue by checking the dashboard visualization of traces.


🌐 Web query:

How does OpenTelemetry's suppressTracing work?

💡 Result:

OpenTelemetry's suppressTracing mechanism prevents specific spans from being generated or exported through multiple configurable layers. Here's how it works:

Span Creation Control

  1. Sampler Configuration
    OpenTelemetry uses samplers to decide whether to record/export spans:

    • AlwaysOffSampler drops all spans for a service[4][11]
    • Custom samplers can filter spans based on attributes (e.g., healthcheck endpoints)[4][6]
  2. Span Recording Flags
    Each span has:

    • IsRecording: When false, discards all span data[4][5]
    • Sampled flag: Exporters only receive spans with this flag set[4][11]
    if not span.is_recording():
        return  # Skip expensive data collection

Endpoint Exclusion

For web frameworks like Quarkus:

# application.properties
quarkus.otel.traces.suppress-application-uris=/health,/ping

Disables tracing for specified URI patterns[8]

Library-Level Suppression

Disable instrumentation for specific libraries via:

OTEL_INSTRUMENTATION_HTTP_ENABLED=false  # Disable HTTP auto-instrumentation
OTEL_INSTRUMENTATION_JDBC_ENABLED=false  # Disable JDBC instrumentation

This reduces overhead by excluding non-critical components[10]

Programmatic Control

  1. Contextual Suppression
    Temporarily disable tracing within code blocks:

    suppressTracing(() => {
      fetch('https://healthcheck.example.com'); // No spans created here
    })[14][16]
  2. Dynamic SDK Control
    Advanced implementations can:

    • Dispose/recreate TracerProvider with new configs[6]
    • Use custom ID generators to filter spans[8]
    • Modify propagators to restrict trace context[8]

Healthcheck Optimization

A common suppression pattern for Kubernetes healthchecks:

# Sample suppression config
otel.traces.sampler = parentbased_ratio
otel.traces.sampler.arg = 0.01  # Sample 1% of healthcheck traffic
otel.instrumentation.http.health.enabled = false[3][8]

Key Implementation Notes

  • Performance: Suppressed spans have minimal overhead (context checks only)[10][16]
  • Propagation: Trace context continues even when spans are suppressed[13]
  • Hierarchy: Child spans inherit suppression from parents[10]
  • Backend Impact: Suppressed spans never reach collectors/exporters[4][6]

For legacy systems, some vendors provide bridge configurations to map suppression rules from older APM systems to OpenTelemetry[9][16].

Citations:


Tracing suppression implementation verified and approved.

The use of context.with(suppressTracing(context.active()), () => fetch(url, requestInitWithCache(requestInit))) is correctly wrapping the fetch call, ensuring that unwanted spans are suppressed according to OpenTelemetry’s mechanism. This approach aligns with the documented behavior—where a suppression context prevents nested spans (such as those generated by @opentelemetry/instrumentation-undici) from appearing—and maintains the existing error handling and retry logic.

Please verify on the dashboard that the undesired nested traces are no longer present.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@erin-allison erin-allison force-pushed the fix/suppress-external-fetch-instrumentation branch from b90251d to 8e8f670 Compare March 12, 2025 14:28
@erin-allison erin-allison marked this pull request as ready for review March 12, 2025 18:31
@erin-allison erin-allison changed the title [WIP] Suppress external instrumentations for fetch calls from ApiClient Suppress external instrumentations for fetch calls from ApiClient Mar 12, 2025
@matt-aitken
Copy link
Member

@erin-allison this is amazing, I had no idea this was possible with OTEL.

The packages won't be published until Run Engine 2 is out but this will go live with that.

@matt-aitken matt-aitken merged commit 2a51ae8 into triggerdotdev:main Mar 16, 2025
6 of 8 checks passed
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