Repository navigation
[core] Add a docstring-level +SKIP_EXAMPLE doctest flag for render-only examples - #66753
Conversation
…ly examples Registers SKIP_EXAMPLE in the default and Ray Data doctest plugins and skips any docstring whose examples carry it. First user: the three TPU examples in ray.util.tpu, which need TPU hardware and were :skipif: True testcode. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a custom doctest option flag SKIP_EXAMPLE and a corresponding pytest collection hook in both bazel/default_doctest_pytest_plugin.py and python/ray/data/tests/doctest_pytest_plugin.py to allow skipping entire docstring examples. It also updates TPU-related docstrings in python/ray/util/tpu.py to use this new flag. The feedback suggests improving the robustness of the pytest collection hooks in both plugin files by safely retrieving the examples attribute and avoiding duplicate skip markers on the same test item.
| def pytest_collection_modifyitems(config, items): | ||
| for item in items: | ||
| dtest = getattr(item, "dtest", None) | ||
| if dtest is not None and any( | ||
| example.options.get(SKIP_EXAMPLE) for example in dtest.examples | ||
| ): | ||
| item.add_marker( | ||
| pytest.mark.skip(reason="render-only example (+SKIP_EXAMPLE)") | ||
| ) |
There was a problem hiding this comment.
To make the collection hook more robust and adhere to defensive programming practices, we should handle cases where dtest might not have an examples attribute (e.g., if it's a mock or custom test item). Additionally, if both doctest plugins are loaded in the same session, we should prevent adding duplicate skip markers to the same item by checking a custom attribute.
| def pytest_collection_modifyitems(config, items): | |
| for item in items: | |
| dtest = getattr(item, "dtest", None) | |
| if dtest is not None and any( | |
| example.options.get(SKIP_EXAMPLE) for example in dtest.examples | |
| ): | |
| item.add_marker( | |
| pytest.mark.skip(reason="render-only example (+SKIP_EXAMPLE)") | |
| ) | |
| def pytest_collection_modifyitems(config, items): | |
| for item in items: | |
| dtest = getattr(item, "dtest", None) | |
| if dtest is not None and not getattr(item, "_skip_example_marked", False): | |
| examples = getattr(dtest, "examples", []) | |
| if any(example.options.get(SKIP_EXAMPLE) for example in examples): | |
| item.add_marker( | |
| pytest.mark.skip(reason="render-only example (+SKIP_EXAMPLE)") | |
| ) | |
| item._skip_example_marked = True |
There was a problem hiding this comment.
Declining. The new hook only runs on items from pytest's doctest collector or ray-project/pytest-sphinx, and both build DoctestItems whose dtest is a doctest.DocTest, which always has examples. Items that aren't doctests have no dtest and are already filtered out. Also, only one of the two plugins loads per session: bazel/python.bzl passes a single -p <pytest_plugin_file>, and Data's targets override it rather than add to it. So the duplicate-marker guard covers a case that can't happen.
| def pytest_collection_modifyitems(config, items): | ||
| for item in items: | ||
| dtest = getattr(item, "dtest", None) | ||
| if dtest is not None and any( | ||
| example.options.get(SKIP_EXAMPLE) for example in dtest.examples | ||
| ): | ||
| item.add_marker( | ||
| pytest.mark.skip(reason="render-only example (+SKIP_EXAMPLE)") | ||
| ) |
There was a problem hiding this comment.
To make the collection hook more robust and adhere to defensive programming practices, we should handle cases where dtest might not have an examples attribute (e.g., if it's a mock or custom test item). Additionally, if both doctest plugins are loaded in the same session, we should prevent adding duplicate skip markers to the same item by checking a custom attribute.
| def pytest_collection_modifyitems(config, items): | |
| for item in items: | |
| dtest = getattr(item, "dtest", None) | |
| if dtest is not None and any( | |
| example.options.get(SKIP_EXAMPLE) for example in dtest.examples | |
| ): | |
| item.add_marker( | |
| pytest.mark.skip(reason="render-only example (+SKIP_EXAMPLE)") | |
| ) | |
| def pytest_collection_modifyitems(config, items): | |
| for item in items: | |
| dtest = getattr(item, "dtest", None) | |
| if dtest is not None and not getattr(item, "_skip_example_marked", False): | |
| examples = getattr(dtest, "examples", []) | |
| if any(example.options.get(SKIP_EXAMPLE) for example in examples): | |
| item.add_marker( | |
| pytest.mark.skip(reason="render-only example (+SKIP_EXAMPLE)") | |
| ) | |
| item._skip_example_marked = True |
There was a problem hiding this comment.
Declining. The new hook only runs on items from pytest's doctest collector or ray-project/pytest-sphinx, and both build DoctestItems whose dtest is a doctest.DocTest, which always has examples. Items that aren't doctests have no dtest and are already filtered out. Also, only one of the two plugins loads per session: bazel/python.bzl passes a single -p <pytest_plugin_file>, and Data's targets override it rather than add to it. So the duplicate-marker guard covers a case that can't happen.
ronny-anyscale
left a comment
There was a problem hiding this comment.
Approving — the mechanism is sound and the fail-loud property is the right call. Registering the flag means a missing plugin errors at collection instead of quietly trying to run examples that need hardware, which is the failure mode you actually want.
One gap worth a follow-up, and I think it's load-bearing rather than cosmetic.
Nothing tells a contributor this flag exists. It's described in two plugin-file comments and this PR description. Someone writing a docstring reads doc/source/ray-contribute/writing-code-snippets.md, and its "How to handle hard-to-test examples" section currently routes them the other way:
[line 203] To skip a doctest-style example, append
# doctest: +SKIPto your Python code.
So the next person with an un-runnable example follows that line and writes +SKIP on every statement — the exact thing this PR exists to avoid. Two other spots say the same: line 214 still presents :skipif: True on testcode as the way to skip, and line 371 repeats the +SKIP / :skipif: pair.
That matters more than usual here because the stated payoff is the ~700 flags across the remaining blocks. The value is almost entirely in future adoption, and right now the guide points away from it. A few lines in the "Skipping doctest-style examples" section — use +SKIP_EXAMPLE once for an example that can never run, +SKIP per statement otherwise — would close it.
Happy to write that if it's useful, either on this PR or as a follow-up.
Smaller, non-blocking: the duplicated hook reads fine with the keep-in-sync comments both ways, and I agree it beats a Bazel data dep on every Data target. If a third plugin file ever appears it'd be worth revisiting, but not now.
|
@ronny-anyscale (and Claude): Yes, planning to drive full deprecation for all other API example patterns. I'm just going to push through a full migration and then document the new standard as code changes land (this will touch every API source file owned by library teams, so there will be maintainer alignment, awareness, and sign-off). This is clearing the way for a pilot batch of conversions, along with a few other in-flight PRs. |
…les to stock doctests (#67070) ## What Convert the remaining `.. testcode::` examples in two `ray.data` torch docstrings to stock `>>>` doctests: - `TorchVisionPreprocessor`: two runnable blocks. - `TorchInference`: one `:skipif: True` block. It needs a GPU (`.cuda()`, `num_gpus=1`), so it carries the docstring-level `# doctest: +SKIP_EXAMPLE` flag from #66753 instead. ## Why This continues the convergence in #66746 and #66812, with the same conversion rules: same code, same order, same docstring, blank lines inside a block dropped, and each example under a plural `Examples:` header with no blank line after it. Lead-in sentences stay inside the section. It's also the first Data PR opened after #66814 merged, and it carries the `docstring-only` label, so its premerge build exercises the new `data: docstring examples` step and the `lint: validate docstring-only scope` guard on a real build. #66812 deferred `preprocessors/torch.py` because it needs `torchvision`. That's true locally only: `torchvision` is in `python/requirements/ml/data-test-requirements.txt`, which the `datalbuild` image the new step uses installs. `TorchInference` changes test reporting as well as markup. Ray's `pytest-sphinx` fork drops `:skipif: True` blocks before collection, so the example wasn't reported at all. Under `+SKIP_EXAMPLE`, the Data doctest plugin and the new runner both report it as skipped. ## Not in this PR `SerializablePreprocessorBase._set_serializable_fields` stays as is, for the reason in #66812: it shows a method pattern in prose, not under an `Examples:` section. `dataset.py`, `read_api.py`, and `llm.py` go in their own PRs. ## Duplicate check I searched open PRs for `TorchVisionPreprocessor`, `torch_inference`, and `testcode doctest data`. The only related open PRs are my own #66746, #66812, and #66809, which touch other files. ## Tests run Locally, against a Ray nightly (`43b706d`) on Python 3.12 with the edited modules overlaid and `torchvision` 0.29.1 installed. The pytest runs use pytest 7.4.4 and the same flags as the `doctest` Bazel macro, `--doctest-modules -c NO_PYTEST_CONFIG -p <Ray Data doctest plugin>`, with both collectors installed. | Run | Before | After | |---|---|---| | pytest, both collectors | 1 passed | 1 passed, 1 skipped (`+SKIP_EXAMPLE`) | | pytest, `-p no:sphinx` | n/a | 1 passed, 1 skipped | | `ci/ray_ci/doc/run_docstring_examples.py` on both files | n/a | 1 docstring run, 0 failed, 1 skipped | | `ci/ray_ci/doc/check_docstring_only.py --base upstream/master` | n/a | passes: 2 files, docstrings only | The `TorchVisionPreprocessor` example reads `s3://anonymous@air-example-data-2/imagenet-sample-images`, as it did before, so it needs network access. `pre-commit` passes on the changed files. **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]>
#67080) ## What Convert the 10 `.. testcode::` blocks in `python/ray/data/read_api.py` to stock `>>>` doctests: - `read_parquet`: the projection and filter pushdown example joins the docstring's existing `>>>` session, and its `testoutput` becomes the expected output, so the `show(2)` result is still checked. - `read_sql`: the SQLite example, which now creates its database in a temporary directory and checks one read with `ds.count()`. See below. - `read_bigquery`, `read_snowflake`, `read_databricks_tables` (2 blocks), `read_delta_sharing_tables`, and `read_kafka` (2 blocks): `:skipif: True` examples that need an external service or credentials. Each docstring carries the docstring-level `# doctest: +SKIP_EXAMPLE` flag from #66753 once. None of these five docstrings has another `>>>` example for the flag to skip by accident. ## Why This continues the convergence in #66746, #66812, and #67070, with the same conversion rules: same code, same order, same docstring, blank lines inside a block dropped, bare expressions with an incidental repr bound to `_`, and each example under a plural `Examples:` header with no blank line after it. `read_snowflake`'s singular `Example:` header becomes `Examples:`. For the label from #66814, this is a larger case than #67070. The runner runs every docstring in a changed file, so it runs all 35 runnable docstrings in `read_api.py`, not only the 10 converted blocks. It also checks output on `read_parquet` and runs five `+SKIP_EXAMPLE` docstrings. ### Design choices for review - **`read_sql` creates its database in a temporary directory.** The original wrote `example.db` to the working directory and removed it in a hidden `.. testcode:: :hide:` block, because a second run in the same directory fails on `CREATE TABLE movie` ("table movie already exists"). Stock doctest has no run-but-hide form. The example now opens `os.path.join(db_dir.name, "example.db")` under a `tempfile.TemporaryDirectory()` and ends with `db_dir.cleanup()`, so it can be rerun by readers as well as in CI, with no test-harness change. An in-memory SQLite database wouldn't work: `read_sql` calls `connection_factory` inside each read task, in a worker process, so each worker would open a new empty database. The same `TemporaryDirectory` pattern is in #66812's `list_stats_summaries`. - **`read_sql` now checks a read.** The example never consumed the datasets it built, so it didn't show that a read works. It now calls `ds.count()` on the all-movies query and expects `4`. With no `shard_keys`, `read_sql` falls back to a single read task whose metadata has no row count, so `count()` runs that task in a worker and opens the database through `create_connection`. On a warm local cluster the count takes about 1 second. - **Two `connection.execute(...)` calls are bound to `_`.** As a statement in `testcode` they printed nothing, but as `>>>` they'd echo a `sqlite3.Cursor` repr with a memory address. ## Duplicate check I searched open PRs for `read_api`, `read_sql`, `read_kafka`, and `testcode doctest data`. #66604 touched `read_api.py` but is merged and changed different text. The only related open PRs are my own #66746, #66812, and #67070, which touch other files. ## Tests run Locally against a Ray nightly (`43b706d`) on Python 3.12, using pytest 7.4.4 and the same flags as the `doctest` Bazel macro, `--doctest-modules -c NO_PYTEST_CONFIG -p <Ray Data doctest plugin>`, with both collectors installed. `master`'s `read_api.py` imports `ray.data.checkpoint.generated_id`, which that nightly predates, so I applied this PR's diff to the nightly's own `read_api.py` rather than overlaying `master`'s copy. | Run | Before | After | |---|---|---| | pytest, both collectors | 31 passed, 5 failed | 30 passed, 5 skipped, 5 failed | | pytest, `-p no:sphinx` | n/a | 30 passed, 5 skipped, 5 failed | | `read_parquet` and `read_sql` alone, each collector setup | 1 passed each | 1 passed each | | `read_sql` run twice in the same directory, `-W error::ResourceWarning` | n/a | passed both times, about 4 seconds each, no `example.db` left in the working directory | | `ci/ray_ci/doc/check_docstring_only.py --base upstream/master` | n/a | passes: 1 file, docstrings only | The pass count drops by one because `pytest-sphinx` collected the `read_parquet` and `read_sql` `testcode` blocks as two extra items. They're now part of the stock doctest items, one per docstring, and `read_sql` gains a stock item it didn't have. The five `:skipif: True` blocks were dropped before collection and never reported. They now report as skipped. The same five docstrings fail before and after, all in docstrings this PR doesn't touch, because of my local environment: `from_tf` (`tensorflow_datasets`), `read_audio` (`soundfile`), `read_avro` (`fastavro`), `read_videos` (`decord`), and `read_json`, whose `ds.schema()` prints `string` where the docstring expects `object` because of a newer local pandas. The `run_docstring_examples.py` runner on the file reports 35 docstrings run, with the same five failures and five skips. `pre-commit` passes on the changed file. **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]> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
…EXAMPLE doctests (#67209) ## Description Converts the never-run `.. testcode::` / `:skipif: True` examples for Ray Data's external-service sinks and the Hive reader to `>>>` doctests. Each docstring is flagged once with the docstring-level `# doctest: +SKIP_EXAMPLE` from #66753. The change touches only docstrings: - **`python/ray/data/dataset.py`**: 10 blocks in `write_iceberg`, `write_delta`, `write_webdataset`, `write_snowflake`, `write_mongo`, `write_bigquery`, `write_clickhouse`, `write_turbopuffer` (2 blocks), and `write_kafka`. - **`python/ray/data/read_api.py`**: the `read_hive` example. - **`python/ray/data/_internal/datasource/turbopuffer_datasink.py`**: the 3 `TurbopufferDatasink` examples. Each example needs a service, credentials, or a bucket that CI doesn't have, so they stay render-only, as before. The flag is stripped at render time by both Sphinx (`trim_doctest_flags`) and griffe. The conversion follows the rules from #67080: same code in the same order, blank lines inside a block dropped, and top-level comments as `>>> #` lines. Two docstrings needed something other than the flag: - **The `Dataset` class docstring runs its example now.** That docstring also holds 10 runnable `>>>` examples, and `+SKIP_EXAMPLE` skips a whole docstring, so it would have stopped them from running. Instead, only the two lines that use placeholder paths, `read_parquet("s3://bucket/path")` and `write_csv("s3://bucket/output")`, carry `# doctest: +SKIP`. The `range` and `from_items` lines run. - **`write_csv`'s example had an unterminated string**, `"s3://bucket/folder/)`. It was already `+SKIP`, so nothing ever parsed it. The closing quote is now in place, so the docstring parses with the stock doctest parser. The `:skipif: True` blocks left in `dataset.py` after this PR are in #67202 (`join`) and #67207 (`streaming_split`). ## Related issues Related to #66753, #67080, #67202, and #67207. ## Additional information **Not a duplicate.** I searched open PRs for each method name, `turbopuffer`, `SKIP_EXAMPLE`, and `testcode skipif data`. #67202 and #67207 are my own and convert other methods in `dataset.py`. Two open PRs edit text these examples sit next to, so whichever PR lands second needs a small rebase: - #66192 edits the `write_iceberg` example's content, adding a REST catalog write. This PR changes only the example's form. - #66308 adds a deprecation notice to `write_clickhouse`, next to its example. #67114 and #67168 change `read_api.py` but not the `read_hive` docstring example. **Tests run** - `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "3 file(s), docstrings only." - `ci/ray_ci/doc/run_docstring_examples.py` on the three files, in an aarch64 image with the Ray nightly at `093faf5583e` and the changed files mounted over the installed ones. None of the three files changed between that commit and this PR's base. Result: 85 docstrings run and 1 failed, with 16 skipped for `+SKIP_EXAMPLE` and 5 for an omitted library (torch, torchvision, TensorFlow, `tensorflow_datasets`). All 13 converted docstrings report `SKIP (+SKIP_EXAMPLE)`, and `Dataset` and `Dataset.write_csv` pass. The one failure is `read_videos`, which this PR doesn't touch. It needs `decord`, which has no aarch64 wheel. The run installed `datasketches`, `Pillow`, `crc32c`, `soundfile`, and `fastavro`, which the base image lacks. Without them, six more untouched docstrings fail on the missing import. - Every `>>>` example in the three files compiles with the stock `doctest` parser once `SKIP_EXAMPLE` is registered. - `pre-commit run --files` on the three files: all hooks pass, including ruff, black, pydoclint, and the Ray docstyle check. The PR carries the `docstring-only` label, and its commit carries an `@rtd-build` line for the Read the Docs preview. AI assistance (Claude Code) was used for this PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…ctests (#67619) ## Description Converts the never-run `.. testcode::` examples in the `TuneReportCheckpointCallback` docstrings of `python/ray/tune/integration/lightgbm.py` and `python/ray/tune/integration/xgboost.py` to `>>>` examples. Sphinx renders `.. testcode::`, but griffe and MkDocs don't, and stock `>>>` examples render in both. Both blocks were `:skipif: True`, so they never ran. They now carry the docstring-level `# doctest: +SKIP_EXAMPLE` flag (#66753), which skips the whole docstring in the doctest targets and in the docstring examples step, so they still never run. The example code is unchanged. The LightGBM docstring's NumPy-style `Examples` header with a dashed underline becomes the Google-style `Examples:` header that the rest of Tune uses. This is a syntax-only change. The three other remaining Tune `testcode` blocks, in `tune/callback.py` and `tune/result_grid.py`, pair with a hidden `testoutput` that matches any output. Converting them changes what each example checks, so they're in #67623 for Tune review rather than in this one. Stacked on #67237, which adds `lightgbm` and `xgboost` to the docstring examples runner's `OMITTED_LIBRARIES`. Both modules import their library at module level, and the `docstringbuild` image installs neither. Without that change, the examples step would fail both modules at import, rather than skip them. ## Related issues Related to #66748, #66753, and #67237. ## Additional information **Not a duplicate.** I searched open PRs for Tune doctest and `testcode` conversions. None touches these docstrings. #66748, which has merged, converted the `Trainable` and `Callback` method examples. **Tests run** - `ci/ray_ci/doc/check_docstring_only.py --base upstream/doc-1863-docstring-runner-bundle`: "2 file(s), docstrings only." - `ci/ray_ci/doc/run_docstring_examples.py` on both files, in a Python 3.12 virtualenv with `ray[tune]==2.59.0` and neither library installed. With #67237's runner, both modules are skipped by name: "module needs lightgbm" and "module needs xgboost," 0 failed. With `master`'s runner, both fail at import. - Parsed both docstrings with `doctest.DocTestParser` and compiled every example: 4 examples in `lightgbm.py` and 6 in `xgboost.py`. Both docstrings carry `SKIP_EXAMPLE`, so `bazel/default_doctest_pytest_plugin.py` skips each one whole. - `pre-commit run --files` on both files: all hooks pass. The PR carries the `docstring-only` label, and its commit carries an `@rtd-build` line for the Read the Docs preview. AI assistance (Claude Code) was used for this PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
) ## 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]>
…#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]>
…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]>
## 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]>
…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]>
…#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]>
…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]>
…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]>
…run (#67759) ## Description This is a correctness change for RLlib review. It fixes `rllib.connectors` docstring examples that were wrong, and it converts the last two `testcode` blocks in `rllib/connectors`. Those blocks needed an expected-output change, so they stayed out of the syntax-only conversion in #67758. After this PR, no `testcode` or `testoutput` remains in `rllib/connectors`. Stacked on #67758. Review that PR first. This diff is against its branch. ### `testcode` blocks this PR converts - `AddObservationsFromEpisodesToBatch` and `AddNextObservationsFromEpisodesToTrainBatch`: each example prints observations drawn from `obs_space.sample()` and shows no expected output. Each print now shows its output, with `...` in place of the random values, such as `1st Episode's last obs is [...]`. The next-observations example shows that `get_observations([1, 2])` returns a list of float32 arrays. Both now run. ### Examples that were wrong - `AgentConnector`: the `FrameSkippingAgentConnector` sketch called `default_dict`, which doesn't exist. It also indexed the frame count with `ac_data.env_id`, but `ac_data` is the input list, not an item. It now uses `collections.defaultdict`, and it indexes with `d.env_id` and `d.agent_id`. With the fix, the class emits an item on every `n`th call, and `reset()` clears the count. The doctest defines the class but doesn't call it. This also fixes the "prosessed" typo in the prose that follows. - `ActionConnector`: the example called `np.zeros_like` without importing NumPy. It now imports it. - `AddColumnsFromEpisodesToTrainBatch`: the config snippet ended with a stray backtick. It also called `config.training(learner_connector=...)`, which is deprecated in favor of `config.learners(learner_connector=...)`, so it now calls `learners()`. It stays a render-only `python` code block, because it sits mid-prose and uses the reader's own `config`. - `AddTimeDimToBatchAndZeroPad`: a comment said the learner connector uses a sequence length of 4. The dummy module sets `max_seq_len` to 3, and the checked output is chunked by 3, so the comment now says 3. ### Review fixes - `AgentConnector`: the `FrameSkippingAgentConnector.reset` sketch used `del self._frame_count[env_id]`, which raises `KeyError` for an env that hasn't stepped yet. It now uses `pop(env_id, None)`. From a gemini-code-assist comment. ## Related issues Stacked on #67758. 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 5 changed files: "5 docstring(s) run, 0 failed, 0 skipped, in 5 file(s)." - A strict stdlib `doctest` pass over the same docstrings with `ELLIPSIS`, which fails on unexpected output the way the RLlib `doctest()` target does: all 5 pass. - `ci/ray_ci/doc/check_docstring_only.py --base doc-1926-rllib-connectors-doctests`: "5 file(s), docstrings only." - `pre-commit run --files` on all 5 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]>
…es and make them run (#67768) ## Description This is a correctness change for RLlib review. It fixes `rllib.evaluation` and `rllib.policy` docstring examples that were wrong or couldn't run. It also turns the two code-block fallbacks from #67767 back into doctests. After this PR, 17 of these docstrings run in the doctest target, and no `testcode` or `testoutput` remains in either subpackage. Stacked on #67767. 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. - `get_learner_stats`: the example called `get_stats`, which doesn't exist, on the result of `worker.learn_on_batch(samples)`, where `worker` and `samples` were undefined. It now passes literal `grad_info` dicts in the shape the old comment showed, covering both the single-agent and the multi-agent case. - `discount_cumsum`: the output was a symbolic formula. It's now the real `array([4.707, 5.23 , 4.7 , 3. ])`, and the formula is a comment. - `RolloutWorker.sample`, `sample_with_count`, `learn_on_batch`, `compute_gradients`, and `apply_gradients`: - `PPOTF1Policy` fails to build with the default config, so each example now passes a `PPOConfig` with the old API stack enabled and `framework("tf")`. - `sample_with_count` used `PPOTFPolicy` instead of `PPOTF1Policy`. - `sample` used `AlgorithmConfig` without importing it. - `learn_on_batch` and `compute_gradients` passed an undefined `samples` instead of `batch`. - `sample()` returns a `MultiAgentBatch`, not a `SampleBatch`, so the outputs now show that. - `chop_into_sequences`: the outputs now show the list of arrays and the array that the function returns. The values are the same as before. - `ViewRequirement`: `ModelV2(...)` raised `TypeError`. The example now builds a `ModelV2` with real spaces. It shows that the model's only default view requirement is `obs`, with `shift=0`. - `SampleBatch.concat`, `rows`, `columns`, `shuffle`, `split_by_episode`, and `right_zero_pad`: - The outputs were dict literals, but `print(batch)` shows a summary such as `SampleBatch(5: ['a'])`. The examples now print columns, and the outputs are real. - `split_by_episode` set a `"dones"` column, which `SampleBatch` rejects with `KeyError`. It now sets `"terminateds"`, which the splitter reads. - `shuffle` now seeds NumPy, so its output is fixed. - `concat_samples` and `concat_samples_into_ma_batch`: - Both passed plain dicts to `MultiAgentBatch`, which asserts on `SampleBatch` values. - The second `concat_samples` call concatenated `b1` and `b2` instead of `c1` and `c2`. - The `concat_samples_into_ma_batch` example called `concat_samples`. - The outputs now show the real `MultiAgentBatch` repr and the concatenated columns. The five `RolloutWorker` examples build old-API-stack TF1 PPO policies. They take about 9 seconds together on CPU. Their outputs show 2,000 sampled steps, which comes from PPO's default config. I ran them locally, but not under Bazel. If RLlib would rather not run old-API-stack TF code in the doctest target, re-adding `# doctest: +SKIP_EXAMPLE` keeps the corrected examples render-only. ### Fixed but still render-only - `RolloutWorker` class docstring: the single-agent half gets the same config fix and runs. The multi-agent half uses placeholders and `PGTFPolicy`, which RLlib no longer has, so the docstring stays skipped. - `RolloutWorker.set_global_vars`: the stray `...` is gone, and so is the assignment of the method's `None` return value. It's a doctest again. - `SampleCollector.add_init_obs`, `add_action_reward_next_obs`, and `get_inference_input_dict`: - The `add_action_reward_next_obs` calls now pass `env_id`. - `add_init_obs` is called with keywords, since its arguments are keyword-only. - `get_inference_input_dict` gets a policy ID, not `policy.model`, and its dict syntax error is fixed. - The examples still use placeholder `env` and `collector` objects. `ObservationFunction.__call__`, `Policy.learn_on_batch`, `Policy.export_checkpoint`, `TFPolicy`, and `RolloutWorker.get_weights`, `set_weights`, and `get_global_vars` use placeholder objects. They're unchanged and stay render-only. ### Found, not fixed here These need RLlib's call, so this PR leaves them alone: - The abstract `SampleCollector.add_init_obs` has no `env_id` parameter, but `SimpleListCollector.add_init_obs`, its only implementation, requires one. The example follows the abstract signature. - The render-only `get_global_vars` output, `{"timestep": 424242}`, leaves out `num_grad_updates_per_policy`, which the real dict contains. ## Related issues Stacked on #67767. 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 7 changed files: "17 docstring(s) run, 0 failed, 8 skipped, in 7 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 17 runnable docstrings pass, and the rest carry `+SKIP_EXAMPLE`. - `ci/ray_ci/doc/check_docstring_only.py --base doc-1926-rllib-evaluation-policy-doctests`: "7 file(s), docstrings only." - `pre-commit run --files` on all 7 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]>
…cstring examples (#67762) ## Description This is a correctness change for RLlib review. It fixes docstring examples in `rllib/models`, `execution`, `offline`, and `callbacks` that were wrong or couldn't run, and it converts the last `testcode` block in those subpackages. Where a fix is verified, the example now runs in the doctest target. After this PR, no `testcode` or `testoutput` remains in these four subpackages. Stacked on #67761. Review that PR first. This diff is against its branch. ### Examples that now run - `models/catalog.py`, `ModelCatalog`: the example used undefined placeholders, such as `env` and `raw_observation`. It also read `model.outputs`, which `ModelV2` doesn't have. It's now a working CartPole example with `framework="torch"`. It gets logits by calling the model and passes them to the distribution class. - `models/preprocessors.py`, `OneHotPreprocessor`: the example called `self.transform` on a random sample, and it wrote the output as `np.array(...)`. It now builds the preprocessor and transforms fixed values. The output is the real `array(..., dtype=float32)`, with the same one-hot values as before. - `models/repeated_values.py`, `unbatch_all` and `unbatch_repeat_dim`: these were `<Tensor shape=...>` pseudocode, and the second one called `batch.unbatch()`, which doesn't exist. Both now use a small torch tensor and print lengths and shapes. Both docstrings gain a `Returns` entry, which pydoclint requires once a docstring has an `Examples:` section. Each entry describes what the method body returns. - `execution/buffers/mixin_replay_buffer.py`, `MixInMultiAgentReplayBuffer`: the hidden `...` output matched anything. The full output varies, because `replay()` appends randomly replayed samples after the newly added batches. The example now prints the first three entries, `[1 2 2]`, which are always the newly added batches. - `offline/input_reader.py`, `InputReader.tf_input_ops`: the example called `self._build_layers_v2`, which doesn't exist in RLlib. It also read `input_ops["action"]`, but the column is `"actions"`. It now calls `self.forward(...)`, as `examples/_old_api_stack/models/custom_loss_model.py` does. The prose pointed to `examples/custom_loss.py`, which doesn't exist, and now points to that file. - `models/modelv2.py`, `get_initial_state` and `forward`: these class-definition sketches pass unchanged, so they drop `+SKIP_EXAMPLE`. - `callbacks/callbacks.py`, `on_offline_eval_runners_recreated`: the example read `is_evaluation`, which isn't a parameter of this hook. It also passed `remote_runner_ids=` to `foreach_runner`, which takes `remote_worker_ids`. Both are fixed. - `callbacks/callbacks.py`, `on_env_runners_recreated`: a comment named `local_worker=False`, but the code passes `local_env_runner=False`. ### Examples that stay render-only - `execution/train_ops.py`, `train_one_step` and `multi_gpu_train_one_step`: these need a built old-API-stack `Algorithm`. This PR removes the stray parenthesis and passes `worker_set=` to `synchronous_parallel_sample`, whose arguments are keyword-only. It also prints the output as a Python dict. They stay code blocks, because an `Examples:` section makes pydoclint require type hints in the function signatures, and that's a code change. - `offline/mixed_input.py`, `MixedInput`: this needs an `IOContext`, local JSON files, and an S3 path. It keeps `+SKIP_EXAMPLE`. ### Found, not fixed here This is a code issue, not a docstring one, so it's out of scope. `Algorithm._run_one_offline_evaluation` fires the `on_offline_eval_runners_recreated` callback with `env_runner_group=` and `env_runner_indices=`. The hook's signature in `callbacks/callbacks.py` declares `offline_eval_runner_group` and `offline_eval_runner_indices` as keyword-only arguments with no defaults. So an override that follows the documented signature would raise `TypeError` when the callback fires. ### Review fixes - `MixInMultiAgentReplayBuffer`: the example defined a batch `C` that it never used, so it's gone. From a gemini-code-assist comment. ## Related issues Stacked on #67761. Related to #66753. ## Additional information **Not a duplicate.** I searched open PRs for fixes to these docstring examples and found none. **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 the 8 changed files: "10 docstring(s) run, 0 failed, 0 skipped, in 8 file(s)." - A strict stdlib `doctest` pass over the same docstrings with `ELLIPSIS`, which fails on unexpected output the way the RLlib `doctest()` target does: all 10 pass. - `ci/ray_ci/doc/check_docstring_only.py --base doc-1926-rllib-models-execution-doctests`: "8 file(s), docstrings only." - `pre-commit run --files` on all 8 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]>
## Description Converts the `.. testcode::` examples in Ray Train API 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 Core conversion in #67760 and the Tune conversion in #67619. This PR covers 23 files under `python/ray/train/`: - **Runnable examples stay runnable.** Pytest doctest collects only `>>>`, so nothing ran these `testcode` blocks before. Fifteen docstrings now have examples that run: the v2 `TorchTrainer` and `XGBoostTrainer`, the five `TrainContext` getters, `get_all_reported_checkpoints`, `get_dataset_shard`, `DataParallelTrainer`, `BaseTrainer.training_loop`, `LightGBMCheckpoint.from_model`, the Keras `ReportCheckpointCallback`, and the v1 `report` and `get_checkpoint` in `_internal/session.py`. - **`:skipif: True` examples become render-only.** They carry the docstring-level `# doctest: +SKIP_EXAMPLE` flag (#66753). `DataParallelTrainer` mixes runnable examples with one `:skipif:` example, so that example's statements carry a per-line `# doctest: +SKIP` instead, and the rest of the docstring still runs. - **Examples in modules no doctest target covers are render-only too.** That's `horovod/horovod_trainer.py`, `v2/jax/jax_trainer.py`, and `xgboost/xgboost_checkpoint.py`. Whether to add any of them to a target is a separate question. This is a syntax-only change. The example code and the claims in each docstring are unchanged, with these exceptions that the format forces: - **Interleaved examples move into `Examples:`.** In `DataParallelTrainer`, `HorovodTrainer`, `BaseTrainer`, `BaseTrainer.restore`, `JaxTrainer`, `get_dataset_shard`, and three `TrainContext` getters, example paragraphs and code sat in the description. They now sit in an `Examples:` section before `Args:`. The paragraphs that aren't about an example stay in the description. Prose text is unchanged. - **`Example:` and numpy-style `Examples` headers become `Examples:`.** In the LightGBM and XGBoost callbacks and checkpoints, the section moves ahead of `Args:` and `Returns:`. - **`Checkpoint.as_directory` drops a hidden setup block and becomes render-only.** Its `:hide:` block created the `checkpoint` the example uses. Doctests have no hidden form, and showing the setup would change what the example shows. - **`get_trial_dir` in `_internal/session.py`** had `+MOCK` output. It's render-only, and the output moved under the `tuner.fit()` call that prints it. - **Two examples now render that didn't.** `prepare_data_loader` in both `train_loop_utils.py` copies was written `.. testcode:` with one colon, and `XGBoostCheckpoint.from_model` was written `... testcode::`. Sphinx read both as comments, so docs.ray.io never showed them. ### Left out of this PR These blocks pair with a `:hide:` `testoutput`, or share a docstring with one. Converting them changes what the example shows, so they'll follow in a separate PR for Train review: - `TensorflowTrainer`, both v1 and v2, the whole docstring. - `TensorflowCheckpoint.from_model`, which is also `+MOCK`. - `WandbLoggerCallback` in `air/integrations/wandb.py`. - Six v1 functions in `_internal/session.py`: `get_world_size`, `get_world_rank`, `get_local_rank`, `get_local_world_size`, `get_node_rank`, and `get_dataset_shard`. ### Questions for Train - **No doctest target collects the examples of APIs whose `__module__` is rewritten.** `ray/train/__init__.py` imports the public API and then sets `__module__ = "ray.train"` on it: `Checkpoint`, `TrainContext`, `report`, `get_checkpoint`, `get_dataset_shard`, `get_all_reported_checkpoints`, `get_preemption_info`, and others. Both places that could collect these examples miss them: - **The defining module rejects them.** `doctest.DocTestFinder` keeps an object only if `inspect.getmodule(obj)` is the module being scanned, and `getmodule` reads `__module__`. So scanning `ray.train.v2.api.train_fn_utils` skips `report`. For a renamed class such as `TrainContext` or `Checkpoint`, the finder never descends into its methods. - **The package `__init__.py` is never scanned.** Scanning `ray.train` itself would find the renamed functions and class docstrings, though still not the methods. But the `doctest()` macro in `bazel/python.bzl` excludes the package-root `__init__.py`. `RAY_TRAIN_V2_ENABLED` decides which implementation gets renamed. `py_doctest[train]` runs with it on and `py_doctest[train-gpu]` with it off, so each implementation is renamed in exactly the target that would run it. With this PR and #67821, that leaves 12 runnable docstrings uncollected: `Checkpoint`, `Checkpoint.as_directory`, the five `TrainContext` getters, the V2 `get_dataset_shard` and `get_all_reported_checkpoints`, and the V1 `report`, `get_checkpoint`, and `get_dataset_shard` in `_internal/session.py`. The `Checkpoint` class's existing `>>>` examples predate this PR and have never run in a doctest target. I checked this with `DocTestFinder` against `ray==2.59.0` under each flag value. Tune rewrites `__module__` the same way. Its only renamed object with examples, `TuneContext`, copies them from `_internal/session.py`, and `py_doctest[tune]` excludes its file. CI's `run_docstring_examples.py` step reads source files directly, so it still runs these examples, but only on PRs that change those files. Two ways to fix collection: - **Keep the rewriting, and have the shared doctest plugin match objects by their defining file.** Docs can do this, and it doesn't change runtime behavior. - **Stop rewriting `__module__` at runtime.** Either present the public path only in the docs build, or define public APIs in public modules. Both change what users see in `repr()`, tracebacks, or import paths. Train chose the first for now: #67831 changes the plugin, stacked on #67821. - **Bare `trainer.fit()` lines.** Seven runnable examples end in `>>> trainer.fit()` with no expected output: the five `TrainContext` getters, `get_all_reported_checkpoints`, and `get_dataset_shard`. `run_docstring_examples.py` only requires an example with no shown output to run. A strict doctest would also compare the echoed `Result` repr and any worker log lines, so these lines need the `print("[ignore]"); ... # doctest: +ELLIPSIS` form that Tune uses and that #67821 adopts. #67831 makes that change along with the collection fix. ## Related issues Related to #67760, #67619, and #66753. ## Additional information **Not a duplicate.** I searched open PRs for Train `testcode`, doctest, and docstring-example changes. None touches these docstrings. #67520 is the only open Train PR the search returned, and it shares no files with this one. **Tests run** These ran in a Python 3.12 virtualenv with `ray==2.59.0`, `torch`, `tensorflow` 2.21 with `tf_keras`, `lightgbm`, `xgboost`, and `scikit-learn`: - `ci/ray_ci/doc/run_docstring_examples.py` on the 19 files `py_doctest[train]` covers, with `RAY_TRAIN_V2_ENABLED=1 TF_USE_LEGACY_KERAS=1`: "15 docstring(s) run, 0 failed, 20 skipped, in 19 file(s)." - The same runner on `_internal/session.py` with `RAY_TRAIN_V2_ENABLED=0`, matching `py_doctest[train-gpu]`: "2 docstring(s) run, 0 failed, 1 skipped." Neither runnable example needs a GPU. - The same runner on `v2/jax/jax_trainer.py` and `xgboost/xgboost_checkpoint.py`: both skip, as render-only. `horovod_trainer.py` can't import without Horovod, and no CPU target covers it. - `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "23 file(s), docstrings only." - `pre-commit run --files` on all 23 files: all hooks pass, including pydoclint and the Train circular-import check. On macOS, the `TorchTrainer` examples needed `GLOO_SOCKET_IFNAME=lo0`. Without it, gloo aborted the workers, and the controller retried worker startup without limit instead of failing. That's a local transport issue, but an unbounded retry would turn any CI worker-start failure into a hang until the test timeout. 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]>
> [!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]>
…run (#67775) ## Description This is a correctness change for RLlib review. It fixes `rllib.algorithms` docstring examples that were wrong or couldn't run, and it converts the last `testcode` blocks in `rllib/algorithms`. Those blocks needed a change to code, output, or prose, so they stayed out of the syntax-only conversion in #67774. After this PR, no `testcode` or `testoutput` remains in `rllib/algorithms`. Stacked on #67774. Review that PR first. This diff is against its branch. ### Tune examples that now check their result The second example in each of `IMPALAConfig`, `MARWILConfig`, `DQNConfig`, `PPOConfig`, and `APPOConfig` runs `tune.Tuner(...).fit()`. Tune always prints its experiment table to stdout, even with `verbose=0`, so a doctest can't check the exact output. `fit()` doesn't raise when a trial fails, so the old `:hide:` output of `...` checked nothing. Each example now uses the convention from Ray Tune's own docstrings, such as `tune/stopper/stopper.py`: `print("[ignore]"); results = tune.Tuner(...).fit() # doctest: +ELLIPSIS`, with `[ignore]...` as the output. Each then shows `results.num_errors` as `0`, so a failed trial fails the doctest. In `MARWILConfig`, `print(f"beta: {config.beta}")` now shows `beta: 1.0`, and the bare config calls discard their return value. ### Examples that were broken and now run `BCConfig` had these problems: - The data path `./rllib/offline/tests/data/cartpole/large.json` no longer exists, because `rllib/` moved to `python/ray/rllib`. The example now reads `cartpole-v1_large` through `Path(__file__).parents[2]`, as `MARWILConfig` does. The `doctest()` target already ships that data. - `build()` failed, because an offline config without evaluation needs `observation_space` and `action_space`. Both now come from `gym.make("CartPole-v1")`. - The second example passed `beta=0.75`, which `BCConfig.validate` rejects, because BC requires `beta` to be 0.0. That argument is gone, and `print(config.beta)` shows `0.0`. - The `Tuner` had no stop condition. It now stops after one iteration. `+SKIP_EXAMPLE` is gone. ### Fixed but still render-only These examples read `offline/tests/data/pendulum/pendulum-v1_enormous`, which the `doctest()` target doesn't ship, so they keep `+SKIP_EXAMPLE`. Adding that data to the target's `data` would let them run. - `IQLConfig`: the same path, spaces, and stop-condition fixes as `BCConfig`, with Pendulum data and spaces. `print(config.beta)` shows `0.1`. It passes the strict check with `+SKIP_EXAMPLE` removed. - `CQLConfig`: the example built on CartPole with no offline data, and it failed on the replay buffer type. CQL learns continuous actions, so the example now uses `Pendulum-v1` and reads the Pendulum data. `lr=0.01` became `lr=None`, because CQL sets a learning rate per optimizer, and its validation rejects a base `lr`. `print(config.to_dict())` stays as-is. ### Possible RLlib bug, not fixed here In the `CQLConfig` example, `dataset_num_iters_per_learner=1` makes `algo.train()` fail every time, with `KeyError: 0` in `Learner._create_iterator_if_necessary`. It works with 2 or 5, and BC, IQL, and MARWIL work with 1. The example uses 5, as `examples/algorithms/cql/pendulum_cql.py` does. I didn't look into the cause. **CI time.** The six runnable docstrings build an algorithm and train it, and the five Tune examples each take 15 to 28 seconds on CPU. Together they add about 150 seconds to the RLlib `doctest()` target. If that's too much, a docstring-level `+SKIP_EXAMPLE` keeps any of them render-only. ### Review fixes - `BCConfig` and `IQLConfig`: each docstring holds two examples, and they ran together. A blank line now separates them. From gemini-code-assist comments on #67774. - `MARWILConfig`: fixed the typo "evalaution". From a gemini-code-assist comment. ## Related issues Stacked on #67774. 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`, `tensorflow` 2.21, and `pillow`. For these runs, the `cartpole-v1_large` data was linked into the install, where the `doctest()` target's `data` puts it. - `ci/ray_ci/doc/run_docstring_examples.py` on all 8 changed files: "6 docstring(s) run, 0 failed, 2 skipped, in 8 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 6 runnable docstrings pass, and `IQLConfig` and `CQLConfig` carry `+SKIP_EXAMPLE`. - With `+SKIP_EXAMPLE` removed, `IQLConfig` passes the strict check. `CQLConfig` runs every statement, and only the `to_dict()` print has no expected output. - `ci/ray_ci/doc/check_docstring_only.py --base doc-1926-rllib-algorithms-doctests`: "8 file(s), docstrings only." - `pre-commit run --files` on all 8 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]>
…to stock doctests (#67821) ## Description This is a correctness change for Train review. It fixes Train and AIR docstring examples that were wrong, and it converts the examples #67786 left out because converting them changes what they show. After this PR, no `testcode` or `testoutput` remains in `python/ray/train` or `python/ray/air`. Stacked on #67786. Review that PR first. This diff is against its branch. ### Examples that were wrong - **`prepare_data_loader`**, in both `train_loop_utils.py` copies: the example built `train_dataloader`, then passed and looped over `train_loader`, which it never defined. Both now use `train_dataloader`. This example never rendered before #67786, because its directive had one colon. - **`get_devices`**, in both copies: each example's first line compared `CUDA_VISIBLE_DEVICES` with `==` where `get_device` assigns it with `=`. It now assigns. - **`JaxTrainer`**: `train_loop_config={"argv": absolute_argv}` used an undefined name. It now passes `main`'s `argv` parameter. - **`WandbLoggerCallback`**: `train_func` called `train.report` without importing `train`. A function passed to `tune.Tuner` reports with `tune.report`, which the example already imports through `from ray import tune`. - **`report`** in `_internal/session.py`: the example called `ray.train.get_context()` but imported only `from ray import train`. It now calls `train.get_context()`. ### Descriptions that were wrong - **`get_checkpoint()` doesn't return a dict.** The train-loop examples in `DataParallelTrainer`, `HorovodTrainer`, and both `TensorflowTrainer` docstrings said "Returns dict of last saved checkpoint." Both `get_checkpoint` implementations are typed `Optional[Checkpoint]`, so the comment now reads "Returns the last saved checkpoint, or None." - **`LightGBMTrainer`'s default backend isn't "rabit".** Rabit is XGBoost's communicator. With no `lightgbm_config`, the trainer uses `LightGBMConfig()` (`lightgbm/v2.py`), and the description now says so. The same sentence on the XGBoost trainers is correct: `XGBoostConfig.xgboost_communicator` defaults to `"rabit"`. - **`BaseTrainer.fit()` returns `ray.train.Result`.** There's no `ray.result` module. ### Examples that change what they show These pair with a hidden `testoutput`, which has no doctest form. - **`Checkpoint.as_directory` is runnable.** Its hidden block created the checkpoint the example uses. The setup is now visible, including the `23` that `write_text` returns. - **Training runs that printed hidden output** use the idiom Tune already uses for this: `print("[ignore]"); ... # doctest: +ELLIPSIS`, with `[ignore]...` as the output. That covers the v2 `TensorflowTrainer` and six v1 functions in `_internal/session.py`: `get_world_size`, `get_world_rank`, `get_local_rank`, `get_local_world_size`, `get_node_rank`, and `get_dataset_shard`. - **`TensorflowTrainer`** (v1 and v2) gets the same `Examples:` layout as `DataParallelTrainer` in #67786. The signature stubs and the train-loop methods block run. - **Render-only, with `+SKIP_EXAMPLE` or per-line `+SKIP`:** - `get_local_rank` uses `use_gpu=True` with two workers. - The v1 `TensorflowTrainer` training example uses three GPU workers. It sits in a docstring with runnable examples, so its statements carry a per-line `+SKIP`. - `TensorflowCheckpoint.from_model` downloads ResNet-101 weights, and its output was `+MOCK`. - `WandbLoggerCallback` needs a WandB API key, and no doctest target covers `air/integrations/wandb.py`. ### Question for Train: the GPU examples `tensorflow/tensorflow_trainer.py` and `_internal/session.py` are in `py_doctest[train-gpu]`, so the `get_local_rank` and v1 `TensorflowTrainer` examples could run there. I made them render-only because I couldn't run them without GPUs. If you'd rather they run in that target, I'll drop the skips. One thing to check first is that the v1 example asks for three GPU workers. ## Related issues Stacked on #67786. Related to #66753. ## Additional information **Not a duplicate.** I searched open PRs for Train `testcode`, doctest, and docstring-example changes. Only #67786, which this PR stacks on, touches these docstrings. **Tests run** These ran in a Python 3.12 virtualenv with `ray==2.59.0`, `torch`, `tensorflow` 2.21 with `tf_keras`, `lightgbm`, `xgboost`, and `scikit-learn`: - `ci/ray_ci/doc/run_docstring_examples.py` on the 8 changed files that `py_doctest[train]` covers, with `RAY_TRAIN_V2_ENABLED=1 TF_USE_LEGACY_KERAS=1`: "6 docstring(s) run, 0 failed, 10 skipped, in 8 file(s)." `Checkpoint.as_directory` and the v2 `TensorflowTrainer` pass. - The same runner on `_internal/session.py` and `tensorflow/tensorflow_trainer.py` with `RAY_TRAIN_V2_ENABLED=0`, matching `py_doctest[train-gpu]`: "8 docstring(s) run, 0 failed, 2 skipped." All six session functions above pass, except `get_local_rank`, which skips. - The same runner on `v2/jax/jax_trainer.py` and `air/integrations/wandb.py`: both skip, as render-only. - `ci/ray_ci/doc/check_docstring_only.py --base doc-1927-train-air-doctests`: "13 file(s), docstrings only." - `pre-commit run --files` on all 13 files: all hooks pass. I checked the fixes in render-only examples (`prepare_data_loader`, `get_devices`, `JaxTrainer`, `WandbLoggerCallback`) by reading them against the source, not by running them. 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]> Signed-off-by: Mark Towers <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Mark Towers <[email protected]>
What
Adds a docstring-level doctest flag,
# doctest: +SKIP_EXAMPLE, for render-only examples. One flag on any line of a docstring's>>>examples skips that whole docstring at collection time.bazel/default_doctest_pytest_plugin.pyandpython/ray/data/tests/doctest_pytest_plugin.pyregister the flag withdoctest.register_optionflagand add apytest_collection_modifyitemshook that marks the matchingDoctestItems skipped. The two plugins load separately (Data's targets pass their ownpytest_plugin_file), so the ~10 lines are duplicated with a keep-in-sync comment. That's simpler than adding the default plugin as a Bazeldatadependency of every Data doctest target.ray.util.tpuexamples (SlicePlacementGroup,run_on_slice,subslice_placement_group). They need TPU hardware and were.. testcode:: :skipif: True. They're now>>>examples flagged once, indented under theirExamples:header.Why
This continues the convergence of docstring examples from Sphinx
.. testcode::to stock>>>doctests (#65901 and follow-ups), which render under both Sphinx and griffe/mkdocstrings. For examples that can never run in CI, the stock option is# doctest: +SKIPon every statement. Across the remaining:skipif: Trueblocks that's about 700 flags, which is noisy in source. The other forms considered don't render on both toolchains:.. code-block:: python: griffe shows the directive line as literal text.::literal block: griffe shows the::.Both Sphinx (
trim_doctest_flags) and griffe (trim_doctest_flags, regex#\s*doctest:.+$) strip any# doctest:comment from rendered output, so a single custom flag stays invisible to readers.Behavior
SKIPPED (render-only example (+SKIP_EXAMPLE)). Nothing in it executes.ValueError: ... has an invalid option: '+SKIP_EXAMPLE'. If the plugin goes missing, the build breaks instead of silently running examples that can't run.doc/source/conf.pychange is needed.MOCKis registered there becausesphinx.ext.doctestvalidates:options:ontestoutputdirectives, and this flag appears only on>>>lines. A Sphinx 8.2.3 build of these docstrings withautodoc,napoleon, andsphinx.ext.doctestemits no warnings.Test-count impact
ray/util/tpu.pygoes from 0 collected items (pytest-sphinx drops:skipif: Trueblocks before creating an item) to 3 reported as skipped. Nothing new executes.Tests run
Locally, against a Ray nightly with the edited module and plugin overlaid, using pytest 7.4.4 and the
doctestmacro's flags (--doctest-modules -c NO_PYTEST_CONFIG -p <plugin>), with both the stock doctest andray-project/pytest-sphinxcollectors installed:ray/util/tpu.py, new default pluginrender-only example (+SKIP_EXAMPLE)ray/util/tpu.py, new Ray Data pluginray/util/tpu.py, current default pluginray/util/queue.py(unflagged), new default pluginray/data/aggregate.py(unflagged), new Ray Data pluginRendering: each of the three docstrings was rendered before and after with Sphinx 8.2.3 and with
mkdocstrings-python2.0.9 /griffelib2.3.0. Sphinx output is unchanged (a highlighted code block under the "Examples" rubric). Under griffe each now renders as an examples section with highlighted prompts, where before it showed a literal.. testcode:: pythonline.SKIP_EXAMPLEappears in neither rendered page.pre-commitpasses on the changed files.Duplicate check
gh pr list --state open --searchfor "doctest", "SKIP", "doctest_pytest_plugin", and "tpu docstring" found no open PR adding a docstring-level skip or touching these examples.AI assistance
Drafted with AI assistance (Claude Code). The submitter reviews every changed line before marking this ready for review.
🤖 Generated with Claude Code