Skip to content

[core] Convert Ray Core docstring examples to stock doctests - #67760

Open
dstrodtman wants to merge 1 commit into
masterfrom
doc-1928-core-testcode-doctests
Open

dstrodtman wants to merge 1 commit into
masterfrom
doc-1928-core-testcode-doctests

Conversation

@dstrodtman

Copy link
Copy Markdown
Contributor

Description

Converts the remaining .. testcode:: examples in Ray Core API docstrings to >>> examples under a plural Examples: header. Sphinx renders .. testcode::, but griffe and MkDocs don't, and stock >>> examples render in both. This follows the earlier Core conversion in #66745.

This PR covers 25 testcode blocks in 7 files:

  • ray.init and ray.remote become runnable doctests. _private/worker.py is in the _private doctest glob, so these run in the Core doctest target for the first time. The two :skipif: True blocks in ray.init (address="auto" and the ray:// address) carry a per-line # doctest: +SKIP.
  • Examples whose output was +MOCK become render-only. +MOCK marks illustrative output that was never checked. These docstrings carry the docstring-level # doctest: +SKIP_EXAMPLE flag ([core] Add a docstring-level +SKIP_EXAMPLE doctest flag for render-only examples #66753): ray.util.as_completed and ray.util.map_unordered in util/helpers.py, RuntimeContext.get_task_id, get_task_name, and get_task_function_name, and ray.util.state.get_log.
  • Examples in modules no doctest target collects also carry +SKIP_EXAMPLE. runtime_context.py, job_config.py, actor.py, _common/deprecation.py, and util/state/api.py are outside every Core doctest() glob, so nothing ran these examples before and nothing runs them now. The flag keeps a >>> from looking tested when it isn't. Whether to add any of these modules to a doctest target is a question for Core, below.

This is a syntax-only change. The example code and the claims in each docstring are unchanged, with these exceptions that the format forces:

  • ray.init and ray.remote gain an Examples: section. Their examples were interleaved with description prose. The example paragraphs and code now sit in an Examples: section before Args:, and the paragraphs that aren't about an example stay in the description above it: the RAY_ADDRESS paragraph in ray.init, and the actor-termination paragraph, the ray.kill sentence, and the tip in ray.remote. The prose text is unchanged.
  • ray.init() shows its return value. A doctest echoes the RayContext that ray.init() returns, so the example shows RayContext(...) under it.
  • ray.remote drops a hidden setup block. A :hide: block restarted Ray with num_cpus=5, num_gpus=5 so the .options(num_gpus=2) example could run. Doctests have no hidden form, so instead the two lines that need two GPUs carry # doctest: +SKIP. Everything else in that example runs on a CPU-only cluster.
  • Hidden setup blocks in render-only examples are gone. JobConfig and get_log had :hide: blocks that shut down or started Ray. Their examples don't run, so the scaffolding has nothing to set up.
  • Output moves under the print that produces it. In get_task_id, get_task_name, and get_task_function_name, one testcode block printed several times and a single testoutput held every result. Each output line now sits under its own print. The output text is unchanged. as_completed also drops the # Output: label line, which a doctest would read as printed output.
  • Deprecated gains Args and Returns entries. An Examples: section makes pydoclint check its signature. Each entry describes what the decorator body does.

Left out of this PR

  • ray.LoggingConfig (_private/ray_logging/logging_config.py). Its docstring is assigned through LoggingConfig.__doc__ = """...""", which check_docstring_only.py reads as a code change, so including it would void the docstring-only label for the whole PR. It'll follow in a separate PR.
  • ObjectRefGenerator and ray._private.profiling.profile. Neither appears in an API reference listing, so their examples don't render on docs.ray.io.

Question for Core: run the out-of-glob examples?

To help decide whether any of these modules should join a doctest target, I ran their examples locally with the +SKIP_EXAMPLE flags removed:

  • Pass: get_session_name, task_id, get_runtime_context, get_task_name, the three JobConfig examples, __ray_call__, Deprecated, and as_completed. get_task_name and as_completed passed on this run, but their output depends on scheduling.
  • Fail on their illustrative output: get_task_id (task IDs differ per run), get_task_function_name (the output uses a [python module name] placeholder), get_log (log lines differ), and map_unordered (completion order differs).

The docstring examples runner accepts an example that prints output it doesn't show. A stock pytest doctest target is stricter, so examples such as task_id and get_runtime_context, which echo object refs and IDs, would need output or +SKIP lines first. If Core wants any of them collected, that change, plus adding the module to a target, will go in a separate PR for Core review rather than this syntax-only one.

Related issues

Related to #66745 and #66753.

Additional information

Not a duplicate. I searched open PRs for Core testcode and doctest conversions, and none touches these docstrings. #66745 converted util/debug.py and util/queue.py and merged.

Tests run

  • ci/ray_ci/doc/run_docstring_examples.py on all 7 files, in a Python 3.11 virtualenv with ray==2.59.0: ray.init and ray.remote pass, and the 14 +SKIP_EXAMPLE docstrings skip. The one failure is ActorMethod.options in actor.py, an existing >>> example this PR doesn't touch. CI's step doesn't run it, because no doctest target covers actor.py.
  • ci/ray_ci/doc/check_docstring_only.py --base upstream/master: "7 file(s), docstrings only."
  • pre-commit run --files on all 7 files: all hooks pass, including pydoclint.

The PR carries the docstring-only label. Its commit carries an @rtd-build line for the Read the Docs preview.

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

🤖 Generated with Claude Code

Converts the remaining `.. testcode::` examples in Ray Core API
docstrings to `>>>` doctests under an `Examples:` header. The
`ray.init` and `ray.remote` examples are runnable; `:skipif: True`
lines carry `# doctest: +SKIP`. Examples with `+MOCK` output, and
examples in modules no doctest target collects, carry the
docstring-level `# doctest: +SKIP_EXAMPLE` flag. Example code is
unchanged.

@rtd-build

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman dstrodtman added core Issues that should be addressed in Ray Core docstring-only Skip heavy library tests for Ray API docstring edits. labels Nov 3, 2026
@dstrodtman
dstrodtman requested review from a team, MengjinYan and edoakes as code owners November 3, 2026 19:57

@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 standardizes the documentation across several Ray modules by converting Sphinx-style test blocks into standard Python doctest examples. While this is a great improvement for documentation consistency, the review identified two issues in the updated examples: the ray.util.as_completed example incorrectly iterates over resolved values instead of tuples of object references, and an assertion in the ray.remote options example compares a returned tuple to a list, which would cause a test failure.

Comment on lines +91 to +97
>>> for x in ray.util.as_completed(refs, chunk_size=2):
... print(x)
4
2
6
8
10

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.

high

The ray.util.as_completed function yields tuples of (ready_refs, remaining_refs) where ready_refs is a list of ObjectRefs, rather than yielding the resolved values directly. Printing x directly would print a tuple of lists of ObjectRefs instead of the integer values. To get the resolved values, you need to call ray.get on the ready_refs list.

Suggested change
>>> for x in ray.util.as_completed(refs, chunk_size=2):
... print(x)
4
2
6
8
10
>>> for ready_refs, _ in ray.util.as_completed(refs, chunk_size=2):
... print(ray.get(ready_refs))
[4, 2]
[6, 8]
[10]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

as_completed yields resolved values, not (ready, remaining) tuples: _wait_and_get_single_batch returns ray.get(ready) unless yield_obj_refs=True, and as_completed does yield from results. Running the example prints the integers. The example code is also unchanged from master; this PR only converts its syntax.

... return 1, 2
>>> f_with_2_gpus = f.options(num_gpus=2)
>>> object_refs = f_with_2_gpus.remote() # doctest: +SKIP
>>> assert ray.get(object_refs) == [1, 2] # doctest: +SKIP

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Since f is defined with num_returns=2, calling f_with_2_gpus.remote() returns a tuple of ObjectRefs. Passing this tuple to ray.get preserves the tuple structure and returns a tuple of values (1, 2). Comparing this tuple to the list [1, 2] will evaluate to False and cause an AssertionError if executed. The assertion should compare against the tuple (1, 2) instead.

Suggested change
>>> assert ray.get(object_refs) == [1, 2] # doctest: +SKIP
>>> assert ray.get(object_refs) == (1, 2) # doctest: +SKIP

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

With num_returns=2, .remote() returns a list of ObjectRefs, so ray.get(object_refs) returns [1, 2] and the assertion holds. Checked locally. This line is also unchanged from master.

@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Nov 3, 2026
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
## Description

Converts the `.. testcode::` examples in Ray Train API docstrings to
`>>>` examples under a plural `Examples:` header. Sphinx renders `..
testcode::`, but griffe and MkDocs don't, and stock `>>>` examples
render in both. This follows the Core conversion in #67760 and the Tune
conversion in #67619.

This PR covers 23 files under `python/ray/train/`:

- **Runnable examples stay runnable.** Pytest doctest collects only
`>>>`, so nothing ran these `testcode` blocks before. Fifteen docstrings
now have examples that run: the v2 `TorchTrainer` and `XGBoostTrainer`,
the five `TrainContext` getters, `get_all_reported_checkpoints`,
`get_dataset_shard`, `DataParallelTrainer`, `BaseTrainer.training_loop`,
`LightGBMCheckpoint.from_model`, the Keras `ReportCheckpointCallback`,
and the v1 `report` and `get_checkpoint` in `_internal/session.py`.
- **`:skipif: True` examples become render-only.** They carry the
docstring-level `# doctest: +SKIP_EXAMPLE` flag (#66753).
`DataParallelTrainer` mixes runnable examples with one `:skipif:`
example, so that example's statements carry a per-line `# doctest:
+SKIP` instead, and the rest of the docstring still runs.
- **Examples in modules no doctest target covers are render-only too.**
That's `horovod/horovod_trainer.py`, `v2/jax/jax_trainer.py`, and
`xgboost/xgboost_checkpoint.py`. Whether to add any of them to a target
is a separate question.

This is a syntax-only change. The example code and the claims in each
docstring are unchanged, with these exceptions that the format forces:

- **Interleaved examples move into `Examples:`.** In
`DataParallelTrainer`, `HorovodTrainer`, `BaseTrainer`,
`BaseTrainer.restore`, `JaxTrainer`, `get_dataset_shard`, and three
`TrainContext` getters, example paragraphs and code sat in the
description. They now sit in an `Examples:` section before `Args:`. The
paragraphs that aren't about an example stay in the description. Prose
text is unchanged.
- **`Example:` and numpy-style `Examples` headers become `Examples:`.**
In the LightGBM and XGBoost callbacks and checkpoints, the section moves
ahead of `Args:` and `Returns:`.
- **`Checkpoint.as_directory` drops a hidden setup block and becomes
render-only.** Its `:hide:` block created the `checkpoint` the example
uses. Doctests have no hidden form, and showing the setup would change
what the example shows.
- **`get_trial_dir` in `_internal/session.py`** had `+MOCK` output. It's
render-only, and the output moved under the `tuner.fit()` call that
prints it.
- **Two examples now render that didn't.** `prepare_data_loader` in both
`train_loop_utils.py` copies was written `.. testcode:` with one colon,
and `XGBoostCheckpoint.from_model` was written `... testcode::`. Sphinx
read both as comments, so docs.ray.io never showed them.

### Left out of this PR

These blocks pair with a `:hide:` `testoutput`, or share a docstring
with one. Converting them changes what the example shows, so they'll
follow in a separate PR for Train review:

- `TensorflowTrainer`, both v1 and v2, the whole docstring.
- `TensorflowCheckpoint.from_model`, which is also `+MOCK`.
- `WandbLoggerCallback` in `air/integrations/wandb.py`.
- Six v1 functions in `_internal/session.py`: `get_world_size`,
`get_world_rank`, `get_local_rank`, `get_local_world_size`,
`get_node_rank`, and `get_dataset_shard`.

### Questions for Train

- **No doctest target collects the examples of APIs whose `__module__`
is rewritten.** `ray/train/__init__.py` imports the public API and then
sets `__module__ = "ray.train"` on it: `Checkpoint`, `TrainContext`,
`report`, `get_checkpoint`, `get_dataset_shard`,
`get_all_reported_checkpoints`, `get_preemption_info`, and others. Both
places that could collect these examples miss them:
- **The defining module rejects them.** `doctest.DocTestFinder` keeps an
object only if `inspect.getmodule(obj)` is the module being scanned, and
`getmodule` reads `__module__`. So scanning
`ray.train.v2.api.train_fn_utils` skips `report`. For a renamed class
such as `TrainContext` or `Checkpoint`, the finder never descends into
its methods.
- **The package `__init__.py` is never scanned.** Scanning `ray.train`
itself would find the renamed functions and class docstrings, though
still not the methods. But the `doctest()` macro in `bazel/python.bzl`
excludes the package-root `__init__.py`.
    
`RAY_TRAIN_V2_ENABLED` decides which implementation gets renamed.
`py_doctest[train]` runs with it on and `py_doctest[train-gpu]` with it
off, so each implementation is renamed in exactly the target that would
run it. With this PR and #67821, that leaves 12 runnable docstrings
uncollected: `Checkpoint`, `Checkpoint.as_directory`, the five
`TrainContext` getters, the V2 `get_dataset_shard` and
`get_all_reported_checkpoints`, and the V1 `report`, `get_checkpoint`,
and `get_dataset_shard` in `_internal/session.py`. The `Checkpoint`
class's existing `>>>` examples predate this PR and have never run in a
doctest target. I checked this with `DocTestFinder` against
`ray==2.59.0` under each flag value. Tune rewrites `__module__` the same
way. Its only renamed object with examples, `TuneContext`, copies them
from `_internal/session.py`, and `py_doctest[tune]` excludes its file.

CI's `run_docstring_examples.py` step reads source files directly, so it
still runs these examples, but only on PRs that change those files. Two
ways to fix collection:
- **Keep the rewriting, and have the shared doctest plugin match objects
by their defining file.** Docs can do this, and it doesn't change
runtime behavior.
- **Stop rewriting `__module__` at runtime.** Either present the public
path only in the docs build, or define public APIs in public modules.
Both change what users see in `repr()`, tracebacks, or import paths.
    
Train chose the first for now: #67831 changes the plugin, stacked on
#67821.
- **Bare `trainer.fit()` lines.** Seven runnable examples end in `>>>
trainer.fit()` with no expected output: the five `TrainContext` getters,
`get_all_reported_checkpoints`, and `get_dataset_shard`.
`run_docstring_examples.py` only requires an example with no shown
output to run. A strict doctest would also compare the echoed `Result`
repr and any worker log lines, so these lines need the
`print("[ignore]"); ... # doctest: +ELLIPSIS` form that Tune uses and
that #67821 adopts. #67831 makes that change along with the collection
fix.

## Related issues

Related to #67760, #67619, and #66753.

## Additional information

**Not a duplicate.** I searched open PRs for Train `testcode`, doctest,
and docstring-example changes. None touches these docstrings. #67520 is
the only open Train PR the search returned, and it shares no files with
this one.

**Tests run**

These ran in a Python 3.12 virtualenv with `ray==2.59.0`, `torch`,
`tensorflow` 2.21 with `tf_keras`, `lightgbm`, `xgboost`, and
`scikit-learn`:

- `ci/ray_ci/doc/run_docstring_examples.py` on the 19 files
`py_doctest[train]` covers, with `RAY_TRAIN_V2_ENABLED=1
TF_USE_LEGACY_KERAS=1`: "15 docstring(s) run, 0 failed, 20 skipped, in
19 file(s)."
- The same runner on `_internal/session.py` with
`RAY_TRAIN_V2_ENABLED=0`, matching `py_doctest[train-gpu]`: "2
docstring(s) run, 0 failed, 1 skipped." Neither runnable example needs a
GPU.
- The same runner on `v2/jax/jax_trainer.py` and
`xgboost/xgboost_checkpoint.py`: both skip, as render-only.
`horovod_trainer.py` can't import without Horovod, and no CPU target
covers it.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "23
file(s), docstrings only."
- `pre-commit run --files` on all 23 files: all hooks pass, including
pydoclint and the Train circular-import check.

On macOS, the `TorchTrainer` examples needed `GLOO_SOCKET_IFNAME=lo0`.
Without it, gloo aborted the workers, and the controller retried worker
startup without limit instead of failing. That's a local transport
issue, but an unbounded retry would turn any CI worker-start failure
into a hang until the test timeout.

The PR carries the `docstring-only` label. Its commit carries an
`@rtd-build` line for the Read the Docs preview.

AI assistance (Claude Code) was used for 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]>
@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 Nov 18, 2026

This branch has not been deployed

No deployments
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 docstring-only Skip heavy library tests for Ray API docstring edits. go add ONLY when ready to merge, run all tests stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant