Skip to content

[RLlib] Convert rllib.env docstring examples to stock doctests - #67763

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

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

Conversation

@dstrodtman

Copy link
Copy Markdown
Contributor

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

Convert the `.. testcode::` examples in `rllib/env` docstrings to `>>>`
examples under an `Examples:` header, so they render in griffe and MkDocs
as well as Sphinx. Runnable blocks become runnable doctests, `:skipif: True`
blocks carry `+SKIP_EXAMPLE`, and blocks that don't parse as Python become
`code-block` directives. Example code and docstring claims are unchanged.

@rtd-build

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman dstrodtman added rllib RLlib related issues docstring-only Skip heavy library tests for Ray API docstring edits. labels Nov 3, 2026
@dstrodtman
dstrodtman marked this pull request as ready for review November 3, 2026 20:59
@dstrodtman
dstrodtman requested a review from a team as a code owner November 3, 2026 20:59
@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Nov 3, 2026

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request converts Sphinx-style testcode and testoutput blocks into doctest-compatible Examples blocks across several RLlib environment and episode files. The review feedback identifies several issues and inaccuracies in the updated example code blocks, such as incorrect argument passing in with_agent_groups, outdated reset() return values, incorrect environment references, and multiple slicing or indexing errors in the expected outputs of get_actions, get_rewards, and get_extra_model_outputs.

Comment on lines +276 to +279
>>> grouped_env = env.with_agent_groups(env, {
... "group1": ["agent1", "agent2", "agent3"],
... "group2": ["agent4", "agent5"],
... })

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 with_agent_groups, self is passed implicitly when called on an instance of MultiAgentEnv. Passing env as the first argument explicitly will result in a TypeError or incorrect behavior as it binds env to the groups parameter.

Suggested change
>>> grouped_env = env.with_agent_groups(env, {
... "group1": ["agent1", "agent2", "agent3"],
... "group2": ["agent4", "agent5"],
... })
>>> grouped_env = env.with_agent_groups({
... "group1": ["agent1", "agent2", "agent3"],
... "group2": ["agent4", "agent5"],
... })

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. #67764, stacked on this PR, fixes this.

Comment on lines +391 to +392
>>> obs = ma_cartpole.reset()
>>> print(obs)

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 Gymnasium and modern RLlib, reset() returns a tuple of (obs, infos). Assigning the result directly to obs and printing it will print the tuple instead of just the observations dictionary.

Suggested change
>>> obs = ma_cartpole.reset()
>>> print(obs)
>>> obs, infos = ma_cartpole.reset()
>>> print(obs)

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. #67764, stacked on this PR, fixes this.

Comment on lines +399 to +401
>>> ma_stateless_cartpole = ma_stateless_cartpole_cls(
... {"num_agents": 3})
>>> print(obs)

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 second print(obs) statement prints the observations from the first environment (ma_cartpole) instead of the newly created ma_stateless_cartpole environment. We should call reset() on ma_stateless_cartpole first to get and print its observations.

Suggested change
>>> ma_stateless_cartpole = ma_stateless_cartpole_cls(
... {"num_agents": 3})
>>> print(obs)
>>> ma_stateless_cartpole = ma_stateless_cartpole_cls(
... {"num_agents": 3})
>>> obs, infos = ma_stateless_cartpole.reset()
>>> print(obs)

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. #67764, stacked on this PR, fixes this.

>>> _ = episode.get_actions(slice(None, 2)) # [1, 2]
>>> _ = episode.get_actions(slice(-2, None)) # [2, 3]
>>> # Using `fill=...` (requesting slices beyond the boundaries).
>>> _ = episode.get_actions(slice(-5, -2), fill=-9) # [-9, -9, 1, 2]

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 slice slice(-5, -2) on a list of length 3 produces exactly 3 elements (indices -5, -4, -3). The returned list is [-9, -9, 1]. The comment incorrectly shows 4 elements [-9, -9, 1, 2].

Suggested change
>>> _ = episode.get_actions(slice(-5, -2), fill=-9) # [-9, -9, 1, 2]
>>> _ = episode.get_actions(slice(-5, -2), fill=-9) # [-9, -9, 1]

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. #67764, stacked on this PR, fixes this. The getter examples there show their real output, so the doctest checks the values.

Comment on lines +959 to +962
>>> _ = episode.get_actions(
... slice(0, 2),
... one_hot_discrete=True,
... ) # [[0 1 0 0], [0 0 0 1]] (actions=1 and 3)

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 slice slice(0, 2) selects indices 0 and 1, which correspond to actions 1 and 2. The one-hot representation of 2 is [0, 0, 1, 0]. The comment incorrectly shows [0, 0, 0, 1] (action 3) and states actions=1 and 3.

Suggested change
>>> _ = episode.get_actions(
... slice(0, 2),
... one_hot_discrete=True,
... ) # [[0 1 0 0], [0 0 0 1]] (actions=1 and 3)
>>> _ = episode.get_actions(
... slice(0, 2),
... one_hot_discrete=True,
... ) # [[0 1 0 0], [0 0 1 0]] (actions=1 and 2)

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. #67764, stacked on this PR, fixes this. The getter examples there show their real output, so the doctest checks the values.

>>> _ = episode.get_rewards(slice(None, 2)) # [1.0, 2.0]
>>> _ = episode.get_rewards(slice(-2, None)) # [2.0, 3.0]
>>> # Using `fill=...` (requesting slices beyond the boundaries).
>>> _ = episode.get_rewards(slice(-5, -2), fill=0.0) # [0.0, 0.0, 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 slice slice(-5, -2) on a list of length 3 produces exactly 3 elements (indices -5, -4, -3). The returned list is [0.0, 0.0, 1.0]. The comment incorrectly shows 4 elements [0.0, 0.0, 1.0, 2.0].

Suggested change
>>> _ = episode.get_rewards(slice(-5, -2), fill=0.0) # [0.0, 0.0, 1.0, 2.0]
>>> _ = episode.get_rewards(slice(-5, -2), fill=0.0) # [0.0, 0.0, 1.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, that's right. This PR is syntax-only on purpose, so it leaves example code unchanged. #67764, stacked on this PR, fixes this. The getter examples there show their real output, so the doctest checks the values.

... )
>>> # Plain usage (`indices` arg only).
>>> _ = episode.get_extra_model_outputs("mo", -1) # 3
>>> _ = episode.get_extra_model_outputs("mo", 1) # 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 extra model outputs list is [1, 2, 3]. Index 1 is 2. The comment incorrectly shows # 0.

Suggested change
>>> _ = episode.get_extra_model_outputs("mo", 1) # 0
>>> _ = episode.get_extra_model_outputs("mo", 1) # 2

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. #67764, stacked on this PR, fixes this. The getter examples there show their real output, so the doctest checks the values.

@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit f7b1a26 into master Nov 4, 2026
7 checks passed
@pseudo-rnd-thoughts
pseudo-rnd-thoughts deleted the doc-1926-rllib-env-doctests branch November 4, 2026 15:19
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 4, 2026
…7764)

## Description

This is a correctness change for RLlib review. It fixes `rllib.env`
docstring examples that were wrong or couldn't run.

Stacked on #67763. 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.

- `EnvContext.set_defaults`: `print(env_ctx)` prints the worker fields
too, such as `worker=0/None`, because `EnvContext.__str__` appends them.
The example now prints `dict(env_ctx)`, which gives the dict the example
showed.
- `make_multi_agent`: `reset()` returns `(obs, infos)`, so `print(obs)`
printed a tuple. The example also never reset the three-agent env, so
its second `print(obs)` reprinted the first env's observations. Both
resets now unpack the tuple, and the outputs show each agent's
observation array.

### Getter examples now check their values

The `SingleAgentEpisode` getter examples called `get_infos`,
`get_actions`, `get_rewards`, and `get_extra_model_outputs`, and each
one gave its result in a comment. The calls now show their output, so
the doctest checks it. Four comments were wrong:

- `get_actions(slice(-5, -2), fill=-9)` returns three items,
`[array(-9), array(-9), 1]`, not four.
- `get_actions(slice(0, 2), one_hot_discrete=True)` returns the one-hot
vectors for actions 1 and 2, not 1 and 3.
- `get_rewards(slice(-5, -2), fill=0.0)` returns three items, not four.
- `get_extra_model_outputs("mo", 1)` returns `2`, not `0`.

In the `SingleAgentEpisode` class example, the comment expects `[0.0,
0.0, 0.0, r0]` when looking back four rewards from ts=1. But `slice(-4,
0)` with `neg_index_as_lookback=True` returns four fill values. The
example now uses `slice(-3, 1)`, which returns what the comment
describes, and it shows that output.

In these outputs, fill values come back as 0-d NumPy arrays, such as
`array(-9)`, mixed with plain Python values. The examples show what the
getters return today.

### Fixed but still render-only

- `MultiAgentEnv.with_agent_groups`: the example passed `env` as the
first argument, but the method's first parameter is `groups`. It now
passes only the groups dict. The example uses a placeholder env, so it
stays render-only. `doc/source/rllib/multi-agent-envs.md` includes this
method's source, so the fix shows there too.
- `PettingZooEnv`: the example used `pettingzoo.butterfly.prison_v3`.
That env isn't in PettingZoo 1.24.3, the version
`python/requirements/ml/rllib-test-requirements.txt` pins, or in 1.27.0.
The example now uses `pistonball_v6`, as the RLlib multi-agent envs page
does. The outputs come from running the example with PettingZoo 1.27.0.
It stays render-only, because PettingZoo isn't installed in the doctest
environment.

`ExternalEnv`, `MultiAgentEnv.step`, `MultiAgentEnv.reset`, and
`BaseEnv` are unchanged and stay render-only. The `ExternalEnv` example
still passes the deprecated `env` argument to `DQN`.

## Related issues

Stacked on #67763. 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 4 changed files: "10
docstring(s) run, 0 failed, 3 skipped, in 4 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 10 runnable docstrings pass,
and the rest carry `+SKIP_EXAMPLE`.
- The `PettingZooEnv` example with `+SKIP_EXAMPLE` removed, in the same
environment plus PettingZoo 1.27.0: all 11 examples pass. I didn't
verify it end to end against the pinned 1.24.3.
- `ci/ray_ci/doc/check_docstring_only.py --base
doc-1926-rllib-env-doctests`: "4 file(s), docstrings only."
- `pre-commit run --files` on all 4 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]>
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