Repository navigation
[ci][train] Collect doctests for APIs whose __module__ is rewritten - #67831
Conversation
There was a problem hiding this comment.
Code Review
This pull request updates doctest collection behavior in both bazel/default_doctest_pytest_plugin.py and python/ray/data/tests/doctest_pytest_plugin.py to correctly scan functions and classes defined in a module even if their __module__ attribute has been overwritten (such as in Ray Train and Tune public re-exports). It also updates various doctest examples in context.py and train_fn_utils.py to suppress and ignore trainer output using ellipsis. The review feedback points out a potential AttributeError in the newly added _defines helper function when accessing __globals__ on unwrapped non-function callables, suggesting the use of getattr for safety.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit e4cd03d. Configure here.
## 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]>
e4cd03d to
54feed7
Compare
…67834) ## Description `//python/ray/rllib:doctest` fails on master in the `APPOConfig` and `IMPALAConfig` examples. #67774 made these examples runnable. Each one builds an algorithm with `learners(num_learners=1)`, and the learner worker sets up a Gloo process group and prints this line: ``` (_WrappedExecutable pid=5360) [Gloo] Rank 0 is connected to 0 peer ranks. Expected number of connected peer ranks is : 0 ``` Ray forwards worker output to the driver's stdout asynchronously. Stock doctest compares the driver's stdout against each example's expected output, so the line fails `algo = config.build()`, which expects nothing. Both bazel attempts failed this way in [premerge build 76224](https://buildkite.com/ray-project/premerge/builds/76224) on #67627, which doesn't touch these files. Any RLlib PR that runs the full doctest target without the `docstring-only` label hits the same failure. #67774 passed premerge because it ran with `docstring-only`, which runs docstring examples in a light image without torch and skips these examples by name. This PR sets `RAY_LOG_TO_DRIVER=0` in the target's `env`. `ray.init()` reads that constant when it isn't passed `log_to_driver`, and these examples don't pass it. #67831 sets the same variable on the Train V2 doctest target for the same Gloo output from `TorchTrainer` workers. No RLlib docstring example expects worker output: a search of `python/ray/rllib` outside `examples/` and `tests/` for `pid=` and worker-actor prefixes finds none. The examples themselves don't change. **Not a duplicate.** I searched open PRs for `APPOConfig`, `IMPALAConfig`, doctest, and Gloo. #67775 is the only match. It changes the second, Tune-based example in each of these docstrings and doesn't touch the first example or `BUILD.bazel`. ## Testing - `pre-commit run --files python/ray/rllib/BUILD.bazel`: all hooks pass, including buildifier and buildifier-lint. - On macOS arm64 with a Ray nightly wheel, master's `appo.py` and `impala.py`, and Ray's default doctest plugin: `pytest -p default_doctest_pytest_plugin --doctest-modules --noconftest ray/rllib/algorithms/appo/appo.py ray/rllib/algorithms/impala/impala.py` passes with and without `RAY_LOG_TO_DRIVER=0` (2 passed each time). The Gloo line doesn't appear on macOS, so this run shows the change doesn't break the examples but doesn't reproduce the failure. This PR's premerge, which runs the full RLlib doctest target on Linux, is the real check. 🤖 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]>
elliot-barn
left a comment
There was a problem hiding this comment.
Nice, closing the __module__ rewrite gap is great. A few comments inline; the main one is that the worker-log fix only covers one of the three targets that now run these examples.
One broader question: this patches doctest.DocTestFinder._from_module process-wide in the plugin every library's doctest target uses (Serve, Core, RLlib, ...) to handle Train/Tune's re-exports. Would a narrower hook work, e.g. Train/Tune recording the defining module before rewriting __module__ (something like obj._ray_defining_module) and the finder checking only that? Then a misfire in the heuristic can't affect other teams' targets.
Ray Train and Tune overwrite __module__ on public re-exports so that
ray.train.report presents as ray.train. Doctest only collects an object
from the module its __module__ names, and the doctest() macro excludes
package __init__.py files, so no doctest target collected these
docstrings. The doctest plugins now also accept a function or class
whose code is defined in the module being scanned.
The newly collected TrainContext getters, get_dataset_shard, and
get_all_reported_checkpoints examples ended in a bare trainer.fit(),
which echoes a Result under strict doctest. They now use the
print("[ignore]") form the V1 session examples use.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
Use getattr for __globals__ in both doctest plugins. inspect.unwrap() follows __wrapped__ through functools.wraps, so a decorator that wraps a builtin unwraps to an object without __globals__ and crashed collection of python/ray/serve/_private/tracing_utils.py. Set RAY_LOG_TO_DRIVER=0 for the train_v2 doctest target. Worker log lines, such as Gloo connection messages from TorchTrainer workers, reach driver stdout asynchronously, and doctest counts them as output of whichever example is running. Signed-off-by: Douglas Strodtman <[email protected]>
The __module__ fix now collects the v1 get_dataset_shard example in _internal/session.py, which runs trainer.fit() in py_doctest[train-gpu]. Set RAY_LOG_TO_DRIVER=0 there too, matching py_doctest[train_v2], so a worker line on driver stdout can't fail the example. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
54feed7 to
c72bd50
Compare
|
Thanks! You're right on the worker logs. On scope: the patch only adds to the stock |
mlflow 3.18 (pulled in by the pyarrow bump) makes the local filesystem tracking backend raise unless MLFLOW_ALLOW_FILE_STORE=true, so the two experiment-tracking examples now set it before using their file: URIs (verified against mlflow 3.18.0 locally). test_from_huggingface_e2e had been accidentally skipped forever (its old skipif passed a function object uncalled, which is always truthy); the previous cleanup un-skipped it, exposing that current huggingface_hub rejects the un-namespaced 'tweet_eval' repo id when from_huggingface builds the hf:// URI. Use the canonical 'cardiffnlp/tweet_eval' id. The merge of master brings in #67831, which already fixes the train v2 TrainContext doctests that failed in this build. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Goutam <[email protected]>

Description
Ray Train and Tune overwrite
__module__on their public re-exports, soray.train.reportpresents asray.traininstead ofray.train.v2.api.train_fn_utils. Doctest collects an object only from the module that__module__names. Thedoctest()macro inbazel/python.bzlexcludes the package__init__.pyfrom every target. Between the two, no doctest target collected these docstrings.This PR changes the two doctest plugins so that collection also accepts a function or class whose code is defined in the module being scanned. Runtime
__module__rewriting is unchanged.How it works
DocTestFinder._from_modulechecksinspect.getmodule(obj)first, which reads__module__, so a renamed object fails before the__globals__check that would accept it. The plugin wraps that method. When the stock check says no, it also accepts the following:__globals__is the scanned module's namespace.Pytest's
MockAwareDocTestFindercallssuper()._from_moduleon Python 3.12 and earlier, and doesn't override it on 3.13, so the patch covers both. An object imported from another module still fails, because its functions' globals are the other module's. That means nothing is collected twice.Both
bazel/default_doctest_pytest_plugin.pyandpython/ray/data/tests/doctest_pytest_plugin.pychange, since each asks to be kept in sync with the other. Ray Data rewrites no__module__, so its targets collect nothing new.What starts running
py_doctest[train](V2 on)Checkpoint,Checkpoint.as_directory, the five V2TrainContextgetters,get_dataset_shard,get_all_reported_checkpointspy_doctest[train](V2 on)report,get_checkpoint,get_preemption_info+SKIP_EXAMPLE)py_doctest[train-gpu](V2 off)report,get_checkpoint,get_dataset_shardpy_doctest[train-gpu](V2 off)TrainContextmethodspy_doctest[train_v2]also globsv2/**, so the V2 examples run there too, the same as every other V2 docstring already does.The six V1
TrainContextmethods copy their docstrings from_internal/session.pywith_copy_doc. Those session functions were already collected, so these examples now run twice in the GPU target.TuneContextcopies the same docstrings, butpy_doctest[tune]excludestune/context.py.Examples changed so they pass
The five V2
TrainContextgetters,get_dataset_shard, andget_all_reported_checkpointsfrom #67786 ended in a bare>>> trainer.fit(). Under strict doctest that line echoes aResultand fails. They now useprint("[ignore]"); trainer.fit() # doctest: +ELLIPSISwith[ignore]...output, the form the V1 session examples in #67821 use.The comment in
ci/ray_ci/doc/run_docstring_examples.pythat said Train's LightGBM and XGBoost examples "are still testcode blocks" now says they skip there and run inpy_doctest[train].Related issues
Follows up the collection question raised in #67786. The longer-term direction is for Train to define public APIs in public modules once Train V1 is removed. At that point the rewriting and this plugin path can both go.
Additional information
Not a duplicate. I searched open PRs for doctest plugin and
__module__changes. Only #67786, this PR's base, came up.Tests run
These ran with Python 3.12 against the
ray==2.59.0wheel. I applied this stack's Train diff to a copy of the installed package. Two files didn't patch cleanly against 2.59, so I moved this branch's docstrings onto the 2.59 code instead.--collect-only --doctest-moduleswith the old and new plugin on thepy_doctest[train]file list (RAY_TRAIN_V2_ENABLED=1) and thepy_doctest[train-gpu]list (=0). The only additions are the items in the table above. Collection errors from libraries missing locally are identical before and after.ray.*subpackage that imports locally (about 1,258 modules) and comparedDocTestFinderoutput under each plugin, withRAY_TRAIN_V2_ENABLEDat 0 and at 1. Onlyray.trainmodules andray.tune.contextgain tests. Nodoctest()target coversray.tune.context.py_doctest[train]items: 9 passed, 3 skipped.py_doctest[train-gpu]items: 7 passed, 2 skipped. None of the GPU-target examples needs a GPU. On macOS, these neededGLOO_SOCKET_IFNAME=lo0.pyrefly (ray data). Pyrefly skips any file under a hidden directory, and my worktree path has one, so I ran that hook from a checkout without one.Changing a file under
bazel/selects most premerge tags, so this PR runs the full suite. That's the end-to-end check that no other library's doctest target breaks.AI assistance (Claude Code) was used for this PR.
🤖 Generated with Claude Code