Skip to content

[Serve][1/2] Add TracingConfig and wire through proxy and replica paths - #63273

Merged
abrarsheikh merged 7 commits into
ray-project:masterfrom
suppagoddo:tracing-config-prA-wiring
Aug 8, 2026
Merged

abrarsheikh merged 7 commits into
ray-project:masterfrom
suppagoddo:tracing-config-prA-wiring

Conversation

@suppagoddo

@suppagoddo suppagoddo commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Schema:

  • New TracingConfig pydantic model (schema.py) with enabled, exporter_import_path, sampling_ratio
  • Exported in ray.serve public API + API doc entry

setup_tracing API:

  • Accepts TracingConfig directly instead of raw kwargs
  • When tracing_config is provided: reads config from it
  • When tracing_config is None: falls back to env vars (backward compatible)
  • Tracing setup errors now propagate (fail fast) instead of being silently swallowed

Replica path:

  • Replica fetches TracingConfig from controller via get_tracing_config() and passes to setup_tracing

Proxy path:

  • ProxyActorInterface accepts tracing_config param (plumbed to setup_tracing)
  • Proxy currently receives None (env-var fallback, same as master). Full proxy wiring via ProxyStateManager deferred to PR 2.

Controller:

  • Stores global_tracing_config and exposes get_tracing_config() method

Decorator fix:

  • tracing_decorator_factory now checks is_tracing_enabled() at call-time instead of decoration-time, because TracingConfig arrives at runtime (after decorators are applied at import time)

Public API:

  • serve.start(tracing_config=...) parameter

Design

  • Global only: cluster-level, not per-app or per-deployment
  • Static: set once at startup, no hot-reload of existing actors
  • No proto changes: constructor arg through actor hierarchy
  • Backward compatible: env vars still work as defaults when tracing_config is None

What's deferred to PR 2

  • Proxy wiring through ProxyStateManager (proxy currently falls back to env vars)
  • Runtime propagation (push config updates to live actors)
  • HAProxy tracing support

Test plan

  • Unit tests for TracingConfig validation (test_schema.py)
  • Updated tracing e2e tests to use TracingConfig
  • Existing proxy/replica/deployment tests pass
  • No Replica class restructuring — existing class unchanged

@suppagoddo
suppagoddo requested a review from a team as a code owner May 11, 2026 17:51
@suppagoddo suppagoddo changed the title Tracing config pr a wiring [Serve][1/2] Add TracingConfig and wire through proxy and replica paths May 11, 2026

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces TracingConfig to enable OpenTelemetry tracing across Ray Serve components, including the controller, proxies, and replicas. It refactors the Replica class into an abstract base class and a concrete implementation to streamline tracing setup and request handling. Feedback identifies a parameter naming inconsistency in _on_request_cancelled that violates the Liskov Substitution Principle and a missing return type hint in _can_accept_request.

Comment thread python/ray/serve/_private/replica.py Outdated
Comment on lines +1993 to +2014
def _on_request_cancelled(
self, metadata: RequestMetadata, e: asyncio.CancelledError
):
"""Recursively cancel child requests.

This includes all requests that are pending assignment, and gRPC
requests that have already been assigned.
"""
# Cancel child requests pending assignment
requests_pending_assignment = (
ray.serve.context._get_requests_pending_assignment(
metadata.internal_request_id
)
)
for task in requests_pending_assignment.values():
task.cancel()

# Cancel child requests that have already been assigned.
# This is for gRPC requests and direct ingress requests.
in_flight_requests = _get_in_flight_requests(metadata.internal_request_id)
for replica_result in in_flight_requests.values():
replica_result.cancel()

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.

medium

The parameter name metadata in Replica._on_request_cancelled is inconsistent with the base class ReplicaBase._on_request_cancelled, which uses request_metadata. This can lead to issues if the method is called using keyword arguments and violates the Liskov Substitution Principle.

    def _on_request_cancelled(
        self, request_metadata: RequestMetadata, e: asyncio.CancelledError
    ):
        """Recursively cancel child requests.

        This includes all requests that are pending assignment, and gRPC
        requests that have already been assigned.
        """
        # Cancel child requests pending assignment
        requests_pending_assignment = (
            ray.serve.context._get_requests_pending_assignment(
                request_metadata.internal_request_id
            )
        )
        for task in requests_pending_assignment.values():
            task.cancel()

        # Cancel child requests that have already been assigned.
        # This is for gRPC requests and direct ingress requests.
        in_flight_requests = _get_in_flight_requests(request_metadata.internal_request_id)
        for replica_result in in_flight_requests.values():
            replica_result.cancel()

Comment thread python/ray/serve/_private/replica.py Outdated
if ray.util.pdb._is_ray_debugger_post_mortem_enabled():
ray.util.pdb._post_mortem()

def _can_accept_request(self, request_metadata: RequestMetadata):

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.

medium

The method _can_accept_request is missing a return type hint. It should return bool to be consistent with the base class ReplicaBase.

Suggested change
def _can_accept_request(self, request_metadata: RequestMetadata):
def _can_accept_request(self, request_metadata: RequestMetadata) -> bool:

Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/haproxy.py Resolved
@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch from e81c4c8 to 67af77c Compare May 11, 2026 19:26
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue docs An issue or change related to documentation observability Issues related to the Ray Dashboard, Logging, Metrics, Tracing, and/or Profiling community-contribution Contributed by the community labels May 11, 2026
@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch from 67af77c to cb4a579 Compare May 11, 2026 19:47
@abrarsheikh abrarsheikh added the go add ONLY when ready to merge, run all tests label May 11, 2026
@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch 3 times, most recently from 393b5aa to fe8e0b6 Compare May 12, 2026 00:18
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/proxy.py Outdated
Comment on lines 1678 to 1682

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.

i think we should start to fail fast here. User has already expressed intent to setup tracing, i think its better to ensure its setup or fail loudly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Got it, will mark this setup as failed then? Just curious won't it be too harsh to fail the setup.

Comment thread python/ray/serve/_private/proxy.py Outdated
Comment on lines 1671 to 1675
is_tracing_setup_successful = setup_tracing(
component_name="proxy", component_id=node_ip_address
component_name="proxy",
component_id=node_ip_address,
**get_tracing_kwargs(self._tracing_config),
)

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.

let's change the API of setup_tracing to accept the TracingConfig object directly instead of denormalizing it. The advantage is that when we need to add a new parameter to setup_tracing through TracingConfig, we dont have to make change to get_tracing_kwargs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ACK, will make this change here.

Comment thread python/ray/serve/_private/replica.py Outdated
Comment on lines +1168 to +1169
except AttributeError:
self._tracing_config = None

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.

when do we expect AttributeError

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This was to support rolling deployment when there is a version update [ Old version does not have get_tracing_config method ], but I think on a different thread we discussed, that a version upgrade will have new deployment, so new controller. So it is not neccasary and I will remove it.

Comment thread python/ray/serve/_private/replica.py Outdated
Comment on lines 1171 to 1184
@@ -1169,10 +1183,6 @@ def __init__(
"The replica will continue running, but traces will not be exported."
)

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.

same comment here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ACK, will fast here as well.

Comment thread python/ray/serve/_private/replica.py Outdated
@@ -1046,7 +1048,7 @@ async def _add_autoscaling_metrics_point_async(self) -> None:
StatusCodeCallback = Callable[[str], None]


class Replica:
class ReplicaBase(ABC):

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.

Is the refactor to Replica necessary for adding tracing? If not, that's better done in a follow-up PR. The context Replica is probably the most critical module in the serve replica path, and I am reluctant to make sweeping changes here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ACK, that's a valid concern! I will do a follow up PR.

Comment on lines +15 to +16
if TYPE_CHECKING:
from ray.serve.schema import TracingConfig

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.

i believe this was introduced to avoid circular dependency, please revert this change and figure out how we can avoid the circular dependency issue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes during the type check phase, will move it to leaf module.

@@ -176,32 +181,38 @@ def my_function(obj):
"""

def tracing_decorator(func):

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.

Is this refactor strictly necessary? If not, let's leave them out for now.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In older version when tracing is enabled via env variables decorater sets the wrapper correctly based on is_tracing_enabled() value.

But in the newer version of TracingConfig intialized via a schema, if there is a class [ Example: for proxy/replica TracingConfig comes from the controller at runtime] which gets tracing via this new setup_tracing() which makes tracing enabled at the runtime then for those, wrapper will never activate because at the decorater time, is_tracing_enabled returned false.

This is the reason for this refactor to now move this check to each wrapper function. Now we always set/return the wrapper and each function spans correctly based on is_tracing_enabled

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

So yes it is necessary because we don't set it via env variables now.

Comment thread python/ray/serve/schema.py Outdated
Comment on lines +285 to +289
@model_validator(mode="after")
def fill_default_exporter_when_enabled(self):
if self.enabled and not self.exporter_import_path:
self.exporter_import_path = DEFAULT_TRACING_EXPORTER_IMPORT_PATH
return self

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.

why is this needed if we already do

exporter_import_path: str = Field(
        default_factory=lambda: RAY_SERVE_TRACING_EXPORTER_IMPORT_PATH

@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch from a9828fc to d2811b1 Compare May 17, 2026 21:12
Comment thread python/ray/serve/_private/proxy.py Resolved
@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch from 0187fff to c0fdc9a Compare May 18, 2026 00:10
Comment thread python/ray/serve/_private/api.py Resolved
@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch 6 times, most recently from 93ecd5a to 54ca9f5 Compare May 19, 2026 17:19
component_name="proxy",
component_id=node_ip_address,
tracing_config=self._tracing_config,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Proxy tracing config never wired through, always None

High Severity

ProxyActor.__init__ doesn't accept tracing_config as a parameter and doesn't pass it to super().__init__(), so self._tracing_config used in the setup_tracing call is always None. Additionally, the controller never passes global_tracing_config to ProxyStateManager, and ProxyStateManager never passes it when creating proxy actors. The entire proxy tracing path described in the PR design is broken — the user-configured TracingConfig only reaches replicas (which fetch it from the controller), never proxies.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 54ca9f55b0150a311c6ef31ca918df3d8a842e22. Configure here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This will be handled in the [2/2] PR for this feature.

@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch from 54ca9f5 to 37f3b98 Compare May 19, 2026 18:47
@suppagoddo

Copy link
Copy Markdown
Contributor Author

this PR needs to test two flows

  1. declarative flow where tracing config is part of serve config python/ray/serve/tests/test_cli.py
  2. imperative flow where tracing config is passed from serve.start(...) python/ray/serve/tests/test_standalone.py

Fixing it in this PR.

@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch from 37f3b98 to cfdc594 Compare July 8, 2026 01:51
@suppagoddo
suppagoddo requested a review from a team as a code owner July 8, 2026 01:51

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

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

There are 3 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit cfdc594. Configure here.

Comment thread python/ray/serve/_private/controller.py Resolved
Comment thread python/ray/serve/_private/proxy.py Resolved
@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch 3 times, most recently from e28a4bb to 4700ce2 Compare July 8, 2026 22:43
Comment thread python/ray/serve/tests/test_cli.py Resolved
Comment thread python/ray/serve/schema.py Resolved
…ierarchy

Introduce TracingConfig as a first-class configuration object for
OpenTelemetry tracing in Ray Serve. Key changes:

- Add TracingConfig(BaseModel) to schema.py with enabled, exporter_import_path,
  and sampling_ratio fields
- setup_tracing() now accepts TracingConfig directly instead of raw kwargs
- Controller stores TracingConfig and exposes get_tracing_config() method
- Replica and Proxy fetch TracingConfig from controller at init
- Tracing decorators check is_tracing_enabled() at call-time (not decoration-time)
  to support runtime TracingConfig that arrives after import
- serve.start() accepts tracing_config parameter
- Fail fast: tracing setup errors propagate instead of being swallowed

No Replica class restructuring — the existing class remains unchanged.

Signed-off-by: Udit Agrawal <[email protected]>
…ow tests

Address review feedback on the TracingConfig PR:

- Simplify setup_tracing() to accept only tracing_config, dropping the
  redundant tracing_exporter_import_path / tracing_sampling_ratio params
  since TracingConfig already carries them. The env-var fallback is kept
  internally for when no TracingConfig is provided.
- Wire the declarative flow: add a tracing_config field to
  ServeDeploySchema and store it in ServeController.apply_config so
  replicas started for that config pick it up via get_tracing_config().
- Add end-to-end tests for both entry points: imperative (serve.start)
  in test_standalone.py and declarative (serve deploy) in test_cli.py.

Proxy tracing propagation and controller-restart checkpointing are handled
separately, as they require long-poll broadcast that does not exist yet.

Signed-off-by: uditagrawal <[email protected]>
Address review feedback: in the declarative tracing test, send traffic to
the deployed app and assert that replica trace spans are produced, verifying
the serve-config tracing_config is applied end-to-end (not just stored on the
controller).

Signed-off-by: uditagrawal <[email protected]>
Address review feedback: move `opentelemetry.trace` and
`ray.serve.utils.get_trace_context` imports out of the imperative tracing
test and up to the module-level import block.

Signed-off-by: uditagrawal <[email protected]>
Address review feedback: source TracingConfig field defaults from the
RAY_SERVE_TRACING_* environment variables instead of hard-coded literals.
`exporter_import_path` and `sampling_ratio` default to their respective env
vars; `enabled` defaults to True when RAY_SERVE_TRACING_EXPORTER_IMPORT_PATH
is set (restoring the pre-existing env-var gating). When no env vars are set,
defaults are unchanged (False / "" / 0.01).

Signed-off-by: uditagrawal <[email protected]>
@suppagoddo
suppagoddo force-pushed the tracing-config-prA-wiring branch from d282865 to 78605b4 Compare August 8, 2026 01:41
…_utils

The `mypy (ray serve)` hook flagged `Name "TracingConfig" is not defined` for
the `setup_tracing` annotation. Add TracingConfig to the existing TYPE_CHECKING
import block (alongside ServeComponentType) so the forward-ref annotation
resolves for type checkers. It's a type-check-only import, so no runtime import
is added and no circular dependency is introduced.

Signed-off-by: uditagrawal <[email protected]>
Comment on lines +267 to +275
tracing_exporter_import_path = tracing_config.exporter_import_path
# Fill default exporter if enabled but path is empty
if not tracing_exporter_import_path:
tracing_exporter_import_path = DEFAULT_TRACING_EXPORTER_IMPORT_PATH
tracing_sampling_ratio = tracing_config.sampling_ratio
else:
# No TracingConfig provided: fall back to env-var configuration.
tracing_exporter_import_path = RAY_SERVE_TRACING_EXPORTER_IMPORT_PATH
tracing_sampling_ratio = RAY_SERVE_TRACING_SAMPLING_RATIO

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.

we should just drop this fallback. tracing_config be the single source of truth.

Comment on lines 277 to 279
if tracing_exporter_import_path == "":
_tracing_enabled = False
return False

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.

same comment here, this check is moot

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

lg2m, left some nits

@suppagoddo

Copy link
Copy Markdown
Contributor Author

@abrarsheikh - Do you want to move these fallbacks nits to other PR or shall be fixed here. Reason is: I want to make sure that get_tracing_config() or setup_tracing should never return None, else we will get attribute error. Currently I am planning to raise another PR for proxy tracing [ which is 2/2 for this feature ], i can take care of deleting these fallbacks there.

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

yup, that works too. merging the PR

@abrarsheikh
abrarsheikh merged commit 47eb107 into ray-project:master Aug 8, 2026
6 checks passed
Artimislyy pushed a commit to Artimislyy/ray that referenced this pull request Aug 11, 2026
…hs (ray-project#63273)

**Schema**:
- New `TracingConfig` pydantic model (`schema.py`) with `enabled`,
`exporter_import_path`, `sampling_ratio`
  - Exported in `ray.serve` public API + API doc entry

  **`setup_tracing` API**:
  - Accepts `TracingConfig` directly instead of raw `kwargs`
  - When `tracing_config` is provided: reads config from it
- When `tracing_config` is `None`: falls back to env vars (backward
compatible)
- Tracing setup errors now propagate (fail fast) instead of being
silently swallowed

  **Replica path**:
- Replica fetches `TracingConfig` from controller via
`get_tracing_config()` and passes to `setup_tracing`

  **Proxy path**:
- `ProxyActorInterface` accepts `tracing_config` param (plumbed to
`setup_tracing`)
- Proxy currently receives `None` (env-var fallback, same as master).
Full proxy wiring via `ProxyStateManager` deferred to PR 2.

  **Controller**:
- Stores `global_tracing_config` and exposes `get_tracing_config()`
method

  **Decorator fix**:
- `tracing_decorator_factory` now checks `is_tracing_enabled()` at
call-time instead of decoration-time, because `TracingConfig` arrives at
runtime (after decorators are applied at import time)

  **Public API:**
  - `serve.start(tracing_config=...)` parameter

  **Design**

  - Global only: cluster-level, not per-app or per-deployment
  - Static: set once at startup, no hot-reload of existing actors
  - No proto changes: constructor arg through actor hierarchy
- Backward compatible: env vars still work as defaults when
`tracing_config` is `None`

  **What's deferred to PR 2**

- Proxy wiring through `ProxyStateManager` (proxy currently falls back
to env vars)
  - Runtime propagation (push config updates to live actors)
  - `HAProxy` tracing support

  **Test plan**

  - Unit tests for `TracingConfig` validation (`test_schema.py`)
  - Updated tracing e2e tests to use TracingConfig
  - Existing proxy/replica/deployment tests pass
  - No Replica class restructuring — existing class unchanged

---------

Signed-off-by: Udit Agrawal <[email protected]>
Signed-off-by: uditagrawal <[email protected]>
suppagoddo added a commit to suppagoddo/ray that referenced this pull request Aug 12, 2026
Follow-up to ray-project#63273 ([1/2]) completing the TracingConfig feature.

- Add a GLOBAL_TRACING_CONFIG long-poll namespace. The controller
  broadcasts the global tracing config and proxies subscribe, running
  setup_tracing on delivery. This wires proxy tracing without the
  init-time controller callback that cannot work (proxies start before
  the controller is queryable), and lets users change the tracing config
  at runtime through the existing serve-config API.
- Controller: checkpoint the tracing config (restored on recovery),
  default it to an env-var-sourced TracingConfig() so it is never None,
  publish the initial snapshot, and broadcast changes from apply_config.
  get_tracing_config() is now non-Optional; reconfigure coerces/validates
  its input since the value is broadcast cluster-wide.
- tracing_utils.setup_tracing: drop the env-var fallback and the now-moot
  empty-path check; tracing_config is required (single source of truth).
  Its fields already default from the RAY_SERVE_TRACING_* env vars.
- Proxy sets tracing up only from the long-poll callback, so
  set_tracer_provider is called once per process (OpenTelemetry ignores
  later calls, which would drop the sampler and duplicate exporters).
  The callback swallows and logs errors so a bad exporter path cannot
  wedge the proxy's long poll client and freeze route table updates.
- Replicas continue to read the config when they start.
- Tests: assert proxy traces are produced via the imperative flow, and
  that a tracing config changed after startup survives controller
  recovery (so the checkpoint, not the constructor arg, is exercised).

Signed-off-by: uditagrawal <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…hs (ray-project#63273)

**Schema**:
- New `TracingConfig` pydantic model (`schema.py`) with `enabled`,
`exporter_import_path`, `sampling_ratio`
  - Exported in `ray.serve` public API + API doc entry

  **`setup_tracing` API**:
  - Accepts `TracingConfig` directly instead of raw `kwargs`
  - When `tracing_config` is provided: reads config from it
- When `tracing_config` is `None`: falls back to env vars (backward
compatible)
- Tracing setup errors now propagate (fail fast) instead of being
silently swallowed

  **Replica path**:
- Replica fetches `TracingConfig` from controller via
`get_tracing_config()` and passes to `setup_tracing`

  **Proxy path**:
- `ProxyActorInterface` accepts `tracing_config` param (plumbed to
`setup_tracing`)
- Proxy currently receives `None` (env-var fallback, same as master).
Full proxy wiring via `ProxyStateManager` deferred to PR 2.

  **Controller**:
- Stores `global_tracing_config` and exposes `get_tracing_config()`
method

  **Decorator fix**:
- `tracing_decorator_factory` now checks `is_tracing_enabled()` at
call-time instead of decoration-time, because `TracingConfig` arrives at
runtime (after decorators are applied at import time)

  **Public API:**
  - `serve.start(tracing_config=...)` parameter

  **Design**

  - Global only: cluster-level, not per-app or per-deployment
  - Static: set once at startup, no hot-reload of existing actors
  - No proto changes: constructor arg through actor hierarchy
- Backward compatible: env vars still work as defaults when
`tracing_config` is `None`

  **What's deferred to PR 2**

- Proxy wiring through `ProxyStateManager` (proxy currently falls back
to env vars)
  - Runtime propagation (push config updates to live actors)
  - `HAProxy` tracing support

  **Test plan**

  - Unit tests for `TracingConfig` validation (`test_schema.py`)
  - Updated tracing e2e tests to use TracingConfig
  - Existing proxy/replica/deployment tests pass
  - No Replica class restructuring — existing class unchanged

---------

Signed-off-by: Udit Agrawal <[email protected]>
Signed-off-by: uditagrawal <[email protected]>
Signed-off-by: 400Ping <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…hs (ray-project#63273)

**Schema**:
- New `TracingConfig` pydantic model (`schema.py`) with `enabled`,
`exporter_import_path`, `sampling_ratio`
  - Exported in `ray.serve` public API + API doc entry

  **`setup_tracing` API**:
  - Accepts `TracingConfig` directly instead of raw `kwargs`
  - When `tracing_config` is provided: reads config from it
- When `tracing_config` is `None`: falls back to env vars (backward
compatible)
- Tracing setup errors now propagate (fail fast) instead of being
silently swallowed

  **Replica path**:
- Replica fetches `TracingConfig` from controller via
`get_tracing_config()` and passes to `setup_tracing`

  **Proxy path**:
- `ProxyActorInterface` accepts `tracing_config` param (plumbed to
`setup_tracing`)
- Proxy currently receives `None` (env-var fallback, same as master).
Full proxy wiring via `ProxyStateManager` deferred to PR 2.

  **Controller**:
- Stores `global_tracing_config` and exposes `get_tracing_config()`
method

  **Decorator fix**:
- `tracing_decorator_factory` now checks `is_tracing_enabled()` at
call-time instead of decoration-time, because `TracingConfig` arrives at
runtime (after decorators are applied at import time)

  **Public API:**
  - `serve.start(tracing_config=...)` parameter

  **Design**

  - Global only: cluster-level, not per-app or per-deployment
  - Static: set once at startup, no hot-reload of existing actors
  - No proto changes: constructor arg through actor hierarchy
- Backward compatible: env vars still work as defaults when
`tracing_config` is `None`

  **What's deferred to PR 2**

- Proxy wiring through `ProxyStateManager` (proxy currently falls back
to env vars)
  - Runtime propagation (push config updates to live actors)
  - `HAProxy` tracing support

  **Test plan**

  - Unit tests for `TracingConfig` validation (`test_schema.py`)
  - Updated tracing e2e tests to use TracingConfig
  - Existing proxy/replica/deployment tests pass
  - No Replica class restructuring — existing class unchanged

---------

Signed-off-by: Udit Agrawal <[email protected]>
Signed-off-by: uditagrawal <[email protected]>
abrarsheikh added a commit that referenced this pull request Nov 17, 2026
Follow-up to #63273 ([1/2]), completing the `TracingConfig` feature.

## Problem

In #63273, `TracingConfig` reached replicas but never reached proxies:
`ProxyActor` gained an optional `tracing_config` argument, but nothing
passed it, so proxies always fell back to their own
`RAY_SERVE_TRACING_*` env vars. Declarative configs (`serve deploy`,
`serve run <config.yaml>`) were applied only after the controller and
proxies had already started. A later `serve deploy` could replace the
stored config, but that only affected replicas started afterwards;
running proxies and replicas kept their original tracing setup, with no
error.

OpenTelemetry allows one tracer provider per process, so a running
component can't adopt a new tracing config.

## Design: tracing is fixed when Serve starts

- **Delivered at controller creation** by every entry point:
`serve.start`, `serve_start_async` (used by `serve deploy`), and `serve
run <config.yaml>`.
- **Proxies** receive it as a constructor argument (through
`ProxyStateManager`, the same way as `logging_config`) and set up
tracing once in `__init__`. **Replicas** read it from the controller
when they start.
- **Changes are rejected.** After Serve has started, a different tracing
config raises `Tracing config cannot be changed after Serve has
started`, whether it comes from `serve deploy` / `apply_config` or a
second `serve.start` call. Re-applying the same config does nothing. To
change tracing, shut down and restart Serve.

## How the config is resolved

- The caller validates `TracingConfig` and passes only the **explicitly
set** fields (`model_dump(exclude_unset=True)`) to the controller. The
controller builds the effective config in its own process, so omitted
fields default from the controller's env vars, which can be set via
`controller_options.runtime_env.env_vars`. Explicit values always win.
- `exporter_import_path` defaults to
`RAY_SERVE_TRACING_EXPORTER_IMPORT_PATH`, or the built-in file exporter
if that's unset. An explicit `""` is now a validation error. The
defaults for `enabled` and `sampling_ratio` are unchanged.
- `apply_config` receives a `ServeDeploySchema` already built by the
dashboard. It compares that request's explicit tracing fields against
the running config, resolved the same way, **before** changing any
controller state.

## Controller recovery

There is no tracing checkpoint and no long poll. When the controller
restarts, Ray replays its constructor argument (the explicit fields), so
it reproduces the same effective config under the same controller
environment. New proxies and replicas created after recovery get it the
same way as before the restart.

## Startup failures

- **The controller validates the exporter when it's first constructed**,
before writing any state:
- It must import. A custom exporter must be a zero-argument function.
The controller calls it once, checks that it returns a
`List[SpanProcessor]`, and shuts the returned processors down. It
doesn't install a tracer provider.
- The built-in exporter is only imported, because calling it opens a
span file. OpenTelemetry must be installed when tracing is enabled.
- Any failure fails construction with `InvalidTracingConfigError` (a
`ValueError`): an unimportable exporter, a bad signature, an exporter
that raises or returns the wrong type, or missing OpenTelemetry.
`serve.start` and `serve_start_async` raise it, and `serve deploy`
returns a 400.
- Ray doesn't restart an actor whose constructor raised, and it releases
the controller's name. So a retry with the same exporter fails again,
and a retry with a corrected exporter starts Serve, with no
`serve.shutdown()` in between.
- **On a controller restart after a crash**, the exporter isn't called
again. The import and signature checks only log a failure, so recovery
isn't blocked.
- **Custom exporters must return promptly**, because the controller
calls them during startup. Proxies and replicas still call them when
they set up tracing, as before.
- **Known limitation:** an exporter can pass in the controller but fail
in a proxy or replica, for example because of a node-specific
environment. That's handled like any other startup failure: Serve's
existing recovery replaces the proxy, and a replica failure fails the
deployment.
- Otherwise, proxy startup failures and readiness timeouts behave as on
master.

## Behavior changes relative to master

- Proxies now use `TracingConfig` instead of only their own env vars.
- `serve deploy` and `serve run <config.yaml>` apply `tracing_config`
when the controller is created.
- Omitted tracing fields default from the controller's env vars, not
from whichever process built the config.
- Changing tracing after startup raises an error. On master,
`apply_config` replaced the config silently, and only replicas started
later picked it up.
- An explicit `exporter_import_path=""` is rejected. On master it meant
"use the built-in exporter".
- `TracingConfig().exporter_import_path` is now the built-in exporter's
path (or the env var) rather than `""`.
- Invalid exporters fail at controller startup with a config error (a
400 from `serve deploy`) instead of failing later during proxy or
replica startup. That covers exporters that can't be imported, have a
bad signature, raise when called, or return the wrong type. On master,
an exporter that raised failed proxy startup and left the controller
running.
- A custom exporter is now also called once in the controller, at
initial startup.

## Testing

**Ran locally:**
- Unit tests:
  - `TracingConfig` defaults and validation.
  - Explicit fields resolving under another environment.
  - Exporter validation:
    - Signature checks.
- A valid exporter is called once, every processor it returns is shut
down once, and no tracer provider is installed.
    - An exporter that raises is rejected.
- Invalid output (not a list, a tuple, or a valid processor followed by
an invalid item) is rejected, and the valid processors are still shut
down.
- A processor shutdown failure is logged without hiding the validation
error.
    - The built-in exporter isn't called.
    - The exporter isn't called on controller recovery.
    - Missing OpenTelemetry is reported.
    - Disabled tracing calls nothing.
  - Recovering the original exception from a pickled `ActorDiedError`.
- Proxy startup errors and readiness timeouts are re-raised as on
master, on sync and async paths.
- Results: `test_controller.py` 79 passed, `test_tracing_utils.py`
exporter-validation tests 22 passed, `test_proxy.py` 43,
`test_proxy_state.py` 38, `TracingConfig` schema tests 14.
- black, ruff, mypy and pyrefly at the versions pinned in
`.pre-commit-config.yaml`.

**Pending CI** (these need a Ray cluster):
- Imperative, `serve deploy` (REST and CLI) and `serve run` tracing
flows.
- A partial config resolving from `controller_options.runtime_env`.
- Invalid exporters, including one that raises when called, returning
`ValueError` / 400.
- Bad → bad → good retries on the sync and async paths, with explicit
and controller-env config, without `serve.shutdown()`.
- An exporter that fails only in replicas failing the deployment.
- Rejected runtime changes, including the CLI message and the
no-state-mutation check.
- Controller recovery, including spans from a newly created proxy and
replica.

```
pytest python/ray/serve/tests/unit/test_schema.py -k TracingConfig
pytest python/ray/serve/tests/unit/test_controller.py
pytest python/ray/serve/tests/test_tracing_utils.py
pytest python/ray/serve/tests/test_standalone.py -k "tracing or exporter"
pytest python/ray/serve/tests/test_cli.py -k tracing
pytest python/ray/serve/tests/test_cli_3.py -k tracing
pytest python/ray/dashboard/modules/serve/tests/test_serve_dashboard.py -k tracing
```

## Not a duplicate

This is part 2 of the work started in #63273; no other open PR covers
delivering the tracing config to proxies and replicas. Follow-up: #66382
(pass the config to replicas as a constructor argument instead of an RPC
at startup).

This PR used Claude Code for writing code.

---------

Signed-off-by: uditagrawal <[email protected]>
Co-authored-by: Abrar Sheikh <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community docs An issue or change related to documentation go add ONLY when ready to merge, run all tests observability Issues related to the Ray Dashboard, Logging, Metrics, Tracing, and/or Profiling serve Ray Serve Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants