Repository navigation
[data] Converge ray.data.aggregate docstring examples to stock doctests - #66746
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
griffe only parses a plural Examples: header with content on the next line as an examples section; Sphinx napoleon renders either way. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Douglas Strodtman <[email protected]>
b26949d to
6a3bd92
Compare
There was a problem hiding this comment.
Code Review
This pull request updates the docstring examples across multiple aggregation classes in python/ray/data/aggregate.py by converting Sphinx .. testcode:: blocks into standard Python doctests. The feedback suggests replacing the deprecated Dataset.add_column method with the recommended Dataset.with_column and ray.data.expressions.col API in these examples to avoid using deprecated APIs and simplify the code.
| >>> import ray | ||
| >>> from ray.data.aggregate import Count | ||
| >>> ds = ray.data.range(100) | ||
| >>> # Schema: {'id': int64} | ||
| >>> ds = ds.add_column( | ||
| ... "group_key", lambda batch: batch["id"].astype("int64") % 3 | ||
| ... ) | ||
| >>> # Schema: {'id': int64, 'group_key': int64} |
There was a problem hiding this comment.
The Dataset.add_column method is deprecated in favor of Dataset.with_column. Since these docstring examples are being updated, we should avoid using deprecated APIs.
Using with_column along with col from ray.data.expressions is the recommended approach and is also cleaner as it avoids lambda functions and explicit pandas type casting.
Please apply this change here and to all other aggregate classes in this file that use add_column in their examples (including AsList, Sum, Min, Max, Mean, Std, AbsMax, Quantile, and Unique).
| >>> import ray | |
| >>> from ray.data.aggregate import Count | |
| >>> ds = ray.data.range(100) | |
| >>> # Schema: {'id': int64} | |
| >>> ds = ds.add_column( | |
| ... "group_key", lambda batch: batch["id"].astype("int64") % 3 | |
| ... ) | |
| >>> # Schema: {'id': int64, 'group_key': int64} | |
| >>> import ray | |
| >>> from ray.data.aggregate import Count | |
| >>> from ray.data.expressions import col | |
| >>> ds = ray.data.range(100) | |
| >>> # Schema: {'id': int64} | |
| >>> ds = ds.with_column("group_key", col("id") % 3) | |
| >>> # Schema: {'id': int64, 'group_key': int64} |
There was a problem hiding this comment.
Out of scope for this syntax-only conversion, so this PR keeps the example code as it was. add_column is deprecated in favor of with_column, so the suggestion is reasonable, but rewriting these examples is the Ray Data owners' call. Leaving it for them.
…ocstring examples, piloted on Ray Data (#66814) > [!NOTE] > **Draft proposal.** This PR is for agreeing on the direction before the label extends past Ray Data. It's rebased on `master` now that #66806 has merged. ## Why are these changes needed? A docstring edit in `python/ray/<lib>/` routes like a code change, so it runs every test suite that library's tag selects, and the `go` premerge runs all of them before merge. Converting docstring examples from Sphinx-only `.. testcode::` to stock `>>>` doctests produces a steady stream of these PRs. On master, 398 `testcode` blocks in 147 files remain. Measured on seven recent docstring-only PRs, one premerge build each: | PR | Library | Premerge runner-hours | |---|---|---| | #65901 | core | 39.6 | | #66745 | core | 43.7 | | #66749 | rllib | 15.3 | | #66747 | train | 10.6 | | #66746 | data | 10.3 | | #66748 | tune | 8.6 | | #66604 | data | 8.2 | Runner-hours are summed job durations from the Buildkite API, so queueing doesn't count. None of those suites can fail on a docstring-only change, except through a test that asserts on `__doc__` text. What a docstring edit can break is the example code in the docstrings it touched. ## What this PR does It adds a `docstring-only` PR label, piloted on Ray Data only. Under the label, a Data PR runs the `>>>` examples in the docstrings of only the modules it changed, plus the API checks and lint, instead of every Data test suite. - **The guard.** `lint: validate docstring-only scope` runs whenever the label is present, is tagged `always`, and can't be turned off. `ci/ray_ci/doc/check_docstring_only.py` parses each changed file at the merge-base and at `HEAD` with Python's `ast`, removes the docstring from the module and from every class and function, and compares `ast.dump` of the two trees. It fails on any difference, on any file that isn't `.py`, on any added, deleted, renamed, copied, or type-changed file, and on any parse error. Comments aren't in the AST, so comment edits pass. A string later in a body and a `__doc__` assignment both count as code. - **What the label skips.** The 10 Data test steps in `data.rayci.yml` that run on premerge get `if: '!(build.pull_request.labels includes "docstring-only")'`, the same pattern `docs-go` used. `pyrefly type check` isn't gated. - **What it runs instead.** A new `data: docstring examples` step, gated on the label, runs `ci/ray_ci/doc/run_docstring_examples.sh`: 1. It lists the `.py` files the PR modified under `python/ray/data/`, excluding `tests/` and `examples/`, and exits if there are none. 1. It builds the Data CI image with the PR's Ray, using `test_in_docker --build-only`, the same Ray install every Data test step uses. 1. In that image, it runs `ci/ray_ci/doc/run_docstring_examples.py` on only those files. The runner imports each module and extracts the `>>>` examples from every docstring in the file. It runs each docstring's examples in order, in a copy of the module's globals, as an interactive session would. An example that shows output must print it, so those examples are unit tests rather than smoke tests. Matching follows Ray's doctest targets: `...` matches any text (pytest's default ELLIPSIS flag), and per-example directives apply. An example that shows no output only has to run without raising, and one that shows a traceback must raise a matching exception. The standard library's doctest module supplies the parser and the output comparison, with no doctest runner, pytest collection, or Bazel doctest target. Examples still written as `.. testcode::` aren't run. - **Docs.** `doc/source/ray-contribute/ci.md` gets a "Docstring-only changes" section. ### Design choices for review - **Changed files only.** The unit is the changed module, not the library. A PR that edits `aggregate.py` runs only `aggregate.py`'s examples. - **Output is checked where it's shown.** A stale result in an example fails the step, the same as in Ray's doctest targets. Examples that show nothing are smoke tests. - **Data only.** Extending the label means an `if:` on most library test steps in every per-library `*.rayci.yml`, which each library team owns. This draft shows the shape on one library first. `ml: data integration tests` also carries the `data` tag but lives in `ml.rayci.yml`, so it still runs under the label. - **Some image builds still run.** The label gates test steps, not the `wanda` image builds they depend on. rayci selects steps by tag and pulls in every image a selected step depends on, and it doesn't evaluate `if:`. `wanda` steps can't take an `if:` either. Under the label, a Data docstring PR still emits 5 image jobs that feed only the gated steps: `datamongobuild-py3.10`, `datatfdsbuild-py3.12`, `docgpubuild-py3.10`, `docgpubuild-py3.12`, and `oss-ci-base_gpu-py3.12`. On premerge builds [74154](https://buildkite.com/ray-project/premerge/builds/74154) and [74459](https://buildkite.com/ray-project/premerge/builds/74459), those 5 jobs took 4.1 and 10.1 minutes. Each takes about 50 seconds as a cache hit, and `docgpubuild-py3.10` took 401 seconds on a miss. That's small next to the 6.9 runner-hours the gated steps took. Dropping them needs a rayci change that evaluates label gates before it marks dependencies. The other 20 image jobs in the build feed a step the label keeps, or rayci selects them on their own. - **Known residual risk.** A test that asserts on `__doc__` text, or on line numbers a docstring edit shifts, isn't visible to the guard. The postmerge build is the backstop. ## Related issue number None. Duplicate check: I searched open PRs for `docstring-only` and `docstring only label`, and found no PR that adds a label or guard for docstring-only changes. ## Tests run - `pytest ci/ray_ci/doc/test_check_docstring_only.py ci/ray_ci/doc/test_run_docstring_examples.py`: 29 passed. The runner's tests cover examples that use module globals, a raising example that fails with its file, line, and docstring name, wrong output that fails with a diff, matching output with ELLIPSIS and a directive, expected and mismatched exceptions, `+SKIP` and `+SKIP_EXAMPLE`, and no names leaking between docstrings. - The guard against real branches: it passes the three open docstring PRs, #66745 (2 files), #66746 (1 file), and #66812 (5 files). It fails #66806's branch and names the two `.py` files with code changes and the three Markdown files. - The runner against a Ray nightly (`43b706d`) on real branches. On #66812's five files, 7 docstrings ran and passed in 24 seconds. On #66746's `aggregate.py`, 18 docstrings ran and passed in 12 seconds. With output checking, on six `master` Data modules that already use `>>>` (`dataset.py`, `expressions.py`, `iterator.py`, `datatype.py`, and two preprocessors), 113 of 118 docstrings passed in 36 seconds. The 5 failures are packages missing from the local environment (`torch`, `tensorflow`, `crc32c`), not output mismatches. - `--list-changed` in a scratch clone whose only change is a docstring edit to `python/ray/data/aggregate.py` lists exactly that file. - Pipeline generation with `rayci` built at `.rayciversion` (0.48.0), for that simulated PR, on the premerge and microcheck pipeline IDs. Both generate, with selected tags `always data lint`. Evaluating the generated `if:` conditions shows the following: - **Without the label:** the Data test steps match the real premerge build of #66746 ([74459](https://buildkite.com/ray-project/premerge/builds/74459)). - **With `docstring-only`:** the 10 gated steps drop out, and `data: docstring examples` and `lint: validate docstring-only scope` are added. The API checks, `pyrefly`, `test-rules`, and `ml: data integration tests` still run. - The image jobs the label leaves running: I reran the same simulation with the 10 gated steps removed from the YAML, which is what a rayci change that evaluates label gates before marking dependencies would emit. The build goes from 25 image jobs to 20. The 5 removed are listed under "Some image builds still run." If the two `continuous-build` Data steps are also dropped, `datalbuild-py3.12` goes too, for 6. - Estimated saving on build 74459: the 10 gated steps took 6.9 of its 10.3 runner-hours. The new step adds one Data image build and a run of seconds per changed file. - `pre-commit` passes on the changed files. Not yet run: the label on a real Buildkite build, including the `--build-only` and `docker run` part of the new step. Nothing in the repo evaluates Buildkite `if:` conditions, so the first labeled Data docstring PR is the confirming check. **AI assistance.** This change was drafted with Claude Code. I reviewed every line and ran the tests above. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…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]>
…tests (#66812) ## What Convert the remaining runnable `.. testcode::` examples in six small `ray.data` docstrings to stock `>>>` doctests: - `DataContext.get_current` - `FilenameProvider` - `RowBasedFileDatasink` and `BlockBasedFileDatasink` - `HiddenRecordFilter` - `list_stats_summaries` ## Why `.. testcode::` / `.. testoutput::` is Sphinx-specific RST, run by Ray's fork of `pytest-sphinx` and not rendered by griffe/mkdocstrings. Stock `>>>` doctests render under both Sphinx and griffe and run under plain `pytest --doctest-modules`. This continues the convergence in #65901, #66745, and #66746, with the same conversion rules: - Same code, same order, same docstring. Each docstring stays one doctest item. - Bare expressions whose repr is incidental are bound to `_`: the two `take_all()` calls in `get_current`. - Blank lines inside a block are dropped, including between methods of a class defined in the example. - Existing `testoutput` becomes the doctest's expected output: `list_stats_summaries` keeps `1`. - Each example sits under a plural `Examples:` header with no blank line after it, the form that renders on both Sphinx and griffe. `FilenameProvider` keeps its lead-in sentence inside the section, and `HiddenRecordFilter` gains the header. ## Not in this PR - `ray.data._internal.util.MemoryProfiler` prints a varying value in a loop. Stock doctest fails on unmatched stdout, so converting it means changing the example, not just its markup. - `SerializablePreprocessorBase._set_serializable_fields` shows a method pattern in prose, not under an `Examples:` section. - The `:skipif: True` examples in `util/torch_inference.py` and `_internal/datasource/turbopuffer_datasink.py`, and `preprocessors/torch.py`, which needs `torchvision`. - `dataset.py`, `read_api.py`, and `llm.py`, which are larger and go in their own PRs. `aggregate.py` is #66746. ## Duplicate check I searched open PRs for `filename_provider`, `file_datasink`, `list_stats_summaries`, `HiddenRecordFilter`, and `testcode doctest`. The only related open PRs are my own #66745 and #66746, which touch other modules. ## Tests run Locally, against a Ray nightly (`43b706d`) with the edited modules overlaid, 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 (stock doctest plus `ray-project/pytest-sphinx`). `RAY_USAGE_STATS_PROMPT_ENABLED=0` suppresses the nightly-wheel-only usage banner. `pre-commit` passes on the changed files. | Modules | Before | After | |---|---|---| | The five changed files | 7 passed | 7 passed | | The same, with pytest-sphinx disabled (`-p no:sphinx`) | n/a | 7 passed, so stock doctest runs every converted block | The test count is unchanged, and everything stays in `//python/ray/data:doctest`. ## CI note The commit carries `@microcheck //python/ray/data:doctest`, which turned out to be unnecessary. Microcheck ran `//python/ray/data:doctest` in the `data: docs example tests` step and it passed ([build 55743](https://buildkite.com/ray-project/microcheck/builds/55743)). But #66746, which had no such line, ran the same target in the same step ([build 55601](https://buildkite.com/ray-project/microcheck/builds/55601)). Microcheck's changed-test lookup doesn't find these targets, because the `doctest()` macro lists module files as `data`, not `srcs`. They run anyway, through microcheck's high-impact or new-test sets. The line is harmless, and Ray squash-merges with the PR title and body, so it never reaches `master`. **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>
## Why are these changes needed? A `testcode` block reads as code that CI runs. On doc pages, 217 of them never run. Most carry `:skipif: True`, which Ray's pytest-sphinx fork drops before it builds an example, so the block never even shows up as skipped. The rest sit on pages that no doctest target collects. Most of these date from the semgrep `code-block-python` rule that required `testcode`, which #65903 removed. ### Changes - 45 doc pages: each never-run `testcode` block becomes a plain fenced `python` block, or `.. code-block:: python` in rST. Its paired `testoutput` becomes a `text` block. pytest-sphinx attaches a `testoutput` to the nearest preceding `testcode`, so leaving one behind would pin its output onto an earlier block that does run. - The 8 never-run blocks marked `:hide:` are deleted. Readers never saw them and CI never ran them. - The `hasattr` self-check asserts in the collective backend example are dropped. The asserts in `testing-tips.md` and the local-mode unit test stay, because they're what those examples teach. - `writing-code-snippets.md` no longer teaches `:skipif: True`. Code CI can't run goes in a plain code block, with a `text` block for sample output. - `doc/test_prose_doctest_targets.py` and `doc/BUILD.bazel`: `core/handling-dependencies.md` and `train/horovod.md` no longer hold a runnable example, so they leave `UNTESTED`, and the BUILD comments that explained their missing targets are trimmed. Docstring `testcode` under `python/ray/` is out of scope. It's moving to `>>>` examples in separate PRs, because `code-block` doesn't suit docstrings. ## Duplicate check No open PR covers this. Searches for `skipif`, `testcode`, and `writing-code-snippets` return only my own docstring-convergence PRs (#66745, #66746, #66812) and #66809, which this PR builds on and which has merged. ## Testing - For every changed page, I extracted examples with the pinned pytest-sphinx fork (`ray-project/pytest-sphinx@c1ab2b33`, `docstring2examples`, `pytest==7.4.4`) before and after the change. On the 36 pages a doctest target collects, the examples are identical: same source, expected output, and options. The 9 pages whose examples changed are exactly the pages no target collects, so no test result changes. - `python doc/test_prose_doctest_targets.py` passes: "45 listed pages; every runnable page is accounted for." Without the two `UNTESTED` removals, it fails on both as stale. - `pre-commit run` on all changed files passes. - No `:skipif:` remains under `doc/` except the guide's instruction not to use it. - Not run: a Sphinx build. The edits are directive-to-fence swaps, and the Read the Docs preview is the check. AI assistance (Claude Code) was used to write this change. 🤖 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]>
…#67202) ## Description Converts the `.. testcode::` examples in six `Dataset` transform methods to stock `>>>` doctests: `map`, `map_batches`, `flat_map`, `groupby`, `aggregate`, and `join`. Stock doctests render without Sphinx-only directives, and the `docstring-only` label's examples step runs them. The change touches only docstrings in `python/ray/data/dataset.py`. **`join` stays render-only.** Its three examples were `:skipif: True`, and their expected output couldn't have matched: a list prints on one line, and `NORMALIZE_WHITESPACE` can't insert the whitespace a multi-line expected block has between `[` and `{`. The examples now print one row per line. They're marked `+SKIP_EXAMPLE` because `Dataset.join` needs `polars`, and neither the docstring examples image nor the Data CI locks install it. With polars installed and the skip removed, all three pass. Running them in CI needs `polars` added to `docstring_examples_depset`, a dependency change that's out of scope here. **`map_batches` runs only in postmerge under the label.** Its third example imports torch, which the docstring examples image omits, so the step skips the whole docstring by name. It still runs in `//python/ray/data:doctest`. ## Related issues Related to #66814 and #67083. ## Additional information **Not a duplicate.** I searched open PRs that touch `python/ray/data/dataset.py` or mention converting its docstring examples. None converts these examples. #66746 and #66812 converted other Data modules and have merged. **Tests run** - `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "1 file(s), docstrings only." - `ci/ray_ci/doc/run_docstring_examples.py python/ray/data/dataset.py` in an aarch64 image built from `python/deplocks/docs/docstring_examples_depset_py3.10.lock`, with the Ray nightly at `093faf5583e`. The run excludes `decord`, which has no aarch64 wheel, and `ray-haproxy`. Result: 56 docstrings run and 0 failed. `map`, `flat_map`, `groupby`, and `aggregate` pass. `map_batches` is skipped for torch, and `join` for `+SKIP_EXAMPLE`. - The same run with `polars` installed and `+SKIP_EXAMPLE` removed: 57 docstrings run, 0 failed, `join` included. - `pre-commit run --files python/ray/data/dataset.py`: 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]>
…examples to stock doctests (#67207) ## Description Converts the remaining runnable `.. testcode::` examples in nine `Dataset` methods to stock `>>>` doctests: `streaming_split`, `split`, `iter_batches`, `iter_jax_batches`, `iter_tf_batches`, `stats`, `explain`, `serialize_lineage`, and `deserialize_lineage`. It also converts the one example each in `SerializablePreprocessorBase._set_serializable_fields` (`preprocessor.py`) and `MemoryProfiler` (`_internal/util.py`). Stock doctests render without Sphinx-only directives, and the `docstring-only` label's examples step runs them. The change touches only docstrings. Three examples used `:options: +MOCK`, which hid their output from comparison. Comparing it surfaced the following fixes: - **`iter_batches`** read `example://image-datasets/simple`, which resolves inside the installed package, and wheels don't ship `ray/data/examples/data/`. It now reads the same images from `s3://anonymous@ray-example-data/image-datasets/simple`, as `Dataset.map` does. The three images make exactly two batches, so the expected output drops the `...` line between them, which wouldn't have matched. - **`stats`** shows the current output format, with ellipses for counts, timings, and the read operator's name, which becomes `ReadRange->SplitBlocks(N)` depending on the CPU count. The `assert ds.stats() == ""` is now `>>> ds.stats()` with `''` as the output. - **`MemoryProfiler`** replaces the `...` placeholder statement with `pass`. In a doctest, a bare `...` expression echoes `Ellipsis` on every loop iteration. The USS values use an ellipsis. **`iter_tf_batches`** called `Dataset.to_tf`, which has its own examples. It now calls `iter_tf_batches` and prints the first batch, matching the `iter_jax_batches` example. The fourth `streaming_split` example deliberately blocks, so it stays render-only, now with `# doctest: +SKIP` on that one line in place of `:skipif: True`. The rest of the docstring runs. `explain`, `split`, and the lineage examples matched as written. **`iter_jax_batches` and `iter_tf_batches` run only in postmerge under the label.** The docstring examples image omits JAX and TensorFlow, so the step skips both docstrings by name. They still run in `//python/ray/data:doctest`. ## Related issues Related to #66814, #67083, and #67202. ## Additional information **Not a duplicate.** I searched open PRs that touch `python/ray/data/dataset.py`, `streaming_split`, `serialize_lineage`, or `MemoryProfiler`. #67202 converts the `Dataset` transform methods (`map`, `map_batches`, `flat_map`, `groupby`, `aggregate`, `join`) in the same file, and the two PRs edit different methods. #64869 and #66340 don't touch these examples. #66746, #66812, #67070, and #67080 converted other Data modules and have merged. **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 built from `python/deplocks/docs/docstring_examples_depset_py3.10.lock`, with the Ray nightly at `093faf5583e` and the changed files mounted over the installed ones. The three files are unchanged between that commit and this PR's base. Result: 61 docstrings run and 0 failed. `iter_jax_batches`, `iter_tf_batches`, `to_tf`, `write_tfrecords`, and `iter_torch_batches` are skipped for libraries the image omits. - The two JAX and TensorFlow docstrings, run with `doctest` in the same image after installing `jax` 0.6.2 and `tensorflow` 2.21.0: 0 failures each. Those aren't CI's pinned versions, so I'll check the postmerge `data: docs example tests` result after merge. - `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]>
What
Convert every
.. testcode::example inray.data.aggregateto stock>>>doctests (18 blocks):AggregateFn,Count,AsList,Sum,Min,Max,Mean,Std,AbsMax,Quantile,Unique,CountDistinct,ValueCounter,MissingValuePercentage,ZeroPercentage,ApproximateQuantile,ApproximateTopK,TopKUnique.Why
.. testcode::/.. testoutput::is Sphinx-specific RST, run by Ray's fork ofpytest-sphinxand not rendered by griffe/mkdocstrings. Stock>>>doctests render under both Sphinx and griffe and run under plainpytest --doctest-modules. This continues the convergence piloted in #65901 (ray.util.actor_pool,ray.util.placement_group), using the same conversion rules.How the blocks convert
Same code, same order, same docstring. Each docstring stays one doctest item and moves from the pytest-sphinx collector to stock doctest.
assertlines stay as plain>>>lines, and existing expected output stays as the doctest's expected output._.One behavior difference to know: a
testcodeblock with notestoutputignores stdout, but stock doctest fails on any unmatched stdout. Every converted block was run to confirm it prints nothing unexpected.This module needs no binds or doctest flags. Every block assigns its result and shows it in a trailing
# result: ...comment, and those comments stay as>>> #lines, the styleray.data.expressionsalready uses.AsListnow runsAsListwas:skipif: True, with a comment saying the example needs ordered output. The example asserts nothing about order, so it now runs, and it passed three of three local runs. Its# result:comment is unchanged. Real groupby output order varies, which is fine because the result isn't checked.Tests run
Locally, against a Ray nightly (
43b706d) with the edited module overlaid, using pytest 7.4.4 and the same flags as thedoctestBazel macro:--doctest-modules -c NO_PYTEST_CONFIG -p <default_doctest_pytest_plugin>, with both collectors installed (stock doctest plusray-project/pytest-sphinx).RAY_USAGE_STATS_PROMPT_ENABLED=0suppresses the nightly-wheel-only usage banner, which source-built CI doesn't print.pre-commitpasses on the changed files.datasketchesis installed locally for the two approximate aggregators. CI has it throughdata-test-requirements.txt.ray/data/aggregate.pyAsListskipped)Possible follow-up, not done here
The global aggregates (
Count,Sum,CountDistinct,ValueCounter,MissingValuePercentage,ZeroPercentage,TopKUnique) return deterministic results. Their# result:comments could become checked expected output. The groupby examples would need an order-independent check. That changes the examples beyond a conversion, so it's left for a separate PR if Data wants it.Rendering
Each converted example sits under a plural
Examples:header, indented, with no blank line after the header. That is the only form that renders as an examples section on both Sphinx (napoleon) and griffe/mkdocstrings. Griffe's Google parser treats singularExample:as an admonition, treats a header followed by a blank line as plain text, and renders>>>in free prose as Markdown blockquotes. On Sphinx this only adds or renames the "Examples" rubric. Every changed docstring was rendered before and after with Sphinx 8.2.3 (autodoc,napoleon,sphinx.ext.doctest) andmkdocstrings-python2.0.9 /griffelib2.3.0. Sphinx output has no regressions, and every converted example renders as highlighted doctest code under griffe.Duplicate check
gh pr list --state open --searchfor "testcode", "doctest", and the touched module names found no open PR converting these docstrings.AI assistance
Drafted with AI assistance (Claude Code). The submitter reviews every changed line before marking this ready for review.
🤖 Generated with Claude Code