Skip to content

[tune] Converge Trainable and Callback docstring examples to stock doctests - #66748

Merged
dstrodtman merged 3 commits into
masterfrom
doc-1636-tune-testcode-doctests
Oct 7, 2026
Merged

dstrodtman merged 3 commits into
masterfrom
doc-1636-tune-testcode-doctests

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

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

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

Also fixes the Callback example's stale tune.report(metric=i) call, which failed inside the trial while the hidden testoutput let the test pass.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman force-pushed the doc-1636-tune-testcode-doctests branch from 06fab70 to 3d9ae37 Compare October 5, 2026 20:22
@dstrodtman
dstrodtman marked this pull request as ready for review October 6, 2026 18:56
@dstrodtman
dstrodtman requested a review from a team as a code owner October 6, 2026 18:56

@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 several docstring examples in ray/tune from .. testcode:: blocks to doctest-style examples, and corrects a tune.report call in a callback test. The review feedback correctly identifies that the set_state method in the Callback example is incorrectly annotated with -> Optional[Dict] and suggests removing or correcting this return type annotation to match the base class signature.

Comment on lines +330 to +331
... def set_state(self, state: Dict) -> Optional[Dict]:
... self._trial_ids = state["trial_ids"]

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 set_state method is a setter that mutates the callback's state and does not return any value. Annotating it with -> Optional[Dict] in the example is incorrect and misleading to users. It should have no return type annotation (or -> None) to match the base class signature def set_state(self, state: Dict).

Suggested change
... def set_state(self, state: Dict) -> Optional[Dict]:
... self._trial_ids = state["trial_ids"]
... def set_state(self, state: Dict):
... self._trial_ids = state["trial_ids"]

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.

Out of scope for this syntax-only conversion. The -> Optional[Dict] annotation on set_state predates this PR and does differ from the base class signature, but this PR keeps the example code as it was. Leaving it for the Ray Tune owners to decide.

@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Oct 6, 2026
@dstrodtman
dstrodtman merged commit 93210d3 into master Oct 7, 2026
7 checks passed
@dstrodtman
dstrodtman deleted the doc-1636-tune-testcode-doctests branch October 7, 2026 12:34
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 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 added a commit that referenced this pull request Nov 3, 2026
…ctests (#67619)

## 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 #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](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

go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants