Skip to content

[rllib] Add missing docstrings, Args, and Returns to offline, SampleBatch, and utils APIs - #67630

Merged
pseudo-rnd-thoughts merged 1 commit into
masterfrom
doc-1914-rllib-offline-utils-docstrings
Nov 3, 2026
Merged

pseudo-rnd-thoughts merged 1 commit into
masterfrom
doc-1914-rllib-offline-utils-docstrings

Conversation

@dstrodtman

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Several public methods and classes in ray.rllib.offline, ray.rllib.policy.sample_batch, and ray.rllib.utils have no docstring, no parameter entry, or no Returns: section. This PR documents their existing behavior and changes only docstrings.

What changed:

  • Offline:
    • A class docstring with Args: for OfflineData, plus docstrings for OfflineData.sample and its two default_*_batches_kwargs properties.
    • Args: and Returns: for OfflineSingleAgentEnvRunner.sample, including when it writes its buffer.
    • Args: on the OfflinePreLearner class docstring.
    • A docstring for get_offline_io_resource_bundles.
    • Docstrings for IOContext.input_config and output_config.
  • SampleBatch and MultiAgentBatch:
    • Returns: for agent_steps and env_steps.
    • A docstring for is_training and Args: for set_training.
    • Args: and Returns: for MultiAgentBatch.timeslices.
  • Utils:
    • Returns: for MetricsLogger.get_state.
    • Args: and Returns: for huber_loss and for the torch and TensorFlow versions of symlog and inverse_symlog.
    • Docstrings for sample() on FlexDict, Repeated, and Simplex.

OfflineData.sample and OfflineSingleAgentEnvRunner.sample have the most new content and need the closest read. Repeated.sample() is documented as returning 1 to max_len items, which is what it does. The Repeated class docstring's example still says "from 0 to 10 boxes", because contains() does accept an empty list.

Rows left out on purpose:

  • Methods whose new Args: sections would need parameter type hints first. Ray's pydoclint configuration fails an Args: section on an unannotated signature. These are MetricsLogger.log_dict, one_hot_multidiscrete, FlexDict.assertSpace, Repeated.contains, Simplex and its contains, to_jsonable, and from_jsonable, and SampleBatch.get. They go in a separate PR without the label.
  • SampleBatch.concat_samples and MultiAgentBatch.concat_samples, which are @Deprecated(error=True) stubs.

Related issue number

None. The work comes from the docs team's inventory of @PublicAPI symbols with missing docstrings. It follows #67626, and its companion for algorithms, core, and connectors is #67629. I searched open PRs for RLlib docstring work and for these files and found no overlap.

Checks

  • pre-commit run --files <changed files>: all hooks pass, including ruff, black, and pydoclint 0.9.1 with the repo's arguments.
  • python ci/ray_ci/doc/check_docstring_only.py --base <merge-base>, with both the guard from this PR's base and the guard as of [ci] Extend the docstring-only guard to Cython and .pyi files #67599: docstring-only guard: 13 file(s), docstrings only.
  • No >>> examples were added or changed.

The commit carries an @rtd-build line so Read the Docs builds a preview.

AI assistance (Claude Code) was used to draft these docstrings. I reviewed every changed line against the code.

🤖 Generated with Claude Code

…atch, and utils APIs

Document existing behavior on public methods and classes in
ray.rllib.offline, ray.rllib.policy.sample_batch, and ray.rllib.utils that
have no docstring, no parameter entry, or no Returns section.

@rtd-build

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman dstrodtman added the docstring-only Skip heavy library tests for Ray API docstring edits. label Oct 30, 2026
@dstrodtman
dstrodtman requested a review from a team as a code owner October 30, 2026 18:06
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

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

@ray-gardener ray-gardener Bot added rllib RLlib related issues docs An issue or change related to documentation labels Oct 30, 2026
@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Nov 3, 2026
@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit dc099e3 into master Nov 3, 2026
7 checks passed
@pseudo-rnd-thoughts
pseudo-rnd-thoughts deleted the doc-1914-rllib-offline-utils-docstrings branch November 3, 2026 14:55
dstrodtman added a commit that referenced this pull request Nov 3, 2026
…#67631)

## Why are these changes needed?

These public RLlib methods and classes had no docstring, or no `Args:`
or `Returns:` section, and their signatures had no type hints. Ray runs
pydoclint with `--arg-type-hints-in-signature`, which fails an `Args:`
section on an unannotated signature. So documenting them means adding
parameter hints too, and they can't go in a `docstring-only` PR the way
#67629 and #67630 do. This PR adds both. It's the companion to those
two.

What changed:

- **`RLlibCallback.on_workers_recreated`:** Type hints and a docstring.
It marks the hook as deprecated in favor of
`on_env_runners_recreated()`, as the existing source comment says, and
notes that `Algorithm` still calls it.
- **`AgentToModuleMapping`:** A hint for `agent_to_module_mapping_fn`,
using the existing `AgentToModuleMappingFn` alias, and `Args:` for all
constructor arguments, including what `as_learner_connector` changes.
- **`ConnectorPipelineV2.__call__` and
`NormalizeAndClipActions.__call__`:** `**kwargs: Any`, plus `Args:` and
`Returns:` sections.
- **`Learner.apply`:** Hints and a docstring.
- **`RLModuleSpec.from_dict` and `MultiRLModuleSpec.from_dict`:** `d:
Dict[str, Any]`, plus `Args:` and `Returns:` sections.
- **`MetricsLogger.log_dict`:** `value_dict: Dict[str, Any]` and an
`Args:` section.
- **`one_hot_multidiscrete`:** Hints and a docstring.
- **`FlexDict.assertSpace`, `Repeated.contains`, `Simplex`, and
`Simplex.contains`, `to_jsonable`, and `from_jsonable`:** Hints and
docstrings.
- **`SampleBatch.get`:** Hints and `Args:` and `Returns:` sections.

Apart from the `one_hot_multidiscrete` and `AgentToModuleMapping` fixes
below, nothing changes at runtime. Stripping docstrings, annotations,
and imports, the AST of every changed file except `utils/numpy.py`
matches the base commit.

### Three fixes to existing mistakes

- `one_hot_multidiscrete(x, depths=List[int])` made the
`typing.List[int]` object the *default* value of `depths` instead of its
annotation. This PR makes it `depths: List[int]`. A call that left out
`depths` already raised `TypeError` when the function iterated the
default, so this only changes the error such a call gets.
- `MultiRLModule.values()` returns `self._rl_modules.values()`, a view
of RLModules, but it was annotated `ValuesView[ModuleID]` and its
summary said it iterates over module IDs. This PR corrects both. The
docstring fix moved here from #67629, so the two PRs don't edit adjacent
lines.
- The `AgentToModuleMapping` docstring example returned `{}` instead of
the output its `check()` expects. Without `as_learner_connector=True`,
the connector keeps only the agents that act next in `episodes`, and the
example passes `episodes=[]`. The example now passes
`as_learner_connector=True` and runs as written.

## Related issue number

None. The work comes from the docs team's inventory of `@PublicAPI`
symbols with missing docstrings, and it completes the RLlib list with
#67626, #67628, #67629, and #67630. I searched open PRs for these files
and for RLlib docstring work and found no overlap.

## Checks

- `pre-commit run --files <changed files>`: all hooks pass, including
ruff, black, and pydoclint 0.9.1 with the repo's arguments.
- `pytest` against this branch's `rllib` on the current nightly wheel,
covering `test_metrics_logger.py`, `test_serialization.py`,
`test_sample_batch.py`, `test_multi_agent_batch.py`, and
`test_multi_agent_env_runner.py`: 63 passed and 2 failed. The failures
are `TestSampleBatch::test_count` and `test_interceptors`, and they fail
the same way without this PR's changes. They look like a mismatch with
the NumPy 2.5 in my local environment.
- A smoke test of every changed symbol: `one_hot_multidiscrete` with
numpy and torch inputs, `Simplex` sample, contains, and the JSON round
trip, `Repeated.contains`, `FlexDict.sample`, `SampleBatch.get`,
`MetricsLogger.log_dict` with a key prefix, `Learner.apply`, and
`on_workers_recreated`.
- The fixed `AgentToModuleMapping` docstring example, run as written:
passes.

AI assistance (Claude Code) was used to draft the docstrings and type
hints. I reviewed every changed line.

🤖 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs An issue or change related to documentation 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