Skip to content

[core] Converge ray.util docstring examples from testcode to stock doctests - #65901

Merged
dstrodtman merged 1 commit into
masterfrom
doc-1636-apiref-testcode-actor-pool
Sep 18, 2026
Merged

dstrodtman merged 1 commit into
masterfrom
doc-1636-apiref-testcode-actor-pool

Conversation

@dstrodtman

Copy link
Copy Markdown
Contributor

What

Convert the runnable examples in two ray.util docstrings from Sphinx
.. testcode:: / .. testoutput:: to stock >>> doctests:

  • ray.util.actor_pool (ActorPool and its methods)
  • ray.util.placement_group (PlacementGroup.ready, get_current_placement_group)

Why

.. testcode:: is Sphinx-specific. It couples the example surface to Ray's
pytest-sphinx fork and is not rendered by griffe/mkdocstrings, the static
API-ref generator currently under evaluation. Stock >>> doctests are native
reStructuredText, render under both Sphinx and griffe, and are still collected
and run by pytest --doctest-modules. This drops the Sphinx-testcode coupling
for these modules without changing what renders or what CI runs.

How the blocks convert

  • Output-validating examples keep their expected output as the doctest's
    expected output. assert-based examples become plain >>> lines.
  • Smoke examples with bare expressions bind the result to _ so they stay
    runnable without asserting an incidental repr.
  • Never-validated examples (previously .. testoutput:: :options: +MOCK,
    shown but unchecked because the result order is nondeterministic) become
    >>> doctests with # doctest: +SKIP on the nondeterministic line. The
    setup still runs; only the unvalidated output is skipped. This keeps the
    snippet in a tested framework, consistent with Ray's code-block-python
    policy that shown Python must be testcode/doctest rather than an untested
    .. code-block:: python.

Test-count impact

Neutral. Every block stays in the same doctest target
(//python/ray/util:doctest) and the same pytest run. Runnable blocks move
from the pytest-sphinx collector to native doctest.

Scope

Pilot for a broader convergence of the API-ref docstring testcode surface. Two
modules here — one @DeveloperAPI, one @PublicAPI — to validate the mechanics
and the test-count parity in CI before scaling.

🤖 Generated with Claude Code

@dstrodtman
dstrodtman requested a review from a team as a code owner September 3, 2026 18:23

@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 refactors the documentation examples in actor_pool.py and placement_group.py by converting Sphinx .. testcode:: directives into standard Python doctests. The review feedback suggests improving the doctests for unordered operations (map_unordered and get_next_unordered) by sorting the results, which allows the tests to be deterministically validated rather than skipped.

Comment thread python/ray/util/actor_pool.py Resolved
Comment thread python/ray/util/actor_pool.py Resolved
@ray-gardener ray-gardener Bot added docs An issue or change related to documentation core Issues that should be addressed in Ray Core labels Sep 3, 2026
…ctests

Ray's public API-ref docstrings carry runnable examples as Sphinx
`.. testcode::` / `.. testoutput::`, which the pytest-sphinx fork collects under
`--doctest-modules`. That construct is Sphinx-specific: it couples the example
surface to the fork and is not rendered by griffe/mkdocstrings, the static
API-ref generator under evaluation.

Convert the examples in `ray.util.actor_pool` and `ray.util.placement_group` to
stock `>>>` doctests, which are native reStructuredText, render under both
Sphinx and griffe, and are still collected and run by `--doctest-modules`:

- Output-validating examples keep their expected output as the doctest's
  expected output; `assert`-based examples become plain `>>>` lines.
- Bare-expression smoke lines are bound to `_` so they stay runnable without
  asserting an incidental repr.
- The `map_unordered` and `get_next_unordered` examples were previously marked
  `+MOCK` (shown but unvalidated) because result order is nondeterministic.
  Rather than skip them, validate order-independently with a set membership
  check (`set(results) == {...}`), which is the correct assertion for an
  unordered API and doesn't imply the output is sorted.

Every example is now a runnable, validated doctest. Test-count neutral: each
block stays in the same doctest target (`//python/ray/util:doctest`) and the
same pytest run, moving from the pytest-sphinx collector to native doctest.

Pilot for a broader convergence of the API-ref testcode surface.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman force-pushed the doc-1636-apiref-testcode-actor-pool branch from b811211 to e8e6056 Compare September 3, 2026 19:24
@dstrodtman

Copy link
Copy Markdown
Contributor Author

Thanks @gemini-code-assist — good call that the map_unordered / get_next_unordered examples don't need to be skipped. Adopted the determinism idea so both are now validated rather than # doctest: +SKIP.

One tweak from the exact suggestion: rather than sorted(...), I validate with an order-independent set-membership check:

>>> results = pool.map_unordered(lambda a, v: a.double.remote(v), [1, 2, 3, 4])
>>> set(results) == {2, 4, 6, 8}
True

sorted() would render in the docs as if the output were ordered, which is a mild anti-pattern for an intentionally-unordered API (someone who wants ordering should use map() / get_next()). set(...) == {...} is the correct assertion for unordered results and keeps the rendered example honest. Every example in the PR is now a runnable, validated doctest.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

That's a great approach. Using set(results) == {...} is the idiomatic and semantically correct way to validate unordered results in Python, as it avoids unnecessary sorting overhead and clearly communicates the expected behavior of the API. Thanks for ensuring all examples are now fully validated!

@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Sep 3, 2026
@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 Sep 18, 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 Sep 18, 2026

@edoakes edoakes left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks great. Just to be clear, in this example, the output of the example is asserted to match [2, 4, 6, 8], right?

        >>> import ray
        >>> from ray.util.actor_pool import ActorPool
        >>> @ray.remote
        ... class Actor:
        ...     def double(self, v):
        ...         return 2 * v
        >>> a1, a2 = Actor.remote(), Actor.remote()
        >>> pool = ActorPool([a1, a2])
        >>> print(list(pool.map(lambda a, v: a.double.remote(v),
        ...                     [1, 2, 3, 4])))
        [2, 4, 6, 8]

@dstrodtman
dstrodtman merged commit 40bca40 into master Sep 18, 2026
7 checks passed
@dstrodtman
dstrodtman deleted the doc-1636-apiref-testcode-actor-pool branch September 18, 2026 19:47
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ctests (ray-project#65901)

## What

Convert the runnable examples in two `ray.util` docstrings from Sphinx
`.. testcode::` / `.. testoutput::` to stock `>>>` doctests:

- `ray.util.actor_pool` (`ActorPool` and its methods)
- `ray.util.placement_group` (`PlacementGroup.ready`,
`get_current_placement_group`)

## Why

`.. testcode::` is Sphinx-specific. It couples the example surface to
Ray's
`pytest-sphinx` fork and is not rendered by griffe/mkdocstrings, the
static
API-ref generator currently under evaluation. Stock `>>>` doctests are
native
reStructuredText, render under both Sphinx and griffe, and are still
collected
and run by `pytest --doctest-modules`. This drops the Sphinx-testcode
coupling
for these modules without changing what renders or what CI runs.

## How the blocks convert

- **Output-validating examples** keep their expected output as the
doctest's
  expected output. `assert`-based examples become plain `>>>` lines.
- **Smoke examples** with bare expressions bind the result to `_` so
they stay
  runnable without asserting an incidental repr.
- **Never-validated examples** (previously `.. testoutput:: :options:
+MOCK`,
shown but unchecked because the result order is nondeterministic) become
`>>>` doctests with `# doctest: +SKIP` on the nondeterministic line. The
setup still runs; only the unvalidated output is skipped. This keeps the
snippet in a tested framework, consistent with Ray's `code-block-python`
policy that shown Python must be testcode/doctest rather than an
untested
  `.. code-block:: python`.

## Test-count impact

Neutral. Every block stays in the same doctest target
(`//python/ray/util:doctest`) and the same `pytest` run. Runnable blocks
move
from the pytest-sphinx collector to native doctest.

## Scope

Pilot for a broader convergence of the API-ref docstring testcode
surface. Two
modules here — one `@DeveloperAPI`, one `@PublicAPI` — to validate the
mechanics
and the test-count parity in CI before scaling.

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

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
dstrodtman added a commit that referenced this pull request Oct 7, 2026
…ly examples (#66753)

## What

Adds a docstring-level doctest flag, `# doctest: +SKIP_EXAMPLE`, for
render-only examples. One flag on any line of a docstring's `>>>`
examples skips that whole docstring at collection time.

- `bazel/default_doctest_pytest_plugin.py` and
`python/ray/data/tests/doctest_pytest_plugin.py` register the flag with
`doctest.register_optionflag` and add a `pytest_collection_modifyitems`
hook that marks the matching `DoctestItem`s skipped. The two plugins
load separately (Data's targets pass their own `pytest_plugin_file`), so
the ~10 lines are duplicated with a keep-in-sync comment. That's simpler
than adding the default plugin as a Bazel `data` dependency of every
Data doctest target.
- First user: the three `ray.util.tpu` examples (`SlicePlacementGroup`,
`run_on_slice`, `subslice_placement_group`). They need TPU hardware and
were `.. testcode:: :skipif: True`. They're now `>>>` examples flagged
once, indented under their `Examples:` header.

## Why

This continues the convergence of docstring examples from Sphinx `..
testcode::` to stock `>>>` doctests (#65901 and follow-ups), which
render under both Sphinx and griffe/mkdocstrings. For examples that can
never run in CI, the stock option is `# doctest: +SKIP` on every
statement. Across the remaining `:skipif: True` blocks that's about 700
flags, which is noisy in source. The other forms considered don't render
on both toolchains:

- `.. code-block:: python`: griffe shows the directive line as literal
text.
- A Markdown code fence: Sphinx renders it as inline text.
- An RST `::` literal block: griffe shows the `::`.

Both Sphinx (`trim_doctest_flags`) and griffe (`trim_doctest_flags`,
regex `#\s*doctest:.+$`) strip any `# doctest:` comment from rendered
output, so a single custom flag stays invisible to readers.

## Behavior

- A docstring carrying the flag is reported as `SKIPPED (render-only
example (+SKIP_EXAMPLE))`. Nothing in it executes.
- A docstring without the flag is unaffected.
- Without the plugin, collection fails with `ValueError: ... has an
invalid option: '+SKIP_EXAMPLE'`. If the plugin goes missing, the build
breaks instead of silently running examples that can't run.
- No `doc/source/conf.py` change is needed. `MOCK` is registered there
because `sphinx.ext.doctest` validates `:options:` on `testoutput`
directives, and this flag appears only on `>>>` lines. A Sphinx 8.2.3
build of these docstrings with `autodoc`, `napoleon`, and
`sphinx.ext.doctest` emits no warnings.

## Test-count impact

`ray/util/tpu.py` goes from 0 collected items (pytest-sphinx drops
`:skipif: True` blocks before creating an item) to 3 reported as
skipped. Nothing new executes.

## Tests run

Locally, against a Ray nightly with the edited module and plugin
overlaid, using pytest 7.4.4 and the `doctest` macro's flags
(`--doctest-modules -c NO_PYTEST_CONFIG -p <plugin>`), with both the
stock doctest and `ray-project/pytest-sphinx` collectors installed:

| Run | Result |
|---|---|
| `ray/util/tpu.py`, new default plugin | 3 skipped, `render-only
example (+SKIP_EXAMPLE)` |
| `ray/util/tpu.py`, new Ray Data plugin | 3 skipped |
| `ray/util/tpu.py`, current default plugin | Collection error on the
unknown flag (fails loudly) |
| `ray/util/queue.py` (unflagged), new default plugin | 1 passed |
| `ray/data/aggregate.py` (unflagged), new Ray Data plugin | 17 passed |

Rendering: each of the three docstrings was rendered before and after
with Sphinx 8.2.3 and with `mkdocstrings-python` 2.0.9 / `griffelib`
2.3.0. Sphinx output is unchanged (a highlighted code block under the
"Examples" rubric). Under griffe each now renders as an examples section
with highlighted prompts, where before it showed a literal `..
testcode:: python` line. `SKIP_EXAMPLE` appears in neither rendered
page. `pre-commit` passes on the changed files.

## Duplicate check

`gh pr list --state open --search` for "doctest", "SKIP",
"doctest_pytest_plugin", and "tpu docstring" found no open PR adding a
docstring-level skip or touching these examples.

## AI assistance

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

🤖 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 7, 2026
…ctests (#66748)

## What

Convert the runnable `.. testcode::` examples in two Tune modules to
stock `>>>` doctests, and fix one broken example:

- `ray.tune.Trainable`: `default_resource_request`, `trial_name`,
`trial_id`, `trial_resources`
- `ray.tune.Callback.get_state`
- **Bug fix:** the `ray.tune.Callback` class example called
`tune.report(metric=i)`, which raises `TypeError` inside every trial
under the current `tune.report(metrics: dict)` signature. The test still
passed because `tuner.fit()` doesn't raise on trial failure and the
hidden `...` testoutput matches anything. The call is now
`tune.report({"metric": i})`, and the callback prints all ten results.

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

## Examples that now check something

- **`trial_name`, `trial_id`, `trial_resources`:** each one assigned the
property and checked nothing. They now show the value on a bare
`Trainable()` as expected output: `'default'`, `'default'`, and `None`.
- **`default_resource_request`:** this one defined a module-level
`@classmethod` that was never called, with an unimported
`PlacementGroupFactory`, so it ran only because nothing invoked it. It
now overrides the method on a `Trainable` subclass and checks
`required_resources` (`{'CPU': 2.0}`). This is a small rewrite rather
than a pure conversion, so please check that it still shows what the
docstring means.

## 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/tune/trainable/trainable.py` | 6 passed | 6 passed (4 now under
doctest) |
| `ray/tune/callback.py` | 2 passed | 2 passed (`get_state` now under
doctest) |

I also confirmed the fixed `Callback` example prints `Got result: ...`
ten times, and it no longer logs trial failures.

## Left as testcode, and why

Three blocks pair `testcode` with a `.. testoutput:: :hide:` whose body
is `...`: the `Callback` class example, `ResultGrid`, and
`ResultGrid.get_dataframe`. Each one runs `Tuner.fit()`, which writes
progress tables with timestamps, paths, and trial IDs to stdout. The
hidden `...` swallows that output. Stock doctest has no run-but-hide
form, and an expected-output section can't start with `...`, so
converting these means changing the example, for example by lowering
verbosity. That's left for a follow-up.

## 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](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 7, 2026
…#66749)

## What

Convert every `.. testcode::` example in
`ray.rllib.algorithms.algorithm_config` to stock `>>>` doctests (8
blocks):

- `AlgorithmConfig`: the class docstring (2 blocks), `from_dict`,
`overrides` (2 blocks), `__getitem__`, and `get_multi_agent_setup`
- `DifferentiableAlgorithmConfig`

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

## Examples that now check something

- **`get_multi_agent_setup`:** this example ran
`is_policy_to_train("pol1")` and `("pol2")` but never checked the
results. It now shows `True` and `False` as expected output.
- **The `AlgorithmConfig` class example:** `config.training(...)` and
`tune.Tuner(...)` are bound to `_`. The `Tuner` repr includes a memory
address.

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

`TF_USE_LEGACY_KERAS=1` is set to match `//python/ray/rllib:doctest`.
`--noconftest` is used locally only, because `rllib/conftest.py` imports
`ray.tests.conftest`, which the wheel doesn't ship.

| Module | Before | After |
|---|---|---|
| `ray/rllib/algorithms/algorithm_config.py` | 6 passed (pytest-sphinx)
| 6 passed (doctest) |

The test count is unchanged.

## 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](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 7, 2026
…#66747)

## What

Convert the `.. testcode::` examples in
`ray.train.torch.TorchCheckpoint` (`from_state_dict`, `from_model`) to
stock `>>>` doctests.

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

## Examples that now check something

Both blocks used `.. testoutput:: :hide:` with a body of `...`, which
matches any output, so they validated nothing. Their output is
deterministic apart from a temp path, so they now check it:

- `from_state_dict` expects `worked`, after its existing `assert`.
- `from_model` expects `Checkpoint(filesystem=local, path=...)` under `#
doctest: +ELLIPSIS`.
- `torch.manual_seed(42)` returns a `Generator`, so it's bound to `_`.

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

`RAY_TRAIN_V2_ENABLED=1` and `TF_USE_LEGACY_KERAS=1` are set to match
`//python/ray/train:py_doctest[train]`.

| Module | Before | After |
|---|---|---|
| `ray/train/torch/torch_checkpoint.py` | 2 passed (pytest-sphinx,
output unchecked) | 2 passed (doctest, output checked) |

## Related finding, not changed here

`ray/train/__init__.py` sets `__module__ = "ray.train"` on `Checkpoint`,
`TrainContext`, and other re-exported classes. `doctest.DocTestFinder`
skips objects whose `__module__` doesn't match the file being collected,
so neither collector ever collects those classes' docstring examples.
For example, `ray/train/v2/api/context.py` collects 0 items. Those
examples are untested today. Several of them also print from inside
Train workers, and Ray forwards that output to the driver's stdout
asynchronously, so they would flake under stock doctest if collection
were fixed. That needs its own decision, so this PR doesn't touch those
files.

## 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](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 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
…ts (#66746)

## What

Convert every `.. testcode::` example in `ray.data.aggregate` to stock
`>>>` doctests (18 blocks): `AggregateFn`, `Count`, `AsList`, `Sum`,
`Min`, `Max`, `Mean`, `Std`, `AbsMax`, `Quantile`, `Unique`,
`CountDistinct`, `ValueCounter`, `MissingValuePercentage`,
`ZeroPercentage`, `ApproximateQuantile`, `ApproximateTopK`,
`TopKUnique`.

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

This module needs no binds or doctest flags. Every block assigns its
result and shows it in a trailing `# result: ...` comment, and those
comments stay as `>>> #` lines, the style `ray.data.expressions` already
uses.

## `AsList` now runs

`AsList` was `:skipif: True`, with a comment saying the example needs
ordered output. The example asserts nothing about order, so it now runs,
and it passed three of three local runs. Its `# result:` comment is
unchanged. Real groupby output order varies, which is fine because the
result isn't checked.

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

`datasketches` is installed locally for the two approximate aggregators.
CI has it through `data-test-requirements.txt`.

| Module | Before | After |
|---|---|---|
| `ray/data/aggregate.py` | 17 passed (pytest-sphinx; `AsList` skipped)
| 18 passed (doctest) |

## Possible follow-up, not done here

The global aggregates (`Count`, `Sum`, `CountDistinct`, `ValueCounter`,
`MissingValuePercentage`, `ZeroPercentage`, `TopKUnique`) return
deterministic results. Their `# result:` comments could become checked
expected output. The groupby examples would need an order-independent
check. That changes the examples beyond a conversion, so it's left for a
separate PR if Data wants it.

## 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](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 Nov 2, 2026
…doctests (#66745)

## 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](https://claude.com/claude-code)

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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 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