Repository navigation
[data] Convert Dataset transform docstring examples to stock doctests - #67202
Conversation
Convert the testcode blocks in Dataset.map, map_batches, flat_map, groupby, aggregate, and join to stock >>> doctests. The join examples were skipped, and their expected output couldn't match: a list printed on one line can't match a multi-line expected block under NORMALIZE_WHITESPACE. They now print one row per line. They stay render-only with +SKIP_EXAMPLE, because Dataset.join needs polars, which the docstring examples image doesn't install. @rtd-build 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 refactors docstring examples in python/ray/data/dataset.py across multiple methods, converting them from Sphinx directives to standard Python doctest format. The feedback points out that in the flat_map example, using [row] * 2 creates duplicate references to the same dictionary object, which can cause bugs if modified downstream; using row.copy() is recommended instead.
| >>> def duplicate_row(row: Dict[str, Any]) -> List[Dict[str, Any]]: | ||
| ... return [row] * 2 |
There was a problem hiding this comment.
Using [row] * 2 creates a list containing two references to the exact same dictionary object. If a downstream operator or user subsequently modifies one of these rows, both will be modified, which is a common source of subtle bugs in Python. It is safer and more idiomatic to return copies of the dictionary using row.copy().
| >>> def duplicate_row(row: Dict[str, Any]) -> List[Dict[str, Any]]: | |
| ... return [row] * 2 | |
| >>> def duplicate_row(row: Dict[str, Any]) -> List[Dict[str, Any]]:\n ... return [row.copy(), row.copy()] |
…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 (#67208) ## Description Converts the seven `.. testcode::` examples in `python/ray/data/llm.py` to `>>>` doctests. They're in `HttpRequestProcessorConfig`, `vLLMEngineProcessorConfig`, `SGLangEngineProcessorConfig`, `ServeDeploymentProcessorConfig`, and `build_processor`, which holds three of them. The change touches only docstrings. **The examples stay render-only.** Every block was `:skipif: True`, because running them needs GPUs and model downloads, an OpenAI API key, or a running Serve deployment. Each docstring now carries one `# doctest: +SKIP_EXAMPLE` flag on its first line, which skips the whole docstring in both the `//python/ray/data:doctest` target and the `docstring-only` examples step. Sphinx strips the flag from the rendered page. The code itself is unchanged apart from the `>>>` and `...` prompts and the removal of the blank lines a doctest can't contain. This is separate from the other Ray Data docstring conversions, such as #67202 and #67207, because CODEOWNERS assigns `python/ray/data/llm.py` to `@ray-project/ray-llm`. ## Related issues Related to #67080, #67202, and #67207. ## Additional information **Not a duplicate.** I searched open PRs that mention `llm.py` or converting `ray.data.llm` docstring examples. None touches these examples. **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/llm.py` against the macOS arm64 Ray nightly at `43b706d733c`, whose `llm.py` matches this PR's base, with the converted file swapped in: 0 run, 0 failed, 5 skipped for `+SKIP_EXAMPLE`. - `pytest --doctest-modules -p doctest_pytest_plugin` on the same file, with the Ray Data doctest plugin: 5 skipped as "render-only example (+SKIP_EXAMPLE)", no collection errors. - Every converted example parses with `doctest.DocTestParser` and compiles. - `pre-commit` on commit: all hooks pass, including black, ruff, 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]>
…ttings in the examples runner (#67237) ## Description Follow-ups to the `docstring-only` label (#66814, #67083) after its first real campaign PRs on Ray Data. They're bundled into one PR because they share files and all need ray-ci review. Stacked on #67204, which updates the contributor docs this PR edits. 1. **Skip polars examples by name instead of marking them render-only.** `Dataset.join` needs `polars`, which the light `docstringbuild` image doesn't install, so #67202 marked the docstring `+SKIP_EXAMPLE`. That also stopped it from running in `//python/ray/data:doctest`, whose image installs polars through `test-requirements.txt`. This PR adds `polars` to `OMITTED_LIBRARIES` and removes the flag. The examples step now reports `SKIP Dataset.join (needs polars)`, and Data's target runs the three `join` examples. - Polars isn't added to the image. `polars==1.40.0` plus `polars-runtime-32==1.40.0` is a 57 MB x86_64 wheel and about 195 MB installed, larger than pyarrow at 136 MB, for one docstring. Every current extra is 21 MB or less. - **lance, the same way.** `Dataset.write_lance` needs `lance`, from the `pylance` distribution. It's about 138 MB installed on Linux aarch64, for one docstring, and Data's doctest image installs it through `data-test-requirements.txt`. This PR adds `lance` to `OMITTED_LIBRARIES`, so the examples step reports `SKIP Dataset.write_lance (needs lance)`. #67238, stacked on this PR, converts that docstring and `write_sql`'s from `testcode` to `>>>`. - **LightGBM and XGBoost, the same way.** `ray.tune.integration.lightgbm` and `.xgboost`, and Ray Train's LightGBM and XGBoost modules, import these at module level. The image installs neither, so a `docstring-only` change to one of those modules failed the examples step at import, even though Tune's examples there are render-only (`+SKIP_EXAMPLE`) and Train's are still `testcode`. The ML images install both through `python/requirements/ml/core-requirements.txt`, which meets the omit rule in item 2. The step now reports `SKIP python/ray/tune/integration/lightgbm.py (module needs lightgbm)`, and likewise for `xgboost`. #67619, stacked on this PR, converts those two Tune examples. 2. **Write the inclusion rule into `docstring-examples-requirements.txt`.** The header now states when to add a library to the image and when to omit it by name. Each entry names the APIs whose examples need it, so it can go once those stop needing it. Comment-only. `raydepsets --check` reports the locks unchanged. 3. **Apply Ray Data's doctest settings in the runner.** `doctest_pytest_plugin.py` sets `preserve_order` and turns off `print_on_execution_start` for every Data docstring. The runner applied neither, so an order-dependent example could pass in its target and flake in the step. It now applies both to `ray.data` modules and restores them after each docstring. 4. **`ml: data integration tests` under the label.** This PR originally added a negated `if:` gate to it. #67341 merged the `docstring-only` keep-only rule in `.buildkite/docs.labels.yaml`, which drops this step with every other library test step, so the gate is removed and `ml.rayci.yml` is unchanged. 5. **Count the output a render-only docstring hides.** `+SKIP_EXAMPLE` skips a whole docstring, so expected output inside it is never checked. The skip line now names how many such examples there are. Across `python/ray` at this commit, 26 docstrings carry the flag, and only `Dataset.join` had expected output, which item 1 makes runnable. So the count is a signal rather than a failure: a render-only example can legitimately show sample output, such as for an external service. 6. **`check_docstring_only.py --base` diffs from the merge base.** It diffed against the ref literally. After master moved past the branch point, `--base upstream/master` flagged files the PR never touched. The CI path, which already used the merge base, is unchanged. This matches `run_docstring_examples.py`, and the `ci.md` instructions drop the manual `git merge-base` wrapper. 7. **Stale comments.** The `doc_example` prose rule's comment in `test.rules.txt` said an unlabeled prose PR still builds the opt-in step's images. Since #67341, the `docs-example-test` label rule drops the step before dependency marking, so the comment now says that. The `doc: doctest` comment in `others.rayci.yml` still called `//doc:doctest` the catch-all target, but #67003 split it into per-page `team:none` targets. The `docstring examples` comment now names the omitted libraries. It also said Buildkite drops the step on an unlabeled PR that selects it, but Buildkite shows it as `broken`, and that the skipped Ray Data examples run in "postmerge", which now says the scheduled postmerge builds, since the build each merge starts doesn't run them. ## Related issues Related to #66814, #67083, #67202, and #67204. #67238 and #67619 are stacked on this PR. ## Additional information **Not a duplicate.** I searched open PRs for `run_docstring_examples`, `check_docstring_only`, `docstring-only`, `OMITTED_LIBRARIES`, and `data integration tests`. Only #67204, which this stacks on, touches these files, and it changes docs only. **Tests run** - `bazel test //ci/ray_ci/doc:test_run_docstring_examples //ci/ray_ci/doc:test_check_docstring_only`: both pass. New cases cover: - The `Dataset.join` polars message. - The hidden-output count. - The Data settings, applied and restored, and left alone for other modules. - `--base` against a base that moved past the branch point. - `missing_library` for `lightgbm` and `xgboost` module-level imports. For that commit I ran the suite with `pytest` directly rather than through Bazel: 33 passed. - `run_docstring_examples.py` on `dataset.py`, `aggregate.py`, and `read_api.py`. I ran it in an aarch64 image built from `docstring_examples_depset_py3.10.lock`, without `decord` (no aarch64 wheel) and `ray-haproxy`, with the Ray nightly at `093faf5583e`. - 114 docstrings ran, and `Dataset.join` skipped for polars. - The one failure is `read_videos`, which needs decord. The x86_64 CI image installs it. - With polars installed, `Dataset.join` passes, and 115 docstrings run. - With the Data settings, `Starting execution of Dataset` lines drop to zero, and all 18 `aggregate.py` docstrings pass. - `run_docstring_examples.py` on `ray.tune.integration.lightgbm` and `.xgboost` from #67619, in a Python 3.12 virtualenv with `ray[tune]==2.59.0` and neither library installed: both modules skipped by name, 0 failed. Before this change, both failed at import. - `bazel run //ci/raydepsets:raydepsets -- build ci/raydepsets/configs/docs.depsets.yaml --check`: lock files are up to date. - `pre-commit run` on the changed files: passes. - `rayci` v0.50.0 pipeline generation for a labeled Data docstring PR on this branch, as above. This PR's own premerge runs the Data and ML suites, because it changes `dataset.py`. That run is also the check that Data's doctest image has polars. 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]>
…ock doctests (#67238) ## Description Converts the last three `.. testcode::` blocks in `python/ray/data/dataset.py` to stock `>>>` doctests, in `Dataset.write_sql` and `Dataset.write_lance`. After this, `dataset.py` has no `testcode` left. The change touches only docstrings. **`write_sql` follows `read_sql`'s pattern.** The example created `example.db` in the working directory, and a hidden `:hide:` testcode block deleted it afterward. Stock doctests have no hidden-cleanup equivalent, so the example now creates the database in a `tempfile.TemporaryDirectory()` and calls `cleanup()` at the end, the way `ray.data.read_sql`'s example does. **`write_lance` was malformed.** Its `.. testcode::` directive had no blank line before its body. The example also wrote to a fixed `/tmp/lance_data/` path. It now writes to a temporary directory too. It needs `lance`, which the docstring examples image doesn't install, so the examples step reports it as skipped by name, and `//python/ray/data:doctest`, whose image installs `pylance`, runs it. Stacked on #67237, which adds `lance` to the runner's `OMITTED_LIBRARIES`. Without that change, the examples step would fail on `write_lance` rather than skip it. ## Related issues Related to #67202, #67207, #67209, and #67237. ## Additional information **Not a duplicate.** I searched open PRs for `write_sql` and `write_lance`. None converts these examples. #67202, #67207, and #67209 converted the rest of `dataset.py` and have merged. **Tests run** - `ci/ray_ci/doc/check_docstring_only.py --base upstream/doc-1863-docstring-runner-bundle`: "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` and this branch's `dataset.py` mounted over the installed one. Result: 64 docstrings run and 0 failed. `write_sql` passes, and `write_lance` is skipped for `lance`. - The same run with `pylance==4.0.0` installed, the version Ray Data's CI pins: 65 docstrings run, 0 failed, and `write_lance` passes. Neither example leaves files in `/tmp`. - `pre-commit run --files python/ray/data/dataset.py`: 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 sixDatasettransform methods to stock>>>doctests:map,map_batches,flat_map,groupby,aggregate, andjoin. Stock doctests render without Sphinx-only directives, and thedocstring-onlylabel's examples step runs them. The change touches only docstrings inpython/ray/data/dataset.py.joinstays render-only. Its three examples were:skipif: True, and their expected output couldn't have matched: a list prints on one line, andNORMALIZE_WHITESPACEcan't insert the whitespace a multi-line expected block has between[and{. The examples now print one row per line. They're marked+SKIP_EXAMPLEbecauseDataset.joinneedspolars, 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 needspolarsadded todocstring_examples_depset, a dependency change that's out of scope here.map_batchesruns 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.pyor 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.pyin an aarch64 image built frompython/deplocks/docs/docstring_examples_depset_py3.10.lock, with the Ray nightly at093faf5583e. The run excludesdecord, which has no aarch64 wheel, andray-haproxy. Result: 56 docstrings run and 0 failed.map,flat_map,groupby, andaggregatepass.map_batchesis skipped for torch, andjoinfor+SKIP_EXAMPLE.polarsinstalled and+SKIP_EXAMPLEremoved: 57 docstrings run, 0 failed,joinincluded.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-onlylabel, and its commit carries an@rtd-buildline for the Read the Docs preview.AI assistance (Claude Code) was used for this PR.
🤖 Generated with Claude Code