Skip to content

[Observability / Train] Add Grafana Annotation support with Ray Train usage - #66958

Merged
pseudo-rnd-thoughts merged 13 commits into
ray-project:masterfrom
pseudo-rnd-thoughts:train/grafana-annotations
Nov 9, 2026
Merged

pseudo-rnd-thoughts merged 13 commits into
ray-project:masterfrom
pseudo-rnd-thoughts:train/grafana-annotations

Conversation

@pseudo-rnd-thoughts

@pseudo-rnd-thoughts pseudo-rnd-thoughts commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Description

Ray's Grafana dashboards show metrics over time, however, users lack any contextual information on what exact code is running that causes a change in a graph which must be inferred from the job which over a long period of time is difficult to do. This PR address this by adding annotations / events to Grafana to note when functions are run (see image below).

image

High level architecture

When an event happens (for example in Ray Train: a report, a controller state change, or a user calling ray.train.annotate), we build an AnnotationEvent protobuf (src/ray/protobuf/annotation_event.proto) and write it to <session>/logs/annotations_<pid>.log. Each process writes its own file so concurrent writers never race as best-effort: the writer resolves the session logs dir per emit (so a process that outlives a session or forks follows it to a new file), and any failure, including a failed disk write, is swallowed and warned about once rather than raised into the caller.

The emitter, AnnotationEmitter, lives in ray._common.observability.annotation as it's completely generic and doesn't depend on any Ray Train component, so data, core, llm can add their own annotations later. It takes a source (the marker Grafana uses to select its own annotations) and base_tags (attached to every event, e.g. the train run name/id and world rank). Each event carries a typed schema:

  • annotation_source, event, timestamp_s, session_name
  • message: the tooltip title
  • tags: the emitter's identity (map<string,string>)
  • fields: the event-specific payload shown as tooltip pills (map<string,string>, values stringified)

Keeping tags and fields in separate maps means a field can never shadow a schema field or a tag. Severity isn't a schema field, because only ray.train.annotate has one; it's carried in that event's fields. The proto is standalone rather than part of ExportEvent; if annotations later move to RayEvent, timestamp_s, session_name and message map onto its base fields and the rest becomes the nested event, without changing what the dashboard queries match.

On disk a line looks like:

{"annotation_source": "ray_train_annotation", "event": "ray.train.report",
 "timestamp_s": 1759330000.12, "session_name": "session_...", "message": "",
 "tags": {"ray_train_run_name": "...", "ray_train_run_id": "...", "ray_train_worker_world_rank": "0"},
 "fields": {"metrics": "{\"loss\": 0.5}", "has_checkpoint": "false", "validation": "false"}}

In Grafana, each event type is a Loki annotation layer generated into the Train dashboard, e.g.:

{ray_annotations="true"} |= "ray_train_annotation"
  | json annotation_source="annotation_source", session_name="session_name",
         event="event", message="message"
  | annotation_source="ray_train_annotation" | session_name=~"${AnnotationSessionName:regex}"
  | event="ray.train.report"
  | json ray_train_run_name="tags.ray_train_run_name", ray_train_run_id="tags.ray_train_run_id"
  | ray_train_run_name=~"$TrainRunName" | ray_train_run_id=~"$TrainRunId"
  | json metrics="fields.metrics", has_checkpoint="fields.has_checkpoint", ...
  | label_format metrics_pill=`metrics: {{.metrics}}`, ...
  | line_format "ray.train.report()"

|= is a cheap line pre-filter. Each | json stage lifts only the fields that query uses into labels, rather than letting the parser flatten the whole record, so a field a collector adds at the top level (e.g. Vector's file or host) can't collide with them. session_name is matched against a hidden AnnotationSessionName variable chained off the SessionName dropdown, so the annotations follow the selected session like the metric panels do. That variable has no custom allValue, so All expands to the sessions Prometheus has under the dashboard's global filters rather than to .*, and a dashboard doesn't render other clusters' events when one Loki serves several. label_format/line_format build the tooltip.

Ray Train integration

For Ray Train there are three event types across five annotation layers:

  • ray.train.report: metrics, whether it has a checkpoint (and its dir name), and whether it has validation. Rank 0 only. Every field value is truncated past 4096 chars, since log backends drop oversized lines (Loki defaults to 256KB). Numpy scalars and 0-d arrays/tensors (e.g. a loss) are serialized by value, any other array or tensor only by its shape, since formatting the data is slow and syncs a GPU tensor to the host. It's emitted once every rank has reached the report barrier but before the checkpoint upload and validation, so a report that's skipped or raises before the barrier isn't annotated, upload time doesn't delay the marker, and a failed upload still shows up at the time of the report. An annotation failure can never break or hang the report.
  • Controller state changes: e.g. Controller: INITIALIZING → RUNNING, emitted by the controller's ControllerMetricsCallback.
  • ray.train.annotate: a DeveloperAPI for users. severity is one of "info", "warning" or "error" (default "info"), emitted as fields.severity; anything else raises ValueError on every rank, whether or not annotations are enabled. Split into info, warning and error layers so each can be toggled. User **fields are serialized together into fields.custom_fields, shown as one JSON tag. Rank 0 only by default.

Collector setup

Ray writes the files but ships no log collector and only provisions Prometheus. To render annotations, an operator needs to

  1. Runs a collector (Vector, Promtail, etc) tailing /tmp/ray/session_*/logs/annotations_*.log and ships each line to Loki, either as-is or with its fields merged into the top level of the record (not nested under a key).
  2. Labels that stream ray_annotations="true".
  3. Optionally sets each log entry's timestamp from timestamp_s, so shipping delay doesn't shift annotations later.
  4. Adds Loki as a Grafana datasource. The dashboard binds to the first Loki datasource automatically via an annotation_datasource variable, and a different one can be picked from its dropdown.
  5. Sets RAY_ANNOTATIONS_ENABLED=1 on every node before starting Ray.

Annotations are off by default (RAY_ANNOTATIONS_ENABLED, default False), because without a collector nothing reads the lines, and without Loki every dashboard load shows failed annotation queries. The one variable gates both sides: worker nodes need it to write annotation log lines, and the head node needs it for the generated dashboards to include the annotation layers. A platform that provides the collector and Loki sets it on every node. Setting it through a job's runtime_env doesn't reach the dashboard. Documented in configure-manage-dashboard.md.

Design justification

Grafana's annotation API can pull from several datasources, including Prometheus which we already use for the rest of our metrics. The reason that Prometheus isn't used is that annotations need to be discrete, text-carrying point events, whereas Prometheus is a numeric time-series scraped at an interval. This means that it can't carry the message/metrics text we would wish, and a point could be quantised to scrape boundaries or even missed entirely between scrapes. I prototyped this with both Gauge and Time metrics and hit exactly these issues. Loki log lines, on the other hand, are discrete, timestamped, can carry arbitrary JSON, and Loki is Grafana's own log backend, which makes them a much better fit.

One caveat on the timing: annotations are positioned by the log-line timestamp while the metric graphs only update at the Prometheus scrape interval, so an annotation can appear slightly ahead of the metric change it's explaining.

Why a dedicated log file rather than the export-event pipeline. The export API (ExportEvent) is being superseded by RayEvent, and RayEvent delivery isn't enabled by default, whereas annotations exist for the dashboards and should work out of the box. A small per-process JSON-line writer with a proto-defined schema gives the format one documented definition, and a path onto RayEvent, without extending an API that's being replaced. Writing the lines is cheap: rank-0 only by default, one line per report or state change.

Data flow overview

flowchart LR
    subgraph Node["Ray node (one per host)"]
        direction TB
        subgraph Controller["Train controller actor"]
            MC["ControllerMetricsCallback<br/>controller_state_change"]
        end
        subgraph Workers["Train worker processes (one per rank)"]
            R["ray.train.report()<br/>ray.train.report"]
            A["ray.train.annotate()<br/>ray.train.annotate"]
        end
        ANN["AnnotationEmitter.emit()<br/>builds AnnotationEvent proto<br/>(session_name, tags, fields, timestamp_s)"]
        W["_write_annotation_line(line, logs_dir)<br/>one handler per process;<br/>reopens on new session or fork"]
        F[("logs/annotations_&lt;pid&gt;.log<br/>flat JSON, one event per line<br/>rotated with RAY_ROTATION_*")]

        MC --> ANN
        R --> ANN
        A --> ANN
        ANN --> W --> F
    end

    subgraph Collector["Log collector (Vector, Promtail, Alloy, …)"]
        direction TB
        V1["file source<br/>tail logs/annotations_*.log"]
        V2["optional: merge JSON fields to root,<br/>set timestamp from timestamp_s"]
        V3["Loki sink<br/>label: ray_annotations=#quot;true#quot;"]
        V1 --> V2 --> V3
    end

    F -->|tail| V1

    LOKI[("Loki")]
    PROM[("Prometheus")]
    V3 --> LOKI

    subgraph Head["Head node: dashboard"]
        MH["MetricsHead"]
        GEN["generate_train_grafana_dashboard()<br/>if RAY_ANNOTATIONS_ENABLED, adds<br/>annotation layers + hidden AnnotationSessionName<br/>+ annotation_datasource variables"]
        MH --> GEN
    end

    G["Grafana<br/>Train dashboard"]
    GEN -->|provisioned dashboard JSON| G
    G -->|"LogQL: {ray_annotations=#quot;true#quot;} | json | session_name=~$AnnotationSessionName"| LOKI
    G -->|PromQL panels| PROM
Loading

Ray owns everything up to the log file and the generated dashboard. The collector, Loki and the Loki datasource are supplied by the operator.

Sequence: one ray.train.report call

sequenceDiagram
    autonumber
    participant U as User train_fn (rank N)
    participant T as ray.train.report
    participant A as AnnotationEmitter
    participant W as _write_annotation_line
    participant F as annotations_<pid>.log
    participant V as Log collector
    participant L as Loki
    participant G as Grafana

    U->>T: report(metrics, checkpoint)
    T->>T: report barrier (all ranks)
    alt rank 0
        T->>A: emit("ray.train.report", metrics=..., has_checkpoint=...)
        A->>A: _global_node → logs_dir, session_name
        A->>W: _write_annotation_line(json_line, logs_dir, max_bytes, backup_count)
        alt same pid and same logs_dir
            W->>W: reuse cached handler
        else new session or forked process
            W->>W: close old handler, open new file
        end
        W->>F: append one JSON line
        Note over T,W: Any failure is swallowed and warned once.<br/>report() is never blocked.
    end
    T->>T: checkpoint upload + validation
    V->>F: tail new line
    V->>V: optionally merge JSON to root
    V->>L: push with label ray_annotations="true"
    G->>L: annotation query (per layer, session pinned)
    L-->>G: matching lines
    G->>G: render marker on every panel's time axis
Loading

Contracts

  • Two contracts cross the file boundary: the file path pattern logs/annotations_<pid>.log, and the JSON field names from AnnotationEvent. The generated LogQL reads annotation_source, session_name, event, message, tags.* and fields.* (including fields.severity for ray.train.annotate) from the top level of each line.
  • One contract crosses the Loki boundary: the ray_annotations="true" stream label.
  • Cluster isolation comes from matching session_name against the hidden AnnotationSessionName variable, whose All lists only the sessions Prometheus has for this cluster. It doesn't depend on Loki labels.

@pseudo-rnd-thoughts pseudo-rnd-thoughts added the train Ray Train Related Issue label Oct 13, 2026
@pseudo-rnd-thoughts
pseudo-rnd-thoughts requested review from a team as code owners October 13, 2026 17:37
@pseudo-rnd-thoughts pseudo-rnd-thoughts added the go add ONLY when ready to merge, run all tests label Oct 13, 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 a new feature to overlay event annotations on Grafana dashboards for Ray Train. It adds a process-specific Annotation writer that serializes structured events to JSON log lines, defines the AnnotationEvent protobuf schema, and integrates annotations into Ray Train's controller state changes, ray.train.report calls, and a new ray.train.annotate API. Additionally, the Grafana dashboard generation factory is updated to append these annotations. The review feedback highlights two key improvements: first, resetting the cached _writer to None in the post-fork handler to prevent a potential deadlock when calling writer.close(); second, enhancing _annotation_json_default to generically serialize scalar and small multi-dimensional tensors from PyTorch, TensorFlow, or Jax so that metric values are not hidden on the dashboard.

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

Stale Bugbot comment from a previous run.

Comment thread src/ray/protobuf/annotation_event.proto Resolved
Signed-off-by: Mark Towers <[email protected]>

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

Stale Bugbot comment from a previous run.

Mark Towers added 3 commits October 14, 2026 17:05
Signed-off-by: Mark Towers <[email protected]>
# Conflicts:
#	python/ray/train/v2/api/train_fn_utils.py
Signed-off-by: Mark Towers <[email protected]>

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

Thanks! Left some comments. Other UX items to consider:

  • Allowing users to toggle the annotations on/off from the train grafana dashboard
  • If we should have the annotations show by default or not
  • If we want to only show certain annotations for certain panels so it's not too noisy

Would be great to add a screenshot of the train dashboard panels.

dstrodtman added a commit that referenced this pull request Oct 26, 2026
## Description

A batch of 15 small docs fixes. Most close an open docs issue, listed
under Related issues. Each fix is its own commit, so a reviewer can drop
any one without touching the rest. Batching follows the "No low-value
busywork PRs" rule in `AGENTS.md`, which allows mechanical fixes when
they're bundled.

The changes are prose and one notebook install cell, all under `doc/`.
Each fix was checked against the current source on master.

| Area | Change | Source checked |
|---|---|---|
| Core | The memory-aware scheduling examples said 2.5 GiB and 1 GiB but
computed 2500 MiB and 1000 MiB. The examples now use exact binary
multiples, and the text says `memory` is in bytes. | `ray.remote`
docstring in `_private/worker.py` (memory request in bytes) |
| Cluster | Link the cluster application guide to the Ray Serve
development and deployment guides. | Existing `serve-dev-workflow`,
`serve-in-production-deploying`, and `serve-in-production-kubernetes`
labels |
| Train | Link the Lightning getting-started guide to the PyTorch data
loading comparison. | `train-datasets-pytorch` section |
| Tune | Pin the hidden install cell of `ax-example.ipynb` to
`ax-platform==1.2.1`, the version in `tune-requirements.txt`, and drop
the cell's stale pip output. #60522 moved `AxSearch` to the Ax 1.0 API.
| `python/requirements/ml/tune-requirements.txt`, `ax_search.py` |
| Train | The fault-tolerance deprecation section called the deprecated
argument `restore_from_checkpoint`. The trainer parameter is
`resume_from_checkpoint`. |
`python/ray/train/v2/api/data_parallel_trainer.py` |
| Tune | The BayesOpt example pinned `bayesian-optimization==1.2.0`,
which uses `np.float` and fails in `tuner.fit()` on current NumPy. Pin
1.4.0, the version in `python/requirements_compiled.txt`. Executing the
notebook with `jupyter nbconvert --execute` on Ray 2.59.0 and NumPy
2.4.6 runs clean with 1.4.0 and reproduces `AttributeError: module
'numpy' has no attribute 'float'` with 1.2.0. |
`python/requirements_compiled.txt` |
| Cluster | Add a manual-configuration tab with SSH port forwarding to
the dashboard access section. | `ray start --dashboard-port`, default
8265 |
| Cluster | Document `RAY_OVERRIDE_DASHBOARD_URL` for reverse proxies. |
`ray_constants.py`, `worker.py` (`get_dashboard_url` and the connect
log) |
| Serve | Note that KubeRay creates `<name>-head-svc` and
`<name>-serve-svc` only after every Serve application is `RUNNING`. |
KubeRay `rayservice_controller.go` (`reconcileServe`,
`getAndCheckServeStatus`) |
| Cluster | Replace the hardcoded Homebrew Grafana path with `$(brew
--prefix)/etc/grafana/grafana.ini`. | The Homebrew `grafana` formula's
service passes `--config etc/grafana/grafana.ini` |
| Cluster | A node type's `worker_setup_commands` replaces both the
general `setup_commands` and `worker_setup_commands`. It doesn't replace
only the latter. | `merge_setup_commands` in
`autoscaler/_private/util.py`, `_get_node_type_specific_fields` in
`autoscaler.py`, `ray-schema.json` |
| Cluster | Add next-steps links to log and metrics persistence on the
VM and KubeRay quickstarts. | Existing persistence guides |
| Cluster | Add a port requirements section to the manual on-premises
setup that links the ports reference. | `core/configure.md` ports
reference |
| Data | Rename the `S3` and `GCS` cloud storage tabs to `Amazon S3` and
`Google Cloud Storage`. In Ray docs, GCS means the Global Control
Service. | `writing-style.md` term table |
| KubeRay | Document where `libtpu` logs appear (`tpu_logs` in the node
log directory and the dashboard Logs view). Link to it from the Logs
view section. | `_private/node.py` (`_init_temp`),
`_private/log_monitor.py`, #47737 |

## Related issues

Closes #42681
Closes #38545
Closes #48024
Closes #54968
Closes #37804
Closes #46794
Closes #50958
Closes #42430
Closes #37831
Closes #37631
Closes #24491
Closes #51102

## Not a duplicate

For each linked issue, `gh pr list --repo ray-project/ray --state open
--search "<issue> in:body"` returned no open PRs. A content search
turned up three open PRs that edit the same pages: #66289 (OCI
provider), #66958 (Grafana annotations), and #66920 (NPU observability).
They touch different hunks and don't overlap these changes. The data tab
rename has no linked issue, and no open PR touches those tabs.

## Testing

- `make -C doc rtd-build` (the RtD-faithful clean build: Python 3.11,
`doc/requirements-doc.lock.txt`, `-W --keep-going`): `build succeeded.`
with exit code 0 and zero Sphinx warnings. The only `WARNING` lines are
two RLlib logger messages printed at import time.
- Vale, run on the changed pages and limited to the added lines: no
findings remain beyond spelling hits on `proxied` (the page already uses
it) and `libtpu`, which is now in backticks.
- Pre-commit hooks passed on every commit.
- Every `{ref}` target added in this PR resolves to exactly one label
under `doc/source/`.
- I didn't execute the Ax notebook. Its only change is the hidden
install cell. CI already tests the Ax integration at
`ax-platform==1.2.1` through `python/ray/tune/examples/ax_example.py`.

## AI assistance

Drafted with AI assistance (Claude Code). Each technical claim was
checked against the source cited in the table.

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

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
justinyeh1995 pushed a commit to justinyeh1995/ray that referenced this pull request Oct 28, 2026
## Description

A batch of 15 small docs fixes. Most close an open docs issue, listed
under Related issues. Each fix is its own commit, so a reviewer can drop
any one without touching the rest. Batching follows the "No low-value
busywork PRs" rule in `AGENTS.md`, which allows mechanical fixes when
they're bundled.

The changes are prose and one notebook install cell, all under `doc/`.
Each fix was checked against the current source on master.

| Area | Change | Source checked |
|---|---|---|
| Core | The memory-aware scheduling examples said 2.5 GiB and 1 GiB but
computed 2500 MiB and 1000 MiB. The examples now use exact binary
multiples, and the text says `memory` is in bytes. | `ray.remote`
docstring in `_private/worker.py` (memory request in bytes) |
| Cluster | Link the cluster application guide to the Ray Serve
development and deployment guides. | Existing `serve-dev-workflow`,
`serve-in-production-deploying`, and `serve-in-production-kubernetes`
labels |
| Train | Link the Lightning getting-started guide to the PyTorch data
loading comparison. | `train-datasets-pytorch` section |
| Tune | Pin the hidden install cell of `ax-example.ipynb` to
`ax-platform==1.2.1`, the version in `tune-requirements.txt`, and drop
the cell's stale pip output. ray-project#60522 moved `AxSearch` to the Ax 1.0 API.
| `python/requirements/ml/tune-requirements.txt`, `ax_search.py` |
| Train | The fault-tolerance deprecation section called the deprecated
argument `restore_from_checkpoint`. The trainer parameter is
`resume_from_checkpoint`. |
`python/ray/train/v2/api/data_parallel_trainer.py` |
| Tune | The BayesOpt example pinned `bayesian-optimization==1.2.0`,
which uses `np.float` and fails in `tuner.fit()` on current NumPy. Pin
1.4.0, the version in `python/requirements_compiled.txt`. Executing the
notebook with `jupyter nbconvert --execute` on Ray 2.59.0 and NumPy
2.4.6 runs clean with 1.4.0 and reproduces `AttributeError: module
'numpy' has no attribute 'float'` with 1.2.0. |
`python/requirements_compiled.txt` |
| Cluster | Add a manual-configuration tab with SSH port forwarding to
the dashboard access section. | `ray start --dashboard-port`, default
8265 |
| Cluster | Document `RAY_OVERRIDE_DASHBOARD_URL` for reverse proxies. |
`ray_constants.py`, `worker.py` (`get_dashboard_url` and the connect
log) |
| Serve | Note that KubeRay creates `<name>-head-svc` and
`<name>-serve-svc` only after every Serve application is `RUNNING`. |
KubeRay `rayservice_controller.go` (`reconcileServe`,
`getAndCheckServeStatus`) |
| Cluster | Replace the hardcoded Homebrew Grafana path with `$(brew
--prefix)/etc/grafana/grafana.ini`. | The Homebrew `grafana` formula's
service passes `--config etc/grafana/grafana.ini` |
| Cluster | A node type's `worker_setup_commands` replaces both the
general `setup_commands` and `worker_setup_commands`. It doesn't replace
only the latter. | `merge_setup_commands` in
`autoscaler/_private/util.py`, `_get_node_type_specific_fields` in
`autoscaler.py`, `ray-schema.json` |
| Cluster | Add next-steps links to log and metrics persistence on the
VM and KubeRay quickstarts. | Existing persistence guides |
| Cluster | Add a port requirements section to the manual on-premises
setup that links the ports reference. | `core/configure.md` ports
reference |
| Data | Rename the `S3` and `GCS` cloud storage tabs to `Amazon S3` and
`Google Cloud Storage`. In Ray docs, GCS means the Global Control
Service. | `writing-style.md` term table |
| KubeRay | Document where `libtpu` logs appear (`tpu_logs` in the node
log directory and the dashboard Logs view). Link to it from the Logs
view section. | `_private/node.py` (`_init_temp`),
`_private/log_monitor.py`, ray-project#47737 |

## Related issues

Closes ray-project#42681
Closes ray-project#38545
Closes ray-project#48024
Closes ray-project#54968
Closes ray-project#37804
Closes ray-project#46794
Closes ray-project#50958
Closes ray-project#42430
Closes ray-project#37831
Closes ray-project#37631
Closes ray-project#24491
Closes ray-project#51102

## Not a duplicate

For each linked issue, `gh pr list --repo ray-project/ray --state open
--search "<issue> in:body"` returned no open PRs. A content search
turned up three open PRs that edit the same pages: ray-project#66289 (OCI
provider), ray-project#66958 (Grafana annotations), and ray-project#66920 (NPU observability).
They touch different hunks and don't overlap these changes. The data tab
rename has no linked issue, and no open PR touches those tabs.

## Testing

- `make -C doc rtd-build` (the RtD-faithful clean build: Python 3.11,
`doc/requirements-doc.lock.txt`, `-W --keep-going`): `build succeeded.`
with exit code 0 and zero Sphinx warnings. The only `WARNING` lines are
two RLlib logger messages printed at import time.
- Vale, run on the changed pages and limited to the added lines: no
findings remain beyond spelling hits on `proxied` (the page already uses
it) and `libtpu`, which is now in backticks.
- Pre-commit hooks passed on every commit.
- Every `{ref}` target added in this PR resolves to exactly one label
under `doc/source/`.
- I didn't execute the Ax notebook. Its only change is the hidden
install cell. CI already tests the Ax integration at
`ax-platform==1.2.1` through `python/ray/tune/examples/ax_example.py`.

## AI assistance

Drafted with AI assistance (Claude Code). Each technical claim was
checked against the source cited in the table.

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

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

@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 and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit d97b8b7. Configure here.

Comment thread src/ray/protobuf/annotation_event.proto Resolved
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
…#67794)

## Problem

- The NCCL hang detector dumps a hung worker's stack with an
unprivileged `py-spy dump --pid <pid> --native`.
- In containers with restricted ptrace that call always fails. The dump
then has no native frames, so it cannot show where NCCL is blocked.
- py-spy reports: `Permission Denied: Try running again with elevated
permissions by going 'sudo env "PATH=$PATH" !!'`
- Verified on an Anyscale worker: `CapEff: 0000000000000000`,
`/proc/sys/kernel/yama/ptrace_scope` is `1`, so a child py-spy cannot
trace its parent.
- The `ray` user there has passwordless sudo, and `sudo env PATH=$PATH
py-spy dump --pid <pid> --native` succeeds with native frames.

## Change

- Try the unprivileged py-spy first, as today.
- If it fails and `sudo -n true` succeeds, retry as `sudo -n env
PATH=... py-spy dump --pid <pid> --native` with the same timeout.
- Otherwise fall through to the Python-only dump, with py-spy's own
error message.
- This mirrors `_can_passwordless_sudo` in
`python/ray/dashboard/modules/reporter/profile_manager.py`, run
synchronously.
- `dump_stack_trace` is split into `_run_py_spy(cmd, timeout_s)` and
`_can_passwordless_sudo()`.

```
py-spy dump --native ──fail──> sudo -n true ok? ──yes──> sudo -n env PATH=... py-spy dump --native
                                      └──no──> Python-only dump (as today)
```

## Decisions to confirm

- The sudo check is cached per process, since the hung worker may dump
more than once.
- `sudo -n` is used everywhere so it can never prompt for a password.
- The `sudo -n true` check has a 5 s timeout.
- sudo is not tried when py-spy is not on `PATH`. A missing binary is
not a permission problem.
- The timeout is a budget for the whole dump. The sudo check and retry
only get what the first attempt left, so the fan-out timeout still
holds.

## Related

- Detector PRs by @pseudo-rnd-thoughts: #64928, #66203, #66629, #66627.
- Companion PR #67795 adds thread names to the Python-only fallback; the
two touch different parts of `dump_stack_trace` and apply independently.

Duplicate-work check: `gh pr list -R ray-project/ray --search "nccl_ras
OR hang detector"` and `--search "py-spy sudo"` returned nothing related
(only the unrelated Grafana PRs #66958 and #66810).

Tests: `python -m pytest
python/ray/train/v2/tests/test_nccl_ras_callback.py -v` passes, 120
passed, including four new `dump_stack_trace` sudo tests.

AI assistance (Claude Code) was used for this PR.

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

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
…mp (#67795)

## Problem

- py-spy is refused on many workers because ptrace is restricted in
containers. Every Anyscale worker is one of them (empty `CapEff`, Yama
`ptrace_scope` 1).
- The Python-only fallback is therefore the dump users actually see.
- It labels each thread with its numeric ident only. The reader has to
infer from the frames which one is Ray Train's
`TrainingThread(train_func)`, which is the `MonitoringThread`, and which
is the actor main thread.
- Current output, from a hung Ray Train worker on Anyscale:

```
# Thread 137667459151424
  File "/usr/lib/python3.12/threading.py", line 1030, in _bootstrap
    self._bootstrap_inner()
```

## Change

- `dump_stack_trace` looks up thread names once through
`threading.enumerate()` and prints the name next to the ident.
- The rest of the dump is unchanged.

```
before:  # Thread 137667459151424
after:   # Thread 137667459151424 (TrainingThread(train_func))
```

## Decisions to confirm

- Threads that are not in `threading.enumerate()` (threads not started
through `threading`, for example C-created ones) are labelled `unknown`.

## Related

- Detector PRs by @pseudo-rnd-thoughts: #64928, #66203, #66629, #66627.
- #67794 (sudo retry for py-spy) touches the same function but not these
lines. The two apply independently.

Duplicate-work check: `gh pr list -R ray-project/ray --search "nccl_ras
OR hang detector"` and a search for "thread name" with "nccl_ras" found
no PR making this change (only the Grafana and user-guide PRs #66958,
#66810, #67068 and the sibling #67794).

Test: `python -m pytest
python/ray/train/v2/tests/test_nccl_ras_callback.py -v` passes, 117
tests. `pre-commit run --files` on both files passes.

AI assistance (Claude Code) was used for this PR.

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

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>

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

Thanks, overall lgtm! Comment:

Image

It might just be simpler to have a single button that turns on/off all the annotations. But if you decide to keep them split, we should indicate in the naming they are annotations (e.g. ray.train.report call annotation). Also maybe we can consolidate the three "Custom Annotation" toggles to a single dropdown defining the threshold logging level.

Comment thread src/ray/protobuf/annotation_event.proto Resolved
Signed-off-by: Mark Towers <[email protected]>

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

Hi @pseudo-rnd-thoughts, this is a docs review of the new annotations section in configure-manage-dashboard.md, run by Douglas Strodtman from the Anyscale docs team. Claude Code assisted with the review. I've read every comment and stand behind it.

Scope. This review covers style, grammar, and Ray docs conventions against the Ray documentation style guide. Anything technical belongs to the Train and Core maintainers, and they have final approval. The suggestions keep the technical claims as written, with two exceptions. They name Ray Train as the only emitter, which I checked against the AnnotationEmitter call sites in this PR. They also replace Promtail, which Grafana's own docs list as end of life, with Grafana Alloy.

Overall the section is in good shape. The heading, the label, the procedure, and the reasons behind each step are all clear. The inline suggestions are small. I agree with @JasonLi1909's open suggestion to add a screenshot of the annotations on a Train panel. A reader setting up a collector and Loki will want to see what they're working toward.

Questions for the maintainers. These are not style blockers.

  1. ray.train.annotate is a new DeveloperAPI exported from ray.train, and its docstring links back to this section. However, the PR doesn't add it to the autosummary in doc/source/train/api/train-loop.md, so the docstring won't render in the API reference. No Train page links here either, so a Train user finds this feature only through the cluster dashboard page. Is that intentional for a DeveloperAPI? If not, adding ~train.annotate to train-loop.md, and adding a short pointer from the Train monitoring docs, would fix both.
  2. Step 1 hardcodes /tmp/ray/session_*/logs/. Is it worth a sentence noting that a custom --temp-dir changes this path? I haven't verified how the annotation writer resolves the logs dir under a custom temp dir, so I've left the step as written.

The docs side has no objection once these suggestions are resolved.

@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit d020a93 into ray-project:master Nov 9, 2026
5 checks passed
eugenepaniot added a commit to eugenepaniot/ray that referenced this pull request Nov 19, 2026
…floop-input

* upstream/master:
  [Data][3/n] update progress bar on lineage reconstruction (ray-project#67366)
  [Data] Enable the Top-N rewrite by default and expose it on DataContext (ray-project#68329)
  [Data] Adaptively skip map-side partial aggregation for high-cardinality keys (ray-project#68118)
  [Core] Spawn specific servers without preexec_fn to fix intermittent startup crashes (ray-project#67947)
  [Serve] Stop the __wrapped__ walk at non-callables (ray-project#67117)
  [Data] Deflake test_read_parquet_v2 by cutting redundant Ray Data executions (ray-project#68318)
  [Data] Retry FooterReader actor deaths with Ray Core and yield footers in listing order (ray-project#67988)
  [Data] Fix order-dependent schema unification when a list<null> arm is present (ray-project#68259)
  [Serve] Make @serve.batch work when wrapped in another decorator (ray-project#68177)
  [serve] Deflake test_metrics_3 - record the batch queue length once a batch is taken (ray-project#68302)
  [serve] Drop completed requests from the multiplexed model ID index (ray-project#68085)
  [Data] Fix flaky test_hudi: read each table once instead of sorting in Ray Data, keep size small (ray-project#68162)
  [Data] Fix flaky test_context: start 2 Ray clusters instead of 5 and keep size small (ray-project#68161)
  [Data] Fix flaky test_kafka: use recent timestamps in test_read_kafka_datetime_partial_range (ray-project#68248)
  [Data] Iceberg DSv2 [2/5]: The listing-to-reading manifest for Iceberg (ray-project#67951)
  [Train] Report training errors when the post-mortem debugger raises a BaseException (ray-project#68317)
  [RLlib] Skip the PPOConfig docstring example that crashes the rllib doctest target (ray-project#68306)
  [Train] Support post-mortem debugging for training function errors (ray-project#68296)
  [train][1/n] Give each health probe its own timeout (ray-project#68191)
  [Data] Fix unifying a fixed-shape tensor array with a lower-ndim variable-shaped one (ray-project#67266)
  [Train] Add a guide to debugging failures and hangs (ray-project#68299)
  [Data] Persist BlockMetadata.num_rows and batch ray.get in _calculate_blocks_rows (ray-project#67662)
  [Data] Vectorize LeRobot delta segment preparation and validate index contiguity (ray-project#67845)
  [Data] Avoid full-DataFrame apply in _AbstractKBinsDiscretizer._transform_pandas (ray-project#67862)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68303)
  [Data] Fix SimpleImputer on categorical columns in append mode and with existing category values (ray-project#67467)
  [Data] Replace O(N) list.pop(0) with deque.popleft() in PushBasedShuffleTaskScheduler (ray-project#67243)
  [Train] Reject an elastic ScalingConfig with max_workers=0 (ray-project#68218)
  [core][move semantics][3/n]Populate task args with is_move for movable refs (ray-project#66803)
  [core][sandbox] Remove the readonly option (ray-project#68088)
  [Data](1/n) Implement the line-chunk reader for CSV and JSONL on DataSource V2 (ray-project#67907)
  [Data] Set MIMALLOC_PURGE_DELAY=0 on random_shuffle to fix the pyarrow 25 OOM regression (ray-project#68151)
  [core] Quote each `uv run` argument in the uv runtime env hook (ray-project#68156)
  [core] Don't let gRPC cancel calls that wait over 30s in the server queue (ray-project#68210)
  [Data] Fix shuffle and join on native tensor columns with pyarrow 25+ (ray-project#68072)
  [serve][llm] Remove decode load progress (ray-project#68258)
  [ci] Bump sglang to 0.5.23 in release tests (ray-project#68250)
  [Core] Build the test auth token file locally so Windows tests can read it (ray-project#68262)
  [image] Bump EFA installer to 1.51.0 in CPU base-extra images (ray-project#67730)
  [serve] Observe the result of rank reassignment reconfigures (ray-project#67923)
  [Serve][Docs] Explain imperative vs declarative deploys and in-place updates from Python (ray-project#68243)
  [Data] (Fault tolerance) Ray Data lineage reconstruction docs (ray-project#68061)
  [RLlib] Add a multi-node footsies APPO memory release test (ray-project#67595)
  [Train] Remove local mode (ray-project#68239)
  [Data] Fix filtered Lance row-count metadata (ray-project#67228)
  [Serve][2/2] Propagate TracingConfig to proxies at startup (ray-project#65437)
  [Data] Fix synthesized path filtering in DataSourceV2 (ray-project#67079)
  [RLlib] Run the BCConfig Tune example one trial at a time to unblock the rllib doctest target (ray-project#68242)
  [Data][Delta DSv2][2/7] List Delta Lake table files from the log (ray-project#67888)
  [Data] Parallelize Parquet and ORC full-schema reads (ray-project#67542)
  [Data] Random Shuffle on Shuffle V2 Map/Reduce Operators (ray-project#68004)
  [Data] Propagate metadata prefetch thread failures to executor (ray-project#68171)
  [core] Send generator consumed-progress updates from io_service_ (ray-project#67160)
  [Data] Add @ray-data-connectors as codeowner for datasource/sinks files (ray-project#68154)
  [data][llm] Keep the prompt in vLLM error rows (ray-project#67665)
  [data][actor-only][3/n] Actor-only backend: operator fusion (ray-project#67699)
  [Data] Read text files on DataSource v2 (ray-project#68063)
  [Autoscaler][KubeRay] Never patch worker group replicas below minReplicas (ray-project#67332)
  [Serve] Show progress of updating (ray-project#67107)
  [core][test] Trigger usage-stats OOM test without exhausting host memory (ray-project#68009)
  [Serve] Remove unused RAY_SERVE_HAPROXY_INGRESS_RETRY_ON and RAY_SERV… (ray-project#68175)
  [Data] Implement lineage tracker garbage collection upon marking operator durable (ray-project#67788)
  [Core] Fix recovery suppression race in ObjectRecoveryManager (ray-project#64974)
  [serve] Pass grpc.so_reuseport to gRPC as an integer (ray-project#66816)
  [Autoscaler][v2] Preserve retry accounting when trimming status history (ray-project#67360)
  [doc] Refresh intersphinx inventory snapshots (ray-project#68069)
  [Doc] Add item to AGENTS.md to update documentation when modifying API-facing code. (ray-project#68204)
  [Train] Preserve `num_boost_round=0` and avoid mutating `callbacks` in legacy LightGBM/XGBoost trainers (ray-project#68145)
  [Train] Raise in prepare_data_loader instead of dropping a custom batch_sampler (ray-project#68201)
  [air] Return None in skip_exceptions when exc or StartTraceback cause is None (ray-project#68172)
  [Train] Fix `checkpoint_manager` to support metrics only reported in a validation function (ray-project#67909)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Refactor Disk shuffle map to use map Operator (ray-project#67130)
  [core][move semantics][2/n] Change state to moved on consumption and add enforcements (ray-project#66767)
  [Data] Propagate labels to object-store SHUFFLE_V2 map/reduce tasks (ray-project#67135)
  feat(core): add Cambricon MLU resource support (ray-project#66368)
  [Data] Make `zero_copy_batch=False` copy default batches (ray-project#67154)
  [data] Fix Parquet filename suffix detection (ray-project#67156)
  [data] Fix docstring/behavior mismatches in read_json and Dataset.sort (ray-project#66927)
  [Data] Run video_object_detection.ray on T4s with more memory (ray-project#68149)
  [core][sandbox] Let a node override network="public" sandboxes' default resolvers (ray-project#67691)
  [Data] read_mcap: resolve each sample's steps and lay out its row (ray-project#67925)
  [Data] read_mcap: sample read inputs: TopicSpec, steps, match and samples checks (ray-project#67924)
  [Data] Keep a map task's buffered rows when max_errored_blocks skips its error; read past corrupt MCAP chunks (ray-project#67167)
  [core][move semantics][1/n] Adding consume_once flag in actor methods (ray-project#66620)
  [Data] Size the schema pin and the columns Ray adds in the Parquet decoded-size estimate [3/6] (ray-project#67838)
  [Serve][LLM][1/3] Token based autoscaling: track autoscaling workload in KV router (ray-project#67937)
  [Data] Add native direct reads for nonpartitioned Hive tables (ray-project#67114)
  [Train] Count elastic workers in resource units for fractional resources (ray-project#68139)
  [Data] Add `condition` to `Dataset.join` and extract equi-join keys from it (ray-project#67590)
  [data] Add Top-N execution (ray-project#66931)
  [build] Bazel 8.8.1: bump protobuf to v29.6, rules_java to 8.12.0 and gRPC to 1.69.0 (ray-project#66483)
  [build] Use Arena::Create and pin Java 8 bytecode ahead of protobuf 29 / rules_java 8 (ray-project#67720)
  [core][sandbox] Don't join a sandbox's cgroup on every exec (ray-project#67690)
  [Data] Run `training_ingest_regression_test` on Instances that can be Provisioned (ray-project#68110)
  [Data] Run Sort on Disk-based Shuffle under SHUFFLE_V2 (ray-project#67850)
  [core] Deflake tests that race on timing (ray-project#67717)
  [ci] Bump pypa manylinux2014 base image to 2026.10.22-0 for CPython 3.15 (ray-project#67285)
  [Data] Make Mcap Data Column Test Insensitive to Struct Field Order (ray-project#68109)
  [Data] read_mcap V2: cut large files where their log-time order holds (ray-project#67166)
  [core][sandbox] Commit sandbox as new registry image (ray-project#67972)
  [Data] read_mcap V2: read neighbouring chunks in one ranged request (ray-project#67930)
  [train][4/n] Wire WorkerProbes through the HealthManager (ray-project#67915)
  [train][3/n] Add WorkerProbe results and health reports to the HealthState (ray-project#67879)
  [Data] (Data fault tolerance ray-project#6/6) Add a manual release test for lineage reconstruction (ray-project#67519)
  [train][6/n] Act on health decisions in the Ray Train controller (ray-project#67856)
  [Train] Do not start an elastic worker group with zero workers (ray-project#68101)
  [Train] Keep the last checkpoint after a metrics-only report in local mode (ray-project#68070)
  [Data][2/n] Migrate GPU Shuffle to Unified Phase Metrics (ray-project#67359)
  [Data][Chkpt] Fix `ArrowInvalid` when loading large generated-ID checkpoints (ray-project#68065)
  [core][test] Create auth token in test_redis_wrong_password (ray-project#68014)
  [data][actor-only][2/n] Actor-only backend: promote task pools to actor pools (ray-project#67698)
  [Data] Fix typing mismatches in Dataset public API (ray-project#62077)
  [Data] read_mcap V2: carry read tasks' summary records in the manifest (ray-project#67929)
  [Data] Distinguish generated ID collisions with synthesized columns (ray-project#67164)
  [Data] Fix incorrect scale-up in rate-based autoscaler for custom resources (ray-project#66647)
  [Data][Delta DSv2][1/7] Shared Parquet and partitioning fixes for the Delta reader (ray-project#67887)
  [Data] Eliminate redundant aggregation shuffle (ray-project#67198)
  [Data] Raise minimum supported pyarrow to 23.0.0 and test up to 26.0.1 (ray-project#68005)
  [Train] Use the default validation timeout when a report's ValidationTaskConfig has none (ray-project#68045)
  [doc][train] Use the global batch size in the TensorFlow Train examples (ray-project#68006)
  [TPU] Default multi-slice MASTER_ADDR to slice 0 host 0 in SlicePlacementGroup (ray-project#67878)
  [Data] Estimate a Parquet row group's decoded Arrow bytes from its footer [2/6] (ray-project#67837)
  [Data] Predicate pushdown through joins: split conjuncts, derive one-sided OR weakenings (ray-project#67122)
  [Data] Add partition_filters to read_delta and take file sizes from the log (ray-project#67900)
  [Data] Stop writing Unity Catalog vended credentials to the environment (ray-project#67899)
  [Data] Raise an error for Delta tables with column mapping in write_delta (ray-project#67898)
  [Core] Add initial foundational configurations and flags for fork server (ray-project#67356)
  [core][sandbox] Image layers caching (ray-project#67874)
  [Doc][Train] Add device stream batch prefetching section to accelerator guide (ray-project#67779)
  [Train] Use user-defined train function name in training thread name and error stack traces (ray-project#64292)
  [serve][docs] Remove beta label from custom autoscaling policies (ray-project#68046)
  [core] Don't treat a gRPC client with calls in flight as idle (ray-project#67718)
  [train] Fix checkpoint sorting to support nested metrics (ray-project#59130)
  [train][5/n] Run ControllerProbes on the controller's node monitor (ray-project#67671)
  [Train] Rank a checkpoint without the score attribute as worst in min order (ray-project#67901)
  [Core][RuntimeEnv] Stream runtime environment package downloads (ray-project#67184)
  [core] Deflake `_run_hanging_command` tests (ray-project#67461)
  [Data] Add Gravitino Iceberg REST catalog provider (ray-project#67007)
  [Data] Fix mixed-root partition filtering in Parquet and ORC V2 (ray-project#67067)
  [core] Keep absl logging at ERROR unless GRPC_VERBOSITY is set (ray-project#67719)
  [Data][1/n]Add Shuffle Metrics Unification Instrumentation (ray-project#66968)
  [ci][release] Stop publishing Python 3.10 wheels and images (ray-project#67722)
  [serve] Copy the ASGI lifespan state into each request scope (ray-project#67844)
  [Serve][LLM][4/5] Support scale-to-zero application routing (ray-project#67087)
  [core][sandbox] Let GPU sandboxes request NVIDIA profiling capabilities (ray-project#67974)
  [Serve][LLM] Exclude LLMRouter from dashboard QPS (ray-project#67873)
  [Data] Read the Parquet SizeStatistics PyArrow doesn't expose [1/6] (ray-project#67836)
  Add perf metrics for 2.60.0 (ray-project#67727)
  [Observability / Train] Add Grafana Annotation support with Ray Train usage (ray-project#66958)

Signed-off-by: Eugene Paniot <[email protected]>

# Conflicts:
#	python/ray/data/_internal/planner/plan_udf_map_op.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests train Ray Train Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants