Skip to content

[RLlib] Converge AlgorithmConfig docstring examples to stock doctests - #66749

Merged
dstrodtman merged 4 commits into
masterfrom
doc-1636-rllib-testcode-doctests
Oct 7, 2026
Merged

dstrodtman merged 4 commits into
masterfrom
doc-1636-rllib-testcode-doctests

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What

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

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

Why

.. testcode:: / .. testoutput:: is Sphinx-specific RST, run by Ray's fork of pytest-sphinx and not rendered by griffe/mkdocstrings. Stock >>> doctests render under both Sphinx and griffe and run under plain pytest --doctest-modules. This continues the convergence piloted in #65901 (ray.util.actor_pool, ray.util.placement_group), using the same conversion rules.

How the blocks convert

Same code, same order, same docstring. Each docstring stays one doctest item and moves from the pytest-sphinx collector to stock doctest.

  • assert lines stay as plain >>> lines, and existing expected output stays as the doctest's expected output.
  • Bare expressions whose repr is incidental are bound to _.
  • Blank lines inside a block are dropped, since a blank line ends a doctest example.

One behavior difference to know: a testcode block with no testoutput ignores stdout, but stock doctest fails on any unmatched stdout. Every converted block was run to confirm it prints nothing unexpected.

Examples that now check something

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

Tests run

Locally, against a Ray nightly (43b706d) with the edited module overlaid, using pytest 7.4.4 and the same flags as the doctest Bazel macro: --doctest-modules -c NO_PYTEST_CONFIG -p <default_doctest_pytest_plugin>, with both collectors installed (stock doctest plus ray-project/pytest-sphinx). RAY_USAGE_STATS_PROMPT_ENABLED=0 suppresses the nightly-wheel-only usage banner, which source-built CI doesn't print. pre-commit passes on the changed files.

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

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

The test count is unchanged.

Rendering

Each converted example sits under a plural Examples: header, indented, with no blank line after the header. That is the only form that renders as an examples section on both Sphinx (napoleon) and griffe/mkdocstrings. Griffe's Google parser treats singular Example: as an admonition, treats a header followed by a blank line as plain text, and renders >>> in free prose as Markdown blockquotes. On Sphinx this only adds or renames the "Examples" rubric. Every changed docstring was rendered before and after with Sphinx 8.2.3 (autodoc, napoleon, sphinx.ext.doctest) and mkdocstrings-python 2.0.9 / griffelib 2.3.0. Sphinx output has no regressions, and every converted example renders as highlighted doctest code under griffe.

Duplicate check

gh pr list --state open --search for "testcode", "doctest", and the touched module names found no open PR converting these docstrings.

AI assistance

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

🤖 Generated with Claude Code

dstrodtman and others added 3 commits October 5, 2026 16:22
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
With the doctest at the header's indent, napoleon folds the header and the prompts into one paragraph instead of rendering a code block.

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-rllib-testcode-doctests branch from b83e756 to 4676192 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 the docstrings in algorithm_config.py to use standard doctest formatting (>>>) instead of Sphinx .. testcode:: blocks. The review feedback suggests updating the code examples to use the recommended build_algo() method instead of the deprecated build() method.

@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Oct 6, 2026
@dstrodtman
dstrodtman merged commit 7145df6 into master Oct 7, 2026
7 checks passed
@dstrodtman
dstrodtman deleted the doc-1636-rllib-testcode-doctests branch October 7, 2026 13:02
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]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
)

## Description

Converts the `.. testcode::` examples in `python/ray/rllib/utils`
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 RLlib conversion in
#66749.

This PR covers 34 of the 42 `testcode` blocks in `rllib/utils`, in 15
files:

- **7 runnable blocks become runnable doctests.** They're in
`lambda_defaultdict.py`, `torch_utils.py` (2),
`postprocessing/zero_padding.py`, and the three episode replay buffers.
None of these ran before, because the RLlib `doctest()` target doesn't
execute `testcode`. All seven pass now.
- **24 never-run blocks stay never-run.** These were `:skipif: True`.
Each now sits in a docstring that carries the `# doctest: +SKIP_EXAMPLE`
flag (#66753), so the doctest target and the docstring examples step
both skip the whole docstring. They're in `numpy.py`,
`actor_manager.py`, `from_config.py`, `filter.py`, `annotations.py`,
`tf_utils.py`, `metrics/window_stat.py`, and `spaces/space_utils.py`.
- **3 blocks that don't parse as Python become `.. code-block::`.** The
two directory layouts in `checkpoints.py` become `text`, and the `def
loss(self, ...)` sketch in `annotations.py` becomes `python`.

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

- **Output moves under the `print` that produces it.** In
`torch_utils.one_hot`, and in the two `flatten_inputs_to_1d_tensor`
examples in `numpy.py` and `tf_utils.py`, one `testcode` block printed
twice, and a single `testoutput` held both results. A doctest checks
output right after each statement, so the first result now sits under
the first `print`. The output text is unchanged.
- **Five docstrings gain `Args` and `Returns` entries.** An `Examples:`
section makes pydoclint check docstrings it used to skip as short, and
the RLlib baseline is empty. `PublicAPI`, `DeveloperAPI`, and
`ExperimentalAPI` document `obj` and return it unchanged.
`OverrideToImplementCustomLogic_CallToSuperRecommended` returns `obj`
with `__is_overridden__` set to False. `MeanStdFilter.sync` documents
`other`. Each entry describes what the function body does.

### Left for a separate correctness PR

The remaining blocks need a change to code, output, or prose, so they
aren't in this syntax-only PR. They'll go to RLlib review as a
correctness change:

- `actor_manager.py`, `FaultTolerantActorManager`: the async half prints
results whose count depends on timing after `time.sleep(2)`, so any
expected output would be flaky.
- `replay_buffers/replay_buffer.py`: the prose says the `True` output is
a Sphinx artifact, but `print(buffer._eviction_started)` prints it. The
bare `buffer.sample(1)` calls would also echo a `SampleBatch` as
doctests.
- `replay_buffers/multi_agent_mixin_replay_buffer.py`: five pseudocode
blocks (`buffer.add(<A>)`) with descriptive "outputs." The fourth block
constructs `MixInReplay`, which doesn't exist in RLlib.
- `pre_checks/env.py`, `_find_offending_sub_space`: the example doesn't
parse.
- `postprocessing/episodes.py:72` and
`postprocessing/zero_padding.py:207`: both use `..testcode::` without a
space, so they render as rST comments today. Converting them would make
them visible for the first time. The `episodes.py` example also calls
`PPOLearner._remove_last_ts_from_data`, which doesn't exist. The
function is `remove_last_ts_from_data` in the same module.

Converting the never-run examples also surfaced these errors, which this
PR leaves as-is:

- `from_config.py`, `_NotProvided`: the example passes
`preprocessor_pref` to `.training()`, but
`AlgorithmConfig.env_runners()` is the method that sets it.
- `annotations.py`: two examples decorate with `@overrides`. The
decorator is `override`.
- `numpy.py`, `flatten_inputs_to_1d_tensor`: the example imports the
function from `ray.rllib.utils.tf_utils`, not from `numpy`.

## Related issues

Related to #66749 and #66753.

## Additional information

**Not a duplicate.** I searched open PRs for RLlib `testcode` and
doctest conversions, and none touches these docstrings. #67630, which
merged today, added `Args` and `Returns` to `numpy.py`, `tf_utils.py`,
and `torch_utils.py` but left their examples alone. This branch is based
on a `master` that includes it.

**Tests run**

- `ci/ray_ci/doc/run_docstring_examples.py` on all 15 files, in a Python
3.12 virtualenv with `ray[rllib]==2.59.0` and `torch`: "7 docstring(s)
run, 0 failed, 16 skipped, in 15 file(s)." The 16 skips are all
`+SKIP_EXAMPLE`.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "15
file(s), docstrings only."
- `pre-commit run --files` on all 15 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](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
…#67758)

## Description

Converts the `.. testcode::` examples in `python/ray/rllib/connectors`
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 `rllib.utils` conversion in
#67753.

This PR covers 17 of the 19 `testcode` blocks in `rllib/connectors`, in
10 files:

- **16 runnable blocks become runnable doctests.** Five are in
`connector_v2.py`, four are in `connector.py`, and seven connector
pieces under `common/`, `learner/`, and `env_to_module/` have one each.
None of these ran before, because the RLlib `doctest()` target doesn't
execute `testcode`. All 16 pass now.
- **1 block that doesn't parse becomes `.. code-block:: python`.** The
`:skipif: True` example in `AddColumnsFromEpisodesToTrainBatch` ends
with a stray backtick.

This is a syntax-only change. The example code and the claims in each
docstring are unchanged, except for one change the format forces. In
`AgentConnector` and `ActionConnector`, the `Example:` header becomes
`Examples:`. In `ActionConnector`, the example now sits indented under
that header.

### Left for a separate correctness PR

`AddObservationsFromEpisodesToBatch` and
`AddNextObservationsFromEpisodesToTrainBatch` print observations drawn
from `obs_space.sample()` and show no expected output. A doctest fails
on that output, so these two need an expected-output change. They'll go
to RLlib review as a correctness change.

## Related issues

Related to #66749, #66753, and #67753.

## Additional information

**Not a duplicate.** I searched open PRs for RLlib `testcode` and
doctest conversions, and none touches these docstrings.

**Tests run**

- `ci/ray_ci/doc/run_docstring_examples.py` on all 10 files, in a Python
3.12 virtualenv with `ray[rllib]==2.59.0`, `torch`, and `tensorflow`
2.21: "14 docstring(s) run, 0 failed, 0 skipped, in 10 file(s)." The 16
blocks sit in 14 docstrings.
- A strict stdlib `doctest` pass over the same docstrings with
`ELLIPSIS`. Unlike the runner above, it fails on unexpected output, the
way the RLlib `doctest()` target does. All 14 docstrings pass.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "10
file(s), docstrings only."
- `pre-commit run --files` on all 10 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](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
…ring examples to stock doctests (#67761)

## Description

Converts the `.. testcode::` examples in the `python/ray/rllib/models`,
`execution`, `offline`, and `callbacks` 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 `rllib.utils` conversion in #67753. The four subpackages are
small, so they share one PR.

This PR covers 17 of the 18 `testcode` blocks in these subpackages, in 9
files:

- **3 runnable blocks become runnable doctests.** They're
`synchronous_parallel_sample` in `execution/rollout_ops.py` and the two
`RLlibCallback` examples in `callbacks/callbacks.py`. None of these ran
before, because the RLlib `doctest()` target doesn't execute `testcode`.
All three pass now.
- **7 never-run blocks stay never-run.** These were `:skipif: True`.
Each now sits in a docstring that carries the `# doctest: +SKIP_EXAMPLE`
flag (#66753). They're in `models/catalog.py`, `models/modelv2.py` (2),
`models/preprocessors.py` (2, in one docstring),
`offline/input_reader.py`, and `offline/mixed_input.py`.
- **7 blocks that don't parse as Python become `.. code-block:: python`,
and their outputs become `.. code-block:: text`.** The five
`RepeatedValues` blocks use `<Tensor shape=...>` placeholders. The two
`train_ops.py` examples have an extra closing parenthesis.

This is a syntax-only change. The example code and the claims in each
docstring are unchanged. No format-forced changes were needed, and
pydoclint passes without new `Args` or `Returns` entries.

### Left for a separate correctness PR

In `execution/buffers/mixin_replay_buffer.py`, the
`MixInMultiAgentReplayBuffer` example's `testoutput` is `:hide:` with a
body of only `...`, which matches any output. Converting it would change
what the example checks.

## Related issues

Related to #66749, #66753, and #67753.

## Additional information

**Not a duplicate.** I searched open PRs for RLlib `testcode` and
doctest conversions, and none touches these docstrings.

**Tests run**

- `ci/ray_ci/doc/run_docstring_examples.py` on all 9 files, in a Python
3.12 virtualenv with `ray[rllib]==2.59.0`, `torch`, and `tensorflow`
2.21: "3 docstring(s) run, 0 failed, 6 skipped, in 9 file(s)." All six
skips are `+SKIP_EXAMPLE`.
- A strict stdlib `doctest` pass over the same docstrings with
`ELLIPSIS`. Unlike the runner above, it fails on unexpected output, the
way the RLlib `doctest()` target does. All 3 runnable docstrings pass.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "9
file(s), docstrings only."
- `pre-commit run --files` on all 9 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](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
## Description

Converts the `.. testcode::` examples in `python/ray/rllib/env`
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 `rllib.utils` conversion in
#67753.

This PR covers all 23 `testcode` blocks in `rllib/env` outside `tests/`,
in 7 files:

- **10 runnable blocks become runnable doctests.** They're the
`SingleAgentEpisode` class example and its `to_numpy`,
`get_observations`, `get_infos`, `get_actions`, `get_rewards`,
`get_extra_model_outputs`, and `slice` examples, plus
`MultiAgentEpisode.to_numpy` and `MultiAgentEpisode.slice`. None of
these ran before, because the RLlib `doctest()` target doesn't execute
`testcode`. All ten pass now.
- **11 never-run blocks stay never-run.** These were `:skipif: True`.
Each now sits in a docstring that carries the `# doctest: +SKIP_EXAMPLE`
flag (#66753). They're in `EnvContext.set_defaults`, `ExternalEnv`,
`MultiAgentEnv.step`, `MultiAgentEnv.with_agent_groups`,
`make_multi_agent`, and `PettingZooEnv` (six blocks).
- **2 blocks that don't parse as Python become `.. code-block:: python`,
and their output becomes `text`.** They're in `BaseEnv` and
`MultiAgentEnv.reset`.

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

- **Bare calls discard their result.** A doctest echoes the return value
of a bare call, so 37 calls such as `episode.get_infos(-1)` and
`episode.to_numpy()` now start with `_ = `. The comments that follow
them are unchanged.
- **Output moves under the `print` that produces it.** In
`MultiAgentEnv.step` and `make_multi_agent`, one `testoutput` held the
output of several prints. The output text is unchanged.

`doc/source/rllib/multi-agent-envs.md` includes the whole
`with_agent_groups` method as Python source through `literalinclude`.
That page showed the `.. testcode::` and `:skipif: True` lines before,
and it shows the `>>>` lines and the `# doctest: +SKIP_EXAMPLE` comment
now.

### Left for a separate correctness PR

Converting the never-run examples surfaced the following errors. This PR
leaves them as-is:

- `EnvContext.set_defaults`: `print(env_ctx)` also prints the worker
fields, not only the dict.
- `make_multi_agent`: `reset()` returns `(obs, infos)`, and the second
`print(obs)` reprints the first env's observations.
- `with_agent_groups`: the example passes `env` as the `groups`
argument.
- `PettingZooEnv`: PettingZoo no longer ships `prison_v3`.
- Several `SingleAgentEpisode` getter comments give the wrong value.

## Related issues

Related to #66749, #66753, and #67753.

## Additional information

**Not a duplicate.** I searched open PRs for RLlib `testcode` and
doctest conversions, and none touches these docstrings.

**Tests run**

These ran in a Python 3.12 virtualenv with `ray[rllib]==2.59.0`,
`torch`, and `tensorflow` 2.21. The wheel doesn't include
`ray/rllib/env/tests`, which `MultiAgentEpisode.to_numpy` imports, so
that module was loaded from the source tree, where the Bazel target
finds it.

- `ci/ray_ci/doc/run_docstring_examples.py` on all 7 files: "10
docstring(s) run, 0 failed, 6 skipped, in 7 file(s)." All six skips are
`+SKIP_EXAMPLE`.
- A strict stdlib `doctest` pass with `ELLIPSIS`. Unlike the runner
above, it fails on unexpected output, the way the RLlib `doctest()`
target does. All 10 runnable docstrings pass.
- `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](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
…to stock doctests (#67767)

## Description

Converts the `.. testcode::` examples in the
`python/ray/rllib/evaluation` and `python/ray/rllib/policy` 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 `rllib.utils` conversion in #67753.

This PR covers all 30 `testcode` blocks in these two subpackages, in 10
files:

- **28 never-run blocks stay never-run.** Every block was `:skipif:
True`. Each now sits in a docstring that carries the `# doctest:
+SKIP_EXAMPLE` flag (#66753), so the doctest target and the docstring
examples step skip the whole docstring. There are 27 such docstrings,
because the two `ObservationFunction.__call__` blocks share one.
- **2 blocks that don't parse as Python become `.. code-block::
python`.** These are `RolloutWorker.set_global_vars`, which has a stray
`...` continuation, and `SampleCollector.get_inference_input_dict`,
which has `"truncated", truncated` inside a dict literal.

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

- **Output moves under the `print` that produces it.** In six
docstrings, one `testcode` block printed several times, and a single
`testoutput` held all the results. They're the `RolloutWorker` and
`TFPolicy` classes, `chop_into_sequences`,
`SampleBatch.split_by_episode`, `SampleBatch.right_zero_pad`, and
`concat_samples`. A doctest checks output right after each statement, so
each result now sits under its own `print`. The output text is
unchanged.
- **`get_learner_stats` gains `Args` and `Returns` entries.** An
`Examples:` section makes pydoclint check docstrings it used to skip as
short, and the RLlib baseline is empty. The function returns the value
under `"learner_stats"` when `grad_info` has that key. Otherwise, it
returns a dict of those values from each nested dict that has the key.
The entries describe that.

### Left for a separate correctness PR

Converting the never-run examples surfaced errors, which this PR leaves
as-is:

- `get_learner_stats` calls `get_stats`, which doesn't exist.
- `RolloutWorker.sample_with_count` uses `PPOTFPolicy`, which doesn't
exist.
- `split_by_episode` sets `"dones"` columns, which `SampleBatch`
rejects.
- `concat_samples` passes plain dicts to `MultiAgentBatch`, which needs
`SampleBatch` values.

## Related issues

Related to #66749, #66753, and #67753.

## Additional information

**Not a duplicate.** I searched open PRs for RLlib `testcode`, doctest,
and docstring-example changes, and none touches these docstrings.

**Tests run**

- `ci/ray_ci/doc/run_docstring_examples.py` on all 10 files, in a Python
3.12 virtualenv with `ray[rllib]==2.59.0`, `torch`, and `tensorflow`
2.21: "0 docstring(s) run, 0 failed, 27 skipped, in 10 file(s)." All 27
skips are `+SKIP_EXAMPLE`.
- A strict stdlib `doctest` pass over the same docstrings, which fails
on unexpected output the way the RLlib `doctest()` target does: 0
failing, with all 27 skipped.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "10
file(s), docstrings only."
- `pre-commit run --files` on all 10 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](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
…#67774)

## Description

Converts the `.. testcode::` examples in the
`python/ray/rllib/algorithms` config class 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 RLlib conversions in #66749 and #67753.
`algorithm_config.py` was already converted in #66749.

This PR covers 12 of the 17 `testcode` blocks in `rllib/algorithms`, in
10 files:

- **7 runnable blocks become runnable doctests.** They're the first
example in each of `SACConfig`, `DreamerV3Config`, `IMPALAConfig`,
`DQNConfig`, `PPOConfig`, `MARWILConfig`, and `APPOConfig`. None of
these ran before, because the RLlib `doctest()` target doesn't execute
`testcode`. All seven pass now. The `MARWILConfig` example reads
`offline/tests/data/cartpole/cartpole-v1_large`, which the `doctest()`
target already lists in `data`.
- **5 never-run blocks stay never-run.** These were `:skipif: True`.
Each now sits in a docstring that carries the `# doctest: +SKIP_EXAMPLE`
flag (#66753). They're in `BCConfig` (2), `CQLConfig`, and `IQLConfig`
(2).

**CI time.** The seven runnable examples build an algorithm and call
`train()`. Each takes 5 to 22 seconds on CPU, so together they add about
90 seconds to the RLlib `doctest()` target, which is `size =
"enormous"`. If that's too much, a docstring-level `+SKIP_EXAMPLE` keeps
any of them render-only.

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

- **Bare calls discard their return value.** `algo.train()` returns a
results dict, and calls such as `config.environment()` and
`config.training()` return the config, so a doctest would echo them. In
the seven runnable examples, these now read `_ = algo.train()` and so
on.
- **Four `__init__` methods gain a one-line docstring.** An `Examples:`
section makes pydoclint check the class docstrings of `BCConfig`,
`CQLConfig`, `IQLConfig`, and `SACConfig` against `__init__(self,
algo_class=None)`, and the RLlib baseline is empty. An `Args` entry
alone doesn't pass, because pydoclint also requires type hints in the
signature, and adding them would change code. Each `__init__` now has
the docstring `"""Initializes a <X>Config instance."""`, which matches
`DQNConfig`, `PPOConfig`, `APPOConfig`, `IMPALAConfig`, and
`MARWILConfig`.

### Left for a separate correctness PR

The second example in each of `IMPALAConfig`, `MARWILConfig`,
`DQNConfig`, `PPOConfig`, and `APPOConfig` runs `tune.Tuner(...).fit()`.
Tune prints its progress tables to stdout, so a doctest fails on the
unexpected output. The `DQNConfig`, `PPOConfig`, and `APPOConfig` blocks
hide this with a `testoutput` whose body is only `...`, which matches
anything. `fit()` doesn't raise when a trial fails, so those examples
check nothing. They stay `testcode` here and go to RLlib review as a
correctness change.

Converting the never-run examples also showed that all three are broken:

- The `BCConfig` and `IQLConfig` data paths start with `./rllib/`, which
no longer exists. Their builds fail without observation and action
spaces, and their `Tuner` calls have no stop condition.
- `CQLConfig` builds on CartPole with no offline data.

## Related issues

Related to #66749, #66753, and #67753.

## Additional information

**Not a duplicate.** I searched open PRs for RLlib `testcode` and
doctest conversions, and none touches these docstrings.

**Tests run**

These ran in a Python 3.12 virtualenv with `ray[rllib]==2.59.0`,
`torch`, `tensorflow` 2.21, and `pillow`. The installed wheel doesn't
include `offline/tests/data`. For these runs, the `cartpole-v1_large`
directory was linked into the install, where the `doctest()` target's
`data` puts it.

- `ci/ray_ci/doc/run_docstring_examples.py` on all 10 files: "7
docstring(s) run, 0 failed, 3 skipped, in 10 file(s)." All three skips
are `+SKIP_EXAMPLE`.
- A strict stdlib `doctest` pass over the same docstrings with
`ELLIPSIS`. Unlike the runner above, it fails on unexpected output, the
way the RLlib `doctest()` target does. All 7 runnable docstrings pass.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "10
file(s), docstrings only."
- `pre-commit run --files` on all 10 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](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
> [!NOTE]
> Stacked on #67822, which fixes the `docstring-only` runner failures
this PR hit on `rllib.core` examples that need torch. Merge #67822
first. GitHub then retargets this PR to `master`.

## Description

Converts the `.. testcode::` examples in `python/ray/rllib/core`
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 #66749 and the `rllib.utils`
conversion in #67753.

This PR covers all 29 `testcode` blocks in `rllib/core`, in 10 files:

- **20 runnable blocks become runnable doctests, in 13 docstrings.**
They're in `distribution.py` (2), `models/base.py` (2),
`models/catalog.py`, `models/torch/base.py`, `models/configs.py` (7),
`default_model_config.py` (2), `rl_module.py` (3), and `learner.py` (2).
None of these ran before, because the RLlib `doctest()` target doesn't
execute `testcode`. All of them pass now.
- **6 never-run blocks stay never-run.** These were `:skipif: True`.
Each now sits in a docstring that carries the `# doctest: +SKIP_EXAMPLE`
flag (#66753). They're in `TorchCategorical`, `TorchDiagGaussian` (2),
`TorchDeterministic`, and `FreeLogStdMLPHeadConfig` (2).
- **3 blocks that don't parse as Python become `.. code-block::
python`.** The two `CNNTransposeHeadConfig` examples have an
unterminated string, `framework="torch)`. The
`InferenceOnlyAPI.get_non_inference_attributes` example is pseudocode
(`[some NN component]`).

This is a syntax-only change. The example code and the claims in each
docstring are unchanged, apart from these format-forced edits:

- **Two calls discard their result.** In `Learner`,
`learner.add_module(...)` and `learner.remove_module(...)` return a
`MultiRLModuleSpec`, which a doctest would echo. They're now assigned to
`_`.
- **Section headers change.** The `Example:` headers in
`models/configs.py` merge into one `Examples:` section per docstring. In
`Catalog`, `Usage example:` becomes `Examples:`, and the stray line `#
Define a custom catalog` becomes a code comment in the example. As plain
docstring text, that line would render as a Markdown heading.
- **Intro prose moves into the `Examples:` section.** Lines such as
"Example for training:" in `RLModule`, the "Note: We use PPO..."
paragraph in `Learner`, and the second paragraph of `DefaultModelConfig`
are unchanged, but they're now indented under `Examples:`.
- **`Model` gains an `Args` entry.** An `Examples:` section makes
pydoclint check the class docstring against `__init__`, and the RLlib
baseline is empty. The entry says `config` is the model config, which
the model stores as `self.config`. That's what `Model.__init__` does.

### Left for a separate correctness PR

Some converted examples run but are wrong, and some never-run examples
fail when run. They'll go to RLlib review as a correctness change. For
example, `MLPHeadConfig` and `MLPEncoderConfig` build with
`framework="tf2"`, which returns `None`. The `RLModule` inference loop
never runs. The `Learner` example's `model` settings are ignored.
`TorchDiagGaussian` is called without its required `scale` argument.

## Related issues

Related to #66749, #66753, and #67753.

## Additional information

**Not a duplicate.** I searched open PRs for RLlib `testcode` and
doctest conversions, and none touches these docstrings.

**Tests run**

- `ci/ray_ci/doc/run_docstring_examples.py` on all 10 files, in a Python
3.12 virtualenv with `ray[rllib]==2.59.0`, `torch`, and `tensorflow`
2.21: "13 docstring(s) run, 0 failed, 4 skipped, in 10 file(s)." All
four skips are `+SKIP_EXAMPLE`.
- A strict stdlib `doctest` pass over the same docstrings with
`ELLIPSIS`. Unlike the runner above, it fails on unexpected output, the
way the RLlib `doctest()` target does. All 13 runnable docstrings pass.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "10
file(s), docstrings only."
- `pre-commit run --files` on all 10 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](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