Skip to content

[tune] Convert the LightGBM and XGBoost callback examples to stock doctests - #67619

Merged
dstrodtman merged 9 commits into
masterfrom
doc-1930-tune-docstring-doctests
Nov 3, 2026
Merged

dstrodtman merged 9 commits into
masterfrom
doc-1930-tune-docstring-doctests

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Description

Converts the never-run .. testcode:: examples in the TuneReportCheckpointCallback docstrings of python/ray/tune/integration/lightgbm.py and python/ray/tune/integration/xgboost.py to >>> examples. Sphinx renders .. testcode::, but griffe and MkDocs don't, and stock >>> examples render in both.

Both blocks were :skipif: True, so they never ran. They now carry the docstring-level # doctest: +SKIP_EXAMPLE flag (#66753), which skips the whole docstring in the doctest targets and in the docstring examples step, so they still never run. The example code is unchanged. The LightGBM docstring's NumPy-style Examples header with a dashed underline becomes the Google-style Examples: header that the rest of Tune uses.

This is a syntax-only change. The three other remaining Tune testcode blocks, in tune/callback.py and tune/result_grid.py, pair with a hidden testoutput that matches any output. Converting them changes what each example checks, so they're in #67623 for Tune review rather than in this one.

Stacked on #67237, which adds lightgbm and xgboost to the docstring examples runner's OMITTED_LIBRARIES. Both modules import their library at module level, and the docstringbuild image installs neither. Without that change, the examples step would fail both modules at import, rather than skip them.

Related issues

Related to #66748, #66753, and #67237.

Additional information

Not a duplicate. I searched open PRs for Tune doctest and testcode conversions. None touches these docstrings. #66748, which has merged, converted the Trainable and Callback method examples.

Tests run

  • ci/ray_ci/doc/check_docstring_only.py --base upstream/doc-1863-docstring-runner-bundle: "2 file(s), docstrings only."
  • ci/ray_ci/doc/run_docstring_examples.py on both files, in a Python 3.12 virtualenv with ray[tune]==2.59.0 and neither library installed. With [ci] Skip polars docstring examples by name and apply Data doctest settings in the examples runner #67237's runner, both modules are skipped by name: "module needs lightgbm" and "module needs xgboost," 0 failed. With master's runner, both fail at import.
  • Parsed both docstrings with doctest.DocTestParser and compiled every example: 4 examples in lightgbm.py and 6 in xgboost.py. Both docstrings carry SKIP_EXAMPLE, so bazel/default_doctest_pytest_plugin.py skips each one whole.
  • pre-commit run --files on both files: all hooks pass.

The PR carries the docstring-only label, and 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

@dstrodtman dstrodtman added tune Tune-related issues docstring-only Skip heavy library tests for Ray API docstring edits. labels Oct 30, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

dstrodtman and others added 8 commits November 2, 2026 15:59
… docstring examples runner

- Add polars to OMITTED_LIBRARIES, so the docstring examples step skips
  Dataset.join by name, and drop +SKIP_EXAMPLE from that docstring so
  its examples run in Ray Data's doctest target, whose image installs
  polars through test-requirements.txt.
- Apply the Ray Data doctest plugin's DataContext settings to ray.data
  modules in the runner, so an order-dependent example behaves as it
  does in its target.
- Count the examples with expected output that a +SKIP_EXAMPLE docstring
  leaves unchecked in its skip line.
- check_docstring_only.py --base now diffs from the merge base, matching
  the CI path and run_docstring_examples.py.
- Skip ml: data integration tests under the docstring-only label, as the
  Data steps sharing its data tag already are.
- Write the inclusion rule for the examples image's libraries into
  docstring-examples-requirements.txt, and name each library's consumers.
- Refresh the stale comments in others.rayci.yml and the guard preview
  in ci.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
…runner

Dataset.write_lance needs lance, from the pylance distribution. It's
about 138 MB installed, for one docstring, and Ray Data's own doctest
image installs it through data-test-requirements.txt. Adding it to
OMITTED_LIBRARIES makes the examples step report the docstring as
skipped by name, the way it does for polars, while Data's doctest
target runs it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
A leave-one-out run of the docstring examples, one library uninstalled
at a time over every module a CPU doctest() target covers, found the
consumers the comments missed. pillow serves eight docstrings, not two;
datasketches also serves Dataset.summary; and pyiceberg's only consumer
is the internal expression visitor, since read_iceberg and write_iceberg
skip their Iceberg calls. No example that runs in the image needs
crc32c, because write_tfrecords also needs TensorFlow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
The previous commit said no example that runs in the image needs crc32c.
It does: the TFRecord datasink checks for crc32c before
Dataset.write_tfrecords's example reaches TensorFlow, so without crc32c
the example fails with ModuleNotFoundError instead of skipping for
TensorFlow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
The docstring-only keep-only rule in .buildkite/docs.labels.yaml (#67341) already drops this step, so the per-step if: is redundant.

Signed-off-by: Douglas Strodtman <[email protected]>
Since #67341, the docs-example-test label rule drops the opt-in step before dependency marking, so unlabeled prose PRs no longer build its images.

Signed-off-by: Douglas Strodtman <[email protected]>
…tring examples runner

ray.tune.integration.lightgbm and .xgboost, and the Train LightGBM and XGBoost modules, import these libraries at module level. The docstring examples image installs neither, so a docstring-only change to one of those modules failed the step at import, even though Tune's examples are render-only. Omitting them reports the modules as skipped by name instead. The ML images install both through core-requirements.txt, so the omit policy in docstring-examples-requirements.txt allows it.

Signed-off-by: Douglas Strodtman <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ctests

The TuneReportCheckpointCallback docstrings in tune/integration/lightgbm.py
and tune/integration/xgboost.py used never-run `.. testcode::` blocks
(`:skipif: True`), which griffe and MkDocs do not render. They are now
`>>>` examples with the docstring-level `# doctest: +SKIP_EXAMPLE` flag, so
they still never run. The example code is unchanged. The LightGBM
docstring's NumPy-style `Examples` header becomes the Google-style
`Examples:` header that the rest of Tune uses.

@rtd-build

Signed-off-by: Douglas Strodtman <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@dstrodtman
dstrodtman force-pushed the doc-1863-docstring-runner-bundle branch from 13290c4 to c98bcaf Compare November 2, 2026 21:00
@dstrodtman
dstrodtman force-pushed the doc-1930-tune-docstring-doctests branch from 51c5d57 to 8f52fa8 Compare November 2, 2026 21:00
Base automatically changed from doc-1863-docstring-runner-bundle to master November 3, 2026 11:49
dstrodtman added a commit that referenced this pull request Nov 3, 2026
…ttings in the examples runner (#67237)

## Description

Follow-ups to the `docstring-only` label (#66814, #67083) after its
first real campaign PRs on Ray Data. They're bundled into one PR because
they share files and all need ray-ci review. Stacked on #67204, which
updates the contributor docs this PR edits.


1. **Skip polars examples by name instead of marking them render-only.**
`Dataset.join` needs `polars`, which the light `docstringbuild` image
doesn't install, so #67202 marked the docstring `+SKIP_EXAMPLE`. That
also stopped it from running in `//python/ray/data:doctest`, whose image
installs polars through `test-requirements.txt`. This PR adds `polars`
to `OMITTED_LIBRARIES` and removes the flag. The examples step now
reports `SKIP Dataset.join (needs polars)`, and Data's target runs the
three `join` examples.
- Polars isn't added to the image. `polars==1.40.0` plus
`polars-runtime-32==1.40.0` is a 57 MB x86_64 wheel and about 195 MB
installed, larger than pyarrow at 136 MB, for one docstring. Every
current extra is 21 MB or less.
- **lance, the same way.** `Dataset.write_lance` needs `lance`, from the
`pylance` distribution. It's about 138 MB installed on Linux aarch64,
for one docstring, and Data's doctest image installs it through
`data-test-requirements.txt`. This PR adds `lance` to
`OMITTED_LIBRARIES`, so the examples step reports `SKIP
Dataset.write_lance (needs lance)`. #67238, stacked on this PR, converts
that docstring and `write_sql`'s from `testcode` to `>>>`.
- **LightGBM and XGBoost, the same way.**
`ray.tune.integration.lightgbm` and `.xgboost`, and Ray Train's LightGBM
and XGBoost modules, import these at module level. The image installs
neither, so a `docstring-only` change to one of those modules failed the
examples step at import, even though Tune's examples there are
render-only (`+SKIP_EXAMPLE`) and Train's are still `testcode`. The ML
images install both through
`python/requirements/ml/core-requirements.txt`, which meets the omit
rule in item 2. The step now reports `SKIP
python/ray/tune/integration/lightgbm.py (module needs lightgbm)`, and
likewise for `xgboost`. #67619, stacked on this PR, converts those two
Tune examples.
2. **Write the inclusion rule into
`docstring-examples-requirements.txt`.** The header now states when to
add a library to the image and when to omit it by name. Each entry names
the APIs whose examples need it, so it can go once those stop needing
it. Comment-only. `raydepsets --check` reports the locks unchanged.
3. **Apply Ray Data's doctest settings in the runner.**
`doctest_pytest_plugin.py` sets `preserve_order` and turns off
`print_on_execution_start` for every Data docstring. The runner applied
neither, so an order-dependent example could pass in its target and
flake in the step. It now applies both to `ray.data` modules and
restores them after each docstring.
4. **`ml: data integration tests` under the label.** This PR originally
added a negated `if:` gate to it. #67341 merged the `docstring-only`
keep-only rule in `.buildkite/docs.labels.yaml`, which drops this step
with every other library test step, so the gate is removed and
`ml.rayci.yml` is unchanged.
5. **Count the output a render-only docstring hides.** `+SKIP_EXAMPLE`
skips a whole docstring, so expected output inside it is never checked.
The skip line now names how many such examples there are. Across
`python/ray` at this commit, 26 docstrings carry the flag, and only
`Dataset.join` had expected output, which item 1 makes runnable. So the
count is a signal rather than a failure: a render-only example can
legitimately show sample output, such as for an external service.
6. **`check_docstring_only.py --base` diffs from the merge base.** It
diffed against the ref literally. After master moved past the branch
point, `--base upstream/master` flagged files the PR never touched. The
CI path, which already used the merge base, is unchanged. This matches
`run_docstring_examples.py`, and the `ci.md` instructions drop the
manual `git merge-base` wrapper.
7. **Stale comments.** The `doc_example` prose rule's comment in
`test.rules.txt` said an unlabeled prose PR still builds the opt-in
step's images. Since #67341, the `docs-example-test` label rule drops
the step before dependency marking, so the comment now says that. The
`doc: doctest` comment in `others.rayci.yml` still called
`//doc:doctest` the catch-all target, but #67003 split it into per-page
`team:none` targets. The `docstring examples` comment now names the
omitted libraries. It also said Buildkite drops the step on an unlabeled
PR that selects it, but Buildkite shows it as `broken`, and that the
skipped Ray Data examples run in "postmerge", which now says the
scheduled postmerge builds, since the build each merge starts doesn't
run them.

## Related issues

Related to #66814, #67083, #67202, and #67204. #67238 and #67619 are
stacked on this PR.

## Additional information

**Not a duplicate.** I searched open PRs for `run_docstring_examples`,
`check_docstring_only`, `docstring-only`, `OMITTED_LIBRARIES`, and `data
integration tests`. Only #67204, which this stacks on, touches these
files, and it changes docs only.

**Tests run**

- `bazel test //ci/ray_ci/doc:test_run_docstring_examples
//ci/ray_ci/doc:test_check_docstring_only`: both pass. New cases cover:
  - The `Dataset.join` polars message.
  - The hidden-output count.
- The Data settings, applied and restored, and left alone for other
modules.
  - `--base` against a base that moved past the branch point.
- `missing_library` for `lightgbm` and `xgboost` module-level imports.
For that commit I ran the suite with `pytest` directly rather than
through Bazel: 33 passed.
- `run_docstring_examples.py` on `dataset.py`, `aggregate.py`, and
`read_api.py`. I ran it in an aarch64 image built from
`docstring_examples_depset_py3.10.lock`, without `decord` (no aarch64
wheel) and `ray-haproxy`, with the Ray nightly at `093faf5583e`.
  - 114 docstrings ran, and `Dataset.join` skipped for polars.
- The one failure is `read_videos`, which needs decord. The x86_64 CI
image installs it.
- With polars installed, `Dataset.join` passes, and 115 docstrings run.
- With the Data settings, `Starting execution of Dataset` lines drop to
zero, and all 18 `aggregate.py` docstrings pass.
- `run_docstring_examples.py` on `ray.tune.integration.lightgbm` and
`.xgboost` from #67619, in a Python 3.12 virtualenv with
`ray[tune]==2.59.0` and neither library installed: both modules skipped
by name, 0 failed. Before this change, both failed at import.
- `bazel run //ci/raydepsets:raydepsets -- build
ci/raydepsets/configs/docs.depsets.yaml --check`: lock files are up to
date.
- `pre-commit run` on the changed files: passes.
- `rayci` v0.50.0 pipeline generation for a labeled Data docstring PR on
this branch, as above.

This PR's own premerge runs the Data and ML suites, because it changes
`dataset.py`. That run is also the check that Data's doctest image has
polars.

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]>
@dstrodtman
dstrodtman marked this pull request as ready for review November 3, 2026 14:27
@dstrodtman
dstrodtman requested review from a team as code owners November 3, 2026 14:27
@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Nov 3, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request updates the docstring testing infrastructure. Key changes include updating check_docstring_only.py to support diffing against a merge base, introducing a library_settings context manager in run_docstring_examples.py to apply specific DataContext settings for ray.data modules, omitting additional heavy libraries (polars, lance, lightgbm, xgboost), and converting several integration examples to doctests. Feedback on the PR suggests properly cleaning up the RAY_DATA_PARQUET_FOOTER_NUM_ACTORS environment variable in the library_settings context manager to prevent it from leaking to other modules, along with adding a corresponding test assertion to verify the cleanup.

Comment on lines +233 to +243
os.environ.setdefault("RAY_DATA_PARQUET_FOOTER_NUM_ACTORS", "1")
context = DataContext.get_current()
preserve_order = context.execution_options.preserve_order
print_on_execution_start = context.print_on_execution_start
context.execution_options.preserve_order = True
context.print_on_execution_start = False
try:
yield
finally:
context.execution_options.preserve_order = preserve_order
context.print_on_execution_start = print_on_execution_start

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

The environment variable RAY_DATA_PARQUET_FOOTER_NUM_ACTORS is set using os.environ.setdefault but is never restored or cleaned up in the finally block. This can leak the environment variable to subsequent non-ray.data modules executed in the same process, potentially causing unexpected side effects or flaky test behavior. We should track whether it was originally set and clean it up in the finally block if we set it.

Suggested change
os.environ.setdefault("RAY_DATA_PARQUET_FOOTER_NUM_ACTORS", "1")
context = DataContext.get_current()
preserve_order = context.execution_options.preserve_order
print_on_execution_start = context.print_on_execution_start
context.execution_options.preserve_order = True
context.print_on_execution_start = False
try:
yield
finally:
context.execution_options.preserve_order = preserve_order
context.print_on_execution_start = print_on_execution_start
has_footer_actors = "RAY_DATA_PARQUET_FOOTER_NUM_ACTORS" in os.environ
if not has_footer_actors:
os.environ["RAY_DATA_PARQUET_FOOTER_NUM_ACTORS"] = "1"
context = DataContext.get_current()
preserve_order = context.execution_options.preserve_order
print_on_execution_start = context.print_on_execution_start
context.execution_options.preserve_order = True
context.print_on_execution_start = False
try:
yield
finally:
context.execution_options.preserve_order = preserve_order
context.print_on_execution_start = print_on_execution_start
if not has_footer_actors:
os.environ.pop("RAY_DATA_PARQUET_FOOTER_NUM_ACTORS", None)

Comment on lines +598 to +600
# Restored afterwards, so one docstring's settings don't leak.
assert fake_data_context.execution_options.preserve_order is False
assert fake_data_context.print_on_execution_start is True

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

Assert that the RAY_DATA_PARQUET_FOOTER_NUM_ACTORS environment variable is successfully cleaned up and no longer present in os.environ after exiting the library_settings context manager.

Suggested change
# Restored afterwards, so one docstring's settings don't leak.
assert fake_data_context.execution_options.preserve_order is False
assert fake_data_context.print_on_execution_start is True
# Restored afterwards, so one docstring's settings don't leak.
assert fake_data_context.execution_options.preserve_order is False
assert fake_data_context.print_on_execution_start is True
assert "RAY_DATA_PARQUET_FOOTER_NUM_ACTORS" not in os.environ

dstrodtman added a commit that referenced this pull request Nov 3, 2026
## Description

This PR changes what three Tune docstring examples check, and corrects
defects that converting them exposed. It needs review from Tune
maintainers. It isn't a syntax-only conversion.

The `Callback`, `ResultGrid`, and `ResultGrid.get_dataframe` examples
were `.. testcode::` blocks, which griffe and MkDocs don't render. Each
was paired with a hidden `testoutput` whose body was only `...`, which
matches any output, so the doctest ran the code but checked nothing it
printed. This PR converts them to `>>>` doctests that show their output,
and makes these corrections:

**`ResultGrid` class example**

- **Removes the `try`/`except ValueError` around `tuner.fit()`.** It
never fires. A trial that raises is recorded in the result grid and
doesn't propagate out of `fit()`, as the "Failure handling" paragraph of
`Tuner.fit`'s docstring says. In a run of this example, `fit()` returned
normally with 5 of 10 trials errored. If `fit()` had raised, the loop
that follows would have failed with a `NameError` on `result_grid`.
- **Adds the missing space in the success message.** The two f-strings
concatenated to `with metrics{'loss': 0.0, ...}`.
- **Passes `filter_metric` and `filter_mode` to `get_dataframe`.** The
example passed `metric=` and `mode=`, which `get_dataframe` doesn't
accept. The line is `+SKIP`, so nothing caught the `TypeError`.
- Normalizes the over-indented `print` calls in the loop to four spaces.

**`Callback` class docstring**

- **Replaces the two `TrialRunner` references.** Tune no longer has a
`TrialRunner` class. Callbacks are passed through
`RunConfig(callbacks=...)`, as the example itself does, and
`TuneController` calls them
(`python/ray/tune/execution/tune_controller.py`).
- The example now shows its `Got result: 0` through `Got result: 9`
lines.

**`Tuner.fit` docstring**

- **Corrects the `Raises` section.** It said `fit()` raises
`RayTaskError` whenever the trainable raises, which contradicts the same
docstring's "Failure handling" paragraph.
`TuneController._trial_task_failure` re-raises a trial's exception only
when `fail_fast` is `"raise"`, and otherwise logs it and records it on
the trial. I ran a trainable that raises `ValueError` under each
`FailureConfig(fail_fast=...)` setting. With `False` and `True`, `fit()`
returned a `ResultGrid` with `num_errors == 1`. With `"raise"`, it
raised `RayTaskError(ValueError)`, which is also a `ValueError`. That's
probably where the `ResultGrid` example's `except ValueError` came from.

**How the output is matched.** Tune prints its progress tables to
stdout, which a stock doctest compares. The examples use the pattern
`python/ray/tune/stopper/stopper.py` already uses: `print("[ignore]");
result_grid = tuner.fit() # doctest: +ELLIPSIS`, with `[ignore]...` as
the expected output. In the `Callback` example, the expected output is
`[ignore]...`, then `Got result: 0`, `...`, `Got result: 9`, and `...`,
so the callback's own lines are still checked. The `ResultGrid`
example's trainable fails at random, so its loop's expected output is
`Trial ...`.

**For reviewers**

- Is the `[ignore]` pattern acceptable in rendered API reference, or
would you prefer `RunConfig(verbose=0)` in these examples? That changes
the example code, so I didn't make it here.
- The `ResultGrid` example fails half its trials at random, so its
printed output can't be pinned down. It could fail trials based on the
config instead, so the output is deterministic. I kept the example's
behavior.

## Related issues

Related to #66748, which converted `Callback`'s method examples and left
this class example, and to #67619, the syntax-only conversion of Tune's
remaining never-run examples.

## Additional information

**Not a duplicate.** I searched open PRs for Tune doctest and `testcode`
changes. None touches these docstrings. #67611, which has merged,
corrected other Tune docstrings.

**Tests run**

These ran in a Python 3.12 virtualenv with `ray[tune]==2.59.0`, with
this branch's `callback.py` and `result_grid.py` copied over the
installed ones. The installed files differ from `master` only in
docstrings.

- `pytest --doctest-modules -p default_doctest_pytest_plugin` on both
files, using `bazel/default_doctest_pytest_plugin.py`, the way
`//python/ray/tune:py_doctest[tune]` runs them: 4 passed and 1 skipped,
three runs in a row. The skip is `get_best_result`'s existing `+SKIP`
example.
- To confirm the `Callback` example checks the callback's output, I
changed the expected `Got result: 9` to `Got result: 99`. The doctest
failed.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "3
file(s), docstrings only."
- `pre-commit run --files` on all three files: all hooks pass.

The PR carries the `docstring-only` label, and 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]>
@dstrodtman
dstrodtman merged commit 096d35b into master Nov 3, 2026
5 of 6 checks passed
@dstrodtman
dstrodtman deleted the doc-1930-tune-docstring-doctests branch November 3, 2026 15:06
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docstring-only Skip heavy library tests for Ray API docstring edits. go add ONLY when ready to merge, run all tests tune Tune-related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants