Skip to content

[core] Converge ray.util debug and queue docstring examples to stock doctests - #66745

Merged
dstrodtman merged 5 commits into
masterfrom
doc-1636-core-testcode-doctests
Nov 2, 2026
Merged

dstrodtman merged 5 commits into
masterfrom
doc-1636-core-testcode-doctests

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What

Convert the remaining runnable .. testcode:: examples in ray.util to stock >>> doctests:

  • ray.util.debug.log_once
  • ray.util.queue.Queue

Why

.. testcode:: / .. testoutput:: is Sphinx-specific RST, run by Ray's fork of pytest-sphinx and not rendered by griffe/mkdocstrings. Stock >>> doctests render under both Sphinx and griffe and run under plain pytest --doctest-modules. This continues the convergence piloted in #65901 (ray.util.actor_pool, ray.util.placement_group), using the same conversion rules.

How the blocks convert

Same code, same order, same docstring. Each docstring stays one doctest item and moves from the pytest-sphinx collector to stock doctest.

  • assert lines stay as plain >>> lines, and existing expected output stays as the doctest's expected output.
  • Bare expressions whose repr is incidental are bound to _.
  • Blank lines inside a block are dropped, since a blank line ends a doctest example.

One behavior difference to know: a testcode block with no testoutput ignores stdout, but stock doctest fails on any unmatched stdout. Every converted block was run to confirm it prints nothing unexpected.

No expected output changes here. log_once only logs to stderr, and Queue checks with its existing assert.

Tests run

Locally, against a Ray nightly (43b706d) with the edited module overlaid, using pytest 7.4.4 and the same flags as the doctest Bazel macro: --doctest-modules -c NO_PYTEST_CONFIG -p <default_doctest_pytest_plugin>, with both collectors installed (stock doctest plus ray-project/pytest-sphinx). RAY_USAGE_STATS_PROMPT_ENABLED=0 suppresses the nightly-wheel-only usage banner, which source-built CI doesn't print. pre-commit passes on the changed files.

Module Before After
ray/util/debug.py 1 passed (pytest-sphinx) 1 passed (doctest)
ray/util/queue.py 1 passed (pytest-sphinx) 1 passed (doctest)

The test count is unchanged, and both stay in //python/ray/util:doctest. ray.util.helpers and ray.util.tpu still use :skipif: True testcode, which a later PR handles.

Rendering

Each converted example sits under a plural Examples: header, indented, with no blank line after the header. That is the only form that renders as an examples section on both Sphinx (napoleon) and griffe/mkdocstrings. Griffe's Google parser treats singular Example: as an admonition, treats a header followed by a blank line as plain text, and renders >>> in free prose as Markdown blockquotes. On Sphinx this only adds or renames the "Examples" rubric. Every changed docstring was rendered before and after with Sphinx 8.2.3 (autodoc, napoleon, sphinx.ext.doctest) and mkdocstrings-python 2.0.9 / griffelib 2.3.0. Sphinx output has no regressions, and every converted example renders as highlighted doctest code under griffe.

Duplicate check

gh pr list --state open --search for "testcode", "doctest", and the touched module names found no open PR converting these docstrings.

AI assistance

Drafted with AI assistance (Claude Code). The submitter reviews every changed line before marking this ready for review.

🤖 Generated with Claude Code

@dstrodtman
dstrodtman marked this pull request as ready for review October 5, 2026 19:29
@dstrodtman
dstrodtman requested a review from a team as a code owner October 5, 2026 19:29

@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 updates the documentation examples in python/ray/util/debug.py and python/ray/util/queue.py by converting the existing .. testcode:: blocks into standard >>> doctest format for better readability and consistency. I have no further feedback to provide.

dstrodtman and others added 2 commits October 5, 2026 16:22
…doctests

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
griffe only parses a plural Examples: header with content on the next line as an examples section; Sphinx napoleon renders either way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman force-pushed the doc-1636-core-testcode-doctests branch from ff8c71f to 0f8ab2e Compare October 5, 2026 20:22
@ray-gardener ray-gardener Bot added docs An issue or change related to documentation core Issues that should be addressed in Ray Core labels Oct 6, 2026
@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Oct 6, 2026
dstrodtman added a commit that referenced this pull request Oct 14, 2026
…ocstring examples, piloted on Ray Data (#66814)

> [!NOTE]
> **Draft proposal.** This PR is for agreeing on the direction before
the label extends past Ray Data. It's rebased on `master` now that
#66806 has merged.

## Why are these changes needed?

A docstring edit in `python/ray/<lib>/` routes like a code change, so it
runs every test suite that library's tag selects, and the `go` premerge
runs all of them before merge. Converting docstring examples from
Sphinx-only `.. testcode::` to stock `>>>` doctests produces a steady
stream of these PRs. On master, 398 `testcode` blocks in 147 files
remain.

Measured on seven recent docstring-only PRs, one premerge build each:

| PR | Library | Premerge runner-hours |
|---|---|---|
| #65901 | core | 39.6 |
| #66745 | core | 43.7 |
| #66749 | rllib | 15.3 |
| #66747 | train | 10.6 |
| #66746 | data | 10.3 |
| #66748 | tune | 8.6 |
| #66604 | data | 8.2 |

Runner-hours are summed job durations from the Buildkite API, so
queueing doesn't count.

None of those suites can fail on a docstring-only change, except through
a test that asserts on `__doc__` text. What a docstring edit can break
is the example code in the docstrings it touched.

## What this PR does

It adds a `docstring-only` PR label, piloted on Ray Data only. Under the
label, a Data PR runs the `>>>` examples in the docstrings of only the
modules it changed, plus the API checks and lint, instead of every Data
test suite.

- **The guard.** `lint: validate docstring-only scope` runs whenever the
label is present, is tagged `always`, and can't be turned off.
`ci/ray_ci/doc/check_docstring_only.py` parses each changed file at the
merge-base and at `HEAD` with Python's `ast`, removes the docstring from
the module and from every class and function, and compares `ast.dump` of
the two trees. It fails on any difference, on any file that isn't `.py`,
on any added, deleted, renamed, copied, or type-changed file, and on any
parse error. Comments aren't in the AST, so comment edits pass. A string
later in a body and a `__doc__` assignment both count as code.
- **What the label skips.** The 10 Data test steps in `data.rayci.yml`
that run on premerge get `if: '!(build.pull_request.labels includes
"docstring-only")'`, the same pattern `docs-go` used. `pyrefly type
check` isn't gated.
- **What it runs instead.** A new `data: docstring examples` step, gated
on the label, runs `ci/ray_ci/doc/run_docstring_examples.sh`:
1. It lists the `.py` files the PR modified under `python/ray/data/`,
excluding `tests/` and `examples/`, and exits if there are none.
1. It builds the Data CI image with the PR's Ray, using `test_in_docker
--build-only`, the same Ray install every Data test step uses.
1. In that image, it runs `ci/ray_ci/doc/run_docstring_examples.py` on
only those files.

The runner imports each module and extracts the `>>>` examples from
every docstring in the file. It runs each docstring's examples in order,
in a copy of the module's globals, as an interactive session would. An
example that shows output must print it, so those examples are unit
tests rather than smoke tests. Matching follows Ray's doctest targets:
`...` matches any text (pytest's default ELLIPSIS flag), and per-example
directives apply. An example that shows no output only has to run
without raising, and one that shows a traceback must raise a matching
exception. The standard library's doctest module supplies the parser and
the output comparison, with no doctest runner, pytest collection, or
Bazel doctest target. Examples still written as `.. testcode::` aren't
run.
- **Docs.** `doc/source/ray-contribute/ci.md` gets a "Docstring-only
changes" section.

### Design choices for review

- **Changed files only.** The unit is the changed module, not the
library. A PR that edits `aggregate.py` runs only `aggregate.py`'s
examples.
- **Output is checked where it's shown.** A stale result in an example
fails the step, the same as in Ray's doctest targets. Examples that show
nothing are smoke tests.
- **Data only.** Extending the label means an `if:` on most library test
steps in every per-library `*.rayci.yml`, which each library team owns.
This draft shows the shape on one library first. `ml: data integration
tests` also carries the `data` tag but lives in `ml.rayci.yml`, so it
still runs under the label.
- **Some image builds still run.** The label gates test steps, not the
`wanda` image builds they depend on. rayci selects steps by tag and
pulls in every image a selected step depends on, and it doesn't evaluate
`if:`. `wanda` steps can't take an `if:` either. Under the label, a Data
docstring PR still emits 5 image jobs that feed only the gated steps:
`datamongobuild-py3.10`, `datatfdsbuild-py3.12`, `docgpubuild-py3.10`,
`docgpubuild-py3.12`, and `oss-ci-base_gpu-py3.12`. On premerge builds
[74154](https://buildkite.com/ray-project/premerge/builds/74154) and
[74459](https://buildkite.com/ray-project/premerge/builds/74459), those
5 jobs took 4.1 and 10.1 minutes. Each takes about 50 seconds as a cache
hit, and `docgpubuild-py3.10` took 401 seconds on a miss. That's small
next to the 6.9 runner-hours the gated steps took. Dropping them needs a
rayci change that evaluates label gates before it marks dependencies.
The other 20 image jobs in the build feed a step the label keeps, or
rayci selects them on their own.
- **Known residual risk.** A test that asserts on `__doc__` text, or on
line numbers a docstring edit shifts, isn't visible to the guard. The
postmerge build is the backstop.

## Related issue number

None. Duplicate check: I searched open PRs for `docstring-only` and
`docstring only label`, and found no PR that adds a label or guard for
docstring-only changes.

## Tests run

- `pytest ci/ray_ci/doc/test_check_docstring_only.py
ci/ray_ci/doc/test_run_docstring_examples.py`: 29 passed. The runner's
tests cover examples that use module globals, a raising example that
fails with its file, line, and docstring name, wrong output that fails
with a diff, matching output with ELLIPSIS and a directive, expected and
mismatched exceptions, `+SKIP` and `+SKIP_EXAMPLE`, and no names leaking
between docstrings.
- The guard against real branches: it passes the three open docstring
PRs, #66745 (2 files), #66746 (1 file), and #66812 (5 files). It fails
#66806's branch and names the two `.py` files with code changes and the
three Markdown files.
- The runner against a Ray nightly (`43b706d`) on real branches. On
#66812's five files, 7 docstrings ran and passed in 24 seconds. On
#66746's `aggregate.py`, 18 docstrings ran and passed in 12 seconds.
With output checking, on six `master` Data modules that already use
`>>>` (`dataset.py`, `expressions.py`, `iterator.py`, `datatype.py`, and
two preprocessors), 113 of 118 docstrings passed in 36 seconds. The 5
failures are packages missing from the local environment (`torch`,
`tensorflow`, `crc32c`), not output mismatches.
- `--list-changed` in a scratch clone whose only change is a docstring
edit to `python/ray/data/aggregate.py` lists exactly that file.
- Pipeline generation with `rayci` built at `.rayciversion` (0.48.0),
for that simulated PR, on the premerge and microcheck pipeline IDs. Both
generate, with selected tags `always data lint`. Evaluating the
generated `if:` conditions shows the following:
- **Without the label:** the Data test steps match the real premerge
build of #66746
([74459](https://buildkite.com/ray-project/premerge/builds/74459)).
- **With `docstring-only`:** the 10 gated steps drop out, and `data:
docstring examples` and `lint: validate docstring-only scope` are added.
The API checks, `pyrefly`, `test-rules`, and `ml: data integration
tests` still run.
- The image jobs the label leaves running: I reran the same simulation
with the 10 gated steps removed from the YAML, which is what a rayci
change that evaluates label gates before marking dependencies would
emit. The build goes from 25 image jobs to 20. The 5 removed are listed
under "Some image builds still run." If the two `continuous-build` Data
steps are also dropped, `datalbuild-py3.12` goes too, for 6.
- Estimated saving on build 74459: the 10 gated steps took 6.9 of its
10.3 runner-hours. The new step adds one Data image build and a run of
seconds per changed file.
- `pre-commit` passes on the changed files.

Not yet run: the label on a real Buildkite build, including the
`--build-only` and `docker run` part of the new step. Nothing in the
repo evaluates Buildkite `if:` conditions, so the first labeled Data
docstring PR is the confirming check.

**AI assistance.** This change was drafted with Claude Code. I reviewed
every line and ran the tests above.

🤖 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]>
dstrodtman added a commit that referenced this pull request Oct 15, 2026
…tests (#66812)

## What

Convert the remaining runnable `.. testcode::` examples in six small
`ray.data` docstrings to stock `>>>` doctests:

- `DataContext.get_current`
- `FilenameProvider`
- `RowBasedFileDatasink` and `BlockBasedFileDatasink`
- `HiddenRecordFilter`
- `list_stats_summaries`

## Why

`.. testcode::` / `.. testoutput::` is Sphinx-specific RST, run by Ray's
fork of `pytest-sphinx` and not rendered by griffe/mkdocstrings. Stock
`>>>` doctests render under both Sphinx and griffe and run under plain
`pytest --doctest-modules`. This continues the convergence in #65901,
#66745, and #66746, with the same conversion rules:

- Same code, same order, same docstring. Each docstring stays one
doctest item.
- Bare expressions whose repr is incidental are bound to `_`: the two
`take_all()` calls in `get_current`.
- Blank lines inside a block are dropped, including between methods of a
class defined in the example.
- Existing `testoutput` becomes the doctest's expected output:
`list_stats_summaries` keeps `1`.
- Each example sits under a plural `Examples:` header with no blank line
after it, the form that renders on both Sphinx and griffe.
`FilenameProvider` keeps its lead-in sentence inside the section, and
`HiddenRecordFilter` gains the header.

## Not in this PR

- `ray.data._internal.util.MemoryProfiler` prints a varying value in a
loop. Stock doctest fails on unmatched stdout, so converting it means
changing the example, not just its markup.
- `SerializablePreprocessorBase._set_serializable_fields` shows a method
pattern in prose, not under an `Examples:` section.
- The `:skipif: True` examples in `util/torch_inference.py` and
`_internal/datasource/turbopuffer_datasink.py`, and
`preprocessors/torch.py`, which needs `torchvision`.
- `dataset.py`, `read_api.py`, and `llm.py`, which are larger and go in
their own PRs. `aggregate.py` is #66746.

## Duplicate check

I searched open PRs for `filename_provider`, `file_datasink`,
`list_stats_summaries`, `HiddenRecordFilter`, and `testcode doctest`.
The only related open PRs are my own #66745 and #66746, which touch
other modules.

## Tests run

Locally, against a Ray nightly (`43b706d`) with the edited modules
overlaid, using pytest 7.4.4 and the same flags as the `doctest` Bazel
macro: `--doctest-modules -c NO_PYTEST_CONFIG -p <Ray Data doctest
plugin>`, with both collectors installed (stock doctest plus
`ray-project/pytest-sphinx`). `RAY_USAGE_STATS_PROMPT_ENABLED=0`
suppresses the nightly-wheel-only usage banner. `pre-commit` passes on
the changed files.

| Modules | Before | After |
|---|---|---|
| The five changed files | 7 passed | 7 passed |
| The same, with pytest-sphinx disabled (`-p no:sphinx`) | n/a | 7
passed, so stock doctest runs every converted block |

The test count is unchanged, and everything stays in
`//python/ray/data:doctest`.

## CI note

The commit carries `@microcheck //python/ray/data:doctest`, which turned
out to be unnecessary. Microcheck ran `//python/ray/data:doctest` in the
`data: docs example tests` step and it passed ([build
55743](https://buildkite.com/ray-project/microcheck/builds/55743)). But
#66746, which had no such line, ran the same target in the same step
([build
55601](https://buildkite.com/ray-project/microcheck/builds/55601)).
Microcheck's changed-test lookup doesn't find these targets, because the
`doctest()` macro lists module files as `data`, not `srcs`. They run
anyway, through microcheck's high-impact or new-test sets. The line is
harmless, and Ray squash-merges with the PR title and body, so it never
reaches `master`.

**AI assistance.** This change was drafted with Claude Code. I reviewed
every line and ran the tests above.

🤖 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]>
dstrodtman added a commit that referenced this pull request Oct 20, 2026
## Why are these changes needed?

A `testcode` block reads as code that CI runs. On doc pages, 217 of them
never run. Most carry `:skipif: True`, which Ray's pytest-sphinx fork
drops before it builds an example, so the block never even shows up as
skipped. The rest sit on pages that no doctest target collects. Most of
these date from the semgrep `code-block-python` rule that required
`testcode`, which #65903 removed.

### Changes

- 45 doc pages: each never-run `testcode` block becomes a plain fenced
`python` block, or `.. code-block:: python` in rST. Its paired
`testoutput` becomes a `text` block. pytest-sphinx attaches a
`testoutput` to the nearest preceding `testcode`, so leaving one behind
would pin its output onto an earlier block that does run.
- The 8 never-run blocks marked `:hide:` are deleted. Readers never saw
them and CI never ran them.
- The `hasattr` self-check asserts in the collective backend example are
dropped. The asserts in `testing-tips.md` and the local-mode unit test
stay, because they're what those examples teach.
- `writing-code-snippets.md` no longer teaches `:skipif: True`. Code CI
can't run goes in a plain code block, with a `text` block for sample
output.
- `doc/test_prose_doctest_targets.py` and `doc/BUILD.bazel`:
`core/handling-dependencies.md` and `train/horovod.md` no longer hold a
runnable example, so they leave `UNTESTED`, and the BUILD comments that
explained their missing targets are trimmed.

Docstring `testcode` under `python/ray/` is out of scope. It's moving to
`>>>` examples in separate PRs, because `code-block` doesn't suit
docstrings.

## Duplicate check

No open PR covers this. Searches for `skipif`, `testcode`, and
`writing-code-snippets` return only my own docstring-convergence PRs
(#66745, #66746, #66812) and #66809, which this PR builds on and which
has merged.

## Testing

- For every changed page, I extracted examples with the pinned
pytest-sphinx fork (`ray-project/pytest-sphinx@c1ab2b33`,
`docstring2examples`, `pytest==7.4.4`) before and after the change. On
the 36 pages a doctest target collects, the examples are identical: same
source, expected output, and options. The 9 pages whose examples changed
are exactly the pages no target collects, so no test result changes.
- `python doc/test_prose_doctest_targets.py` passes: "45 listed pages;
every runnable page is accounted for." Without the two `UNTESTED`
removals, it fails on both as stale.
- `pre-commit run` on all changed files passes.
- No `:skipif:` remains under `doc/` except the guide's instruction not
to use it.
- Not run: a Sphinx build. The edits are directive-to-fence swaps, and
the Read the Docs preview is the check.

AI assistance (Claude Code) was used to write this change.

🤖 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]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 21, 2026
@dstrodtman dstrodtman added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 21, 2026
@dstrodtman dstrodtman added the docstring-only Skip heavy library tests for Ray API docstring edits. label Oct 28, 2026
dstrodtman added a commit that referenced this pull request Oct 29, 2026
…blocks (#67432)

## Description

Converts the last `>>>` doctest examples on documentation pages, so
`>>>` examples remain only in docstrings and on the two pages that teach
the docstring format. #67429 changes the contributor guidance to match.
This PR is independent of that stack and targets `master`.

Before this PR, seven pages under `doc/source/` had `>>>` prompts. Two
of them teach the docstring format and stay as they are:
`ray-contribute/writing-code-snippets.md` and
`ray-contribute/getting-involved.md`. This PR converts the other five:

| Page | Before | After | Test coverage |
|---|---|---|---|
| `data/working-with-tensors.md` | Three `{doctest}` blocks |
`{testcode}` and `{testoutput}` blocks | Unchanged. The `dtype` and
shape checks still run. The two per-image shapes the doctest skipped are
now a `+MOCK` sample. |
| `ray-references/glossary.md` | One `{doctest}` block with `+SKIP` on
every line | `{testcode}` and `{testoutput}` | Gained. The block used to
run nothing and now runs. The expected output is unchanged, because Ray
produces it exactly. |
| `serve/advanced-guides/multi-app-container.md` | `>>>` prompts in a
`python` fence, with every request skipped | Plain `python` and `text`
blocks | None before or after. The requests need the containerized Serve
apps running. The doctest only ran `import requests` and two string
assignments. |
| `core/tasks/nested-tasks.md` | REPL transcript in a `bash` block |
Plain `python` and `text` blocks | None before or after. The page's
`doc_code/` script is tested. |
| `serve/production-guide/fault-tolerance.md` | Interactive `$ python` /
`>>>` transcripts | Plain `python` blocks, with `text` blocks for output
| None before or after. These steps kill actors on a live cluster. |

### Test wiring

- `doc/BUILD.bazel`:
- Removes the Serve `doctest_each` call. Its only file was
`multi-app-container.md`, which no longer has a runnable example, so the
target would pass without testing anything.
- Drops the comment explaining why `nested-tasks.md` isn't listed, since
the page no longer has anything runnable to explain.
- The glossary and tensors entries stay, because both pages still have
runnable examples.
- `doc/test_prose_doctest_targets.py`: removes `nested-tasks.md` and
`fault-tolerance.md` from `UNTESTED`. Neither page has a runnable
example now. The two docstring-teaching pages stay exempt.

No `.buildkite/test.rules.txt` change. All prose routes to `doc_example`
whether or not a doctest target names the page, and the existing routing
cases for these pages still hold.

This PR edits `doc/BUILD.bazel`, so premerge runs every library's docs
example step. The glossary target is tagged `team:none`, which runs only
post-merge or with `docs-example-test`, so this PR carries that label
too.

## Related issues

Companion to #67429, which reserves `>>>` doctest-style examples for
docstrings in the contributor guide.

## Additional information

### Duplicate check

I searched open PRs for each converted page and for `doctest` in titles.
#66705 edits `fault-tolerance.md` around line 53, far from these hunks.
Draft #66851 appends a line to `nested-tasks.md` after these hunks.
Neither converts these examples. The docstring conversion PRs (#67238,
#66745, #67237) touch `python/`, not pages.

### Testing

I reproduced the CI doctest runner locally: Ray 2.59.0, Python 3.11,
`pytest==7.4.4`, `ray-project/pytest-sphinx@c1ab2b33`, the Ray Data
`doctest_pytest_plugin.py`, and the macro's `--doctest-modules
--doctest-glob='*.md' -c NO_PYTEST_CONFIG` arguments.

- `working-with-tensors.md`: passes before (2 items: the doctest blocks
and the testcode blocks) and after (1 item). A copy with a wrong
expected shape fails with `Expected (32, 28, 99) / Got (32, 28, 28)`, so
the new assertions are live.
- `glossary.md`: before, 1 skipped. After, 1 passed. A copy with a wrong
expected value fails.
- `python doc/test_prose_doctest_targets.py`: "73 listed pages; every
runnable page is accounted for."
- `pre-commit run --files` on the changed files passes, including
buildifier and buildifier-lint.
- `vale` on each changed page: no new alerts compared with `master`.
- After this PR, `git grep -l '^\s*>>> '` over `doc/source/*.md` and
`*.rst` returns only the two pages that teach the docstring format.
- The Read the Docs preview covers rendering.

This PR was prepared with AI assistance (Claude Code). I reviewed every
changed line.

🤖 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]>
@dstrodtman
dstrodtman merged commit d55aeef into master Nov 2, 2026
5 of 6 checks passed
@dstrodtman
dstrodtman deleted the doc-1636-core-testcode-doctests branch November 2, 2026 13:26
edoakes pushed a commit that referenced this pull request Nov 3, 2026
… them, to Ray Core public APIs (#67635)

## Summary

Documents the public Ray Core symbols that are still missing docstrings,
`Args:` entries, or `Returns:` sections in `ray.util`, `ray.util.queue`,
`ray.util.spark`, `ray.util.tpu`, `ray.experimental`, `ray.actor`,
`ray.remote_function`, `ray.types`, `ray.exceptions`, `ray.runtime_env`,
`ray.runtime_context`, and `ObjectRefGenerator`. Each docstring
describes existing behavior, written from the code.

Some of these symbols couldn't be documented without a signature change.
Ray's pydoclint config rejects an `Args:` section until every parameter
has a type hint, so this PR also adds type hints to the untyped public
signatures it documents. It also corrects five return annotations that
didn't match what the functions return.

#67540 applied the ruff `D212` and `D200` auto-fixes to these files, and
#67634 documented `ray.runtime_env`, `ray.exceptions`, and
`ObjectRefGenerator`. Both are merged. This PR builds on them and has
two commits: the docstring additions, then the type annotations. The
second commit was reviewed as #67636, which merged into this branch
instead of `master`.

Because the signatures change, this PR isn't docstring-only and runs the
full Core premerge.

## Docstrings

- `ray.util.queue`: `Empty` and `Full` are documented, and `Queue.size`,
`qsize`, `empty`, and `full` have `Returns:` sections.
- `ray.util.list_named_actors` documents `all_namespaces` and returns,
including the dict entries it returns when `all_namespaces` is True.
- `ray.util.spark.setup_global_ray_cluster` documents all 17 parameters
and what it returns. Most entries follow the matching
`setup_ray_cluster` parameter, which the existing docstring already says
they share, and point to it for defaults and caps.
- `ray.util.tpu.dispatch`, the deprecated alias of `run_on_slice`, gets
`Args:` and `Returns:` sections. Adding `Returns:` makes pydoclint check
`*args` and `**kwargs`, so they're documented too.
- `ray.experimental`: `CompiledDAGRef.get` and the `CompiledDAGFuture`
constructor parameters, the `RayActorHandleResolver` constructor and its
`get`, `forget`, `list_names`, and `kill` methods, and the `ReduceOp`,
`AllGatherOp`, `AllReduceOp`, `ReduceScatterOp`, and `Device` types are
documented.
- `ActorMethod.__call__` and `remote`, `ActorClassInheritanceException`,
`RemoteFunction.__call__`, and `ray.types.ObjectRef` have docstrings.

## Type hints

Type hints added, with the parameters documented in the same change:

- `ObjectRefGenerator.send`, `throw`, `asend`, and `athrow`: `value:
Any`. Each method only raises `NotImplementedError`, and the docstrings
say so.
- `RayError.from_bytes(b: bytes) -> BaseException` and
`from_ray_exception(ray_exception: RayException) -> BaseException`.
- The constructors of `CrossLanguageError`, `RayTaskError`,
`RaySystemError`, `OutOfMemoryError`, and `NodeDiedError`.
- `RuntimeContext.__init__(worker: Any)`. The worker is either the
global Ray worker or Ray Client's `_ClientWorkerPropertyAPI`, which
emulates it, so `Any` is the honest hint without new imports.
- `RuntimeEnv.get(name: str, default: Any = None, data_class:
Optional[type] = None) -> Any` and `get_extension(key: str)`.

Return annotations corrected to match the code:

- `RuntimeEnv.has_conda`: `str` to `bool`.
- `RuntimeEnv.conda_env_name` and `conda_config`: `str` to
`Optional[str]`. Both return None when `conda` isn't set or has the
other form.
- `RuntimeEnv.py_container_run_options`: `List` to `Optional[List]`. It
returns None when `container` isn't set.
- `ray.util.list_named_actors`: `List[str]` to `Union[List[str],
List[Dict[str, str]]]`. With `all_namespaces=True`, it returns dicts
with `name` and `namespace` keys.

`AsyncioRouter` in `python/ray/serve/_private/router.py` reads
`RayTaskError.cause` into a local variable before the `ActorDiedError`
check instead of calling `getattr` in the condition. It returns the same
value in the same cases.

Type hints don't change runtime behavior. None of these files are in
Ray's mypy hook.

## For reviewers

CODEOWNERS adds two reviewers beyond `@ray-project/ray-core`:
`@ray-project/ray-serve` for `serve/_private/router.py`, and one of the
individual owners of `util/tpu.py`.

These are worth a close read:

- `setup_global_ray_cluster` returns the `(address,
remote_connection_address)` tuple only when `is_blocking` is False. When
blocking, it returns None after the cluster shuts down.
- `CompiledDAGRef.get` describes the `timeout` values from
`CompiledDAG._execute_until`, which it calls. `ray.get()` on a
CompiledDAGRef calls this method.
- `Device` describes its members from the `device` argument of
`TorchTensorType`.
- `RayTaskError.cause` is hinted `BaseException`, which matches what the
task-execution path in `_raylet.pyx` and `CompiledDAG` pass. `actor_id`
is the actor ID in hex, as `_raylet.pyx` computes it.
- `RaySystemError.client_exc` is hinted `str`. The callers in
`worker.py`, `serialization.py`, and `_raylet.pyx` pass a message
string, despite the parameter name.
- `RayError.from_bytes` and `from_ray_exception` return `BaseException`:
an unpickled exception, an `UnserializableException`, or a
`CrossLanguageError`.

`ray.util.client.api.ClientAPI.list_named_actors` has the same
`List[str]` annotation for Ray Client. It isn't public API, so this PR
leaves it alone.

## Duplicate check

No open PR documents these symbols or changes these signatures. I
searched open PRs for the module, class, and method names. #66745
converts the `Queue` class docstring example to doctest form, which
doesn't overlap the lines this PR changes.

## Testing

These checks ran on each commit before the rebase onto `master`. The
rebase applied both commits unchanged.

- The full pre-commit suite on every changed file, including ruff,
black, pydoclint, and the docstyle hook: passed.
- `uvx [email protected] check --select D212,D200,D210` on the changed files:
passed.
- The docstring commit passed `ci/ray_ci/doc/check_docstring_only.py`.
The type-annotation commit changes signatures, so it's outside that
guard by design.
- A smoke test against the latest nightly wheel with the type-annotated
files overlaid: a task error and an actor task error round-trip through
`to_bytes` and `from_bytes`, `ray.get_runtime_context()` works in the
driver and in an actor, the exception constructors format their
messages, `RuntimeEnv.get`, `get_extension`, and the re-annotated
accessors return what their annotations now say, and the streaming
generator's `send`, `throw`, `asend`, and `athrow` raise
`NotImplementedError`.
- `python/ray/tests/unit/test_runtime_env.py` and
`test_runtime_env_validation.py` against the same overlay: 96 passed, 12
failed. The same 12 fail with `master`'s versions of those files in the
same environment, because the nightly wheel's commit and the copied test
fixtures don't match this checkout, so none come from this change.
- Both commits carry an `@rtd-build` line, so the Read the Docs preview
renders the changed docstrings.

AI assistance (Claude Code) was used to prepare this PR.

🤖 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]>
pawelbeza pushed a commit to pawelbeza/ray that referenced this pull request Nov 9, 2026
… them, to Ray Core public APIs (ray-project#67635)

## Summary

Documents the public Ray Core symbols that are still missing docstrings,
`Args:` entries, or `Returns:` sections in `ray.util`, `ray.util.queue`,
`ray.util.spark`, `ray.util.tpu`, `ray.experimental`, `ray.actor`,
`ray.remote_function`, `ray.types`, `ray.exceptions`, `ray.runtime_env`,
`ray.runtime_context`, and `ObjectRefGenerator`. Each docstring
describes existing behavior, written from the code.

Some of these symbols couldn't be documented without a signature change.
Ray's pydoclint config rejects an `Args:` section until every parameter
has a type hint, so this PR also adds type hints to the untyped public
signatures it documents. It also corrects five return annotations that
didn't match what the functions return.

ray-project#67540 applied the ruff `D212` and `D200` auto-fixes to these files, and
ray-project#67634 documented `ray.runtime_env`, `ray.exceptions`, and
`ObjectRefGenerator`. Both are merged. This PR builds on them and has
two commits: the docstring additions, then the type annotations. The
second commit was reviewed as ray-project#67636, which merged into this branch
instead of `master`.

Because the signatures change, this PR isn't docstring-only and runs the
full Core premerge.

## Docstrings

- `ray.util.queue`: `Empty` and `Full` are documented, and `Queue.size`,
`qsize`, `empty`, and `full` have `Returns:` sections.
- `ray.util.list_named_actors` documents `all_namespaces` and returns,
including the dict entries it returns when `all_namespaces` is True.
- `ray.util.spark.setup_global_ray_cluster` documents all 17 parameters
and what it returns. Most entries follow the matching
`setup_ray_cluster` parameter, which the existing docstring already says
they share, and point to it for defaults and caps.
- `ray.util.tpu.dispatch`, the deprecated alias of `run_on_slice`, gets
`Args:` and `Returns:` sections. Adding `Returns:` makes pydoclint check
`*args` and `**kwargs`, so they're documented too.
- `ray.experimental`: `CompiledDAGRef.get` and the `CompiledDAGFuture`
constructor parameters, the `RayActorHandleResolver` constructor and its
`get`, `forget`, `list_names`, and `kill` methods, and the `ReduceOp`,
`AllGatherOp`, `AllReduceOp`, `ReduceScatterOp`, and `Device` types are
documented.
- `ActorMethod.__call__` and `remote`, `ActorClassInheritanceException`,
`RemoteFunction.__call__`, and `ray.types.ObjectRef` have docstrings.

## Type hints

Type hints added, with the parameters documented in the same change:

- `ObjectRefGenerator.send`, `throw`, `asend`, and `athrow`: `value:
Any`. Each method only raises `NotImplementedError`, and the docstrings
say so.
- `RayError.from_bytes(b: bytes) -> BaseException` and
`from_ray_exception(ray_exception: RayException) -> BaseException`.
- The constructors of `CrossLanguageError`, `RayTaskError`,
`RaySystemError`, `OutOfMemoryError`, and `NodeDiedError`.
- `RuntimeContext.__init__(worker: Any)`. The worker is either the
global Ray worker or Ray Client's `_ClientWorkerPropertyAPI`, which
emulates it, so `Any` is the honest hint without new imports.
- `RuntimeEnv.get(name: str, default: Any = None, data_class:
Optional[type] = None) -> Any` and `get_extension(key: str)`.

Return annotations corrected to match the code:

- `RuntimeEnv.has_conda`: `str` to `bool`.
- `RuntimeEnv.conda_env_name` and `conda_config`: `str` to
`Optional[str]`. Both return None when `conda` isn't set or has the
other form.
- `RuntimeEnv.py_container_run_options`: `List` to `Optional[List]`. It
returns None when `container` isn't set.
- `ray.util.list_named_actors`: `List[str]` to `Union[List[str],
List[Dict[str, str]]]`. With `all_namespaces=True`, it returns dicts
with `name` and `namespace` keys.

`AsyncioRouter` in `python/ray/serve/_private/router.py` reads
`RayTaskError.cause` into a local variable before the `ActorDiedError`
check instead of calling `getattr` in the condition. It returns the same
value in the same cases.

Type hints don't change runtime behavior. None of these files are in
Ray's mypy hook.

## For reviewers

CODEOWNERS adds two reviewers beyond `@ray-project/ray-core`:
`@ray-project/ray-serve` for `serve/_private/router.py`, and one of the
individual owners of `util/tpu.py`.

These are worth a close read:

- `setup_global_ray_cluster` returns the `(address,
remote_connection_address)` tuple only when `is_blocking` is False. When
blocking, it returns None after the cluster shuts down.
- `CompiledDAGRef.get` describes the `timeout` values from
`CompiledDAG._execute_until`, which it calls. `ray.get()` on a
CompiledDAGRef calls this method.
- `Device` describes its members from the `device` argument of
`TorchTensorType`.
- `RayTaskError.cause` is hinted `BaseException`, which matches what the
task-execution path in `_raylet.pyx` and `CompiledDAG` pass. `actor_id`
is the actor ID in hex, as `_raylet.pyx` computes it.
- `RaySystemError.client_exc` is hinted `str`. The callers in
`worker.py`, `serialization.py`, and `_raylet.pyx` pass a message
string, despite the parameter name.
- `RayError.from_bytes` and `from_ray_exception` return `BaseException`:
an unpickled exception, an `UnserializableException`, or a
`CrossLanguageError`.

`ray.util.client.api.ClientAPI.list_named_actors` has the same
`List[str]` annotation for Ray Client. It isn't public API, so this PR
leaves it alone.

## Duplicate check

No open PR documents these symbols or changes these signatures. I
searched open PRs for the module, class, and method names. ray-project#66745
converts the `Queue` class docstring example to doctest form, which
doesn't overlap the lines this PR changes.

## Testing

These checks ran on each commit before the rebase onto `master`. The
rebase applied both commits unchanged.

- The full pre-commit suite on every changed file, including ruff,
black, pydoclint, and the docstyle hook: passed.
- `uvx [email protected] check --select D212,D200,D210` on the changed files:
passed.
- The docstring commit passed `ci/ray_ci/doc/check_docstring_only.py`.
The type-annotation commit changes signatures, so it's outside that
guard by design.
- A smoke test against the latest nightly wheel with the type-annotated
files overlaid: a task error and an actor task error round-trip through
`to_bytes` and `from_bytes`, `ray.get_runtime_context()` works in the
driver and in an actor, the exception constructors format their
messages, `RuntimeEnv.get`, `get_extension`, and the re-annotated
accessors return what their annotations now say, and the streaming
generator's `send`, `throw`, `asend`, and `athrow` raise
`NotImplementedError`.
- `python/ray/tests/unit/test_runtime_env.py` and
`test_runtime_env_validation.py` against the same overlay: 96 passed, 12
failed. The same 12 fail with `master`'s versions of those files in the
same environment, because the nightly wheel's commit and the copied test
fixtures don't match this checkout, so none come from this change.
- Both commits carry an `@rtd-build` line, so the Read the Docs preview
renders the changed docstrings.

AI assistance (Claude Code) was used to prepare this PR.

🤖 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]>
Signed-off-by: Pawel Beza <[email protected]>
Upstream-commit: 6357e3c (sandbox resolver only; unrelated API changes excluded)
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 0baa3cf-af4e-472e-ad89-8f02c6e8be11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Issues that should be addressed in Ray Core docs An issue or change related to documentation docstring-only Skip heavy library tests for Ray API docstring edits. go add ONLY when ready to merge, run all tests 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