Skip to content

[RLlib] Convert rllib.utils docstring examples to stock doctests - #67753

Merged
pseudo-rnd-thoughts merged 1 commit into
masterfrom
doc-1926-rllib-utils-doctests
Nov 4, 2026
Merged

pseudo-rnd-thoughts merged 1 commit into
masterfrom
doc-1926-rllib-utils-doctests

Conversation

@dstrodtman

Copy link
Copy Markdown
Contributor

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 ([core] Add a docstring-level +SKIP_EXAMPLE doctest flag for render-only examples #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

Converts the mechanical `.. testcode::` examples in python/ray/rllib/utils
to `>>>` doctests under an `Examples:` header. Runnable blocks stay
runnable; `:skipif: True` blocks carry the docstring-level
`# doctest: +SKIP_EXAMPLE` flag; blocks that don't parse as Python become
`.. code-block::`. Example code is unchanged.

@rtd-build

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

@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 converts Sphinx .. testcode:: blocks into standard Python doctest Examples: blocks across various RLlib utility modules to improve documentation consistency. The review feedback identifies several issues within the updated example codes, such as incorrect imports (e.g., importing from tf_utils instead of numpy in numpy.py), incorrect decorator names (overrides instead of override), outdated configuration methods in AlgorithmConfig, minor indentation misalignments, potential side effects from mutating env.agents, and a boundary bug in the episode sampling loop across multiple replay buffer examples.


Examples:
>>> # B=2
>>> from ray.rllib.utils.tf_utils import flatten_inputs_to_1d_tensor # doctest: +SKIP_EXAMPLE

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

In numpy.py, the example should import flatten_inputs_to_1d_tensor from ray.rllib.utils.numpy instead of ray.rllib.utils.tf_utils.

Suggested change
>>> from ray.rllib.utils.tf_utils import flatten_inputs_to_1d_tensor # doctest: +SKIP_EXAMPLE
>>> from ray.rllib.utils.numpy import flatten_inputs_to_1d_tensor # doctest: +SKIP_EXAMPLE

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.

Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67755, stacked on this PR, fixes this.

.. code-block:: python

from ray.rllib.policy.torch_policy import TorchPolicy
@overrides(TorchPolicy)

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 decorator defined in this module is override, not overrides. Please correct the decorator name in the example.

Suggested change
@overrides(TorchPolicy)
@override(TorchPolicy)

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.

Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67755, stacked on this PR, fixes this.


Examples:
>>> from ray import tune # doctest: +SKIP_EXAMPLE
>>> @overrides(tune.Trainable)

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 decorator defined in this module is override, not overrides. Please correct the decorator name in the example.

Suggested change
>>> @overrides(tune.Trainable)
>>> @override(tune.Trainable)

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.

Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67755, stacked on this PR, fixes this.


>>> # Will only set the `preprocessor_pref` property (to None) and leave
>>> # all other properties at their default values.
>>> config.training(preprocessor_pref=None)

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

In AlgorithmConfig, preprocessor_pref is configured via .env_runners(), not .training(). Please update the example to use the correct configuration method.

Suggested change
>>> config.training(preprocessor_pref=None)
>>> config.env_runners(preprocessor_pref=None)

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.

Thanks, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67755, stacked on this PR, fixes this.

Comment on lines +422 to +424
... "c": {
... "cb": np.array([1.0, 2.0]),
... },

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 dictionary key "c" and its closing brace are misaligned. They should be aligned with "a" and "b".

Suggested change
... "c": {
... "cb": np.array([1.0, 2.0]),
... },
... "c": {
... "cb": np.array([1.0, 2.0]),
... },

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.

Thanks. This PR leaves example code unchanged, so the fix is in #67755: 4e40202.

Comment on lines +62 to +63
>>> agent_ids = env.agents
>>> agent_ids.append("__all__")

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

Mutating env.agents directly by appending "__all__" can lead to unexpected side effects in the environment. It is safer to create a new list containing the agent IDs and "__all__".

Suggested change
>>> agent_ids = env.agents
>>> agent_ids.append("__all__")
>>> agent_ids = list(env.agents) + ["__all__"]

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.

Thanks. env.agents is the env's own list, so the append added "__all__" as an agent. This PR leaves example code unchanged, so the fix is in #67755: 4e40202.

Comment on lines +98 to +100
>>> # Add the last (truncated) episode to the list of episodes.
>>> if not eps.is_done:
... episodes.append(eps)

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

There is a boundary bug in the sampling loop: if the last episode terminates exactly on the last timestep of the loop, it will not be appended to episodes because the append logic only runs at the start of the next iteration. Unconditionally appending the final episode eps after the loop ensures that the last episode is never lost.

Suggested change
>>> # Add the last (truncated) episode to the list of episodes.
>>> if not eps.is_done:
... episodes.append(eps)
>>> # Add the last episode to the list of episodes.
>>> episodes.append(eps)

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.

Thanks. This PR leaves example code unchanged, so the fix is in #67755: 4e40202.

Comment on lines +72 to +73
>>> agent_ids = env.agents
>>> agent_ids.append("__all__")

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

Mutating env.agents directly by appending "__all__" can lead to unexpected side effects in the environment. It is safer to create a new list containing the agent IDs and "__all__".

Suggested change
>>> agent_ids = env.agents
>>> agent_ids.append("__all__")
>>> agent_ids = list(env.agents) + ["__all__"]

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.

Thanks. This PR leaves example code unchanged, so the fix is in #67755: 4e40202.

Comment on lines +108 to +110
>>> # Add the last (truncated) episode to the list of episodes.
>>> if not eps.is_done:
... episodes.append(eps)

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

There is a boundary bug in the sampling loop: if the last episode terminates exactly on the last timestep of the loop, it will not be appended to episodes because the append logic only runs at the start of the next iteration. Unconditionally appending the final episode eps after the loop ensures that the last episode is never lost.

Suggested change
>>> # Add the last (truncated) episode to the list of episodes.
>>> if not eps.is_done:
... episodes.append(eps)
>>> # Add the last episode to the list of episodes.
>>> episodes.append(eps)

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.

Thanks. This PR leaves example code unchanged, so the fix is in #67755: 4e40202.

Comment on lines +98 to +100
>>> # Add the last (truncated) episode to the list of episodes.
>>> if not terminated or truncated:
... episodes.append(eps)

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

There is a boundary bug in the sampling loop: if the last episode terminates exactly on the last timestep of the loop, it will not be appended to episodes because the append logic only runs at the start of the next iteration. Unconditionally appending the final episode eps after the loop ensures that the last episode is never lost.

Suggested change
>>> # Add the last (truncated) episode to the list of episodes.
>>> if not terminated or truncated:
... episodes.append(eps)
>>> # Add the last episode to the list of episodes.
>>> episodes.append(eps)

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.

Thanks. This PR leaves example code unchanged, so the fix is in #67755: 4e40202.

@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit 27d3464 into master Nov 4, 2026
7 checks passed
@pseudo-rnd-thoughts
pseudo-rnd-thoughts deleted the doc-1926-rllib-utils-doctests branch November 4, 2026 15:05
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
…67755)

## Description

This is a correctness change for RLlib review. It fixes `rllib.utils`
docstring examples that were wrong or couldn't run, and it converts the
last `testcode` blocks in `rllib/utils`. Those blocks needed a change to
code, output, or prose, so they stayed out of the syntax-only conversion
in #67753. After this PR, no `testcode` or `testoutput` remains in
`rllib/utils`.

Stacked on #67753. Review that PR first. This diff is against its
branch.

### Examples that were broken and now run

Before this PR, each of these was `:skipif: True` and failed when run.
Each now runs, and the `+SKIP_EXAMPLE` flag is gone, so the doctest
target checks it.

- `numpy.flatten_inputs_to_1d_tensor`: the example imported the function
from `tf_utils`, not from `numpy`. It built `Box(shape=...)` without the
`low` and `high` arguments Gymnasium requires, passed a ragged list for
`"b"`, and passed plain lists where the function needs NumPy arrays. The
outputs now show what the function returns. The values are the same as
before.
- `MeanStdFilter.apply_changes` and `MeanStdFilter.sync`:
`running_stats.mean` is a 0-d array, so the output reads `array(1.5)`,
not `1.5`. `a(1)` returns the filtered value, which a doctest would
echo, so the example now discards it.
- `_NotProvided`: the example passed `preprocessor_pref` to
`.training()`. `AlgorithmConfig.env_runners()` is the method that sets
it. The printed default is `deepmind`, without quotes.
- `space_utils.get_base_struct_from_space` and
`flatten_to_single_ndarray`: the first example now imports the Gymnasium
spaces and gives `Box` bounds. Both outputs are the real reprs. Before,
they were pseudo-reprs such as `dict(a=Box(), ...)`.
- `RemoteCallResults`: the example used `actors` without defining it. It
now defines the same three-actor setup as `FaultTolerantActorManager`.

### `testcode` blocks this PR converts

- `FaultTolerantActorManager`: the async half slept for two seconds and
printed whatever was ready, so its output depended on timing. It now
calls `fetch_ready_async_reqs(timeout_seconds=None)`, which waits for
every in-flight request, so it prints `True` three times.
`foreach_actor_async` returns a count, which the example now discards.
- `ReplayBuffer`: the prose said the `True` output was a Sphinx
artifact. `print(buffer._eviction_started)` prints it, so the output now
sits under that line, and the prose is gone. The `buffer.sample(1)`
calls discard their result.
- `remove_last_ts_from_data`, in `postprocessing/episodes.py`: the
directive was `..testcode::` without a space, so it rendered as an rST
comment. The example called `PPOLearner._remove_last_ts_from_data`,
which doesn't exist. The function is `remove_last_ts_from_data` in the
same module. The function returns a bare array when it gets one data
item, not a tuple, so the first assertion now compares `unpadded`, not
`unpadded[0]`. `Returns` now says so too.
- `unpad_data_if_necessary`, in `postprocessing/zero_padding.py`: the
directive had the same missing space. The example was correct and runs
unchanged.
- `_find_offending_sub_space`, in `pre_checks/env.py`: the example
didn't parse. It's rebuilt from what was legible, a `Box(-2.0, 1.5,
(2,), np.int8)` and the value `np.array([-1.5, 3.0])`, wrapped in a
`Dict` space so there's a path to report. The function is private and
isn't in the API reference.
- `MultiAgentMixInReplayBuffer`: the five blocks are pseudocode
(`buffer.add(<A>)`) with descriptive outputs, so they become `python`
and `text` code blocks. The fourth block constructed `MixInReplay`,
which doesn't exist. It now constructs `MultiAgentMixInReplayBuffer`.

### Fixed but still render-only

- `tf_utils.flatten_inputs_to_1d_tensor`: the same input fixes as the
`numpy` version. The calls ran into `TypeError` before and run now. They
stay `+SKIP_EXAMPLE`. Under RLlib's TensorFlow setup the tensors are
graph-mode, so `print(out)` shows a tensor name, not the values the
example shows.
- `annotations.py`: two examples decorated with `@overrides`. The
decorator is `override`.

`tf_utils.one_hot`, `make_action_immutable`, and the other
`annotations.py` examples are unchanged and stay render-only.

### Review fixes

These address gemini-code-assist comments on #67753:

- `torch_utils.flatten_inputs_to_1d_tensor`: the `"c"` key of the
example dict is now indented like `"a"` and `"b"`.
- `MultiAgentEpisodeReplayBuffer` and
`MultiAgentPrioritizedEpisodeReplayBuffer`: the examples appended
`"__all__"` to `env.agents`, which is the env's own list, so the env
then listed `"__all__"` as an agent. They now build a new list.
- The three episode replay buffer examples dropped the final episode if
it terminated on the loop's last step, because the after-loop append
only ran for unfinished episodes. The loop already appends every episode
that ends inside it, so the last episode is now appended
unconditionally.

## Related issues

Stacked on #67753. Related to #66753.

## Additional information

**Not a duplicate.** I searched open PRs for RLlib `testcode`, doctest,
and docstring-example changes, 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:

- `ci/ray_ci/doc/run_docstring_examples.py` on all 16 changed files: "18
docstring(s) run, 0 failed, 8 skipped, in 16 file(s)."
- 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 18 runnable docstrings pass,
and the rest carry `+SKIP_EXAMPLE`. The seven runnable docstrings from
#67753 pass this check too.
- The two `tf_utils` examples run with `+SKIP_EXAMPLE` removed. Every
call succeeds, and only the graph-mode output differs.
- `ci/ray_ci/doc/check_docstring_only.py --base
doc-1926-rllib-utils-doctests`: "16 file(s), docstrings only."
- `pre-commit run --files` on all 16 files: all hooks pass.

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants